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);
76 ret = ReadLine(sizeof(tmp)-1, tmp);
77 printf("ret = %i, tmp = '%s'\n", ret, tmp);
80 fprintf(stderr, "Coke machine is not being chatty (read = %i)\n", ret);
82 perror("Coke Machine");
86 ret = RunRegex(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
91 tmp[ matches[3].rm_eo ] = '\0';
92 status = &tmp[ matches[3].rm_so ];
94 printf("Machine responded slot status '%s'\n", status);
96 if( strcmp(status, "full") == 0 )
103 * \brief Actually do a dispense from the coke machine
105 int Coke_DoDispense(int User, int Item)
107 char tmp[32], *status;
108 regmatch_t matches[4];
111 if( Item < 0 || Item > 6 ) return -1;
116 sprintf(tmp, "d%i\r\n", Item);
117 write(giCoke_SerialFD, tmp, 4);
122 ReadLine(sizeof(tmp)-1, tmp);
124 tmp[ matches[3].rm_eo ] = '\0';
125 status = &tmp[ matches[3].rm_so ];
127 printf("Machine responded slot status '%s'\n", status);
137 struct timeval timeout;
139 timeout.tv_sec = 5; // 5 second timeout
143 FD_SET(giCoke_SerialFD, &readfs);
145 ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
146 if( ret == 0 ) return 0; // Timeout
148 printf("readchar return %i\n", ret);
152 ret = read(giCoke_SerialFD, &ch, 1);
154 printf("ret = %i\n", ret);
166 FD_SET(giCoke_SerialFD, &readfs);
168 while( (ch = ReadChar()) != ':' && ch != 0);
170 if( ch == 0 ) return -1; // Timeout
175 int ReadLine(int len, char *output)
191 if( ch == '\n' || ch == '\r' ) {