diu_main.c 49 KB

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