Fixing serial handling
[tpg/opendispense2.git] / src / server / handler_snack.c
1 /*
2  * OpenDispense 2 
3  * UCC (University [of WA] Computer Club) Electronic Accounting System
4  * - Dispense Server
5  *
6  * handler_snack.c - Snack machine code
7  *
8  * This file is licenced under the 3-clause BSD Licence. See the file
9  * COPYING for full details.
10  */
11 #include "common.h"
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <sys/stat.h>
16 #include <fcntl.h>
17 #include <regex.h>
18
19 // === IMPORTS ===
20
21 // === PROTOTYPES ===
22  int    Snack_InitHandler();
23  int    Snack_CanDispense(int User, int Item);
24  int    Snack_DoDispense(int User, int Item);
25
26 // === GLOBALS ===
27 tHandler        gSnack_Handler = {
28         "snack",
29         Snack_InitHandler,
30         Snack_CanDispense,
31         Snack_DoDispense
32 };
33 char    *gsSnack_SerialPort = "/dev/ttyS1";
34  int    giSnack_SerialFD;
35 regex_t gSnack_ResponseRegex;
36
37 // == CODE ===
38 int Snack_InitHandler()
39 {
40         giSnack_SerialFD = open(gsSnack_SerialPort, O_RDWR | O_NOCTTY | O_NONBLOCK);
41         if( giSnack_SerialFD == -1 ) {
42                 fprintf(stderr, "ERROR: Unable to open snack serial port ('%s')\n", gsSnack_SerialPort);
43         }
44         
45         InitSerial(giSnack_SerialFD, 9600);
46         
47         regcomp(&gSnack_ResponseRegex, "^(\\d\\d\\d)(.*)$", REG_EXTENDED);
48         return 0;
49 }
50
51 int Snack_CanDispense(int User, int Item)
52 {
53         // Sanity please
54         if( Item < 0 || Item > 99 )     return -1;
55         
56         // Hmm... could we implement slot statuses?
57         
58         return 0;
59 }
60
61 /**
62  * \brief Actually do a dispense from the coke machine
63  */
64 int Snack_DoDispense(int User, int Item)
65 {
66         char    tmp[32];
67         regmatch_t      matches[4];
68
69         // Sanity please
70         if( Item < 0 || Item > 99 )     return -1;
71
72         // Dispense
73         sprintf(tmp, "V%02i\n", Item);
74         write(giSnack_SerialFD, tmp, 2);
75
76         // Get status
77         read(giSnack_SerialFD, tmp, sizeof(tmp)-1);
78         regexec(&gSnack_ResponseRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, 0);
79
80         return 0;
81 }

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