diu_main.c 48 KB

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