3 * UCC (University [of WA] Computer Club) Electronic Accounting System
5 * handler_coke.c - Coke controller code
7 * This file is licenced under the 3-clause BSD Licence. See the file
8 * COPYING for full details.
21 int Coke_InitHandler();
22 int Coke_CanDispense(int User, int Item);
23 int Coke_DoDispense(int User, int Item);
25 int ReadLine(int len, char *output);
28 tHandler gCoke_Handler = {
34 char *gsCoke_SerialPort = "/dev/ttyS0";
36 regex_t gCoke_StatusRegex;
39 int Coke_InitHandler()
41 printf("connecting to coke machine...\n");
43 giCoke_SerialFD = InitSerial(gsCoke_SerialPort, 9600);
44 if( giCoke_SerialFD == -1 ) {
45 fprintf(stderr, "ERROR: Unable to open coke serial port ('%s')\n", gsCoke_SerialPort);
48 CompileRegex(&gCoke_StatusRegex, "^slot\\s+(\\d)\\s+([^:]+):([a-zA-Z]+)\\s*", REG_EXTENDED);
52 int Coke_CanDispense(int User, int Item)
54 char tmp[32], *status;
55 regmatch_t matches[4];
59 if( Item < 0 || Item > 6 ) return -1; // -EYOURBAD
63 write(giCoke_SerialFD, "d7\r\n", 4);
64 } while( WaitForColon() && ret++ < 3 );
67 fprintf(stderr, "Coke machine timed out\n");
71 // TODO: Handle "not ok" response to D7
73 // Ask the coke machine
74 sprintf(tmp, "s%i\r\n", Item);
75 write(giCoke_SerialFD, tmp, 4);
77 ret = ReadLine(sizeof(tmp)-1, tmp);
78 printf("ret = %i, tmp = '%s'\n", ret, tmp);
80 // ret = ReadLine(sizeof(tmp)-1, tmp);
81 printf("ret = %i, tmp = '%s'\n", ret, tmp);
85 fprintf(stderr, "Coke machine is not being chatty (read = %i)\n", ret);
87 perror("Coke Machine");
92 // Parse status response
93 ret = RunRegex(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
99 tmp[ matches[3].rm_eo ] = '\0';
100 status = &tmp[ matches[3].rm_so ];
102 printf("Machine responded slot status '%s'\n", status);
104 if( strcmp(status, "full") == 0 )
111 * \brief Actually do a dispense from the coke machine
113 int Coke_DoDispense(int User, int Item)
115 char tmp[32], *status;
116 regmatch_t matches[4];
119 if( Item < 0 || Item > 6 ) return -1;
124 sprintf(tmp, "d%i\r\n", Item);
125 write(giCoke_SerialFD, tmp, 4);
130 ReadLine(sizeof(tmp)-1, tmp);
132 tmp[ matches[3].rm_eo ] = '\0';
133 status = &tmp[ matches[3].rm_so ];
135 printf("Machine responded slot status '%s'\n", status);
145 struct timeval timeout;
147 timeout.tv_sec = 5; // 5 second timeout
151 FD_SET(giCoke_SerialFD, &readfs);
153 ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
154 if( ret == 0 ) return 0; // Timeout
156 printf("readchar return %i\n", ret);
160 ret = read(giCoke_SerialFD, &ch, 1);
162 printf("ret = %i\n", ret);
174 FD_SET(giCoke_SerialFD, &readfs);
176 while( (ch = ReadChar()) != ':' && ch != 0);
178 if( ch == 0 ) return -1; // Timeout
183 int ReadLine(int len, char *output)
199 if( ch == '\n' || ch == '\r' ) {
206 //printf("ReadLine: output=%s\n", output);