From 3e7700e1b9b652bb3ed7daaff76cf891907a63b3 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 4 Dec 2010 21:05:49 +0800 Subject: [PATCH] Moved serial port opening out into a helper, added delay to coke read. --- src/server/common.h | 2 +- src/server/handler_coke.c | 11 ++++++++--- src/server/main.c | 14 ++++++++++++-- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/server/common.h b/src/server/common.h index 9f2c3b3..4fad81c 100644 --- a/src/server/common.h +++ b/src/server/common.h @@ -71,7 +71,7 @@ extern int giDebugLevel; // --- Helpers -- extern void CompileRegex(regex_t *Regex, const char *Pattern, int Flags); extern int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage); -extern void InitSerial(int FD, int BaudRate); +extern int InitSerial(const char *Path, int BaudRate); // --- Dispense --- extern int DispenseItem(int User, tItem *Item); diff --git a/src/server/handler_coke.c b/src/server/handler_coke.c index 53cbd0f..c937756 100644 --- a/src/server/handler_coke.c +++ b/src/server/handler_coke.c @@ -37,13 +37,12 @@ regex_t gCoke_StatusRegex; int Coke_InitHandler() { printf("connecting to coke machine...\n"); - giCoke_SerialFD = open(gsCoke_SerialPort, O_RDWR | O_NOCTTY | O_NONBLOCK); + + giCoke_SerialFD = InitSerial(gsCoke_SerialPort, 9600); if( giCoke_SerialFD == -1 ) { fprintf(stderr, "ERROR: Unable to open coke serial port ('%s')\n", gsCoke_SerialPort); } - InitSerial(giCoke_SerialFD, 9600); - CompileRegex(&gCoke_StatusRegex, "^slot\\s+(\\d)\\s+([^:]+):([a-zA-Z]+)\\s*", REG_EXTENDED); return 0; } @@ -61,6 +60,9 @@ int Coke_CanDispense(int User, int Item) sprintf(tmp, "s%i\n", Item); write(giCoke_SerialFD, tmp, 2); + // Wait a little + sleep(250); + // Read the response tmp[0] = '\0'; ret = read(giCoke_SerialFD, tmp, sizeof(tmp)-1); @@ -99,6 +101,9 @@ int Coke_DoDispense(int User, int Item) // Dispense sprintf(tmp, "d%i\n", Item); write(giCoke_SerialFD, tmp, 2); + + // Wait a little + sleep(250); // Get status read(giCoke_SerialFD, tmp, sizeof(tmp)-1); diff --git a/src/server/main.c b/src/server/main.c index a903f75..17397c1 100644 --- a/src/server/main.c +++ b/src/server/main.c @@ -13,6 +13,9 @@ #include #include "common.h" #include +#include +#include +#include // === IMPORTS === extern void Init_Cokebank(const char *Argument); // cokebank.c @@ -120,10 +123,15 @@ void CompileRegex(regex_t *regex, const char *pattern, int flags) } // Serial helper -void InitSerial(int FD, int BaudRate) +int InitSerial(const char *File, int BaudRate) { struct termios info; int baud; + int fd; + + + fd = open(File, O_RDWR | O_NOCTTY); + if( fd == -1 ) return -1; switch(BaudRate) { @@ -134,7 +142,9 @@ void InitSerial(int FD, int BaudRate) cfmakeraw(&info); // Sets 8N1 cfsetspeed(&info, baud); - tcsetattr(FD, TCSANOW, &info); + tcsetattr(fd, TCSANOW, &info); + + return fd; } -- 2.20.1