Cleaning up a little
[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         }
200
201         #if TRACE_COKE
202         printf("Coke_DoDispense: sending 'd%i'\n", Item);
203         #endif
204         // Dispense
205         Writef("d%i\r\n", Item);
206         
207         // Read empty lines and echo-backs
208         do {
209                 ret = ReadLine(sizeof(tmp)-1, tmp);
210                 if( ret == -1 ) {
211                         pthread_mutex_unlock(&gCoke_Mutex);
212                         return -1;
213                 }
214                 #if TRACE_COKE
215                 printf("Coke_DoDispense: read %i '%s'\n", ret, tmp);
216                 #endif
217         } while( ret == 0 || tmp[0] == ':' || tmp[0] == 'd' );
218
219         WaitForColon(); // Eat up rest of response
220         
221         #if TRACE_COKE
222         printf("Coke_DoDispense: done\n");
223         #endif
224
225         // TODO: Regex instead?
226         if( strcmp(tmp, "ok") == 0 ) {
227                 // We think dispense worked
228                 // - The machine returns 'ok' if an empty slot is dispensed, even if
229                 //   it doesn't actually try to dispense (no sound)
230                 ret = 0;
231         }
232         else {
233                 printf("Coke_DoDispense: Machine returned unknown value '%s'\n", tmp);
234                 ret = -1;
235         }
236         
237         #if TRACE_COKE
238         printf("Coke_DoDispense: Updating slot status\n");
239         #endif
240         // Update status
241         Writef("s%i\r\n", Item);
242         len = ReadLine(sizeof tmp, tmp);
243         if(len == -1)   gaCoke_CachedStatus[Item] = -1;
244         Coke_int_GetSlotStatus(tmp, Item);
245         
246         // Release and return
247         pthread_mutex_unlock(&gCoke_Mutex);
248         
249         return ret;
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