Server/Coke - Improved logging
[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 <stdbool.h>
13 #include <string.h>
14 #include <signal.h>
15 #include "common.h"
16 #include <termios.h>
17 #include <unistd.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <stdarg.h>
21 #include <syslog.h>
22 #include <pthread.h>
23 #include "../cokebank.h"
24 #include "../common/config.h"
25
26 // === IMPORTS ===
27 extern void     Init_Handlers(void);
28 extern void     Load_Itemlist(void);
29 extern void     Server_Start(void);
30 extern bool     gbServer_RunInBackground;
31 extern int      giServer_Port;
32 extern const char       *gsItemListFile;
33 extern const char       *gsCoke_ModbusAddress;
34 extern int      giCoke_ModbusPort;
35 extern const char       *gsDoor_SerialPort;
36
37 // === PROTOTYPES ===
38 void    *Periodic_Thread(void *Unused);
39
40 // === GLOBALS ===
41  int    giDebugLevel = 0;
42 bool    gbNoCostMode = 0;
43 const char      *gsCokebankPath = "cokebank.db";
44 // - Functions called every 20s (or so)
45 #define ciMaxPeriodics  10
46 struct sPeriodicCall {
47         void    (*Function)(void);
48 }       gaPeriodicCalls[ciMaxPeriodics];
49 pthread_t       gTimerThread;
50
51 // === CODE ===
52 void sigint_handler()
53 {
54         exit(0);
55 }
56
57 void PrintUsage(const char *progname)
58 {
59         fprintf(stderr, "Usage: %s\n", progname);
60         fprintf(stderr, "  -f,--configfile\n");
61         fprintf(stderr, "        Set the config file path (default `dispsrv.conf')\n");
62         fprintf(stderr, "  -d    Set debug level (0 - 2, default 0)\n");
63         fprintf(stderr, "  --[dont-]daemonise\n");
64         fprintf(stderr, "        Run (or explicitly don't run) the server disconnected from the terminal\n");
65 }
66
67 int main(int argc, char *argv[])
68 {
69          int    i;
70         const char      *config_file = "dispsrv.conf";
71
72         // Parse Arguments
73         for( i = 1; i < argc; i++ )
74         {
75                 char    *arg = argv[i];
76                 if( arg[0] != '-' )
77                 {
78                         // No free arguments please
79                         PrintUsage(argv[0]);
80                         return -1;
81                 }
82                 else if( arg[1] != '-' )
83                 {
84                         // Single character arguments
85                         // - TODO: Process in a loop
86                         switch(arg[1])
87                         {
88                         case 'f':
89                                 if( i + 1 >= argc )     return -1;
90                                 config_file = argv[++i];
91                                 break;
92                         case 'd':
93                                 if( i + 1 >= argc )     return -1;
94                                 Config_AddValue("debug_level", argv[++i]);
95                                 giDebugLevel = atoi(argv[i]);
96                                 break;
97                         default:
98                                 // Usage Error
99                                 fprintf(stderr, "Unknown option '-%c'\n", arg[1]);
100                                 PrintUsage(argv[0]);
101                                 return -1;
102                         }
103                 }
104                 else
105                 {
106                         // Long arguments
107                         if( strcmp(arg, "--configfile") == 0 ) {
108                                 if( i + 1 >= argc )     return -1;
109                                 config_file = argv[++i];
110                         }
111                         else if( strcmp(arg, "--daemonise") == 0 ) {
112                                 Config_AddValue("daemonise", "true");
113                         }
114                         else if( strcmp(arg, "--dont-daemonise") == 0 ) {
115                                 Config_AddValue("daemonise", "false");
116                         }
117                         else {
118                                 // Usage error
119                                 fprintf(stderr, "Unknown option '%s'\n", arg);
120                                 PrintUsage(argv[0]);
121                                 return -1;
122                         }
123                 }
124         }
125
126         if( Config_ParseFile( config_file ) ) {
127                 fprintf(stderr, "NOTICE: Loading of config file '%s' failed, using defaults\n", config_file);
128         }
129
130         // Parse config values
131         {
132                 bool rv = true;
133                 #define REQ_CFG(variable, type, name)   rv = Config_GetValue_##type(name, &variable) && rv
134                 #define OPT_CFG(variable, type, name)        Config_GetValue_##type(name, &variable)
135                 OPT_CFG(gbServer_RunInBackground, Bool, "daemonise");
136                 OPT_CFG(giServer_Port, Int, "server_port");
137                 
138                 REQ_CFG(gsCokebankPath, Str, "cokebank_database");
139                 REQ_CFG(gsItemListFile, Str, "items_file");
140
141                 OPT_CFG(gsDoor_SerialPort, Str, "door_serial_port");
142                 REQ_CFG(gsCoke_ModbusAddress, Str, "coke_modbus_address");
143                 OPT_CFG(giCoke_ModbusPort,    Int,    "coke_modbus_port");
144                 
145                 OPT_CFG(gbNoCostMode,    Bool, "test_mode");
146                 OPT_CFG(gbSyslogDisabled, Bool, "disable_syslog");
147                 
148                 if( !rv ) {
149                         fprintf(stderr, "ERROR: Some required configuration items were missing\n");
150                         return -1;
151                 }
152         }
153
154         // - Cleanly tear down the server on SIGINT/SIGTERM
155         signal(SIGINT, sigint_handler);
156         signal(SIGTERM, sigint_handler);
157         // - ignore SIGPIPE to prevent a crashing client from bringing the server down too
158         signal(SIGPIPE, SIG_IGN);
159         
160         openlog("odispense2", 0, LOG_LOCAL4);
161         
162         if( Bank_Initialise(gsCokebankPath) )
163                 return -1;
164
165         Init_Handlers();
166
167         Load_Itemlist();
168         
169         Server_Start();
170         
171         if(gTimerThread)
172                 pthread_kill(gTimerThread, SIGKILL);
173
174         return 0;
175 }
176
177 void *Periodic_Thread(void *Unused __attribute__((unused)))
178 {
179          int    i;
180         
181         for( ;; )
182         {
183                 sleep(10);      // Sleep for a while
184 //              printf("Periodic firing\n");
185                 for( i = 0; i < ciMaxPeriodics; i ++ )
186                 {
187                         if( gaPeriodicCalls[i].Function )
188                                 gaPeriodicCalls[i].Function();
189                 }
190         }
191         return NULL;
192 }
193
194 void StartPeriodicThread(void)
195 {
196         pthread_create( &gTimerThread, NULL, Periodic_Thread, NULL );
197 }
198
199 void AddPeriodicFunction(void (*Fcn)(void))
200 {
201         int i;
202         for( i = 0; i < ciMaxPeriodics; i ++ )
203         {
204                 if( gaPeriodicCalls[i].Function )       continue;
205                 gaPeriodicCalls[i].Function = Fcn;
206                 return ;
207         }
208         
209         fprintf(stderr, "Error: No space for %p in periodic list\n", Fcn);
210 }
211
212 // Serial helper
213 int InitSerial(const char *File, int BaudRate)
214 {
215         struct termios  info;
216          int    baud;
217          int    fd;
218         
219         fd = open(File, O_RDWR | O_NOCTTY | O_NONBLOCK);
220         if( fd == -1 )  return -1;
221         
222         switch(BaudRate)
223         {
224         case 1200:      baud = B1200;   break;
225         case 9600:      baud = B9600;   break;
226         case 115200:    baud = B115200; break;
227         default:
228                 fprintf(stderr, "ERROR: Invalid baud rate to InitSerial (%i)\n", BaudRate);
229                 exit(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