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 ret = ReadLine(sizeof(tmp)-1, tmp);
75 printf("ret = %i, tmp = '%s'\n", ret, tmp);
78 fprintf(stderr, "Coke machine is not being chatty (read = %i)\n", ret);
80 perror("Coke Machine");
84 ret = RunRegex(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
89 tmp[ matches[3].rm_eo ] = '\0';
90 status = &tmp[ matches[3].rm_so ];
92 printf("Machine responded slot status '%s'\n", status);
94 if( strcmp(status, "full") == 0 )
101 * \brief Actually do a dispense from the coke machine
103 int Coke_DoDispense(int User, int Item)
105 char tmp[32], *status;
106 regmatch_t matches[4];
109 if( Item < 0 || Item > 6 ) return -1;
114 sprintf(tmp, "d%i\r\n", Item);
115 write(giCoke_SerialFD, tmp, 4);
120 ReadLine(sizeof(tmp)-1, tmp);
122 tmp[ matches[3].rm_eo ] = '\0';
123 status = &tmp[ matches[3].rm_so ];
125 printf("Machine responded slot status '%s'\n", status);
135 struct timeval timeout;
137 timeout.tv_sec = 5; // 5 second timeout
141 FD_SET(giCoke_SerialFD, &readfs);
143 ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
144 if( ret == 0 ) return 0; // Timeout
146 printf("readchar return %i\n", ret);
150 ret = read(giCoke_SerialFD, &ch, 1);
152 printf("ret = %i\n", ret);
164 FD_SET(giCoke_SerialFD, &readfs);
166 while( (ch = ReadChar()) != ':' && ch != 0);
168 if( ch == 0 ) return -1; // Timeout
173 int ReadLine(int len, char *output)
189 if( ch == '\n' || ch == '\r' ) {