4eb371000f6ed277a296cdba77a9f770256e3258
[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         Writef("d7\r\n");       // Update slot statuses
134         if( WaitForColon() )    goto ret;
135         Writef("s\n");
136         ReadLine(sizeof tmp, tmp);      // Read back what we just said
137         
138         for( i = 0; i <= 6; i ++ )
139         {
140                 len = ReadLine(sizeof tmp, tmp);
141                 if( len == -1 ) {
142                         #if TRACE_COKE
143                         printf("Coke_int_UpdateSlotStatuses: Read failed on slot %i\n", i);
144                         #endif
145                         goto ret;       // I give up :(
146                 }
147                 Coke_int_GetSlotStatus(tmp, i);
148         }
149
150 ret:
151         pthread_mutex_unlock(&gCoke_Mutex);
152 }
153
154 int Coke_CanDispense(int UNUSED(User), int Item)
155 {
156         // Sanity please
157         if( Item < 0 || Item > 6 )      return -1;      // -EYOURBAD
158         
159         // Can't dispense if the machine is not connected
160         if( giCoke_SerialFD == -1 )
161                 return -2;
162         
163         return gaCoke_CachedStatus[Item];
164 }
165
166 /**
167  * \brief Actually do a dispense from the coke machine
168  */
169 int Coke_DoDispense(int UNUSED(User), int Item)
170 {
171         char    tmp[32];
172          int    ret, len;
173
174         // Sanity please
175         if( Item < 0 || Item > 6 )      return -1;
176
177         // Can't dispense if the machine is not connected
178         if( giCoke_SerialFD == -1 )
179                 return -2;
180         
181         // LOCK
182         pthread_mutex_lock(&gCoke_Mutex);
183         
184         #if TRACE_COKE
185         printf("Coke_DoDispense: flushing input\n");
186         #endif
187         
188         // Wait for prompt
189         ret = 0;
190         while( WaitForColon() && ret < 3 )
191         {
192                 // Flush the input buffer
193                 char    tmpbuf[512];
194                 read(giCoke_SerialFD, tmpbuf, sizeof(tmpbuf));
195                 #if TRACE_COKE
196                 printf("Coke_DoDispense: sending 'd7'\n");
197                 #endif
198                 Writef("d7\r\n");
199                 ret ++;
200         }
201         if( ret == 3 )
202         {
203                 #if TRACE_COKE
204                 printf("Coke_DoDispense: timed out\n");
205                 #endif
206                 pthread_mutex_unlock(&gCoke_Mutex);
207                 return -1;
208         }
209
210         #if TRACE_COKE
211         printf("Coke_DoDispense: sending 'd%i'\n", Item);
212         #endif
213         // Dispense
214         Writef("d%i\r\n", Item);
215         
216         // Read empty lines and echo-backs
217         do {
218                 ret = ReadLine(sizeof(tmp)-1, tmp);
219                 if( ret == -1 ) {
220                         pthread_mutex_unlock(&gCoke_Mutex);
221                         return -1;
222                 }
223                 #if TRACE_COKE
224                 printf("Coke_DoDispense: read %i '%s'\n", ret, tmp);
225                 #endif
226         } while( ret == 0 || tmp[0] == ':' || tmp[0] == 'd' );
227
228         WaitForColon(); // Eat up rest of response
229         
230         #if TRACE_COKE
231         printf("Coke_DoDispense: done\n");
232         #endif
233
234         // TODO: Regex instead?
235         if( strcmp(tmp, "ok") == 0 ) {
236                 // We think dispense worked
237                 // - The machine returns 'ok' if an empty slot is dispensed, even if
238                 //   it doesn't actually try to dispense (no sound)
239                 ret = 0;
240         }
241         else {
242                 printf("Coke_DoDispense: Machine returned unknown value '%s'\n", tmp);
243                 ret = -1;
244         }
245         
246         #if TRACE_COKE
247         printf("Coke_DoDispense: Updating slot status\n");
248         #endif
249         // Update status
250         Writef("s%i\r\n", Item);
251         len = ReadLine(sizeof tmp, tmp);
252         if(len == -1)   gaCoke_CachedStatus[Item] = -1;
253         Coke_int_GetSlotStatus(tmp, Item);
254         
255         // Release and return
256         pthread_mutex_unlock(&gCoke_Mutex);
257         
258         return ret;
259 }
260
261 char ReadChar()
262 {
263         fd_set  readfs;
264         char    ch = 0;
265          int    ret;
266         struct timeval  timeout;
267         
268         timeout.tv_sec = READ_TIMEOUT;
269         timeout.tv_usec = 0;
270         
271         FD_ZERO(&readfs);
272         FD_SET(giCoke_SerialFD, &readfs);
273         
274         ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
275         if( ret == 0 )  return 0;       // Timeout
276         if( ret != 1 ) {
277                 printf("readchar return %i\n", ret);
278                 return 0;
279         }
280         
281         ret = read(giCoke_SerialFD, &ch, 1);
282         if( ret != 1 ) {
283                 printf("ret = %i\n", ret);
284                 return 0;
285         }
286         
287         return ch;
288 }
289
290 int Writef(const char *Format, ...)
291 {
292         va_list args;
293          int    len;
294         
295         va_start(args, Format);
296         len = vsnprintf(NULL, 0, Format, args);
297         va_end(args);
298         
299         {
300                 char    buf[len+1];
301                 va_start(args, Format);
302                 vsnprintf(buf, len+1, Format, args);
303                 va_end(args);
304                 
305                 #if DEBUG
306                 printf("Writef: %s", buf);
307                 #endif
308                 
309                 return write(giCoke_SerialFD, buf, len);
310         }
311         
312 }
313
314 int WaitForColon()
315 {
316         fd_set  readfs;
317         char    ch = 0;
318         
319         FD_SET(giCoke_SerialFD, &readfs);
320         
321         while( (ch = ReadChar()) != ':' && ch != 0);
322         
323         if( ch == 0 )   return -1;      // Timeout
324         
325         return 0;
326 }
327
328 int ReadLine(int len, char *output)
329 {
330         char    ch;
331          int    i = 0;
332         
333         for(;;)
334         {
335                 ch = ReadChar();
336                         
337                 if( i < len )
338                         output[i++] = ch;
339                 
340                 if( ch == '\0' ) {
341                         break;
342                 }
343                 if( ch == '\n' || ch == '\r' ) {
344                         if( i < len )
345                                 output[--i] = '\0';
346                         break;
347                 }
348         }
349
350         //printf("ReadLine: output=%s\n", output);
351
352         if( !ch )       return -1;
353         return i;
354 }
355
356

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