Fixed coke handler regex, added init for handlers
[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 #include "common.h"
11 #include <stdio.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <sys/stat.h>
15 #include <fcntl.h>
16 #include <regex.h>
17
18 // === IMPORTS ===
19
20 // === PROTOTYPES ===
21  int    Coke_InitHandler();
22  int    Coke_CanDispense(int User, int Item);
23  int    Coke_DoDispense(int User, int Item);
24
25 // === GLOBALS ===
26 tHandler        gCoke_Handler = {
27         "coke",
28         Coke_InitHandler,
29         Coke_CanDispense,
30         Coke_DoDispense
31 };
32 char    *gsCoke_SerialPort = "/dev/ttyS0";
33  int    giCoke_SerialFD;
34 regex_t gCoke_StatusRegex;
35
36 // == CODE ===
37 int Coke_InitHandler()
38 {
39         giCoke_SerialFD = open(gsCoke_SerialPort, O_RDWR);
40         regcomp(&gCoke_StatusRegex, "^slot\\s+(\\d)\\s+([^:]+):([a-zA-Z]+)\\s*", REG_EXTENDED);
41         return 0;
42 }
43
44 int Coke_CanDispense(int User, int Item)
45 {
46         char    tmp[32], *status;
47         regmatch_t      matches[4];
48
49         // Sanity please
50         if( Item < 0 || Item > 6 )      return -1;
51         
52         // Ask the coke machine
53         sprintf(tmp, "s%i\n", Item);
54         write(giCoke_SerialFD, tmp, 2);
55
56         // Read the response
57         read(giCoke_SerialFD, tmp, sizeof(tmp)-1);
58         regexec(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, 0);
59
60         tmp[ matches[3].rm_eo ] = '\0';
61         status = &tmp[ matches[3].rm_so ];
62
63         printf("Machine responded slot status '%s'\n", status);
64
65         if( strcmp(status, "full") == 0 )
66                 return 1;
67
68         return 0;
69 }
70
71 /**
72  * \brief Actually do a dispense from the coke machine
73  */
74 int Coke_DoDispense(int User, int Item)
75 {
76         char    tmp[32], *status;
77         regmatch_t      matches[4];
78
79         // Sanity please
80         if( Item < 0 || Item > 6 )      return -1;
81
82         // Dispense
83         sprintf(tmp, "d%i\n", Item);
84         write(giCoke_SerialFD, tmp, 2);
85
86         // Get status
87         read(giCoke_SerialFD, tmp, sizeof(tmp)-1);
88         regexec(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, 0);
89         
90         tmp[ matches[3].rm_eo ] = '\0';
91         status = &tmp[ matches[3].rm_so ];
92
93         printf("Machine responded slot status '%s'\n", status);
94
95         return 0;
96 }
97
98

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