diu_main.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. while( exit_request_status == EXIT_REQUEST_NONE ) //loop until we get asked to exit...
  499. {
  500. //DEBUG
  501. printf("[%lli] diu_minder: heartbeat\n", get_usec_time());
  502. //DEBUG
  503. RESET_WATCHDOG();
  504. maintain_ipc_hub_connect(argv[0]);
  505. if(diu_fd < 0)
  506. {
  507. diu_fd = open_rs232_device(DRIVER_UI_PORT, USE_DEFAULT_BAUD, RS232_LINE);
  508. if(diu_fd < 0)
  509. {
  510. fprintf(stderr, "Cannot open serial port %s for DIU!\n", DRIVER_UI_PORT);
  511. }
  512. else
  513. {
  514. write(diu_fd, "/Q:aK\r", 6); //Turn on all messages except ACKs for sent commands
  515. }
  516. }
  517. now = time(NULL);
  518. //Every second, we want to update the DIU clock (even though it only shows minutes, this covers power events...)
  519. if((now - last_diu_clock) > 0)
  520. {
  521. if(diu_fd)
  522. {
  523. set_diu_clock(diu_fd, now);
  524. last_diu_clock = now;
  525. }
  526. //Also request a UI redraw if nothing else has, just so that status line gets redrawn
  527. redraw_flag |= 1;
  528. }
  529. //Every second we want to check to make sure that our GPS data have note gone stale...
  530. if((now - last_stale_gps_check) > 0)
  531. {
  532. // If the stale check results in an update to my_gps_stat, we must update any other
  533. // modules which may be tracking GPS status via the IPC hub.
  534. if( handle_stale_gps_condition() > 0 )
  535. {
  536. //If we have a connection to the IPC hub
  537. if(hub_fd >= 0)
  538. {
  539. //Go and toss the data to any other modules who happen to care about GPS
  540. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  541. send_message(hub_fd, &outgoing_msg);
  542. }
  543. }
  544. // Either way, remember that we did this stale check.
  545. last_stale_gps_check = now;
  546. }
  547. if(hup_request_status)
  548. {
  549. unsigned char temp_menu_checksum[MD5_DIGEST_LENGTH];
  550. hup_request_status = 0;
  551. //Go and generate a checksum of the new menu file
  552. md5_of_file(DRIVER_MENU_FILE, temp_menu_checksum);
  553. //if it differs from the old one, reload the menu file...
  554. if(memcmp(menu_checksum, temp_menu_checksum, MD5_DIGEST_LENGTH))
  555. {
  556. //Update the remembered checksum to be that of the new menu...
  557. memcpy(menu_checksum, temp_menu_checksum, MD5_DIGEST_LENGTH);
  558. //Free the old menu tree
  559. if(mt)
  560. {
  561. free_menutree(mt);
  562. mt = NULL;
  563. }
  564. //Try and load the new one...
  565. mt = load_menutree(DRIVER_MENU_FILE);
  566. //If that failed, bitch about it!
  567. if(!mt)
  568. {
  569. fprintf(stderr, "Error loading %s\n", DRIVER_MENU_FILE);
  570. return -1;
  571. }
  572. else //otherwise initialize the menu tree
  573. {
  574. if(init_menutree(mt))
  575. {
  576. fprintf(stderr, "Error initializing menu tree from %s\n", DRIVER_MENU_FILE);
  577. }
  578. redraw_flag = 1;
  579. }
  580. }
  581. }
  582. //If it is time to send out a driver status update
  583. if(update_driver_status && (hub_fd >= 0))
  584. {
  585. //do so...
  586. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  587. send_message(hub_fd, &outgoing_msg);
  588. update_driver_status = 0;
  589. }
  590. //If a paddle change request has resulted in a change
  591. if(check_paddle_request(mt))
  592. {
  593. //do a redraw of the UI
  594. redraw_flag |= 1;
  595. }
  596. //If we have to redraw the UI
  597. if(redraw_flag && !calibration)
  598. {
  599. //Redraw the menu reflecting any changes from the last touchscreen input
  600. //or other stimulus
  601. draw_menu(mt);
  602. #ifdef TOUCHSCREEN_QUIET
  603. write(diu_fd, "/Q:t\r", 5); //Un-Quiet the touch screen, now that we've responded to the user we want
  604. #endif //to hear if they have any further input to give us...
  605. redraw_flag = 0; //Clear the 'redraw required' flag
  606. }
  607. nfd = 0;
  608. if(hub_fd >= 0)
  609. {
  610. fds[nfd].fd = hub_fd;
  611. fds[nfd].events = POLLIN;
  612. fds[nfd].revents = 0;
  613. nfd++;
  614. }
  615. if(diu_fd >= 0)
  616. {
  617. fds[nfd].fd = diu_fd;
  618. fds[nfd].events = POLLIN;
  619. fds[nfd].revents = 0;
  620. nfd++;
  621. }
  622. if(nfd > 0) //if we have any file descriptors, poll them
  623. {
  624. poll_return = poll(fds, nfd, POLL_TIMEOUT);
  625. }
  626. else //otherwise, whistle and look busy
  627. {
  628. poll_return = 0; //(this keeps us from buringing 100% cpu cycles if we don't have contact with either
  629. sleep(1); //the IPC hub or the DIU hardware).
  630. }
  631. //--------------------------------------------------------------------------------------------------
  632. if(poll_return < 1) //if poll didn't net us any work to do,
  633. {
  634. continue; //lets try again
  635. }
  636. for(i = 0; i < nfd; i++) //Loop through all polled file descriptors
  637. {
  638. if( fds[i].fd == diu_fd ) //If we're looking at the DIU...
  639. {
  640. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) //if poll says our serial port has become bogus...
  641. {
  642. fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
  643. close(diu_fd); //close it
  644. diu_fd = -1; //flag it invalid
  645. break; //and break out of the for loop to allow the while to cycle
  646. }
  647. if(fds[i].revents & POLLIN)
  648. {
  649. read_return = read(fds[i].fd, line, sizeof(line));
  650. if(read_return > 0)
  651. {
  652. char *trav = line;
  653. line[read_return] = '\0';
  654. strip_crlf(line);
  655. while(*trav && (*trav != '/') ) //advance until EOL or we hit our start sentinel
  656. {
  657. trav++;
  658. }
  659. //Check to see that our address header is intact...
  660. if( (trav[0] == '/') && (trav[2] == ':') )
  661. {
  662. switch(trav[1])
  663. {
  664. case 'T': //-----------------------------------"/T:" means it's a touchscreen event
  665. trav += 3; //advance past the header
  666. retval = sscanf(trav, "%x,%x,%x", &tz, &tx, &ty);
  667. if(retval == 3)
  668. {
  669. if(tz)
  670. {
  671. if(down_time == 0)
  672. {
  673. down_time = time(NULL);
  674. }
  675. else
  676. {
  677. if( (time(NULL) - down_time) > TS_CALIB_HOLD_TIME)
  678. {
  679. begin_touchscreen_calibration();
  680. calibration = 1;
  681. }
  682. }
  683. if(!calibration)
  684. {
  685. //printf("Touch at (%d, %d)\n", translate_ts_x(tx), translate_ts_y(ty));
  686. if(process_pen(mt, translate_ts_x(tx), translate_ts_y(ty), 1) > 0)
  687. {
  688. #ifdef TOUCHSCREEN_QUIET
  689. write(diu_fd, "/Q:T\r", 5);
  690. #endif
  691. redraw_flag = 1;
  692. }
  693. }
  694. else
  695. {
  696. if(advance_touchscreen_calibration(tx, ty, tz))
  697. {
  698. calibration = 0;
  699. redraw_flag = 1;
  700. }
  701. else
  702. {
  703. draw_touchscreen_calibration();
  704. }
  705. }
  706. }
  707. else
  708. {
  709. down_time = 0;
  710. //printf("Touch Release\n");
  711. if(!calibration)
  712. {
  713. if(process_pen(mt, 0,0,0) > 0)
  714. {
  715. #ifdef TOUCHSCREEN_QUIET
  716. write(diu_fd, "/Q:T\r", 5);
  717. #endif
  718. redraw_flag = 1;
  719. }
  720. }
  721. else
  722. {
  723. if(advance_touchscreen_calibration(tx, ty, tz))
  724. {
  725. calibration = 0;
  726. redraw_flag = 1;
  727. }
  728. else
  729. {
  730. draw_touchscreen_calibration();
  731. }
  732. }
  733. }
  734. }
  735. break;
  736. case 'G': //-----------------------------------"/G:" means it is a new GPS input
  737. trav += 3; //advance past the header
  738. //If this GPS update constitutes a meaningful piece of data
  739. if(update_gps(trav) > 0)
  740. {
  741. //and we have a connection to the IPC hub
  742. if(hub_fd >= 0)
  743. {
  744. //Go and toss the data to any other modules who happen to care about GPS
  745. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  746. send_message(hub_fd, &outgoing_msg);
  747. }
  748. last_stale_gps_check = now; //Remember that we did a stale GPS check as part of our update.
  749. }
  750. break;
  751. case '*': //handle warnings
  752. case '#': //debugs
  753. case '!': //and errors
  754. //If this DIU error/debug message has not run afoul of the rate limiting policy...
  755. if( can_report_diu_error() )
  756. {
  757. format_log_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3); //send them all to the log server
  758. send_message(hub_fd, &outgoing_msg);
  759. if(trav[1] == '!') //but in the case of errors, send them to the driver too
  760. {
  761. format_driver_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  762. send_message(hub_fd, &outgoing_msg);
  763. }
  764. }
  765. break;
  766. default: //ignore any message addresses that we don't know what to do with
  767. printf("Ignoring command \"%s\"\n", trav);
  768. break;
  769. }
  770. }
  771. else
  772. {
  773. // printf("Ignoring non-command line \"%s\"\n", trav);
  774. }
  775. }
  776. else
  777. {
  778. fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
  779. close(diu_fd); //close it
  780. diu_fd = -1; //flag it invalid
  781. break; //and break out of the for loop to allow the while to cycle
  782. }
  783. }
  784. }
  785. else if( fds[i].fd == hub_fd ) //If we're looking at the IPC hub...
  786. {
  787. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) //if poll says our connection to the IPC hub has died...
  788. {
  789. fprintf(stderr, "The connection to the IPC hub has gone away...\n"); //complain
  790. close(hub_fd); //close it
  791. hub_fd = -1; //flag it dead
  792. break; //break out of the for loop
  793. }
  794. if(fds[i].revents & POLLIN) //if we have mail in any of our mailboxes...
  795. {
  796. read_return = get_message(hub_fd, &incoming_msg);
  797. if(read_return < 0)
  798. {
  799. fprintf(stderr, "The connection to the IPC hub has gone away...\n"); //complain
  800. close(hub_fd); //close it
  801. hub_fd = -1; //flag it dead
  802. break; //break out of the for loop
  803. }
  804. else
  805. {
  806. message_callback_return msg_status;
  807. msg_status = process_message(&incoming_msg);
  808. }
  809. }
  810. }
  811. }
  812. }
  813. set_color(255,255,255);
  814. cls();
  815. present_framebuffer();
  816. close_framebuffer();
  817. if(hub_fd >= 0)
  818. {
  819. close(hub_fd);
  820. }
  821. if(diu_fd >= 0)
  822. {
  823. write(diu_fd, "/C:----\r",8);
  824. close(diu_fd);
  825. }
  826. return 0;
  827. }