f2f66c38667256f827d17476818036e600ce2a31
[tpg/opendispense2.git] / src / server / main.c
1 /*
2  * OpenDispense 2 
3  * UCC (University [of WA] Computer Club) Electronic Accounting System
4  *
5  * main.c - Initialisation Code
6  *
7  * This file is licenced under the 3-clause BSD Licence. See the file
8  * COPYING for full details.
9  */
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <signal.h>
14 #include "common.h"
15 #include <termios.h>
16 #include <unistd.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <stdarg.h>
20 #include <syslog.h>
21 #include <pthread.h>
22 #include "../cokebank.h"
23
24 // === IMPORTS ===
25 extern void     Init_Handlers(void);
26 extern void     Load_Itemlist(void);
27 extern void     Server_Start(void);
28 extern int      gbServer_RunInBackground;
29 extern int      giServer_Port;
30 extern const char       *gsItemListFile;
31 extern const char       *gsCoke_ModbusAddress;
32 extern const char       *gsDoor_SerialPort;
33
34 // === PROTOTYPES ===
35 void    *Periodic_Thread(void *Unused);
36
37 // === GLOBALS ===
38  int    giDebugLevel = 0;
39  int    gbNoCostMode = 0;
40 const char      *gsCokebankPath = "cokebank.db";
41 // - Functions called every 20s (or so)
42 #define ciMaxPeriodics  10
43 struct sPeriodicCall {
44         void    (*Function)(void);
45 }       gaPeriodicCalls[ciMaxPeriodics];
46 pthread_t       gTimerThread;
47
48 // === CODE ===
49 void sigint_handler()
50 {
51         exit(0);
52 }
53
54 void PrintUsage(const char *progname)
55 {
56         fprintf(stderr, "Usage: %s\n", progname);
57         fprintf(stderr, "  -d    Set debug level (0 - 2, default 0)\n");
58         fprintf(stderr, "  --[dont-]daemonise\n");
59         fprintf(stderr, "        Run (or explicitly don't run) the server disconnected from the terminal\n");
60 }
61
62 int main(int argc, char *argv[])
63 {
64          int    i;
65         const char      *config_file = "dispsrv.conf";
66
67         // Parse Arguments
68         for( i = 1; i < argc; i++ )
69         {
70                 char    *arg = argv[i];
71                 if( arg[0] == '-' && arg[1] != '-')
72                 {
73                         switch(arg[1])
74                         {
75                         case 'f':
76                                 if( i + 1 >= argc )     return -1;
77                                 config_file = argv[++i];
78                                 break;
79                         case 'd':
80                                 if( i + 1 >= argc )     return -1;
81                                 Config_AddValue("debug_level", argv[++i]);
82                                 giDebugLevel = atoi(argv[i]);
83                                 break;
84                         default:
85                                 // Usage Error
86                                 PrintUsage(argv[0]);
87                                 return -1;
88                         }
89                 }
90                 else if( arg[0] == '-' && arg[1] == '-' )
91                 {
92                         if( strcmp(arg, "--configfile") == 0 ) {
93                                 if( i + 1 >= argc )     return -1;
94                                 config_file = argv[++i];
95                         }
96                         else if( strcmp(arg, "--daemonise") == 0 ) {
97                                 Config_AddValue("daemonise", "true");
98                         }
99                         else if( strcmp(arg, "--dont-daemonise") == 0 ) {
100                                 Config_AddValue("daemonise", "false");
101                         }
102                         else {
103                                 // Usage error
104                                 PrintUsage(argv[0]);
105                                 return -1;
106                         }
107                 }
108                 else
109                 {
110                         // Usage Error
111                         PrintUsage(argv[0]);
112                         return -1;
113                 }
114         }
115
116         Config_ParseFile( config_file );
117
118         // Parse config values
119         gbServer_RunInBackground = Config_GetValue_Bool("daemonise", 0);
120         gsCokebankPath       = Config_GetValue("cokebank_database", 0);
121         gsDoor_SerialPort    = Config_GetValue("door_serial_port", 0);
122         gsCoke_ModbusAddress = Config_GetValue("coke_modbus_address", 0);
123         giServer_Port        = Config_GetValue_Int("server_port", 0);
124         gsItemListFile       = Config_GetValue("items_file", 0);
125
126         gbNoCostMode         = Config_GetValue_Bool("test_mode", 0);
127
128         signal(SIGINT, sigint_handler);
129         signal(SIGTERM, sigint_handler);
130         
131         openlog("odispense2", 0, LOG_LOCAL4);
132         
133         if( Bank_Initialise(gsCokebankPath) )
134                 return -1;
135
136         Init_Handlers();
137
138         Load_Itemlist();
139         
140         Server_Start();
141         
142         if(gTimerThread)
143                 pthread_kill(gTimerThread, SIGKILL);
144
145         return 0;
146 }
147
148 void *Periodic_Thread(void *Unused __attribute__((unused)))
149 {
150          int    i;
151         
152         for( ;; )
153         {
154                 sleep(10);      // Sleep for a while
155 //              printf("Periodic firing\n");
156                 for( i = 0; i < ciMaxPeriodics; i ++ )
157                 {
158                         if( gaPeriodicCalls[i].Function )
159                                 gaPeriodicCalls[i].Function();
160                 }
161         }
162         return NULL;
163 }
164
165 void StartPeriodicThread(void)
166 {
167         pthread_create( &gTimerThread, NULL, Periodic_Thread, NULL );
168 }
169
170 void AddPeriodicFunction(void (*Fcn)(void))
171 {
172         int i;
173         for( i = 0; i < ciMaxPeriodics; i ++ )
174         {
175                 if( gaPeriodicCalls[i].Function )       continue;
176                 gaPeriodicCalls[i].Function = Fcn;
177                 return ;
178         }
179         
180         fprintf(stderr, "Error: No space for %p in periodic list\n", Fcn);
181 }
182
183 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
184 {
185          int    ret;
186         
187         ret = regexec(regex, string, nMatches, matches, 0);
188         if( ret == REG_NOMATCH ) {
189                 return -1;
190         }
191         if( ret ) {
192                 size_t  len = regerror(ret, regex, NULL, 0);
193                 char    errorStr[len];
194                 regerror(ret, regex, errorStr, len);
195                 printf("string = '%s'\n", string);
196                 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
197                 exit(-1);
198         }
199         
200         return ret;
201 }
202
203 void CompileRegex(regex_t *regex, const char *pattern, int flags)
204 {
205          int    ret = regcomp(regex, pattern, flags);
206         if( ret ) {
207                 size_t  len = regerror(ret, regex, NULL, 0);
208                 char    errorStr[len];
209                 regerror(ret, regex, errorStr, len);
210                 fprintf(stderr, "Regex compilation failed - %s\n%s\n", errorStr, pattern);
211                 exit(-1);
212         }
213 }
214
215 // Serial helper
216 int InitSerial(const char *File, int BaudRate)
217 {
218         struct termios  info;
219          int    baud;
220          int    fd;
221         
222         fd = open(File, O_RDWR | O_NOCTTY | O_NONBLOCK);
223         if( fd == -1 )  return -1;
224         
225         switch(BaudRate)
226         {
227         case 1200:      baud = B1200;   break;
228         case 9600:      baud = B9600;   break;
229         default:        close(fd);      return -1;
230         }
231         
232         info.c_lflag = 0;       // Non-Canoical, No Echo
233         info.c_cflag = baud | CS8 | CLOCAL | CREAD;     // baud, 8N1
234         info.c_iflag = IGNCR;   // Ignore \r
235         info.c_oflag = 0;       // ???
236         cfsetspeed(&info, baud);
237         info.c_cc[VTIME] = 0;   // No time limit
238         info.c_cc[VMIN] = 1;    // Block until 1 char
239         
240         tcflush(fd, TCIFLUSH);
241         tcsetattr(fd, TCSANOW, &info);
242         
243         return fd;
244 }
245
246
247 /**
248  * \brief Create a formatted heap string
249  */
250 char *mkstr(const char *Format, ...)
251 {
252         va_list args;
253          int    len;
254         char    *ret;
255
256         va_start(args, Format);
257         len = vsnprintf(NULL, 0, Format, args);
258         va_end(args);
259
260         ret = malloc( len + 1 );
261         if(!ret)        return NULL;
262
263         va_start(args, Format);
264         vsprintf(ret, Format, args);
265         va_end(args);
266         
267         return ret;
268 }
269

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