diu_main.c 44 KB

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