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
61 write(giCoke_SerialFD, "d7\r\n", 4);
62 write(giCoke_SerialFD, "d7\r\n", 4);
63 write(giCoke_SerialFD, "d7\r\n", 4);
65 if( WaitForColon() ) {
66 fprintf(stderr, "Coke machine timed out\n");
70 // Ask the coke machine
71 sprintf(tmp, "s%i\r\n", Item);
72 write(giCoke_SerialFD, tmp, 4);
74 if( WaitForColon() ) {
75 fprintf(stderr, "Coke machine timed out (after initial)\n");
79 ret = ReadLine(sizeof(tmp)-1, tmp);
80 printf("ret = %i, tmp = '%s'\n", ret, tmp);
83 fprintf(stderr, "Coke machine is not being chatty (read = %i)\n", ret);
85 perror("Coke Machine");
89 ret = RunRegex(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
94 tmp[ matches[3].rm_eo ] = '\0';
95 status = &tmp[ matches[3].rm_so ];
97 printf("Machine responded slot status '%s'\n", status);
99 if( strcmp(status, "full") == 0 )
106 * \brief Actually do a dispense from the coke machine
108 int Coke_DoDispense(int User, int Item)
110 char tmp[32], *status;
111 regmatch_t matches[4];
114 if( Item < 0 || Item > 6 ) return -1;
119 sprintf(tmp, "d%i\r\n", Item);
120 write(giCoke_SerialFD, tmp, 4);
125 ReadLine(sizeof(tmp)-1, tmp);
127 tmp[ matches[3].rm_eo ] = '\0';
128 status = &tmp[ matches[3].rm_so ];
130 printf("Machine responded slot status '%s'\n", status);
140 struct timeval timeout;
142 timeout.tv_sec = 5; // 5 second timeout
146 FD_SET(giCoke_SerialFD, &readfs);
148 ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
149 if( ret == 0 ) return 0; // Timeout
151 printf("readchar return %i\n", ret);
155 ret = read(giCoke_SerialFD, &ch, 1);
157 printf("ret = %i\n", ret);
169 FD_SET(giCoke_SerialFD, &readfs);
171 while( (ch = ReadChar()) != ':' && ch != 0);
173 if( ch == 0 ) return -1; // Timeout
178 int ReadLine(int len, char *output)
194 if( ch == '\n' || ch == '\r' ) {