diu_main.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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 "../common/common_defs.h"
  33. #include "../commhub/commhub.h"
  34. #include "../commhub/client_utils.h"
  35. #include "fbutil.h"
  36. #include "expat-2.0.1/lib/expat.h"
  37. #include "menu.h"
  38. int diu_fd = -1;
  39. int hub_fd = -1;
  40. time_t last_hub_try = 0;
  41. time_t last_diu_clock = 0;
  42. gps_status my_gps_stat={0};
  43. time_t mkgmtime(struct tm *tm);
  44. int token_diag_serial = 0;
  45. char token_diag_string[LINE_BUFFER_SIZE] = {0};
  46. unsigned char menu_checksum[MD5_DIGEST_LENGTH];
  47. int md5_of_file(char *filename, void *result)
  48. {
  49. FILE *f = NULL;
  50. char chunk[LINE_BUFFER_SIZE]={0};
  51. int retval = 0;
  52. MD5_CTX ctx;
  53. if(!result)
  54. return -1;
  55. if(!filename)
  56. return -1;
  57. if(!MD5_Init(&ctx))
  58. {
  59. return -1;
  60. }
  61. f = fopen(filename, "rb");
  62. if(!f)
  63. {
  64. return -1;
  65. }
  66. while(1)
  67. {
  68. retval = fread(chunk, 1, LINE_BUFFER_SIZE, f);
  69. if(retval <= 0)
  70. {
  71. break;
  72. }
  73. else
  74. {
  75. MD5_Update(&ctx, chunk, retval);
  76. }
  77. }
  78. fclose(f);
  79. MD5_Final((unsigned char *)result, &ctx);
  80. return 0;
  81. }
  82. void set_diu_clock(int fd, time_t tt)
  83. {
  84. struct tm t;
  85. char buffer[16];
  86. int n;
  87. localtime_r(&tt, &t);
  88. n = sprintf(buffer, "/C:%02d%02d\r", t.tm_hour, t.tm_min);
  89. write(fd, buffer, n);
  90. }
  91. // This function takes a GPS timestamp (in gross GPS float format + gross integer date) and
  92. //makes it into a sane UTC timestamp. If we are more than MAX_GPS_CLOCK_DRIFT seconds off
  93. //from GPS time, it sets the system clock to GPS time.
  94. int handle_gps_time(float gtime, int date)
  95. {
  96. int day,month,year;
  97. int hour,min,sec,frac;
  98. int n = 0;
  99. time_t utc,now;
  100. char buffer[32] = {0};
  101. struct message_record outgoing_msg;
  102. now = time(NULL);
  103. day = month = year = 0;
  104. hour = min = sec = frac = 0;
  105. // Just to be *ahem* clear, as per NMEA standard the date is encoded DDMMYY, and the time of day
  106. // is encoded HHMMSS[.frac] where there is an optional fractional second field denoted by a decimal point.
  107. // we must be able to decode the fractional seconds field but we discard the information since it is not
  108. // reliable enough to be worth the bother.
  109. // Whoever thought that NMEA GPS should encode the time in this format ought to be shot...
  110. n = 0; //Start out with zero parsed fields
  111. // Construct and then re-parse the time from its icky format to discrete values (this should result
  112. // in at least three (possibly four) fields.
  113. sprintf(buffer,"%010.3f", gtime);
  114. n += sscanf(buffer,"%02d%02d%02d.%d", &hour, &min, &sec, &frac);
  115. //Construct and then re-parse the date from its icky format to discrete values. This should result in three fields.
  116. sprintf(buffer,"%06d", date);
  117. n += sscanf(buffer,"%02d%02d%02d", &day, &month, &year);
  118. if(n >= 6) //if we scanned at all required fields
  119. {
  120. struct tm gpstm = {0};
  121. year += GPS_DATE_CENTURY; //GPS date only uses two digits for year, so we must assume the century
  122. gpstm.tm_year = year - 1900; //tm.tm_year is based on the year 1900
  123. gpstm.tm_mon = month - 1; //January = month 0 in struct tm.tm_mon whereas January = month 1 in an NMEA GPS date.
  124. gpstm.tm_mday = day;
  125. gpstm.tm_hour = hour;
  126. gpstm.tm_min = min;
  127. gpstm.tm_sec = sec;
  128. utc = mkgmtime(&gpstm); //Go and turn the struct tm we've just populated into an utc time stamp (seconds since epoch)
  129. my_gps_stat.gpstime = utc; //Most importantly... Remember what the self-reported GPS time stamp is.
  130. // printf("%02d-%02d-%04d %02d:%02d:%02d\n",day,month,year,hour,min,sec);
  131. // printf("CALCULATED: %d\nSYSTEM : %d\n\n",(int)utc,(int)time(NULL));
  132. if(abs(utc - now) > MAX_GPS_CLOCK_DRIFT) //if we have more than MAX_GPS_CLOCK_DRIFT seconds of clock drift
  133. {
  134. struct timeval ts = {0};
  135. ts.tv_sec = utc; //Set the timeval struct to the calculated utc timestamp from the GPS unit.
  136. ts.tv_usec = 0;
  137. settimeofday(&ts, NULL); //Set the system clock from GPS time using said timeval struct.
  138. //system("/sbin/hwclock --systohc"); //Go and push the new system clock value into the hardware realtime clock chip.
  139. if( hub_fd >= 0) //If we have a valid connection to the IPC hub
  140. {
  141. //Stick a message into the diagnostic log to record the fact that we've set the system clock from GPS
  142. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "Set syatem clock from previous value (%d) to GPS time (%d).", (int)now, (int)utc );
  143. send_message(hub_fd, &outgoing_msg);
  144. }
  145. }
  146. }
  147. return 0;
  148. }
  149. #ifdef CLEAR_GPS_ON_STALE
  150. static inline void clear_stale_gps_data()
  151. {
  152. my_gps_stat.lat = my_gps_stat.lon = my_gps_stat.heading = my_gps_stat.velocity = 0;
  153. my_gps_stat.num_sats = 0;
  154. }
  155. #else
  156. static inline void clear_stale_gps_data()
  157. {
  158. }
  159. #endif
  160. static int handle_stale_gps_condition()
  161. {
  162. // This return code will be > 0 if this function generates a status change that
  163. // will then need to be communicated to other modules in the system via a message to
  164. // MAILBOX_GPS_STATUS.
  165. int return_code = 0;
  166. // This will hold the gps_good flag as it stood at the beginning of this subroutine
  167. // previous to any adjustments we make.
  168. int previous_good_flag = my_gps_stat.gps_good;
  169. int stale_time = 0;
  170. time_t now = time(NULL);
  171. stale_time = (now - my_gps_stat.stamp);
  172. // If we have entered this function with the impression that we have a valid GPS fix...
  173. if(previous_good_flag > 0)
  174. {
  175. // If it has been at least GPS_STALE_THRESHOLD seconds since the last fix
  176. if( stale_time >= GPS_STALE_THRESHOLD )
  177. {
  178. clear_stale_gps_data();
  179. my_gps_stat.gps_good = 0;
  180. return_code |= 1;
  181. }
  182. }
  183. // If we have determined that we need to declare the GPS data stale and invalid and
  184. // we have a valid connection to the IPC hub we should use that IPC hub connection to
  185. // add a note to the diagnostic log indicating that we've declared the GPS data stale.
  186. if( return_code && (hub_fd >= 0) )
  187. {
  188. struct message_record outgoing_msg;
  189. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix has been stale for %d seconds, setting GPS = NO.", stale_time);
  190. send_message(hub_fd, &outgoing_msg);
  191. }
  192. return return_code;
  193. }
  194. int update_gps(char *in)
  195. {
  196. // This will hold the number of matched variables populated by sscanf().
  197. int num = 0;
  198. // This will allow us to know if we have made a transition from an invalid
  199. // GPS fix to a valid one so that we can log this information.
  200. int previous_good_flag = my_gps_stat.gps_good;
  201. // This return code will be > 0 if this function generates a status change that
  202. // will then need to be communicated to other modules in the system via a message to
  203. // MAILBOX_GPS_STATUS.
  204. int return_code = 0;
  205. if(!strncmp(in,"$GPRMC",6))
  206. {
  207. float f1=0;
  208. char f2=0;
  209. float f3=0;
  210. char f4=0;
  211. float f5=0;
  212. char f6=0;
  213. float f7=0;
  214. float f8=0;
  215. int f9=0;
  216. float f10=0;
  217. char f11=0;
  218. 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);
  219. if(num == 11) //If we have a full GPRMC sentence we can consider setting the time
  220. {
  221. // Require at least MIN_SATS_FOR_TIME satellites to accept a new system clock value from the GPS unit.
  222. // This is to keep a crummy GPS fix from generating a bogus or unstable system time.
  223. if(my_gps_stat.num_sats >= MIN_SATS_FOR_TIME)
  224. {
  225. // Pass the time field (f1) and the date field (f9) in to the routine that sets the system clock if needed.
  226. // (this routine also stores the utc timestamp derived from the GPS date and time fields so it can be passed to
  227. // other modules that may have a need for this information).
  228. handle_gps_time(f1,f9);
  229. }
  230. }
  231. if(num > 0)
  232. {
  233. my_gps_stat.lat = f3 * ((f4 == 'N')?(1):(-1)); //update snapshot with latitude
  234. my_gps_stat.lon = f5 * ((f6 == 'E')?(1):(-1)); //longitude
  235. my_gps_stat.velocity = f7 / 1.94384449f; //meters per second (converted from knots)
  236. my_gps_stat.heading = f8; //course
  237. my_gps_stat.stamp = time(NULL); //update snapshot's staledate
  238. return_code |= 1;
  239. }
  240. }
  241. else if(!strncmp(in,"$GPGGA",6))
  242. {
  243. int f1=0;
  244. float f2=0;
  245. char f3=0;
  246. float f4=0;
  247. char f5=0;
  248. int f6=0;
  249. int f7=0;
  250. float f8=0;
  251. float f9=0;
  252. char f10=0;
  253. float f11=0;
  254. char f12=0;
  255. 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);
  256. if(num == 12)
  257. {
  258. if ( f7 >= 3 ) // require 3 satellites minimum
  259. {
  260. my_gps_stat.gps_good = f6; //store GPS valid flag in snapshot
  261. my_gps_stat.num_sats = f7; //store number of satellites in view in snapshot
  262. // Do NOT store the timestamp since we only want to remember timestamps of position
  263. // fixes and the GPGGA message is all metadata (number of satellites, fix quality, etc...).
  264. // It is worth noting that GPGGA does report altitude, but that is not a piece of information
  265. // we track because the road is where the road is, and if a bus becomes airborn we have much
  266. // bigger problems than figuring out how far off the ground it is...
  267. return_code |= 1;
  268. }
  269. }
  270. }
  271. return_code |= handle_stale_gps_condition();
  272. // If we have a connection to the IPC hub and we had previously not had a valid
  273. // GPS fix but we now do, make a note of it in the diagnostic log.
  274. if( (previous_good_flag == 0) && (my_gps_stat.gps_good != 0) && (hub_fd >= 0) )
  275. {
  276. struct message_record outgoing_msg;
  277. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix is now valid with %d satellites. Setting GPS = YES.", my_gps_stat.num_sats);
  278. send_message(hub_fd, &outgoing_msg);
  279. }
  280. return return_code;
  281. }
  282. void maintain_ipc_hub_connect(char *progname)
  283. {
  284. struct message_record outgoing_msg;
  285. if(hub_fd < 0) //if we have no connection to the IPC hub
  286. {
  287. if( (time(NULL) - last_hub_try) > HUB_RETRY_TIME ) //if we haven't tried the hub in a few seconds
  288. {
  289. last_hub_try = time(NULL); //retry it
  290. hub_fd = connect_to_message_server(progname); //try and get one
  291. if(hub_fd >= 0)
  292. {
  293. //Subscribe to the default status messages
  294. subscribe_to_default_messages(hub_fd);
  295. //Subscribe to our specific message
  296. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_DRIVER_NOTIFY, strlen(MAILBOX_DRIVER_NOTIFY));
  297. send_message(hub_fd,&outgoing_msg);
  298. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_PADDLE_ACK, strlen(MAILBOX_PADDLE_ACK));
  299. send_message(hub_fd,&outgoing_msg);
  300. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_VAULT_DROP, strlen(MAILBOX_VAULT_DROP));
  301. send_message(hub_fd,&outgoing_msg);
  302. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_MAG, strlen(MAILBOX_TOKEN_MAG));
  303. send_message(hub_fd,&outgoing_msg);
  304. prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_RFID, strlen(MAILBOX_TOKEN_RFID));
  305. send_message(hub_fd,&outgoing_msg);
  306. //Ask for a status update
  307. prepare_message(&outgoing_msg, MAILBOX_STATUS_REQUEST, "", 0);
  308. send_message(hub_fd,&outgoing_msg);
  309. }
  310. else
  311. {
  312. fprintf(stderr, "Cannot connect to IPC hub!\n");
  313. }
  314. }
  315. }
  316. }
  317. menutree *mt = NULL;
  318. int redraw_flag = 0;
  319. message_callback_return handle_status_request(struct message_record *msg, void *param)
  320. {
  321. struct message_record outgoing_msg;
  322. if(hub_fd >= 0)
  323. {
  324. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  325. send_message(hub_fd, &outgoing_msg);
  326. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  327. send_message(hub_fd, &outgoing_msg);
  328. }
  329. return MESSAGE_HANDLED_CONT;
  330. }
  331. message_callback_return handle_vault_drop(struct message_record *msg, void *param)
  332. {
  333. if(diu_fd >= 0)
  334. {
  335. write(diu_fd, "/V:\r", 4);
  336. }
  337. return MESSAGE_HANDLED_CONT;
  338. }
  339. char dup_notify_str[MAX_PAYLOAD_LENGTH] = {0};
  340. int dup_notify_count = 0;
  341. long long dup_notify_usec = 0;
  342. message_callback_return handle_driver_notify(struct message_record *msg, void *param)
  343. {
  344. int is_dup;
  345. char dup_text[MAX_PAYLOAD_LENGTH] = {0};
  346. pixel bgcolor = FBCOLOR_WHITE;
  347. pixel textcolor = FBCOLOR_BLACK;
  348. long long dup_usec_delta = 0;
  349. if(strncmp((const char *)(msg->payload), dup_notify_str, MAX_PAYLOAD_LENGTH))
  350. {
  351. dup_notify_count = 1;
  352. strncpy(dup_notify_str, (const char *)(msg->payload), MAX_PAYLOAD_LENGTH - 1);
  353. dup_notify_str[MAX_PAYLOAD_LENGTH - 1] = '\0';
  354. is_dup = 0;
  355. dup_notify_usec = 0;
  356. }
  357. else
  358. {
  359. dup_notify_count++;
  360. is_dup = 1;
  361. dup_usec_delta = get_usec_time() - dup_notify_usec;
  362. dup_notify_usec = get_usec_time();
  363. }
  364. switch(msg->payload[0])
  365. {
  366. case LOGLEVEL_EVENT:
  367. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  368. {
  369. DIU_ACK_BEEP(diu_fd);
  370. }
  371. break;
  372. case LOGLEVEL_REJECT:
  373. bgcolor = FBCOLOR_LTRED;
  374. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  375. {
  376. DIU_ERROR_BEEP(diu_fd);
  377. }
  378. break;
  379. case LOGLEVEL_ACCEPT:
  380. bgcolor = FBCOLOR_LTGREEN;
  381. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  382. {
  383. DIU_ACK_BEEP(diu_fd);
  384. }
  385. break;
  386. case LOGLEVEL_ERROR:
  387. bgcolor = FBCOLOR_RED;
  388. textcolor = FBCOLOR_CYAN;
  389. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  390. {
  391. DIU_CRITICAL_BEEP(diu_fd);
  392. }
  393. break;
  394. default:
  395. break;
  396. }
  397. if(is_dup)
  398. {
  399. snprintf(dup_text, MAX_PAYLOAD_LENGTH, "%d x %s", dup_notify_count, &msg->payload[1]);
  400. replace_diu_message(bgcolor, textcolor, dup_text);
  401. }
  402. else
  403. {
  404. add_diu_message(bgcolor, textcolor, (char *)(&(msg->payload[1])));
  405. }
  406. redraw_flag |= 1;
  407. return MESSAGE_HANDLED_CONT;
  408. }
  409. message_callback_return handle_paddle_ack(struct message_record *msg, void *param)
  410. {
  411. set_paddle_req *pr = (set_paddle_req *)msg->payload;
  412. paddle_req.result = pr->result;
  413. return MESSAGE_HANDLED_CONT;
  414. }
  415. message_callback_return handle_token_diag(struct message_record *msg, void *param)
  416. {
  417. strncpy(token_diag_string, (const char *)(msg->payload), sizeof(token_diag_string));
  418. token_diag_string[sizeof(token_diag_string) - 1] = '\0';
  419. token_diag_serial++;
  420. return MESSAGE_HANDLED_CONT;
  421. }
  422. //----------------------------------
  423. time_t diu_error_burst = 0;
  424. int diu_error_counter = 0;
  425. static inline int can_report_diu_error()
  426. {
  427. time_t now = time(NULL);
  428. //If our last potential burst lockout has expired...
  429. if( (now - diu_error_burst) >= DIU_ERROR_RATE_LIMIT)
  430. {
  431. diu_error_counter = 0; //reset our burst counter
  432. diu_error_burst = now; //and start the "potential burst" time at this message
  433. }
  434. if(diu_error_counter < DIU_ERROR_BURST_LIMIT) //if we haven't hit our burst limit...
  435. {
  436. diu_error_counter++; //count this message against our burst limit
  437. return 1; //and allow it to pass
  438. }
  439. else //if we have hit our limit
  440. {
  441. return 0; //ignore this message
  442. }
  443. }
  444. //----------------------------------
  445. int main(int argc, char **argv)
  446. {
  447. char line[LINE_BUFFER_SIZE] = {0};
  448. struct message_record incoming_msg;
  449. struct message_record outgoing_msg;
  450. struct pollfd fds[2];
  451. int nfd;
  452. int poll_return;
  453. int read_return;
  454. int i;
  455. time_t down_time = 0;
  456. int calibration = 0;
  457. time_t now;
  458. int retval = 0;
  459. int tz = 0;
  460. int tx = 0;
  461. int ty = 0;
  462. time_t last_stale_gps_check = 0;
  463. if(open_framebuffer())
  464. {
  465. fprintf(stderr,"Cannot open framebuffer!\n");
  466. }
  467. mt = load_menutree(DRIVER_MENU_FILE);
  468. if(!mt)
  469. {
  470. fprintf(stderr, "Error loading %s\n", DRIVER_MENU_FILE);
  471. return -1;
  472. }
  473. else
  474. {
  475. //Remember a checksum so we don't have to boot a logged in driver for a system-wide HUP if
  476. //the menu tree hasn't indeed changed...
  477. md5_of_file(DRIVER_MENU_FILE, menu_checksum);
  478. // print_menu_tree(mt);
  479. if(init_menutree(mt))
  480. {
  481. fprintf(stderr, "Error initializing menu tree from %s\n", DRIVER_MENU_FILE);
  482. }
  483. redraw_flag = 1;
  484. }
  485. //Configure our signal handlers to deal with SIGINT, SIGTERM, etc... and make graceful exits while logging
  486. configure_signal_handlers(argv[0]);
  487. //Make an initial attempt to get in touch with the interprocess communication hub (it may not be up yet depending on the start order)
  488. maintain_ipc_hub_connect(argv[0]);
  489. //Register our defualt system message processing callbacks
  490. register_system_status_callbacks();
  491. register_dispatch_callback(MAILBOX_STATUS_REQUEST, CALLBACK_USER(1), handle_status_request, NULL);
  492. register_dispatch_callback(MAILBOX_DRIVER_NOTIFY, CALLBACK_USER(2), handle_driver_notify, NULL);
  493. register_dispatch_callback(MAILBOX_PADDLE_ACK, CALLBACK_USER(3), handle_paddle_ack, NULL);
  494. register_dispatch_callback(MAILBOX_VAULT_DROP, CALLBACK_USER(4), handle_vault_drop, NULL);
  495. register_dispatch_callback(MAILBOX_TOKEN_MAG, CALLBACK_USER(5), handle_token_diag, NULL);
  496. register_dispatch_callback(MAILBOX_TOKEN_RFID, CALLBACK_USER(6), handle_token_diag, NULL);
  497. clear_diu_messages();
  498. // This is the main dispatch loop:
  499. //
  500. // * reset watchdog to make sure we haven't crashed/frozen
  501. // * if need be, open a connection to the DIU microcontroller, quieting all messages except for acks
  502. // * handle GPS message dispatch through IPC
  503. // * if need be, handle reload of menu.xml
  504. // * manage driver status message communication
  505. // * handle paddle change
  506. // * draw menu
  507. // * listen on the mailboxes for messages and process. This includes
  508. // - touchscreen events
  509. // - gps updates
  510. // - warning/debug/error messages
  511. //
  512. while( exit_request_status == EXIT_REQUEST_NONE ) //loop until we get asked to exit...
  513. {
  514. //DEBUG
  515. printf("[%lli] diu_minder: heartbeat\n", get_usec_time());
  516. //DEBUG
  517. RESET_WATCHDOG();
  518. maintain_ipc_hub_connect(argv[0]);
  519. if(diu_fd < 0)
  520. {
  521. diu_fd = open_rs232_device(DRIVER_UI_PORT, USE_DEFAULT_BAUD, RS232_LINE);
  522. if(diu_fd < 0)
  523. {
  524. fprintf(stderr, "Cannot open serial port %s for DIU!\n", DRIVER_UI_PORT);
  525. }
  526. else
  527. {
  528. write(diu_fd, "/Q:aK\r", 6); //Turn on all messages except ACKs for sent commands
  529. }
  530. }
  531. now = time(NULL);
  532. //Every second, we want to update the DIU clock (even though it only shows minutes, this covers power events...)
  533. if((now - last_diu_clock) > 0)
  534. {
  535. if(diu_fd)
  536. {
  537. set_diu_clock(diu_fd, now);
  538. last_diu_clock = now;
  539. }
  540. //Also request a UI redraw if nothing else has, just so that status line gets redrawn
  541. redraw_flag |= 1;
  542. }
  543. //Every second we want to check to make sure that our GPS data have note gone stale...
  544. if((now - last_stale_gps_check) > 0)
  545. {
  546. // If the stale check results in an update to my_gps_stat, we must update any other
  547. // modules which may be tracking GPS status via the IPC hub.
  548. if( handle_stale_gps_condition() > 0 )
  549. {
  550. //If we have a connection to the IPC hub
  551. if(hub_fd >= 0)
  552. {
  553. //Go and toss the data to any other modules who happen to care about GPS
  554. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  555. send_message(hub_fd, &outgoing_msg);
  556. }
  557. }
  558. // Either way, remember that we did this stale check.
  559. last_stale_gps_check = now;
  560. }
  561. if(hup_request_status)
  562. {
  563. unsigned char temp_menu_checksum[MD5_DIGEST_LENGTH];
  564. hup_request_status = 0;
  565. //Go and generate a checksum of the new menu file
  566. md5_of_file(DRIVER_MENU_FILE, temp_menu_checksum);
  567. //if it differs from the old one, reload the menu file...
  568. if(memcmp(menu_checksum, temp_menu_checksum, MD5_DIGEST_LENGTH))
  569. {
  570. //Update the remembered checksum to be that of the new menu...
  571. memcpy(menu_checksum, temp_menu_checksum, MD5_DIGEST_LENGTH);
  572. //Free the old menu tree
  573. if(mt)
  574. {
  575. free_menutree(mt);
  576. mt = NULL;
  577. }
  578. //Try and load the new one...
  579. mt = load_menutree(DRIVER_MENU_FILE);
  580. //If that failed, bitch about it!
  581. if(!mt)
  582. {
  583. fprintf(stderr, "Error loading %s\n", DRIVER_MENU_FILE);
  584. return -1;
  585. }
  586. else //otherwise initialize the menu tree
  587. {
  588. if(init_menutree(mt))
  589. {
  590. fprintf(stderr, "Error initializing menu tree from %s\n", DRIVER_MENU_FILE);
  591. }
  592. redraw_flag = 1;
  593. }
  594. }
  595. }
  596. //If it is time to send out a driver status update
  597. if(update_driver_status && (hub_fd >= 0))
  598. {
  599. //do so...
  600. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  601. send_message(hub_fd, &outgoing_msg);
  602. update_driver_status = 0;
  603. }
  604. //If a paddle change request has resulted in a change
  605. if(check_paddle_request(mt))
  606. {
  607. //do a redraw of the UI
  608. redraw_flag |= 1;
  609. }
  610. //If we have to redraw the UI
  611. if(redraw_flag && !calibration)
  612. {
  613. //Redraw the menu reflecting any changes from the last touchscreen input
  614. //or other stimulus
  615. draw_menu(mt);
  616. #ifdef TOUCHSCREEN_QUIET
  617. write(diu_fd, "/Q:t\r", 5); //Un-Quiet the touch screen, now that we've responded to the user we want
  618. #endif //to hear if they have any further input to give us...
  619. redraw_flag = 0; //Clear the 'redraw required' flag
  620. }
  621. nfd = 0;
  622. if(hub_fd >= 0)
  623. {
  624. fds[nfd].fd = hub_fd;
  625. fds[nfd].events = POLLIN;
  626. fds[nfd].revents = 0;
  627. nfd++;
  628. }
  629. if(diu_fd >= 0)
  630. {
  631. fds[nfd].fd = diu_fd;
  632. fds[nfd].events = POLLIN;
  633. fds[nfd].revents = 0;
  634. nfd++;
  635. }
  636. for (int i=0; i<nfd; i++) {
  637. printf("[%i] %i\n", i, (int)fds[nfd].fd);
  638. }
  639. printf("\n\n");
  640. if(nfd > 0) //if we have any file descriptors, poll them
  641. {
  642. poll_return = poll(fds, nfd, POLL_TIMEOUT);
  643. }
  644. else //otherwise, whistle and look busy
  645. {
  646. poll_return = 0; //(this keeps us from buringing 100% cpu cycles if we don't have contact with either
  647. sleep(1); //the IPC hub or the DIU hardware).
  648. }
  649. //--------------------------------------------------------------------------------------------------
  650. if(poll_return < 1) //if poll didn't net us any work to do,
  651. {
  652. continue; //lets try again
  653. }
  654. for(i = 0; i < nfd; i++) //Loop through all polled file descriptors
  655. {
  656. if( fds[i].fd == diu_fd ) //If we're looking at the DIU...
  657. {
  658. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) //if poll says our serial port has become bogus...
  659. {
  660. fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
  661. close(diu_fd); //close it
  662. diu_fd = -1; //flag it invalid
  663. break; //and break out of the for loop to allow the while to cycle
  664. }
  665. if(fds[i].revents & POLLIN)
  666. {
  667. read_return = read(fds[i].fd, line, sizeof(line));
  668. if(read_return > 0)
  669. {
  670. char *trav = line;
  671. line[read_return] = '\0';
  672. strip_crlf(line);
  673. while(*trav && (*trav != '/') ) //advance until EOL or we hit our start sentinel
  674. {
  675. trav++;
  676. }
  677. //Check to see that our address header is intact...
  678. if( (trav[0] == '/') && (trav[2] == ':') )
  679. {
  680. switch(trav[1])
  681. {
  682. case 'T': //-----------------------------------"/T:" means it's a touchscreen event
  683. trav += 3; //advance past the header
  684. retval = sscanf(trav, "%x,%x,%x", &tz, &tx, &ty);
  685. if(retval == 3)
  686. {
  687. if(tz)
  688. {
  689. if(down_time == 0)
  690. {
  691. down_time = time(NULL);
  692. }
  693. else
  694. {
  695. if( (time(NULL) - down_time) > TS_CALIB_HOLD_TIME)
  696. {
  697. begin_touchscreen_calibration();
  698. calibration = 1;
  699. }
  700. }
  701. if(!calibration)
  702. {
  703. //printf("Touch at (%d, %d)\n", translate_ts_x(tx), translate_ts_y(ty));
  704. if(process_pen(mt, translate_ts_x(tx), translate_ts_y(ty), 1) > 0)
  705. {
  706. #ifdef TOUCHSCREEN_QUIET
  707. write(diu_fd, "/Q:T\r", 5);
  708. #endif
  709. redraw_flag = 1;
  710. }
  711. }
  712. else
  713. {
  714. if(advance_touchscreen_calibration(tx, ty, tz))
  715. {
  716. calibration = 0;
  717. redraw_flag = 1;
  718. }
  719. else
  720. {
  721. draw_touchscreen_calibration();
  722. }
  723. }
  724. }
  725. else
  726. {
  727. down_time = 0;
  728. //printf("Touch Release\n");
  729. if(!calibration)
  730. {
  731. if(process_pen(mt, 0,0,0) > 0)
  732. {
  733. #ifdef TOUCHSCREEN_QUIET
  734. write(diu_fd, "/Q:T\r", 5);
  735. #endif
  736. redraw_flag = 1;
  737. }
  738. }
  739. else
  740. {
  741. if(advance_touchscreen_calibration(tx, ty, tz))
  742. {
  743. calibration = 0;
  744. redraw_flag = 1;
  745. }
  746. else
  747. {
  748. draw_touchscreen_calibration();
  749. }
  750. }
  751. }
  752. }
  753. break;
  754. case 'G': //-----------------------------------"/G:" means it is a new GPS input
  755. trav += 3; //advance past the header
  756. //If this GPS update constitutes a meaningful piece of data
  757. if(update_gps(trav) > 0)
  758. {
  759. //and we have a connection to the IPC hub
  760. if(hub_fd >= 0)
  761. {
  762. //Go and toss the data to any other modules who happen to care about GPS
  763. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  764. send_message(hub_fd, &outgoing_msg);
  765. }
  766. last_stale_gps_check = now; //Remember that we did a stale GPS check as part of our update.
  767. }
  768. break;
  769. case '*': //handle warnings
  770. case '#': //debugs
  771. case '!': //and errors
  772. //If this DIU error/debug message has not run afoul of the rate limiting policy...
  773. if( can_report_diu_error() )
  774. {
  775. format_log_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3); //send them all to the log server
  776. send_message(hub_fd, &outgoing_msg);
  777. if(trav[1] == '!') //but in the case of errors, send them to the driver too
  778. {
  779. format_driver_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  780. send_message(hub_fd, &outgoing_msg);
  781. }
  782. }
  783. break;
  784. default: //ignore any message addresses that we don't know what to do with
  785. printf("Ignoring command \"%s\"\n", trav);
  786. break;
  787. }
  788. }
  789. else
  790. {
  791. // printf("Ignoring non-command line \"%s\"\n", trav);
  792. }
  793. }
  794. else
  795. {
  796. fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
  797. close(diu_fd); //close it
  798. diu_fd = -1; //flag it invalid
  799. break; //and break out of the for loop to allow the while to cycle
  800. }
  801. }
  802. }
  803. else if( fds[i].fd == hub_fd ) //If we're looking at the IPC hub...
  804. {
  805. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) //if poll says our connection to the IPC hub has died...
  806. {
  807. fprintf(stderr, "The connection to the IPC hub has gone away...\n"); //complain
  808. close(hub_fd); //close it
  809. hub_fd = -1; //flag it dead
  810. break; //break out of the for loop
  811. }
  812. if(fds[i].revents & POLLIN) //if we have mail in any of our mailboxes...
  813. {
  814. read_return = get_message(hub_fd, &incoming_msg);
  815. if(read_return < 0)
  816. {
  817. fprintf(stderr, "The connection to the IPC hub has gone away...\n"); //complain
  818. close(hub_fd); //close it
  819. hub_fd = -1; //flag it dead
  820. break; //break out of the for loop
  821. }
  822. else
  823. {
  824. message_callback_return msg_status;
  825. msg_status = process_message(&incoming_msg);
  826. }
  827. }
  828. }
  829. }
  830. }
  831. set_color(255,255,255);
  832. cls();
  833. present_framebuffer();
  834. close_framebuffer();
  835. if(hub_fd >= 0)
  836. {
  837. close(hub_fd);
  838. }
  839. if(diu_fd >= 0)
  840. {
  841. write(diu_fd, "/C:----\r",8);
  842. close(diu_fd);
  843. }
  844. return 0;
  845. }