15cb8d3ab1c279db1ec12e9c634f83ba7774bad3
[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 #include <pthread.h>
22
23 #define READ_TIMEOUT    2       // 2 seconds for ReadChar
24 #define TRACE_COKE      0
25
26 #if TRACE_COKE
27 # define TRACE(v...) do{printf("%s: ",__func__);printf(v);}while(0)
28 #else
29 # define TRACE(...)
30 #endif
31
32 // === IMPORTS ===
33
34 // === PROTOTYPES ===
35  int    Coke_InitHandler();
36  int    Coke_int_GetSlotStatus(char *Buffer, int Slot);
37 void    Coke_int_UpdateSlotStatuses(void);
38  int    Coke_CanDispense(int User, int Item);
39  int    Coke_DoDispense(int User, int Item);
40  int    Writef(const char *Format, ...);
41  int    WaitForColon();
42  int    ReadLine(int len, char *output);
43
44 // === GLOBALS ===
45 tHandler        gCoke_Handler = {
46         "coke",
47         Coke_InitHandler,
48         Coke_CanDispense,
49         Coke_DoDispense
50 };
51 char    *gsCoke_SerialPort = "/dev/ttyS0";
52  int    giCoke_SerialFD;
53 regex_t gCoke_StatusRegex;
54  int    gaCoke_CachedStatus[7];
55 pthread_mutex_t gCoke_Mutex = PTHREAD_MUTEX_INITIALIZER;
56 time_t  gtCoke_LastDispenseTime;
57
58 // == CODE ===
59 int Coke_InitHandler()
60 {
61         CompileRegex(&gCoke_StatusRegex, "^slot\\s+([0-9]+)\\s+([^:]+):([a-zA-Z]+)\\s*", REG_EXTENDED);
62         
63         printf("Connecting to coke machine on '%s'\n", gsCoke_SerialPort);
64         
65         giCoke_SerialFD = InitSerial(gsCoke_SerialPort, 9600);
66         if( giCoke_SerialFD == -1 ) {
67                 fprintf(stderr, "ERROR: Unable to open coke serial port ('%s')\n", gsCoke_SerialPort);
68         }
69         else {
70                 int i;
71                 for( i = 0; i < 7; i ++ )
72                         gaCoke_CachedStatus[i] = -1;
73                 // Reset the slot names.
74                 // - Dunno why this is needed, but the machine plays silly
75                 //   sometimes.
76                 Writef("n0 Slot0\n");
77                 if( !WaitForColon() )
78                 {
79                         Writef("n1 Slot1\n");
80                         WaitForColon();
81                         Writef("n2 Slot2\n");
82                         WaitForColon();
83                         Writef("n3 Slot3\n");
84                         WaitForColon();
85                         Writef("n4 Slot4\n");
86                         WaitForColon();
87                         Writef("n5 Slot5\n");
88                         WaitForColon();
89                         Writef("n6 Coke\n");
90                         
91                         Coke_int_UpdateSlotStatuses();
92                 }
93                 else
94                         fprintf(stderr, "Coke machine timed out.\n");
95         }
96         
97         AddPeriodicFunction(Coke_int_UpdateSlotStatuses);
98         
99         return 0;
100 }
101
102 int Coke_int_GetSlotStatus(char *Buffer, int Slot)
103 {
104         regmatch_t      matches[4];
105          int    ret;
106         char    *status;        
107         
108         // Parse status response
109         ret = RunRegex(&gCoke_StatusRegex, Buffer, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
110         if( ret ) {
111                 return -1;
112         }
113
114         // Get slot status
115         Buffer[ matches[3].rm_eo ] = '\0';
116         status = &Buffer[ matches[3].rm_so ];
117         
118         TRACE("Machine responded slot %i status '%s'\n", Slot, status);
119
120         if( strcmp(status, "full") == 0 ) {
121                 gaCoke_CachedStatus[Slot] = 0;  // 0: Avaliiable
122                 return 0;
123         }
124         else {
125                 gaCoke_CachedStatus[Slot] = 1;  // 1: Empty
126                 return 1;
127         }
128 }
129
130 /**
131  * \brief Update the status of all coke slots
132  * \note Uses goto to reduce the chance of the lock being kept
133  */
134 void Coke_int_UpdateSlotStatuses(void)
135 {
136          int    i, len;
137         char    tmp[40];
138         
139         if( giCoke_SerialFD == -1 )     return ;
140         
141         pthread_mutex_lock(&gCoke_Mutex);
142         
143         while( ReadLine(sizeof tmp, tmp) >= 0 ) ;
144         TRACE("send d7\n");
145         Writef("d7\r\n");       // Update slot statuses
146         if( WaitForColon() )    goto ret;
147         TRACE("send s\n");
148         Writef("s\r\n");
149         do {
150                 i = ReadLine(sizeof tmp, tmp);  // Read back what we just said
151                 if( i == -1 ) {
152                         TRACE("Eat read failed");
153                         goto ret;
154                 }
155         } while(tmp[0] != ':' && tmp[1] != 's');
156         
157         for( i = 0; i <= 6; i ++ )
158         {
159                 // Read until non-blank line
160                 while( (len = ReadLine(sizeof tmp, tmp)) == 0 ) ;
161                 if( len == -1 ) {
162                         TRACE("Read failed on slot %i\n", i);
163                         goto ret;       // I give up :(
164                 }
165                 TRACE("tmp = '%s'\n", tmp);
166                 Coke_int_GetSlotStatus(tmp, i);
167         }
168         // Eat blank line
169         len = ReadLine(sizeof tmp, tmp);
170         if( len == -1 ) {
171                 TRACE("Read failed on blank line\n");
172         }
173
174         TRACE("Updated\n");
175
176 ret:
177         pthread_mutex_unlock(&gCoke_Mutex);
178 }
179
180 int Coke_CanDispense(int UNUSED(User), int Item)
181 {
182         // Sanity please
183         if( Item < 0 || Item > 6 )      return -1;      // -EYOURBAD
184         
185         // Can't dispense if the machine is not connected
186         if( giCoke_SerialFD == -1 )
187                 return -2;
188         
189         return gaCoke_CachedStatus[Item];
190 }
191
192 /**
193  * \brief Actually do a dispense from the coke machine
194  */
195 int Coke_DoDispense(int UNUSED(User), int Item)
196 {
197         char    tmp[32];
198          int    ret, len;
199
200         // Sanity please
201         if( Item < 0 || Item > 6 )      return -1;
202
203         // Can't dispense if the machine is not connected
204         if( giCoke_SerialFD == -1 )
205                 return -2;
206
207         // Make sure there are not two dispenses within n seconds
208         if( time(NULL) - gtCoke_LastDispenseTime < 10 )
209         {
210                 printf("Wait %li seconds?\n", 10 - (time(NULL) - gtCoke_LastDispenseTime));
211                 sleep( 10 - (time(NULL) - gtCoke_LastDispenseTime) );
212                 printf("wait done\n");
213         }
214         
215         // LOCK
216         pthread_mutex_lock(&gCoke_Mutex);
217         
218         TRACE("flushing input\n");
219         
220
221         // Wait for prompt
222         ret = 0;
223         while( WaitForColon() && ret < 3 )
224         {
225                 // Flush the input buffer
226                 char    tmpbuf[512];
227                 read(giCoke_SerialFD, tmpbuf, sizeof(tmpbuf));
228                 TRACE("sending 'd7'\n");
229                 Writef("d7\r\n");
230                 ret ++;
231         }
232         if( ret == 3 )
233         {
234                 TRACE("timed out\n");
235                 pthread_mutex_unlock(&gCoke_Mutex);
236                 return -1;
237         }
238
239         TRACE("sending 'd%i'\n", Item);
240         // Dispense
241         Writef("d%i\r\n", Item);
242         
243         // Read empty lines and echo-backs
244         do {
245                 ret = ReadLine(sizeof(tmp)-1, tmp);
246                 if( ret == -1 ) {
247                         pthread_mutex_unlock(&gCoke_Mutex);
248                         return -1;
249                 }
250                 TRACE("read %i '%s'\n", ret, tmp);
251         } while( ret == 0 || tmp[0] == ':' || tmp[0] == 'd' );
252
253         WaitForColon(); // Eat up rest of response
254         
255         TRACE("done\n");
256
257         // TODO: Regex instead?
258         if( strcmp(tmp, "ok") == 0 ) {
259                 // We think dispense worked
260                 // - The machine returns 'ok' if an empty slot is dispensed, even if
261                 //   it doesn't actually try to dispense (no sound)
262                 ret = 0;
263         }
264         else {
265                 printf("Coke_DoDispense: Machine returned unknown value '%s'\n", tmp);
266                 ret = -1;
267         }
268         
269         TRACE("Updating slot status\n");
270         
271         // Update status
272         WaitForColon();
273         Writef("s%i\r\n", Item);
274         len = ReadLine(sizeof tmp, tmp);
275         if(len == -1)   gaCoke_CachedStatus[Item] = -1;
276         Coke_int_GetSlotStatus(tmp, Item);
277         {
278                 char buf[512];
279                 read(giCoke_SerialFD, buf, 512);        // Flush
280         }
281
282         gtCoke_LastDispenseTime = time(NULL);
283         
284         // Release and return
285         pthread_mutex_unlock(&gCoke_Mutex);
286         
287         //return ret;
288         // HACK!!!
289         return 0;
290 }
291
292 char ReadChar()
293 {
294         fd_set  readfs;
295         char    ch = 0;
296          int    ret;
297         struct timeval  timeout;
298         
299         timeout.tv_sec = READ_TIMEOUT;
300         timeout.tv_usec = 0;
301         
302         FD_ZERO(&readfs);
303         FD_SET(giCoke_SerialFD, &readfs);
304         
305         ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
306         if( ret == 0 )  return 0;       // Timeout
307         if( ret != 1 ) {
308                 printf("ReadChar: select return %i\n", ret);
309                 return 0;
310         }
311         
312         ret = read(giCoke_SerialFD, &ch, 1);
313         if( ret != 1 ) {
314                 printf("ReadChar: ret != 1 (%i)\n", ret);
315                 return 0;
316         }
317         
318         return ch;
319 }
320
321 int Writef(const char *Format, ...)
322 {
323         va_list args;
324          int    len;
325         
326         va_start(args, Format);
327         len = vsnprintf(NULL, 0, Format, args);
328         va_end(args);
329         
330         {
331                 char    buf[len+1];
332                 va_start(args, Format);
333                 vsnprintf(buf, len+1, Format, args);
334                 va_end(args);
335                 
336                 #if DEBUG
337                 printf("Writef: %s", buf);
338                 #endif
339                 
340                 return write(giCoke_SerialFD, buf, len);
341         }
342         
343 }
344
345 int WaitForColon()
346 {
347         fd_set  readfs;
348         char    ch = 0;
349         
350         FD_SET(giCoke_SerialFD, &readfs);
351         
352         while( (ch = ReadChar()) != ':' && ch != 0);
353         
354         if( ch == 0 )   return -1;      // Timeout
355         
356         return 0;
357 }
358
359 int ReadLine(int len, char *output)
360 {
361         char    ch;
362          int    i = 0;
363         
364         for(;;)
365         {
366                 ch = ReadChar();
367                         
368                 if( i < len )
369                         output[i++] = ch;
370                 
371                 if( ch == '\0' ) {
372                         break;
373                 }
374                 if( ch == '\n' || ch == '\r' ) {
375                         if( i < len )
376                                 output[--i] = '\0';
377                         break;
378                 }
379         }
380
381         if( !ch )       return -1;
382         return i;
383 }
384
385

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