diu_main.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779
  1. /*
  2. * Copyright (c) 2019 Clementine Computing LLC.
  3. *
  4. * This file is part of PopuFare.
  5. *
  6. * PopuFare is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * PopuFare is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with PopuFare. If not, see <https://www.gnu.org/licenses/>.
  18. *
  19. */
  20. #include <sys/time.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <poll.h>
  24. #include <unistd.h>
  25. #include <errno.h>
  26. #include <string.h>
  27. #include <signal.h>
  28. #include <time.h>
  29. #include <openssl/md5.h>
  30. #include <ctype.h>
  31. #include <string.h>
  32. #include <sys/types.h>
  33. #include <ifaddrs.h>
  34. #include <arpa/inet.h>
  35. #include <sys/socket.h>
  36. #include <netdb.h>
  37. #include <ifaddrs.h>
  38. #include <linux/if_link.h>
  39. #include "../common/common_defs.h"
  40. #include "../commhub/commhub.h"
  41. #include "../commhub/client_utils.h"
  42. #include "driver.h"
  43. #include "touchscreen.h"
  44. #include "mongoose.h"
  45. #define _SLEN LINE_BUFFER_SIZE
  46. static const char *s_http_port = "60535";
  47. static struct mg_serve_http_opts s_http_server_opts;
  48. struct mg_mgr g_mgr;
  49. int diu_fd = -1;
  50. int hub_fd = -1;
  51. time_t last_hub_try = 0;
  52. time_t last_diu_clock = 0;
  53. gps_status my_gps_stat={0};
  54. time_t mkgmtime(struct tm *tm);
  55. int token_diag_serial = 0;
  56. char token_diag_string[LINE_BUFFER_SIZE] = {0};
  57. // return total bytes in dst
  58. //
  59. static size_t _strnncat(char *dst, char *src, size_t n) {
  60. size_t dst_n, src_n, N, i;
  61. dst_n = strlen(dst);
  62. src_n = strlen(src);
  63. N = n-1;
  64. if (dst_n < N) { N -= dst_n; }
  65. for (i=0; (i<N) && (i<src_n); i++) {
  66. dst[dst_n + i] = src[i];
  67. }
  68. dst[dst_n+i] = '\0';
  69. return dst_n + i;
  70. }
  71. time_t paddle_req_timeout = 0;
  72. set_paddle_req paddle_req = {0};
  73. driver_status my_driver_status={0};
  74. int update_driver_status = 0;
  75. int md5_of_file(char *filename, void *result) {
  76. FILE *f = NULL;
  77. char chunk[LINE_BUFFER_SIZE]={0};
  78. int retval = 0;
  79. MD5_CTX ctx;
  80. if (!result) { return -1; }
  81. if (!filename) { return -1; }
  82. if(!MD5_Init(&ctx)) {
  83. return -1;
  84. }
  85. f = fopen(filename, "rb");
  86. if(!f) {
  87. return -1;
  88. }
  89. while(1) {
  90. retval = fread(chunk, 1, LINE_BUFFER_SIZE, f);
  91. if(retval <= 0) {
  92. break;
  93. }
  94. else {
  95. MD5_Update(&ctx, chunk, retval);
  96. }
  97. }
  98. fclose(f);
  99. MD5_Final((unsigned char *)result, &ctx);
  100. return 0;
  101. }
  102. //--------------------
  103. static int is_websocket(const struct mg_connection *nc) {
  104. return nc->flags & MG_F_IS_WEBSOCKET;
  105. }
  106. void ws_send(struct mg_mgr *mgr, char *msg) {
  107. struct mg_connection *conn;
  108. for (conn = mg_next(mgr, NULL); conn; conn = mg_next(mgr, conn)) {
  109. if (!is_websocket(conn)) { continue; }
  110. mg_send_websocket_frame(conn, WEBSOCKET_OP_TEXT, msg, strlen(msg));
  111. }
  112. }
  113. //--------------------
  114. void beep(int fd, int hz, int milis) {
  115. char buffer[64];
  116. int n;
  117. n = sprintf(buffer, "/B:%X,%X\r", hz, milis);
  118. write(fd,buffer,n);
  119. }
  120. void set_backlight(int fd, int on) {
  121. char buffer[64];
  122. int n;
  123. n = sprintf(buffer, "/D:%c\r", on?'0':'1');
  124. write(fd,buffer,n);
  125. }
  126. void set_diu_clock(int fd, time_t tt) {
  127. struct tm t;
  128. char buffer[16];
  129. int n;
  130. localtime_r(&tt, &t);
  131. n = sprintf(buffer, "/C:%02d%02d\r", t.tm_hour, t.tm_min);
  132. write(fd, buffer, n);
  133. }
  134. //--------------------
  135. void clear_diu_messages() {
  136. }
  137. //--------------------
  138. // This function takes a GPS timestamp (in gross GPS float format + gross integer date) and
  139. //makes it into a sane UTC timestamp. If we are more than MAX_GPS_CLOCK_DRIFT seconds off
  140. //from GPS time, it sets the system clock to GPS time.
  141. //
  142. int handle_gps_time(float gtime, int date) {
  143. int day,month,year;
  144. int hour,min,sec,frac;
  145. int n = 0;
  146. time_t utc,now;
  147. char buffer[32] = {0};
  148. struct message_record outgoing_msg;
  149. now = time(NULL);
  150. day = month = year = 0;
  151. hour = min = sec = frac = 0;
  152. // Just to be *ahem* clear, as per NMEA standard the date is encoded DDMMYY, and the time of day
  153. // is encoded HHMMSS[.frac] where there is an optional fractional second field denoted by a decimal point.
  154. // we must be able to decode the fractional seconds field but we discard the information since it is not
  155. // reliable enough to be worth the bother.
  156. // Whoever thought that NMEA GPS should encode the time in this format ought to be shot...
  157. // Start out with zero parsed fields
  158. //
  159. n = 0;
  160. // Construct and then re-parse the time from its icky format to discrete values (this should result
  161. // in at least three (possibly four) fields.
  162. //
  163. sprintf(buffer,"%010.3f", gtime);
  164. n += sscanf(buffer,"%02d%02d%02d.%d", &hour, &min, &sec, &frac);
  165. // Construct and then re-parse the date from its icky format to discrete values. This should result in three fields.
  166. //
  167. sprintf(buffer,"%06d", date);
  168. n += sscanf(buffer,"%02d%02d%02d", &day, &month, &year);
  169. // If we scanned at all required fields
  170. //
  171. if(n >= 6) {
  172. struct tm gpstm = {0};
  173. // GPS date only uses two digits for year, so we must assume the century
  174. //
  175. year += GPS_DATE_CENTURY;
  176. // tm.tm_year is based on the year 1900
  177. //
  178. gpstm.tm_year = year - 1900;
  179. // January = month 0 in struct tm.tm_mon whereas January = month 1 in an NMEA GPS date.
  180. //
  181. gpstm.tm_mon = month - 1;
  182. gpstm.tm_mday = day;
  183. gpstm.tm_hour = hour;
  184. gpstm.tm_min = min;
  185. gpstm.tm_sec = sec;
  186. // Go and turn the struct tm we've just populated into an utc time stamp (seconds since epoch)
  187. //
  188. utc = mkgmtime(&gpstm);
  189. // Most importantly... Remember what the self-reported GPS time stamp is.
  190. //
  191. my_gps_stat.gpstime = utc;
  192. //printf("%02d-%02d-%04d %02d:%02d:%02d\n",day,month,year,hour,min,sec);
  193. //printf("CALCULATED: %d\nSYSTEM : %d\n\n",(int)utc,(int)time(NULL));
  194. // if we have more than MAX_GPS_CLOCK_DRIFT seconds of clock drift
  195. //
  196. if(abs(utc - now) > MAX_GPS_CLOCK_DRIFT) {
  197. struct timeval ts = {0};
  198. // Set the timeval struct to the calculated utc timestamp from the GPS unit.
  199. //
  200. ts.tv_sec = utc;
  201. ts.tv_usec = 0;
  202. // Set the system clock from GPS time using said timeval struct.
  203. //
  204. settimeofday(&ts, NULL);
  205. // If we have a valid connection to the IPC hub
  206. //
  207. if( hub_fd >= 0) {
  208. // Stick a message into the diagnostic log to record the fact that we've set the system clock from GPS
  209. //
  210. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "Set syatem clock from previous value (%d) to GPS time (%d).", (int)now, (int)utc );
  211. send_message(hub_fd, &outgoing_msg);
  212. }
  213. }
  214. }
  215. return 0;
  216. }
  217. #ifdef CLEAR_GPS_ON_STALE
  218. static inline void clear_stale_gps_data()
  219. {
  220. my_gps_stat.lat = my_gps_stat.lon = my_gps_stat.heading = my_gps_stat.velocity = 0;
  221. my_gps_stat.num_sats = 0;
  222. }
  223. #else
  224. static inline void clear_stale_gps_data()
  225. {
  226. }
  227. #endif
  228. static int handle_stale_gps_condition() {
  229. // This return code will be > 0 if this function generates a status change that
  230. // will then need to be communicated to other modules in the system via a message to
  231. // MAILBOX_GPS_STATUS.
  232. //
  233. int return_code = 0;
  234. // This will hold the gps_good flag as it stood at the beginning of this subroutine
  235. // previous to any adjustments we make.
  236. //
  237. int previous_good_flag = my_gps_stat.gps_good;
  238. int stale_time = 0;
  239. time_t now = time(NULL);
  240. stale_time = (now - my_gps_stat.stamp);
  241. // If we have entered this function with the impression that we have a valid GPS fix...
  242. //
  243. if(previous_good_flag > 0) {
  244. // If it has been at least GPS_STALE_THRESHOLD seconds since the last fix
  245. //
  246. if( stale_time >= GPS_STALE_THRESHOLD ) {
  247. clear_stale_gps_data();
  248. my_gps_stat.gps_good = 0;
  249. return_code |= 1;
  250. }
  251. }
  252. // If we have determined that we need to declare the GPS data stale and invalid and
  253. // we have a valid connection to the IPC hub we should use that IPC hub connection to
  254. // add a note to the diagnostic log indicating that we've declared the GPS data stale.
  255. //
  256. if( return_code && (hub_fd >= 0) ) {
  257. struct message_record outgoing_msg;
  258. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix has been stale for %d seconds, setting GPS = NO.", stale_time);
  259. send_message(hub_fd, &outgoing_msg);
  260. }
  261. return return_code;
  262. }
  263. int update_gps(char *in) {
  264. // This will hold the number of matched variables populated by sscanf().
  265. //
  266. int num = 0;
  267. // This will allow us to know if we have made a transition from an invalid
  268. // GPS fix to a valid one so that we can log this information.
  269. //
  270. int previous_good_flag = my_gps_stat.gps_good;
  271. // This return code will be > 0 if this function generates a status change that
  272. // will then need to be communicated to other modules in the system via a message to
  273. // MAILBOX_GPS_STATUS.
  274. //
  275. int return_code = 0;
  276. if(!strncmp(in,"$GPRMC",6)) {
  277. float f1=0;
  278. char f2=0;
  279. float f3=0;
  280. char f4=0;
  281. float f5=0;
  282. char f6=0;
  283. float f7=0;
  284. float f8=0;
  285. int f9=0;
  286. float f10=0;
  287. char f11=0;
  288. num = sscanf(in,"$GPRMC,%f,%c,%f,%c,%f,%c,%f,%f,%d,%f,%c",&f1,&f2,&f3,&f4,&f5,&f6,&f7,&f8,&f9,&f10,&f11);
  289. // If we have a full GPRMC sentence we can consider setting the time
  290. //
  291. if(num == 11) {
  292. // Require at least MIN_SATS_FOR_TIME satellites to accept a new system clock value from the GPS unit.
  293. // This is to keep a crummy GPS fix from generating a bogus or unstable system time.
  294. //
  295. if(my_gps_stat.num_sats >= MIN_SATS_FOR_TIME) {
  296. // Pass the time field (f1) and the date field (f9) in to the routine that sets the system clock if needed.
  297. // (this routine also stores the utc timestamp derived from the GPS date and time fields so it can be passed to
  298. // other modules that may have a need for this information).
  299. //handle_gps_time(f1,f9);
  300. }
  301. }
  302. if(num > 0) {
  303. // update snapshot with latitude
  304. //
  305. my_gps_stat.lat = f3 * ((f4 == 'N')?(1):(-1));
  306. // longitude
  307. //
  308. my_gps_stat.lon = f5 * ((f6 == 'E')?(1):(-1));
  309. // meters per second (converted from knots)
  310. //
  311. my_gps_stat.velocity = f7 / 1.94384449f;
  312. // course
  313. //
  314. my_gps_stat.heading = f8;
  315. // update snapshot's staledate
  316. //
  317. my_gps_stat.stamp = time(NULL);
  318. return_code |= 1;
  319. }
  320. }
  321. else if(!strncmp(in,"$GPGGA",6)) {
  322. int f1=0;
  323. float f2=0;
  324. char f3=0;
  325. float f4=0;
  326. char f5=0;
  327. int f6=0;
  328. int f7=0;
  329. float f8=0;
  330. float f9=0;
  331. char f10=0;
  332. float f11=0;
  333. char f12=0;
  334. num=sscanf(in,"$GPGGA,%d,%f,%c,%f,%c,%d,%d,%f,%f,%c,%f,%c",&f1,&f2,&f3,&f4,&f5,&f6,&f7,&f8,&f9,&f10,&f11,&f12);
  335. if(num == 12) {
  336. // require 3 satellites minimum
  337. //
  338. if ( f7 >= 3 ) {
  339. // store GPS valid flag in snapshot
  340. //
  341. my_gps_stat.gps_good = f6;
  342. // store number of satellites in view in snapshot
  343. //
  344. my_gps_stat.num_sats = f7;
  345. // Do NOT store the timestamp since we only want to remember timestamps of position
  346. // fixes and the GPGGA message is all metadata (number of satellites, fix quality, etc...).
  347. // It is worth noting that GPGGA does report altitude, but that is not a piece of information
  348. // we track because the road is where the road is, and if a bus becomes airborn we have much
  349. // bigger problems than figuring out how far off the ground it is...
  350. //
  351. return_code |= 1;
  352. }
  353. }
  354. }
  355. return_code |= handle_stale_gps_condition();
  356. // If we have a connection to the IPC hub and we had previously not had a valid
  357. // GPS fix but we now do, make a note of it in the diagnostic log.
  358. //
  359. if( (previous_good_flag == 0) && (my_gps_stat.gps_good != 0) && (hub_fd >= 0) ) {
  360. struct message_record outgoing_msg;
  361. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix is now valid with %d satellites. Setting GPS = YES.", my_gps_stat.num_sats);
  362. send_message(hub_fd, &outgoing_msg);
  363. }
  364. return return_code;
  365. }
  366. void maintain_ipc_hub_connect(char *progname) {
  367. struct message_record outgoing_msg;
  368. // if we have no connection to the IPC hub
  369. //
  370. if(hub_fd < 0) {
  371. // if we haven't tried the hub in a few seconds
  372. //
  373. if( (time(NULL) - last_hub_try) > HUB_RETRY_TIME ) {
  374. // retry it
  375. //
  376. last_hub_try = time(NULL);
  377. // try and get one
  378. //
  379. hub_fd = connect_to_message_server(progname);
  380. if(hub_fd >= 0) {
  381. // Subscribe to the default status messages
  382. //
  383. subscribe_to_default_messages(hub_fd);
  384. // Subscribe to our specific message
  385. //
  386. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_DRIVER_NOTIFY, strlen(MAILBOX_DRIVER_NOTIFY));
  387. send_message(hub_fd,&outgoing_msg);
  388. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_PADDLE_ACK, strlen(MAILBOX_PADDLE_ACK));
  389. send_message(hub_fd,&outgoing_msg);
  390. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_VAULT_DROP, strlen(MAILBOX_VAULT_DROP));
  391. send_message(hub_fd,&outgoing_msg);
  392. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_MAG, strlen(MAILBOX_TOKEN_MAG));
  393. send_message(hub_fd,&outgoing_msg);
  394. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_RFID, strlen(MAILBOX_TOKEN_RFID));
  395. send_message(hub_fd,&outgoing_msg);
  396. // Ask for a status update
  397. //
  398. prepare_message(&outgoing_msg, MAILBOX_STATUS_REQUEST, "", 0);
  399. send_message(hub_fd,&outgoing_msg);
  400. }
  401. else {
  402. fprintf(stderr, "Cannot connect to IPC hub!\n");
  403. }
  404. }
  405. }
  406. }
  407. message_callback_return handle_status_request(struct message_record *msg, void *param) {
  408. struct message_record outgoing_msg;
  409. if(hub_fd >= 0) {
  410. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  411. send_message(hub_fd, &outgoing_msg);
  412. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  413. send_message(hub_fd, &outgoing_msg);
  414. }
  415. return MESSAGE_HANDLED_CONT;
  416. }
  417. message_callback_return handle_vault_drop(struct message_record *msg, void *param) {
  418. if(diu_fd >= 0) { write(diu_fd, "/V:\r", 4); }
  419. return MESSAGE_HANDLED_CONT;
  420. }
  421. char dup_notify_str[MAX_PAYLOAD_LENGTH] = {0};
  422. int dup_notify_count = 0;
  423. long long dup_notify_usec = 0;
  424. message_callback_return handle_driver_notify(struct message_record *msg, void *param) {
  425. int is_dup;
  426. char _text[MAX_PAYLOAD_LENGTH] = {0};
  427. long long dup_usec_delta = 0;
  428. if(strncmp((const char *)(msg->payload), dup_notify_str, MAX_PAYLOAD_LENGTH)) {
  429. dup_notify_count = 1;
  430. strncpy(dup_notify_str, (const char *)(msg->payload), MAX_PAYLOAD_LENGTH - 1);
  431. dup_notify_str[MAX_PAYLOAD_LENGTH - 1] = '\0';
  432. is_dup = 0;
  433. dup_notify_usec = 0;
  434. }
  435. else {
  436. dup_notify_count++;
  437. is_dup = 1;
  438. dup_usec_delta = get_usec_time() - dup_notify_usec;
  439. dup_notify_usec = get_usec_time();
  440. }
  441. switch(msg->payload[0]) {
  442. case LOGLEVEL_EVENT:
  443. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
  444. DIU_ACK_BEEP(diu_fd);
  445. }
  446. break;
  447. case LOGLEVEL_REJECT:
  448. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
  449. DIU_ERROR_BEEP(diu_fd);
  450. }
  451. break;
  452. case LOGLEVEL_ACCEPT:
  453. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
  454. DIU_ACK_BEEP(diu_fd);
  455. }
  456. break;
  457. case LOGLEVEL_ERROR:
  458. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
  459. DIU_CRITICAL_BEEP(diu_fd);
  460. }
  461. break;
  462. default: break;
  463. }
  464. if(is_dup) {
  465. snprintf(_text, MAX_PAYLOAD_LENGTH, "driver_notify replace %s %s %d x %s", "white", "black", dup_notify_count, &msg->payload[1]);
  466. ws_send(&g_mgr, _text);
  467. }
  468. else {
  469. snprintf(_text, MAX_PAYLOAD_LENGTH, "driver_notify ok %s %s %d x %s", "white", "black", dup_notify_count, &msg->payload[1]);
  470. ws_send(&g_mgr, _text);
  471. }
  472. return MESSAGE_HANDLED_CONT;
  473. }
  474. message_callback_return handle_paddle_ack(struct message_record *msg, void *param) {
  475. set_paddle_req *pr = (set_paddle_req *)msg->payload;
  476. paddle_req.result = pr->result;
  477. return MESSAGE_HANDLED_CONT;
  478. }
  479. message_callback_return handle_token_diag(struct message_record *msg, void *param) {
  480. strncpy(token_diag_string, (const char *)(msg->payload), sizeof(token_diag_string));
  481. token_diag_string[sizeof(token_diag_string) - 1] = '\0';
  482. token_diag_serial++;
  483. return MESSAGE_HANDLED_CONT;
  484. }
  485. //----------------------------------
  486. time_t diu_error_burst = 0;
  487. int diu_error_counter = 0;
  488. static inline int can_report_diu_error() {
  489. time_t now = time(NULL);
  490. // If our last potential burst lockout has expired...
  491. //
  492. if( (now - diu_error_burst) >= DIU_ERROR_RATE_LIMIT) {
  493. // reset our burst counter
  494. //
  495. diu_error_counter = 0;
  496. // and start the "potential burst" time at this message
  497. //
  498. diu_error_burst = now;
  499. }
  500. // if we haven't hit our burst limit...
  501. //
  502. if(diu_error_counter < DIU_ERROR_BURST_LIMIT) {
  503. // count this message against our burst limit
  504. //
  505. diu_error_counter++;
  506. // and allow it to pass
  507. //
  508. return 1;
  509. }
  510. // if we have hit our limit
  511. //
  512. else {
  513. // ignore this message
  514. //
  515. return 0;
  516. }
  517. }
  518. //----------------------------------
  519. //-------- web server functions ----
  520. /*
  521. static void send_ws_heartbeat(struct mg_connection *nc) {
  522. int n;
  523. char buf[_SLEN];
  524. struct mg_connection *c;
  525. for (c=mg_next(nc->mgr, NULL); c ; c = mg_next(nc->mgr, c)) {
  526. if (c==nc) { continue; }
  527. if (!is_websocket(c)) { continue; }
  528. printf("...\n");
  529. snprintf(buf, _SLEN, "hello");
  530. n = strlen(buf);
  531. mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, buf, n);
  532. }
  533. }
  534. */
  535. static void process_ws_message(struct websocket_message *ws_msg) {
  536. int i;
  537. char *data;
  538. data = (char *)(ws_msg->data);
  539. printf("#ws, got(%i)\n:", (int)(ws_msg->size));
  540. for (i=0; i<ws_msg->size; i++) {
  541. printf("%c", data[i]);
  542. }
  543. printf("\n");
  544. }
  545. #define MAX_PKGS (16)
  546. //
  547. // ui wants status information
  548. //
  549. static void ui_handle_status_input(struct mg_connection *nc, struct http_message *hm) {
  550. int i, npkgs, npkgnet=0;
  551. char buf[4*_SLEN],
  552. pkgnetline[_SLEN],
  553. _str[_SLEN];
  554. char date_str[32];
  555. time_t t;
  556. struct tm tm, pkgtime;
  557. FILE *fp;
  558. package_signature pkgs[MAX_PKGS];
  559. t = time(NULL);
  560. localtime_r(&t, &tm);
  561. strftime(date_str, 32, "%Y-%m-%d", &tm);
  562. pkgnetline[0] = '\0';
  563. npkgs = find_packages(pkgs,MAX_PKGS);
  564. for (i=0; i<npkgs; i++) {
  565. localtime_r(&pkgs[i].installed, &pkgtime);
  566. snprintf(_str, _SLEN, "pkg%i=%s %s %02d/%02d/%02d %02d:%02d:%02d",
  567. i,
  568. pkgs[i].pkgname, pkgs[i].pkgver,
  569. pkgtime.tm_mon + 1, pkgtime.tm_mday, pkgtime.tm_year + 1900,
  570. pkgtime.tm_hour, pkgtime.tm_min, pkgtime.tm_sec);
  571. _strnncat(pkgnetline, "|", _SLEN);
  572. _strnncat(pkgnetline, _str, _SLEN);
  573. npkgnet++;
  574. }
  575. fp = fopen("/tmp/net_ids", "rb");
  576. if (fp) {
  577. i=0;
  578. while (fgets(_str, _SLEN, fp)) {
  579. strip_crlf(_str);
  580. _strnncat(pkgnetline, "|", _SLEN);
  581. _strnncat(pkgnetline, _str, _SLEN);
  582. npkgnet++;
  583. }
  584. fclose(fp);
  585. }
  586. snprintf(buf, 4*_SLEN, "ok msg=status\n"
  587. "equipno=%d|"
  588. "route=%d|"
  589. "trip=%d|"
  590. "stop=%d|"
  591. "gps=%i|"
  592. "gpslat=%f|"
  593. "gpslon=%f|"
  594. "gpsv=%f|"
  595. "gpsheading=%f|"
  596. "tunnel=%i|"
  597. "gprs=%i|"
  598. "date=%s|"
  599. "nmsg=%d|"
  600. "last_token=%d"
  601. "%s",
  602. get_equip_num(),
  603. stop_stat.route,
  604. stop_stat.trip,
  605. stop_stat.stop,
  606. gps_stat.gps_good,
  607. gps_stat.lat,
  608. gps_stat.lon,
  609. gps_stat.velocity,
  610. gps_stat.heading,
  611. tunnel_is_up(),
  612. gprs_is_up(),
  613. date_str,
  614. bill_stat.unsynced_messages,
  615. token_diag_serial % 100,
  616. pkgnetline);
  617. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  618. (unsigned long)strlen(buf), buf);
  619. }
  620. // driver logout
  621. //
  622. static void ui_handle_logout_input(struct mg_connection *nc, struct http_message *hm) {
  623. char msg[][_SLEN] = {
  624. "fail error",
  625. "ok .",
  626. };
  627. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  628. (unsigned long)strlen(msg[1]), msg[1]);
  629. }
  630. // (manual) next stop pressed
  631. //
  632. static void ui_handle_nextstop_input(struct mg_connection *nc, struct http_message *hm) {
  633. char msg[][_SLEN] = {
  634. "fail error",
  635. "ok .",
  636. };
  637. action_nextstop();
  638. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  639. (unsigned long)strlen(msg[1]), msg[1]);
  640. }
  641. // (manual) previous stop pressed
  642. //
  643. static void ui_handle_prevstop_input(struct mg_connection *nc, struct http_message *hm) {
  644. char msg[][_SLEN] = {
  645. "fail error",
  646. "ok .",
  647. };
  648. action_prevstop();
  649. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  650. (unsigned long)strlen(msg[1]), msg[1]);
  651. }
  652. // generic fare input
  653. //
  654. static void ui_handle_fare_input(struct mg_connection *nc, struct http_message *hm) {
  655. int ret;
  656. char s_rule[_SLEN], s_param[_SLEN];
  657. char msg_ok[] = "ok .";
  658. driver_rulecall dr = {{0}};
  659. struct message_record outgoing;
  660. ret = mg_get_http_var(&(hm->body), "rule", s_rule, _SLEN);
  661. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  662. ret = mg_get_http_var(&(hm->body), "param", s_param, _SLEN);
  663. if (ret<=0) { s_param[0] = '\0'; }
  664. if (hub_fd >= 0) {
  665. strncpy(dr.rulename, s_rule, DRIVER_RULECALL_LEN - 1);
  666. strncpy(dr.ruleparam, s_param, DRIVER_RULECALL_LEN - 1);
  667. prepare_message(&outgoing, MAILBOX_RULE_CALL, &dr, sizeof(dr));
  668. send_message(hub_fd, &outgoing);
  669. }
  670. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  671. (unsigned long)strlen(msg_ok), msg_ok);
  672. }
  673. // driver paddle (route) input
  674. //
  675. static void ui_handle_paddle_input(struct mg_connection *nc, struct http_message *hm) {
  676. int ret;
  677. char s_paddle[_SLEN];
  678. //char msg_fail[] = "fail .";
  679. char msg_ok[] = "ok .";
  680. int ipaddle;
  681. ret = mg_get_http_var(&(hm->body), "paddle", s_paddle, _SLEN);
  682. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  683. //DEBUG
  684. printf("#got paddle %s\n", s_paddle);
  685. ipaddle = atoi(s_paddle);
  686. make_paddle_request(ipaddle);
  687. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  688. (unsigned long)strlen(msg_ok), msg_ok);
  689. }
  690. // driver login
  691. //
  692. static void ui_handle_driver_login(struct mg_connection *nc, struct http_message *hm) {
  693. int ret;
  694. char s_driver[_SLEN], s_pin[_SLEN];
  695. int idrv=-1;
  696. char msg_fail[] = "fail driver_login";
  697. char msg_success[] = "ok driver";
  698. ret = mg_get_http_var(&(hm->body), "driver", s_driver, _SLEN);
  699. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  700. ret = mg_get_http_var(&(hm->body), "pin", s_pin, _SLEN);
  701. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  702. idrv = atoi(s_driver);
  703. ret = driver_login(idrv, s_pin);
  704. if (ret!=0) {
  705. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  706. (unsigned long)strlen(msg_fail), msg_fail);
  707. return;
  708. }
  709. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  710. (unsigned long)strlen(msg_success), msg_success);
  711. }
  712. // screen dim event
  713. //
  714. static void ui_handle_dim(struct mg_connection *nc, struct http_message *hm) {
  715. int ret;
  716. char msg_fail[] = "fail dim";
  717. char msg_success[] = "ok dim";
  718. // assuming we're running as root for now
  719. //
  720. ret = system("su - pi -c \"/usr/bin/xset -display :0 dpms force off\" &");
  721. if (ret!=0) {
  722. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  723. (unsigned long)strlen(msg_fail), msg_fail);
  724. return;
  725. }
  726. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  727. (unsigned long)strlen(msg_success), msg_success);
  728. }
  729. // set volume
  730. //
  731. static void ui_handle_volume(struct mg_connection *nc, struct http_message *hm) {
  732. int ret;
  733. char s_volume[_SLEN], _cmd[1024];
  734. float f_vol = 100.0;
  735. char msg_fail[] = "fail volume";
  736. char msg_success[] = "ok volume";
  737. ret = mg_get_http_var(&(hm->body), "volume", s_volume, _SLEN);
  738. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  739. // assuming we're running as root for now
  740. //
  741. f_vol = atof(s_volume);
  742. snprintf(_cmd, 1023, "/home/bus/bin/volumeset %04f &", f_vol);
  743. ret = system(_cmd);
  744. if (ret!=0) {
  745. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  746. (unsigned long)strlen(msg_fail), msg_fail);
  747. return;
  748. }
  749. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  750. (unsigned long)strlen(msg_success), msg_success);
  751. }
  752. // bring network interface up/down
  753. //
  754. static void ui_handle_interfaceupdown(struct mg_connection *nc, struct http_message *hm) {
  755. int ret;
  756. char s_interface[_SLEN], s_updown[_SLEN];
  757. char msg_fail[] = "fail interfaceupdown";
  758. char msg_success[] = "ok interfaceupdown";
  759. int _iface_updown = -1;
  760. ret = mg_get_http_var(&(hm->body), "interface", s_interface, _SLEN);
  761. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  762. ret = mg_get_http_var(&(hm->body), "state", s_updown, _SLEN);
  763. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  764. // only allow eth0 and up/down for now
  765. //
  766. if (strncmp(s_interface, "eth0", strlen("eth0")+1)!=0) {
  767. mg_http_send_error(nc, 404, NULL);
  768. return;
  769. }
  770. if (strncmp(s_updown, "up", strlen("up")+1)==0) {
  771. _iface_updown=1;
  772. }
  773. else if (strncmp(s_updown, "down", strlen("down")+1)==0) {
  774. _iface_updown=0;
  775. }
  776. if (_iface_updown < 0) {
  777. mg_http_send_error(nc, 404, NULL);
  778. return;
  779. }
  780. // Assuming we're running as root for now.
  781. // Bring eth0 interface up or down.
  782. //
  783. if (_iface_updown==1) {
  784. ret = system("/sbin/ip link set eth0 up &");
  785. }
  786. else if (_iface_updown==0) {
  787. ret = system("/sbin/ip link set eth0 down &");
  788. }
  789. if (ret!=0) {
  790. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  791. (unsigned long)strlen(msg_fail), msg_fail);
  792. return;
  793. }
  794. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  795. (unsigned long)strlen(msg_success), msg_success);
  796. }
  797. // bring network interface up/down
  798. //
  799. static void ui_handle_calibration(struct mg_connection *nc, struct http_message *hm) {
  800. int ret;
  801. char msg_fail[] = "fail calibration";
  802. char msg_success[] = "ok calibration";
  803. // Assuming we're running as root for now.
  804. //
  805. ret = system("/usr/bin/ts_calibrate &");
  806. if (ret!=0) {
  807. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  808. (unsigned long)strlen(msg_fail), msg_fail);
  809. return;
  810. }
  811. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  812. (unsigned long)strlen(msg_success), msg_success);
  813. }
  814. // bring network interface up/down
  815. //
  816. static void ui_handle_switchserver(struct mg_connection *nc, struct http_message *hm) {
  817. int ret;
  818. char s_server[_SLEN];
  819. char msg_fail[] = "fail switchserver";
  820. char msg_success[] = "ok switchserver";
  821. ret = mg_get_http_var(&(hm->body), "server", s_server, _SLEN);
  822. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  823. //TODO: switch server code (call shell script)...
  824. //
  825. if (ret!=0) {
  826. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  827. (unsigned long)strlen(msg_fail), msg_fail);
  828. return;
  829. }
  830. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  831. (unsigned long)strlen(msg_success), msg_success);
  832. }
  833. // get network interface information
  834. //
  835. static void ui_handle_interfaceinfo(struct mg_connection *nc, struct http_message *hm) {
  836. int n, fam, s;
  837. struct ifaddrs *_addr, *ifa;
  838. char host[NI_MAXHOST];
  839. char msg_fail[] = "fail interfaceinfo";
  840. char buf[4*_SLEN];
  841. // We're going to restrict to eth0 and only ip4
  842. //
  843. if (getifaddrs(&_addr)==-1) {
  844. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  845. (unsigned long)strlen(msg_fail), msg_fail);
  846. return;
  847. }
  848. for (ifa = _addr, n=0; ifa!=NULL; ifa = ifa->ifa_next, n++) {
  849. if (ifa->ifa_addr == NULL) { continue; }
  850. fam = ifa->ifa_addr->sa_family;
  851. if (fam != AF_INET) { continue; }
  852. if (strncmp(ifa->ifa_name, "eth0", strlen("eth0") + 1)!=0) { continue; }
  853. s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
  854. host, NI_MAXHOST,
  855. NULL, 0, NI_NUMERICHOST);
  856. if (s != 0) {
  857. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  858. (unsigned long)strlen(msg_fail), msg_fail);
  859. return;
  860. }
  861. snprintf(buf, (4*_SLEN) - 1, "ok msg=interfaceinfo\n%s=%s", ifa->ifa_name, host);
  862. }
  863. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  864. (unsigned long)strlen(buf), buf);
  865. }
  866. // run 'say' custom script for voice text to speech
  867. //
  868. static void ui_handle_say(struct mg_connection *nc, struct http_message *hm) {
  869. int ret;
  870. char msg_ok[] = "ok say";
  871. char s_message[_SLEN];
  872. char buf[4*_SLEN];
  873. ret = mg_get_http_var(&(hm->body), "message", s_message, _SLEN);
  874. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  875. snprintf(buf, 4*_SLEN-1, "/home/bus/bin/say \"%s\" &", s_message);
  876. system(buf);
  877. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  878. (unsigned long)strlen(msg_ok), msg_ok);
  879. }
  880. // change equipment number
  881. //
  882. static void ui_handle_eqnum(struct mg_connection *nc, struct http_message *hm) {
  883. int ret;
  884. char msg_ok[] = "ok eqnum";
  885. char s_eqnum[_SLEN];
  886. ret = mg_get_http_var(&(hm->body), "eqnum", s_eqnum, _SLEN);
  887. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  888. ret = set_equip_num(atoi(s_eqnum));
  889. if (ret < 0) {
  890. mg_http_send_error(nc, 404, NULL);
  891. return;
  892. }
  893. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  894. (unsigned long)strlen(msg_ok), msg_ok);
  895. }
  896. //-----
  897. //-----
  898. //-----
  899. // api point
  900. //
  901. static void api_handle_req(struct mg_connection *nc, struct http_message *hm) {
  902. int ret;
  903. char s_action[_SLEN];
  904. ret = mg_get_http_var(&(hm->body), "action", s_action, _SLEN);
  905. if (ret==0) {
  906. mg_http_send_error(nc, 404, NULL);
  907. return;
  908. }
  909. if (strncmp(s_action, "driverlogin", strlen("driverlogin")+1)==0) {
  910. ui_handle_driver_login(nc, hm);
  911. }
  912. else if (strncmp(s_action, "paddleinput", strlen("paddleinput")+1)==0) {
  913. ui_handle_paddle_input(nc, hm);
  914. }
  915. else if (strncmp(s_action, "prevstop", strlen("prevstop")+1)==0) {
  916. ui_handle_prevstop_input(nc, hm);
  917. }
  918. else if (strncmp(s_action, "nextstop", strlen("nextstop")+1)==0) {
  919. ui_handle_nextstop_input(nc, hm);
  920. }
  921. else if (strncmp(s_action, "status", strlen("status")+1)==0) {
  922. ui_handle_status_input(nc, hm);
  923. }
  924. else if (strncmp(s_action, "logout", strlen("logout")+1)==0) {
  925. ui_handle_logout_input(nc, hm);
  926. }
  927. else if (strncmp(s_action, "fare", strlen("fare")+1)==0) {
  928. ui_handle_fare_input(nc, hm);
  929. }
  930. else if (strncmp(s_action, "dim", strlen("dim")+1)==0) {
  931. ui_handle_dim(nc, hm);
  932. }
  933. else if (strncmp(s_action, "volume", strlen("volume")+1)==0) {
  934. ui_handle_volume(nc, hm);
  935. }
  936. else if (strncmp(s_action, "interfaceupdown", strlen("interfaceupdown")+1)==0) {
  937. ui_handle_interfaceupdown(nc, hm);
  938. }
  939. else if (strncmp(s_action, "interfaceinfo", strlen("interfaceinfo")+1)==0) {
  940. ui_handle_interfaceinfo(nc, hm);
  941. }
  942. else if (strncmp(s_action, "say", strlen("say")+1)==0) {
  943. ui_handle_say(nc, hm);
  944. }
  945. else if (strncmp(s_action, "eqnum", strlen("eqnum")+1)==0) {
  946. ui_handle_eqnum(nc, hm);
  947. }
  948. else if (strncmp(s_action, "calibration", strlen("calibration")+1)==0) {
  949. ui_handle_calibration(nc, hm);
  950. }
  951. else if (strncmp(s_action, "switchserver", strlen("switchserver")+1)==0) {
  952. ui_handle_switchserver(nc, hm);
  953. }
  954. else {
  955. mg_http_send_error(nc, 404, NULL);
  956. }
  957. }
  958. static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  959. struct http_message *hm = (struct http_message *) ev_data;
  960. char buf[1024];
  961. int debug_print = 0;
  962. if (debug_print) {
  963. mg_sock_addr_to_str(&(nc->sa), buf, 1023, MG_SOCK_STRINGIFY_IP);
  964. printf("%s\n", buf);
  965. }
  966. switch (ev){
  967. case MG_EV_HTTP_REQUEST:
  968. if (mg_vcmp(&hm->uri, "/req")==0) {
  969. api_handle_req(nc, (struct http_message *)ev_data);
  970. }
  971. else {
  972. mg_serve_http(nc, (struct http_message *) ev_data, s_http_server_opts);
  973. }
  974. break;
  975. case MG_EV_WEBSOCKET_HANDSHAKE_DONE:
  976. break;
  977. case MG_EV_WEBSOCKET_FRAME:
  978. process_ws_message((struct websocket_message *)ev_data);
  979. break;
  980. case MG_EV_CLOSE:
  981. if (is_websocket(nc)) {
  982. // websocket closed
  983. }
  984. break;
  985. default:
  986. break;
  987. }
  988. }
  989. //DEBUG
  990. void _test_ws(struct mg_mgr *mgr) {
  991. struct mg_connection *conn;
  992. char buf[_SLEN];
  993. snprintf(buf, _SLEN, "test message");
  994. for (conn = mg_next(mgr, NULL); conn; conn = mg_next(mgr, conn)) {
  995. if (!is_websocket(conn)) { continue; }
  996. mg_send_websocket_frame(conn, WEBSOCKET_OP_TEXT, buf, strlen(buf));
  997. }
  998. }
  999. //-------- web server functions ----
  1000. int main(int argc, char **argv) {
  1001. char line[LINE_BUFFER_SIZE] = {0};
  1002. struct message_record incoming_msg;
  1003. struct message_record outgoing_msg;
  1004. struct pollfd fds[32];
  1005. int nfd=0;
  1006. int poll_return;
  1007. int read_return;
  1008. int i;
  1009. time_t down_time = 0;
  1010. int calibration = 0;
  1011. time_t now;
  1012. int retval = 0;
  1013. int tz = 0;
  1014. int tx = 0;
  1015. int ty = 0;
  1016. time_t last_stale_gps_check = 0;
  1017. long long int _usec_now, _usec_prv, _usec_del;
  1018. _usec_now = get_usec_time();
  1019. _usec_prv = _usec_now;
  1020. _usec_del = 60000000;
  1021. // setup mongoose web server
  1022. //
  1023. struct mg_connection *nc;
  1024. mg_mgr_init(&g_mgr, NULL);
  1025. nc = mg_bind(&g_mgr, s_http_port, ev_handler);
  1026. if (!nc) {
  1027. printf("failed to create listener\n");
  1028. return 1;
  1029. }
  1030. mg_set_protocol_http_websocket(nc);
  1031. s_http_server_opts.document_root = CONFIG_FILE_PATH "/html";
  1032. s_http_server_opts.enable_directory_listing = "no";
  1033. // Configure our signal handlers to deal with SIGINT, SIGTERM, etc... and make graceful exits while logging
  1034. //
  1035. configure_signal_handlers(argv[0]);
  1036. // Make an initial attempt to get in touch with the interprocess communication hub (it may not be up yet depending on the start order)
  1037. //
  1038. maintain_ipc_hub_connect(argv[0]);
  1039. // Register our defualt system message processing callbacks
  1040. //
  1041. register_system_status_callbacks();
  1042. register_dispatch_callback(MAILBOX_STATUS_REQUEST, CALLBACK_USER(1), handle_status_request, NULL);
  1043. register_dispatch_callback(MAILBOX_DRIVER_NOTIFY, CALLBACK_USER(2), handle_driver_notify, NULL);
  1044. register_dispatch_callback(MAILBOX_PADDLE_ACK, CALLBACK_USER(3), handle_paddle_ack, NULL);
  1045. register_dispatch_callback(MAILBOX_VAULT_DROP, CALLBACK_USER(4), handle_vault_drop, NULL);
  1046. register_dispatch_callback(MAILBOX_TOKEN_MAG, CALLBACK_USER(5), handle_token_diag, NULL);
  1047. register_dispatch_callback(MAILBOX_TOKEN_RFID, CALLBACK_USER(6), handle_token_diag, NULL);
  1048. clear_diu_messages();
  1049. // This is the main dispatch loop:
  1050. //
  1051. // * reset watchdog to make sure we haven't crashed/frozen
  1052. // * if need be, open a connection to the DIU microcontroller, quieting all messages except for acks
  1053. // * handle GPS message dispatch through IPC
  1054. // * manage driver status message communication
  1055. // * handle paddle change
  1056. // * listen on the mailboxes for messages and process. This includes
  1057. // - gps updates
  1058. // - warning/debug/error messages
  1059. //
  1060. //loop until we get asked to exit.../
  1061. //
  1062. while( exit_request_status == EXIT_REQUEST_NONE ) {
  1063. _usec_now = get_usec_time();
  1064. if ((_usec_now - _usec_prv) > _usec_del) {
  1065. //DEBUG
  1066. printf("[%lli] diu_minder: heartbeat\n", get_usec_time());
  1067. //DEBUG
  1068. _usec_prv = _usec_now;
  1069. }
  1070. RESET_WATCHDOG();
  1071. maintain_ipc_hub_connect(argv[0]);
  1072. if(diu_fd < 0) {
  1073. diu_fd = open_rs232_device(DRIVER_UI_PORT, USE_DEFAULT_BAUD, RS232_LINE);
  1074. if(diu_fd < 0) {
  1075. //fprintf(stderr, "Cannot open serial port %s for DIU!\n", DRIVER_UI_PORT);
  1076. }
  1077. else {
  1078. write(diu_fd, "/Q:aK\r", 6); //Turn on all messages except ACKs for sent commands
  1079. }
  1080. }
  1081. now = time(NULL);
  1082. //Every second, we want to update the DIU clock (even though it only shows minutes, this covers power events...)
  1083. //
  1084. if((now - last_diu_clock) > 0) {
  1085. if(diu_fd) {
  1086. set_diu_clock(diu_fd, now);
  1087. last_diu_clock = now;
  1088. }
  1089. }
  1090. //Every second we want to check to make sure that our GPS data have note gone stale...
  1091. //
  1092. if((now - last_stale_gps_check) > 0) {
  1093. // If the stale check results in an update to my_gps_stat, we must update any other
  1094. // modules which may be tracking GPS status via the IPC hub.
  1095. //
  1096. if( handle_stale_gps_condition() > 0 ) {
  1097. // If we have a connection to the IPC hub
  1098. //
  1099. if(hub_fd >= 0) {
  1100. //Go and toss the data to any other modules who happen to care about GPS
  1101. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  1102. send_message(hub_fd, &outgoing_msg);
  1103. }
  1104. }
  1105. // Either way, remember that we did this stale check.
  1106. //
  1107. last_stale_gps_check = now;
  1108. }
  1109. if(hup_request_status) {
  1110. hup_request_status = 0;
  1111. // reserve ui if necssary ...
  1112. //
  1113. }
  1114. //If it is time to send out a driver status update
  1115. //
  1116. if(update_driver_status && (hub_fd >= 0)) {
  1117. //do so...
  1118. //
  1119. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  1120. send_message(hub_fd, &outgoing_msg);
  1121. update_driver_status = 0;
  1122. }
  1123. check_paddle_request();
  1124. //If we have to redraw the UI
  1125. //if(redraw_flag && !calibration)
  1126. //
  1127. if(!calibration) {
  1128. //Redraw the menu reflecting any changes from the last touchscreen input
  1129. //or other stimulus
  1130. //draw_menu(mt);
  1131. //
  1132. #ifdef TOUCHSCREEN_QUIET
  1133. write(diu_fd, "/Q:t\r", 5); //Un-Quiet the touch screen, now that we've responded to the user we want
  1134. #endif //to hear if they have any further input to give us...
  1135. }
  1136. nfd = 0;
  1137. if(hub_fd >= 0) {
  1138. fds[nfd].fd = hub_fd;
  1139. fds[nfd].events = POLLIN;
  1140. fds[nfd].revents = 0;
  1141. nfd++;
  1142. }
  1143. if(diu_fd >= 0) {
  1144. fds[nfd].fd = diu_fd;
  1145. fds[nfd].events = POLLIN;
  1146. fds[nfd].revents = 0;
  1147. nfd++;
  1148. }
  1149. // Add our websocket socket to the list of file descriptors
  1150. // to select on.
  1151. //
  1152. for (nc = g_mgr.active_connections; nc != NULL; nc = nc->next) {
  1153. if (nc->sock != INVALID_SOCKET) {
  1154. if (nfd < 32) {
  1155. fds[nfd].fd = nc->sock;
  1156. fds[nfd].events = POLLIN | POLLOUT;
  1157. fds[nfd].revents = 0;
  1158. nfd++;
  1159. }
  1160. }
  1161. }
  1162. //if we have any file descriptors, poll them
  1163. //
  1164. if(nfd > 0) {
  1165. poll_return = poll(fds, nfd, POLL_TIMEOUT);
  1166. }
  1167. //otherwise, whistle and look busy
  1168. //
  1169. else {
  1170. // (this keeps us from buringing 100% cpu cycles if we don't have contact with either
  1171. // the IPC hub or the DIU hardware).
  1172. //
  1173. poll_return = 0;
  1174. sleep(1);
  1175. }
  1176. //--------------------------------------------------------------------------------------------------
  1177. //if poll didn't net us any work to do,
  1178. //
  1179. if(poll_return < 1) {
  1180. //lets try again
  1181. //
  1182. continue;
  1183. }
  1184. for(i = 0; i < nfd; i++) //Loop through all polled file descriptors
  1185. {
  1186. //If we're looking at the DIU...
  1187. //
  1188. if( fds[i].fd == diu_fd ) {
  1189. //if poll says our serial port has become bogus...
  1190. //
  1191. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  1192. fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
  1193. close(diu_fd);
  1194. diu_fd = -1;
  1195. break;
  1196. }
  1197. if(fds[i].revents & POLLIN) {
  1198. read_return = read(fds[i].fd, line, sizeof(line));
  1199. if(read_return > 0) {
  1200. char *trav = line;
  1201. line[read_return] = '\0';
  1202. strip_crlf(line);
  1203. //advance until EOL or we hit our start sentinel
  1204. while(*trav && (*trav != '/') ) { trav++; }
  1205. //Check to see that our address header is intact...
  1206. //
  1207. if( (trav[0] == '/') && (trav[2] == ':') ) {
  1208. switch(trav[1]) {
  1209. //-----------------------------------"/T:" means it's a touchscreen event
  1210. //
  1211. case 'T':
  1212. //advance past the header
  1213. //
  1214. trav += 3;
  1215. retval = sscanf(trav, "%x,%x,%x", &tz, &tx, &ty);
  1216. if(retval == 3) {
  1217. if(tz) {
  1218. if(down_time == 0) {
  1219. down_time = time(NULL);
  1220. }
  1221. else {
  1222. if( (time(NULL) - down_time) > TS_CALIB_HOLD_TIME) {
  1223. begin_touchscreen_calibration();
  1224. calibration = 1;
  1225. }
  1226. }
  1227. if(!calibration) {
  1228. // calibration from here turned off...
  1229. }
  1230. else {
  1231. if(advance_touchscreen_calibration(tx, ty, tz)) {
  1232. calibration = 0;
  1233. }
  1234. else {
  1235. draw_touchscreen_calibration();
  1236. }
  1237. }
  1238. }
  1239. else
  1240. {
  1241. down_time = 0;
  1242. if(!calibration) { }
  1243. else {
  1244. if(advance_touchscreen_calibration(tx, ty, tz)) {
  1245. calibration = 0;
  1246. //redraw_flag = 1;
  1247. }
  1248. else {
  1249. draw_touchscreen_calibration();
  1250. }
  1251. }
  1252. }
  1253. }
  1254. break;
  1255. //-----------------------------------"/G:" means it is a new GPS input
  1256. //
  1257. case 'G':
  1258. //advance past the header
  1259. //
  1260. trav += 3;
  1261. //If this GPS update constitutes a meaningful piece of data
  1262. //
  1263. if(update_gps(trav) > 0) {
  1264. //and we have a connection to the IPC hub
  1265. //
  1266. if(hub_fd >= 0) {
  1267. //Go and toss the data to any other modules who happen to care about GPS
  1268. //
  1269. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  1270. send_message(hub_fd, &outgoing_msg);
  1271. }
  1272. last_stale_gps_check = now; //Remember that we did a stale GPS check as part of our update.
  1273. }
  1274. break;
  1275. //handle warnings
  1276. //
  1277. case '*':
  1278. //debugs
  1279. //
  1280. case '#':
  1281. //and errors
  1282. //
  1283. case '!':
  1284. //If this DIU error/debug message has not run afoul of the rate limiting policy...
  1285. //
  1286. if( can_report_diu_error() ) {
  1287. //send them all to the log server
  1288. //
  1289. format_log_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  1290. send_message(hub_fd, &outgoing_msg);
  1291. //but in the case of errors, send them to the driver too
  1292. if(trav[1] == '!') {
  1293. format_driver_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  1294. send_message(hub_fd, &outgoing_msg);
  1295. }
  1296. }
  1297. break;
  1298. default: //ignore any message addresses that we don't know what to do with
  1299. printf("Ignoring command \"%s\"\n", trav);
  1300. break;
  1301. }
  1302. }
  1303. else {
  1304. //printf("Ignoring non-command line \"%s\"\n", trav);
  1305. }
  1306. }
  1307. else {
  1308. fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
  1309. close(diu_fd);
  1310. diu_fd = -1;
  1311. break;
  1312. }
  1313. }
  1314. }
  1315. //If we're looking at the IPC hub...
  1316. //
  1317. else if( fds[i].fd == hub_fd ) {
  1318. //if poll says our connection to the IPC hub has died...
  1319. //
  1320. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  1321. fprintf(stderr, "The connection to the IPC hub has gone away...\n");
  1322. close(hub_fd);
  1323. hub_fd = -1;
  1324. break;
  1325. }
  1326. //if we have mail in any of our mailboxes...
  1327. //
  1328. if(fds[i].revents & POLLIN) {
  1329. read_return = get_message(hub_fd, &incoming_msg);
  1330. if(read_return < 0) {
  1331. fprintf(stderr, "The connection to the IPC hub has gone away...\n");
  1332. close(hub_fd);
  1333. hub_fd = -1;
  1334. break;
  1335. }
  1336. else {
  1337. message_callback_return msg_status;
  1338. msg_status = process_message(&incoming_msg);
  1339. if (msg_status) {
  1340. //pass
  1341. }
  1342. }
  1343. }
  1344. }
  1345. else {
  1346. if (fds[i].revents & (POLLIN | POLLOUT)) {
  1347. mg_mgr_poll(&g_mgr, 10);
  1348. }
  1349. }
  1350. }
  1351. }
  1352. if(hub_fd >= 0) {
  1353. close(hub_fd);
  1354. }
  1355. if(diu_fd >= 0) {
  1356. write(diu_fd, "/C:----\r",8);
  1357. close(diu_fd);
  1358. }
  1359. return 0;
  1360. }