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

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