diu_main.c 48 KB

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