188beb44ffb2b85ab9408e30715b71387cad89df
[tpg/opendispense2.git] / src / server / handler_coke.c
1 /*
2  * OpenDispense 2 
3  * UCC (University [of WA] Computer Club) Electronic Accounting System
4  *
5  * handler_coke.c - Coke controller code
6  *
7  * This file is licenced under the 3-clause BSD Licence. See the file
8  * COPYING for full details.
9  *
10  * NOTES:
11  * - Remember, the coke machine echoes your text back to you!
12  */
13 #include "common.h"
14 #include <stdio.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <regex.h>
20 #include <stdarg.h>
21
22 #define READ_TIMEOUT    2       // 2 seconds for ReadChar
23 #define TRACE_COKE      1
24
25 // === IMPORTS ===
26
27 // === PROTOTYPES ===
28  int    Coke_InitHandler();
29  int    Coke_CanDispense(int User, int Item);
30  int    Coke_DoDispense(int User, int Item);
31  int    Writef(const char *Format, ...);
32  int    WaitForColon();
33  int    ReadLine(int len, char *output);
34
35 // === GLOBALS ===
36 tHandler        gCoke_Handler = {
37         "coke",
38         Coke_InitHandler,
39         Coke_CanDispense,
40         Coke_DoDispense
41 };
42 char    *gsCoke_SerialPort = "/dev/ttyS0";
43  int    giCoke_SerialFD;
44 regex_t gCoke_StatusRegex;
45
46 // == CODE ===
47 int Coke_InitHandler()
48 {
49         printf("connecting to coke machine...\n");
50         
51         giCoke_SerialFD = InitSerial(gsCoke_SerialPort, 9600);
52         if( giCoke_SerialFD == -1 ) {
53                 fprintf(stderr, "ERROR: Unable to open coke serial port ('%s')\n", gsCoke_SerialPort);
54         }
55         else {
56                 // Reset the slot names.
57                 // - Dunno why this is needed, but the machine plays silly
58                 //   sometimes.
59                 Writef("n0 Slot0\n");
60                 if( !WaitForColon() )
61                 {
62                         Writef("n1 Slot1\n");
63                         WaitForColon();
64                         Writef("n2 Slot2\n");
65                         WaitForColon();
66                         Writef("n3 Slot3\n");
67                         WaitForColon();
68                         Writef("n4 Slot4\n");
69                         WaitForColon();
70                         Writef("n5 Slot5\n");
71                         WaitForColon();
72                         Writef("n6 Coke\n");
73                 }
74         }
75         
76         CompileRegex(&gCoke_StatusRegex, "^slot\\s+([0-9]+)\\s+([^:]+):([a-zA-Z]+)\\s*", REG_EXTENDED);
77         return 0;
78 }
79
80 int Coke_CanDispense(int UNUSED(User), int Item)
81 {
82         char    tmp[40], *status;
83         regmatch_t      matches[4];
84          int    ret;
85
86         // Sanity please
87         if( Item < 0 || Item > 6 )      return -1;      // -EYOURBAD
88         
89         // Can't dispense if the machine is not connected
90         if( giCoke_SerialFD == -1 )
91                 return -2;
92         
93         #if TRACE_COKE
94         printf("Coke_CanDispense: Flushing\n");
95         #endif
96         
97         
98         // Wait for a prompt
99         ret = 0;
100         while( WaitForColon() && ret < 3 )
101         {
102                 // Flush the input buffer
103                 char    tmpbuf[512];
104                 read(giCoke_SerialFD, tmpbuf, sizeof(tmpbuf));
105                 #if TRACE_COKE
106                 printf("Coke_CanDispense: sending 'd7'\n");
107                 #endif
108                 Writef("d7\r\n");
109                 ret ++;
110         }
111         // Check for a timeout error
112         if( !(ret < 3) ) {
113                 fprintf(stderr, "Coke machine timed out\n");
114                 return -2;      // -EMYBAD
115         }
116         
117         // You need to do a 'd7' before reading the status
118         // - Otherwise it sometimes reports a full slot as empty
119         //   [TPG] (2011-02-19)
120         if( ret == 0 )
121         {
122                 Writef("d7\r\n");
123                 WaitForColon();
124         }
125
126         // TODO: Handle "not ok" response to D7
127         
128         #if TRACE_COKE
129         printf("Coke_CanDispense: sending 's%i'\n", Item);
130         #endif
131         
132         // Ask the coke machine
133         Writef("s%i\r\n", Item);
134
135         #if TRACE_COKE
136         printf("Coke_CanDispense: reading response\n");
137         #endif
138         // Read from the machine (ignoring empty lines)
139         while( (ret = ReadLine(sizeof(tmp)-1, tmp)) == 0 );
140         #if TRACE_COKE
141         printf("ret = %i, tmp = '%s'\n", ret, tmp);
142         #endif
143         // Read back-echoed lines
144         while( tmp[0] == ':' || tmp[1] != 'l' )
145         {
146                 ret = ReadLine(sizeof(tmp)-1, tmp);
147                 printf("ret = %i, tmp = '%s'\n", ret, tmp);
148         }
149
150         // Catch an error       
151         if( ret <= 0 ) {
152                 fprintf(stderr, "Coke machine is not being chatty (read = %i)\n", ret);
153                 if( ret == -1 ) {
154                         perror("Coke Machine");
155                 }
156                 return -1;
157         }
158         
159         #if TRACE_COKE
160         printf("Coke_CanDispense: wait for the prompt again\n");
161         #endif
162
163         // Eat rest of response
164         WaitForColon();
165
166         // Parse status response
167         ret = RunRegex(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
168         if( ret ) {
169                 return -1;
170         }
171
172         // Get slot status
173         tmp[ matches[3].rm_eo ] = '\0';
174         status = &tmp[ matches[3].rm_so ];
175         
176         #if TRACE_COKE
177         printf("Coke_CanDispense: Machine responded slot status '%s'\n", status);
178         #endif
179
180         if( strcmp(status, "full") == 0 )
181                 return 0;
182
183         return 1;
184 }
185
186 /**
187  * \brief Actually do a dispense from the coke machine
188  */
189 int Coke_DoDispense(int UNUSED(User), int Item)
190 {
191         char    tmp[32];
192          int    ret;
193
194         // Sanity please
195         if( Item < 0 || Item > 6 )      return -1;
196
197         // Can't dispense if the machine is not connected
198         if( giCoke_SerialFD == -1 )
199                 return -2;
200         
201         #if TRACE_COKE
202         printf("Coke_DoDispense: flushing input\n");
203         #endif
204         
205         // Wait for prompt
206         ret = 0;
207         while( WaitForColon() && ret < 3 )
208         {
209                 // Flush the input buffer
210                 char    tmpbuf[512];
211                 read(giCoke_SerialFD, tmpbuf, sizeof(tmpbuf));
212                 #if TRACE_COKE
213                 printf("Coke_DoDispense: sending 'd7'\n");
214                 #endif
215                 Writef("d7\r\n");
216         }
217
218         #if TRACE_COKE
219         printf("Coke_DoDispense: sending 'd%i'\n", Item);
220         #endif
221         // Dispense
222         Writef("d%i\r\n", Item);
223         
224         // Read empty lines and echo-backs
225         do {
226                 ret = ReadLine(sizeof(tmp)-1, tmp);
227                 if( ret == -1 ) return -1;
228                 #if TRACE_COKE
229                 printf("Coke_DoDispense: read %i '%s'\n", ret, tmp);
230                 #endif
231         } while( ret == 0 || tmp[0] == ':' || tmp[0] == 'd' );
232
233         WaitForColon(); // Eat up rest of response
234         
235         #if TRACE_COKE
236         printf("Coke_DoDispense: done\n");
237         #endif
238
239         // TODO: Regex
240         if( strcmp(tmp, "ok") == 0 ) {
241                 // We think dispense worked
242                 // - The machine returns 'ok' if an empty slot is dispensed, even if
243                 //   it doesn't actually try to dispense (no sound)
244                 return 0;
245         }
246
247         printf("Machine returned unknown value '%s'\n", tmp);   
248
249         return -1;
250 }
251
252 char ReadChar()
253 {
254         fd_set  readfs;
255         char    ch = 0;
256          int    ret;
257         struct timeval  timeout;
258         
259         timeout.tv_sec = READ_TIMEOUT;
260         timeout.tv_usec = 0;
261         
262         FD_ZERO(&readfs);
263         FD_SET(giCoke_SerialFD, &readfs);
264         
265         ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
266         if( ret == 0 )  return 0;       // Timeout
267         if( ret != 1 ) {
268                 printf("readchar return %i\n", ret);
269                 return 0;
270         }
271         
272         ret = read(giCoke_SerialFD, &ch, 1);
273         if( ret != 1 ) {
274                 printf("ret = %i\n", ret);
275                 return 0;
276         }
277         
278         return ch;
279 }
280
281 int Writef(const char *Format, ...)
282 {
283         va_list args;
284          int    len;
285         
286         va_start(args, Format);
287         len = vsnprintf(NULL, 0, Format, args);
288         va_end(args);
289         
290         {
291                 char    buf[len+1];
292                 va_start(args, Format);
293                 vsnprintf(buf, len+1, Format, args);
294                 va_end(args);
295                 
296                 #if DEBUG
297                 printf("Writef: %s", buf);
298                 #endif
299                 
300                 return write(giCoke_SerialFD, buf, len);
301         }
302         
303 }
304
305 int WaitForColon()
306 {
307         fd_set  readfs;
308         char    ch = 0;
309         
310         FD_SET(giCoke_SerialFD, &readfs);
311         
312         while( (ch = ReadChar()) != ':' && ch != 0);
313         
314         if( ch == 0 )   return -1;      // Timeout
315         
316         return 0;
317 }
318
319 int ReadLine(int len, char *output)
320 {
321         char    ch;
322          int    i = 0;
323         
324         for(;;)
325         {
326                 ch = ReadChar();
327                         
328                 if( i < len )
329                         output[i++] = ch;
330                 
331                 if( ch == '\0' ) {
332                         break;
333                 }
334                 if( ch == '\n' || ch == '\r' ) {
335                         if( i < len )
336                                 output[--i] = '\0';
337                         break;
338                 }
339         }
340
341         //printf("ReadLine: output=%s\n", output);
342
343         if( !ch )       return -1;
344         return i;
345 }
346
347

UCC git Repository :: git.ucc.asn.au