3e0623000db18462479ebcd8fa1f79b4fc1f451e
[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 extern bool     gbSyslogEnabled;
37
38 // === PROTOTYPES ===
39 void    *Periodic_Thread(void *Unused);
40
41 // === GLOBALS ===
42  int    giDebugLevel = 0;
43 bool    gbNoCostMode = 0;
44 const char      *gsCokebankPath = "cokebank.db";
45 // - Functions called every 20s (or so)
46 #define ciMaxPeriodics  10
47 struct sPeriodicCall {
48         void    (*Function)(void);
49 }       gaPeriodicCalls[ciMaxPeriodics];
50 pthread_t       gTimerThread;
51
52 // === CODE ===
53 void sigint_handler()
54 {
55         exit(0);
56 }
57
58 void PrintUsage(const char *progname)
59 {
60         fprintf(stderr, "Usage: %s\n", progname);
61         fprintf(stderr, "  -f,--configfile\n");
62         fprintf(stderr, "        Set the config file path (default `dispsrv.conf')\n");
63         fprintf(stderr, "  -d    Set debug level (0 - 2, default 0)\n");
64         fprintf(stderr, "  --[dont-]daemonise\n");
65         fprintf(stderr, "        Run (or explicitly don't run) the server disconnected from the terminal\n");
66 }
67
68 int main(int argc, char *argv[])
69 {
70          int    i;
71         const char      *config_file = "dispsrv.conf";
72
73         // Parse Arguments
74         for( i = 1; i < argc; i++ )
75         {
76                 char    *arg = argv[i];
77                 if( arg[0] != '-' )
78                 {
79                         // No free arguments please
80                         PrintUsage(argv[0]);
81                         return -1;
82                 }
83                 else if( arg[1] != '-' )
84                 {
85                         // Single character arguments
86                         // - TODO: Process in a loop
87                         switch(arg[1])
88                         {
89                         case 'f':
90                                 if( i + 1 >= argc )     return -1;
91                                 config_file = argv[++i];
92                                 break;
93                         case 'd':
94                                 if( i + 1 >= argc )     return -1;
95                                 Config_AddValue("debug_level", argv[++i]);
96                                 giDebugLevel = atoi(argv[i]);
97                                 break;
98                         default:
99                                 // Usage Error
100                                 fprintf(stderr, "Unknown option '-%c'\n", arg[1]);
101                                 PrintUsage(argv[0]);
102                                 return -1;
103                         }
104                 }
105                 else
106                 {
107                         // Long arguments
108                         if( strcmp(arg, "--configfile") == 0 ) {
109                                 if( i + 1 >= argc )     return -1;
110                                 config_file = argv[++i];
111                         }
112                         else if( strcmp(arg, "--daemonise") == 0 ) {
113                                 Config_AddValue("daemonise", "true");
114                         }
115                         else if( strcmp(arg, "--dont-daemonise") == 0 ) {
116                                 Config_AddValue("daemonise", "false");
117                         }
118                         else {
119                                 // Usage error
120                                 fprintf(stderr, "Unknown option '%s'\n", arg);
121                                 PrintUsage(argv[0]);
122                                 return -1;
123                         }
124                 }
125         }
126
127         if( Config_ParseFile( config_file ) ) {
128                 fprintf(stderr, "NOTICE: Loading of config file '%s' failed, using defaults\n", config_file);
129         }
130
131         // Parse config values
132         {
133                 bool rv = true;
134                 #define REQ_CFG(variable, type, name)   rv = Config_GetValue_##type(name, &variable) && rv
135                 #define OPT_CFG(variable, type, name)        Config_GetValue_##type(name, &variable)
136                 OPT_CFG(gbServer_RunInBackground, Bool, "daemonise");
137                 OPT_CFG(giServer_Port, Int, "server_port");
138                 
139                 REQ_CFG(gsCokebankPath, Str, "cokebank_database");
140                 REQ_CFG(gsItemListFile, Str, "items_file");
141
142                 OPT_CFG(gsDoor_SerialPort, Str, "door_serial_port");
143                 REQ_CFG(gsCoke_ModbusAddress, Str, "coke_modbus_address");
144                 OPT_CFG(giCoke_ModbusPort,    Int,    "coke_modbus_port");
145                 
146                 OPT_CFG(gbNoCostMode,    Bool, "test_mode");
147                 OPT_CFG(gbSyslogEnabled, Bool, "disable_syslog");
148                 
149                 if( !rv ) {
150                         fprintf(stderr, "ERROR: Some required configuration items were missing\n");
151                         return -1;
152                 }
153         }
154
155         // - Cleanly tear down the server on SIGINT/SIGTERM
156         signal(SIGINT, sigint_handler);
157         signal(SIGTERM, sigint_handler);
158         // - ignore SIGPIPE to prevent a crashing client from bringing the server down too
159         signal(SIGPIPE, SIG_IGN);
160         
161         openlog("odispense2", 0, LOG_LOCAL4);
162         
163         if( Bank_Initialise(gsCokebankPath) )
164                 return -1;
165
166         Init_Handlers();
167
168         Load_Itemlist();
169         
170         Server_Start();
171         
172         if(gTimerThread)
173                 pthread_kill(gTimerThread, SIGKILL);
174
175         return 0;
176 }
177
178 void *Periodic_Thread(void *Unused __attribute__((unused)))
179 {
180          int    i;
181         
182         for( ;; )
183         {
184                 sleep(10);      // Sleep for a while
185 //              printf("Periodic firing\n");
186                 for( i = 0; i < ciMaxPeriodics; i ++ )
187                 {
188                         if( gaPeriodicCalls[i].Function )
189                                 gaPeriodicCalls[i].Function();
190                 }
191         }
192         return NULL;
193 }
194
195 void StartPeriodicThread(void)
196 {
197         pthread_create( &gTimerThread, NULL, Periodic_Thread, NULL );
198 }
199
200 void AddPeriodicFunction(void (*Fcn)(void))
201 {
202         int i;
203         for( i = 0; i < ciMaxPeriodics; i ++ )
204         {
205                 if( gaPeriodicCalls[i].Function )       continue;
206                 gaPeriodicCalls[i].Function = Fcn;
207                 return ;
208         }
209         
210         fprintf(stderr, "Error: No space for %p in periodic list\n", Fcn);
211 }
212
213 // Serial helper
214 int InitSerial(const char *File, int BaudRate)
215 {
216         struct termios  info;
217          int    baud;
218          int    fd;
219         
220         fd = open(File, O_RDWR | O_NOCTTY | O_NONBLOCK);
221         if( fd == -1 )  return -1;
222         
223         switch(BaudRate)
224         {
225         case 1200:      baud = B1200;   break;
226         case 9600:      baud = B9600;   break;
227         case 115200:    baud = B115200; break;
228         default:
229                 fprintf(stderr, "ERROR: Invalid baud rate to InitSerial (%i)\n", BaudRate);
230                 exit(1);
231         }
232         
233         info.c_lflag = 0;       // Non-Canoical, No Echo
234         info.c_cflag = baud | CS8 | CLOCAL | CREAD;     // baud, 8N1
235         info.c_iflag = IGNCR;   // Ignore \r
236         info.c_oflag = 0;       // ???
237         cfsetspeed(&info, baud);
238         info.c_cc[VTIME] = 0;   // No time limit
239         info.c_cc[VMIN] = 1;    // Block until 1 char
240         
241         tcflush(fd, TCIFLUSH);
242         tcsetattr(fd, TCSANOW, &info);
243         
244         return fd;
245 }
246
247
248 /**
249  * \brief Create a formatted heap string
250  */
251 char *mkstr(const char *Format, ...)
252 {
253         va_list args;
254          int    len;
255         char    *ret;
256
257         va_start(args, Format);
258         len = vsnprintf(NULL, 0, Format, args);
259         va_end(args);
260
261         ret = malloc( len + 1 );
262         if(!ret)        return NULL;
263
264         va_start(args, Format);
265         vsprintf(ret, Format, args);
266         va_end(args);
267         
268         return ret;
269 }
270

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