diu_main.c 42 KB

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