diu_main.c 47 KB

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