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

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