diu_main.c 41 KB

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