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

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