diu_main.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  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. {
  373. struct message_record outgoing_msg;
  374. if(hub_fd >= 0)
  375. {
  376. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  377. send_message(hub_fd, &outgoing_msg);
  378. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  379. send_message(hub_fd, &outgoing_msg);
  380. }
  381. return MESSAGE_HANDLED_CONT;
  382. }
  383. message_callback_return handle_vault_drop(struct message_record *msg, void *param)
  384. {
  385. if(diu_fd >= 0)
  386. {
  387. write(diu_fd, "/V:\r", 4);
  388. }
  389. return MESSAGE_HANDLED_CONT;
  390. }
  391. char dup_notify_str[MAX_PAYLOAD_LENGTH] = {0};
  392. int dup_notify_count = 0;
  393. long long dup_notify_usec = 0;
  394. message_callback_return handle_driver_notify(struct message_record *msg, void *param)
  395. {
  396. int is_dup;
  397. char _text[MAX_PAYLOAD_LENGTH] = {0};
  398. //pixel bgcolor = FBCOLOR_WHITE;
  399. //pixel textcolor = FBCOLOR_BLACK;
  400. long long dup_usec_delta = 0;
  401. if(strncmp((const char *)(msg->payload), dup_notify_str, MAX_PAYLOAD_LENGTH))
  402. {
  403. dup_notify_count = 1;
  404. strncpy(dup_notify_str, (const char *)(msg->payload), MAX_PAYLOAD_LENGTH - 1);
  405. dup_notify_str[MAX_PAYLOAD_LENGTH - 1] = '\0';
  406. is_dup = 0;
  407. dup_notify_usec = 0;
  408. }
  409. else
  410. {
  411. dup_notify_count++;
  412. is_dup = 1;
  413. dup_usec_delta = get_usec_time() - dup_notify_usec;
  414. dup_notify_usec = get_usec_time();
  415. }
  416. switch(msg->payload[0])
  417. {
  418. case LOGLEVEL_EVENT:
  419. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  420. {
  421. DIU_ACK_BEEP(diu_fd);
  422. }
  423. break;
  424. case LOGLEVEL_REJECT:
  425. //bgcolor = FBCOLOR_LTRED;
  426. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  427. {
  428. DIU_ERROR_BEEP(diu_fd);
  429. }
  430. break;
  431. case LOGLEVEL_ACCEPT:
  432. //bgcolor = FBCOLOR_LTGREEN;
  433. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  434. {
  435. DIU_ACK_BEEP(diu_fd);
  436. }
  437. break;
  438. case LOGLEVEL_ERROR:
  439. //bgcolor = FBCOLOR_RED;
  440. //textcolor = FBCOLOR_CYAN;
  441. if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
  442. {
  443. DIU_CRITICAL_BEEP(diu_fd);
  444. }
  445. break;
  446. default:
  447. break;
  448. }
  449. //DEBUG
  450. printf("driver_notify: %s\n", (char *)(&(msg->payload[1])));
  451. if(is_dup)
  452. {
  453. //snprintf(dup_text, MAX_PAYLOAD_LENGTH, "%d x %s", dup_notify_count, &msg->payload[1]);
  454. //replace_diu_message(bgcolor, textcolor, dup_text);
  455. snprintf(_text, MAX_PAYLOAD_LENGTH, "driver_notify replace %s %s %d x %s", "white", "black", dup_notify_count, &msg->payload[1]);
  456. ws_send(&g_mgr, _text);
  457. }
  458. else
  459. {
  460. //add_diu_message(bgcolor, textcolor, (char *)(&(msg->payload[1])));
  461. snprintf(_text, MAX_PAYLOAD_LENGTH, "driver_notify ok %s %s %d x %s", "white", "black", dup_notify_count, &msg->payload[1]);
  462. ws_send(&g_mgr, _text);
  463. }
  464. //redraw_flag |= 1;
  465. return MESSAGE_HANDLED_CONT;
  466. }
  467. message_callback_return handle_paddle_ack(struct message_record *msg, void *param) {
  468. set_paddle_req *pr = (set_paddle_req *)msg->payload;
  469. paddle_req.result = pr->result;
  470. return MESSAGE_HANDLED_CONT;
  471. }
  472. message_callback_return handle_token_diag(struct message_record *msg, void *param) {
  473. strncpy(token_diag_string, (const char *)(msg->payload), sizeof(token_diag_string));
  474. token_diag_string[sizeof(token_diag_string) - 1] = '\0';
  475. token_diag_serial++;
  476. return MESSAGE_HANDLED_CONT;
  477. }
  478. //----------------------------------
  479. time_t diu_error_burst = 0;
  480. int diu_error_counter = 0;
  481. static inline int can_report_diu_error()
  482. {
  483. time_t now = time(NULL);
  484. //If our last potential burst lockout has expired...
  485. if( (now - diu_error_burst) >= DIU_ERROR_RATE_LIMIT)
  486. {
  487. diu_error_counter = 0; //reset our burst counter
  488. diu_error_burst = now; //and start the "potential burst" time at this message
  489. }
  490. if(diu_error_counter < DIU_ERROR_BURST_LIMIT) //if we haven't hit our burst limit...
  491. {
  492. diu_error_counter++; //count this message against our burst limit
  493. return 1; //and allow it to pass
  494. }
  495. else //if we have hit our limit
  496. {
  497. return 0; //ignore this message
  498. }
  499. }
  500. //----------------------------------
  501. //-------- web server functions ----
  502. /*
  503. static void send_ws_heartbeat(struct mg_connection *nc) {
  504. int n;
  505. char buf[_SLEN];
  506. struct mg_connection *c;
  507. for (c=mg_next(nc->mgr, NULL); c ; c = mg_next(nc->mgr, c)) {
  508. if (c==nc) { continue; }
  509. if (!is_websocket(c)) { continue; }
  510. printf("...\n");
  511. snprintf(buf, _SLEN, "hello");
  512. n = strlen(buf);
  513. mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, buf, n);
  514. }
  515. }
  516. */
  517. static void process_ws_message(struct websocket_message *ws_msg) {
  518. int i;
  519. char *data;
  520. data = (char *)(ws_msg->data);
  521. printf("#ws, got(%i)\n:", (int)(ws_msg->size));
  522. for (i=0; i<ws_msg->size; i++) {
  523. printf("%c", data[i]);
  524. }
  525. printf("\n");
  526. }
  527. #define MAX_PKGS (16)
  528. //
  529. // ui wants status information
  530. //
  531. static void ui_handle_status_input(struct mg_connection *nc, struct http_message *hm) {
  532. int i, npkgs, npkgnet=0;
  533. char buf[4*_SLEN],
  534. pkgnetline[_SLEN],
  535. _str[_SLEN];
  536. char date_str[32];
  537. time_t t;
  538. struct tm tm, pkgtime;
  539. FILE *fp;
  540. package_signature pkgs[MAX_PKGS];
  541. t = time(NULL);
  542. localtime_r(&t, &tm);
  543. strftime(date_str, 32, "%Y-%m-%d", &tm);
  544. pkgnetline[0] = '\0';
  545. npkgs = find_packages(pkgs,MAX_PKGS);
  546. for (i=0; i<npkgs; i++) {
  547. localtime_r(&pkgs[i].installed, &pkgtime);
  548. snprintf(_str, _SLEN, "pkg%i=%s %s %02d/%02d/%02d %02d:%02d:%02d",
  549. i,
  550. pkgs[i].pkgname, pkgs[i].pkgver,
  551. pkgtime.tm_mon + 1, pkgtime.tm_mday, pkgtime.tm_year + 1900,
  552. pkgtime.tm_hour, pkgtime.tm_min, pkgtime.tm_sec);
  553. _strnncat(pkgnetline, "|", _SLEN);
  554. _strnncat(pkgnetline, _str, _SLEN);
  555. npkgnet++;
  556. }
  557. fp = fopen("/tmp/net_ids", "rb");
  558. if (fp) {
  559. i=0;
  560. while (fgets(_str, _SLEN, fp)) {
  561. strip_crlf(_str);
  562. _strnncat(pkgnetline, "|", _SLEN);
  563. _strnncat(pkgnetline, _str, _SLEN);
  564. npkgnet++;
  565. }
  566. fclose(fp);
  567. }
  568. snprintf(buf, 4*_SLEN, "ok msg=status\n"
  569. "equipno=%d|"
  570. "route=%d|"
  571. "trip=%d|"
  572. "stop=%d|"
  573. "gps=%i|"
  574. "tunnel=%i|"
  575. "gprs=%i|"
  576. "date=%s|"
  577. "nmsg=%d|"
  578. "last_token=%d"
  579. "%s",
  580. get_equip_num(),
  581. stop_stat.route,
  582. stop_stat.trip,
  583. stop_stat.stop,
  584. gps_stat.gps_good,
  585. tunnel_is_up(),
  586. gprs_is_up(),
  587. date_str,
  588. bill_stat.unsynced_messages,
  589. token_diag_serial % 100,
  590. pkgnetline);
  591. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  592. (unsigned long)strlen(buf), buf);
  593. }
  594. // driver logout
  595. //
  596. static void ui_handle_logout_input(struct mg_connection *nc, struct http_message *hm) {
  597. char msg[][_SLEN] = {
  598. "fail error",
  599. "ok .",
  600. };
  601. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  602. (unsigned long)strlen(msg[1]), msg[1]);
  603. }
  604. // (manual) next stop pressed
  605. //
  606. static void ui_handle_nextstop_input(struct mg_connection *nc, struct http_message *hm) {
  607. char msg[][_SLEN] = {
  608. "fail error",
  609. "ok .",
  610. };
  611. action_nextstop();
  612. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  613. (unsigned long)strlen(msg[1]), msg[1]);
  614. }
  615. // (manual) previous stop pressed
  616. //
  617. static void ui_handle_prevstop_input(struct mg_connection *nc, struct http_message *hm) {
  618. char msg[][_SLEN] = {
  619. "fail error",
  620. "ok .",
  621. };
  622. action_prevstop();
  623. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  624. (unsigned long)strlen(msg[1]), msg[1]);
  625. }
  626. // generic fare input
  627. //
  628. static void ui_handle_fare_input(struct mg_connection *nc, struct http_message *hm) {
  629. int ret;
  630. char s_rule[_SLEN], s_param[_SLEN];
  631. char msg_ok[] = "ok .";
  632. driver_rulecall dr = {{0}};
  633. struct message_record outgoing;
  634. ret = mg_get_http_var(&(hm->body), "rule", s_rule, _SLEN);
  635. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  636. printf("got rule '%s'\n", s_rule);
  637. ret = mg_get_http_var(&(hm->body), "param", s_param, _SLEN);
  638. //if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  639. if (ret<=0) { s_param[0] = '\0'; }
  640. printf("got param '%s'\n", s_param);
  641. if (hub_fd >= 0) {
  642. strncpy(dr.rulename, s_rule, DRIVER_RULECALL_LEN - 1);
  643. strncpy(dr.ruleparam, s_param, DRIVER_RULECALL_LEN - 1);
  644. prepare_message(&outgoing, MAILBOX_RULE_CALL, &dr, sizeof(dr));
  645. send_message(hub_fd, &outgoing);
  646. }
  647. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  648. (unsigned long)strlen(msg_ok), msg_ok);
  649. }
  650. // driver paddle (route) input
  651. //
  652. static void ui_handle_paddle_input(struct mg_connection *nc, struct http_message *hm) {
  653. int ret;
  654. char s_paddle[_SLEN];
  655. //char msg_fail[] = "fail .";
  656. char msg_ok[] = "ok .";
  657. int ipaddle;
  658. ret = mg_get_http_var(&(hm->body), "paddle", s_paddle, _SLEN);
  659. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  660. //DEBUG
  661. printf("#got paddle %s\n", s_paddle);
  662. ipaddle = atoi(s_paddle);
  663. make_paddle_request(ipaddle);
  664. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  665. (unsigned long)strlen(msg_ok), msg_ok);
  666. }
  667. // driver login
  668. //
  669. static void ui_handle_driver_login(struct mg_connection *nc, struct http_message *hm) {
  670. int ret;
  671. char s_driver[_SLEN], s_pin[_SLEN];
  672. int idrv=-1;
  673. char msg_fail[] = "fail driver_login";
  674. char msg_success[] = "ok driver";
  675. ret = mg_get_http_var(&(hm->body), "driver", s_driver, _SLEN);
  676. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  677. ret = mg_get_http_var(&(hm->body), "pin", s_pin, _SLEN);
  678. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  679. idrv = atoi(s_driver);
  680. ret = driver_login(idrv, s_pin);
  681. if (ret!=0) {
  682. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  683. (unsigned long)strlen(msg_fail), msg_fail);
  684. return;
  685. }
  686. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  687. (unsigned long)strlen(msg_success), msg_success);
  688. }
  689. // api point
  690. //
  691. static void api_handle_req(struct mg_connection *nc, struct http_message *hm) {
  692. int ret;
  693. char s_action[_SLEN];
  694. ret = mg_get_http_var(&(hm->body), "action", s_action, _SLEN);
  695. if (ret==0) {
  696. //printf(">>> %p\n", s_action);
  697. mg_http_send_error(nc, 404, NULL);
  698. return;
  699. }
  700. printf("#req: action: (%s)\n", s_action);
  701. if (strncmp(s_action, "driverlogin", strlen("driverlogin"))==0) {
  702. ui_handle_driver_login(nc, hm);
  703. }
  704. else if (strncmp(s_action, "paddleinput", strlen("paddleinput"))==0) {
  705. ui_handle_paddle_input(nc, hm);
  706. }
  707. else if (strncmp(s_action, "prevstop", strlen("prevstop"))==0) {
  708. ui_handle_prevstop_input(nc, hm);
  709. }
  710. else if (strncmp(s_action, "nextstop", strlen("nextstop"))==0) {
  711. ui_handle_nextstop_input(nc, hm);
  712. }
  713. else if (strncmp(s_action, "status", strlen("status"))==0) {
  714. ui_handle_status_input(nc, hm);
  715. }
  716. else if (strncmp(s_action, "logout", strlen("logout"))==0) {
  717. ui_handle_logout_input(nc, hm);
  718. }
  719. else if (strncmp(s_action, "fare", strlen("fare"))==0) {
  720. ui_handle_fare_input(nc, hm);
  721. }
  722. else {
  723. mg_http_send_error(nc, 404, NULL);
  724. }
  725. }
  726. static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  727. struct http_message *hm = (struct http_message *) ev_data;
  728. char buf[1024];
  729. int debug_print = 0;
  730. if (debug_print) {
  731. mg_sock_addr_to_str(&(nc->sa), buf, 1023, MG_SOCK_STRINGIFY_IP);
  732. printf("%s\n", buf);
  733. }
  734. switch (ev){
  735. case MG_EV_HTTP_REQUEST:
  736. printf("http request\n");
  737. if (mg_vcmp(&hm->uri, "/req")==0) {
  738. api_handle_req(nc, (struct http_message *)ev_data);
  739. }
  740. else {
  741. mg_serve_http(nc, (struct http_message *) ev_data, s_http_server_opts);
  742. }
  743. break;
  744. case MG_EV_WEBSOCKET_HANDSHAKE_DONE:
  745. //DEBUG
  746. printf("ws handshake done\n");
  747. break;
  748. case MG_EV_WEBSOCKET_FRAME:
  749. //DEBUG
  750. printf("ws frame\n");
  751. process_ws_message((struct websocket_message *)ev_data);
  752. break;
  753. case MG_EV_CLOSE:
  754. if (is_websocket(nc)) {
  755. //DEBUG
  756. printf("ws closed\n");
  757. }
  758. break;
  759. default:
  760. //printf("? %i\n", ev);
  761. break;
  762. }
  763. }
  764. //DEBUG
  765. void _test_ws(struct mg_mgr *mgr) {
  766. struct mg_connection *conn;
  767. char buf[_SLEN];
  768. snprintf(buf, _SLEN, "test message");
  769. for (conn = mg_next(mgr, NULL); conn; conn = mg_next(mgr, conn)) {
  770. if (!is_websocket(conn)) { continue; }
  771. mg_send_websocket_frame(conn, WEBSOCKET_OP_TEXT, buf, strlen(buf));
  772. }
  773. }
  774. //-------- web server functions ----
  775. int main(int argc, char **argv) {
  776. char line[LINE_BUFFER_SIZE] = {0};
  777. struct message_record incoming_msg;
  778. struct message_record outgoing_msg;
  779. struct pollfd fds[32];
  780. int nfd=0;
  781. int poll_return;
  782. int read_return;
  783. int i;
  784. time_t down_time = 0;
  785. int calibration = 0;
  786. time_t now;
  787. int retval = 0;
  788. int tz = 0;
  789. int tx = 0;
  790. int ty = 0;
  791. time_t last_stale_gps_check = 0;
  792. long long int _usec_now, _usec_prv, _usec_del;
  793. _usec_del = 1000000;
  794. // setup mongoose web server
  795. //
  796. struct mg_connection *nc;
  797. mg_mgr_init(&g_mgr, NULL);
  798. nc = mg_bind(&g_mgr, s_http_port, ev_handler);
  799. if (!nc) {
  800. printf("failed to create listener\n");
  801. return 1;
  802. }
  803. mg_set_protocol_http_websocket(nc);
  804. s_http_server_opts.document_root = CONFIG_FILE_PATH "/html";
  805. s_http_server_opts.enable_directory_listing = "no";
  806. // Configure our signal handlers to deal with SIGINT, SIGTERM, etc... and make graceful exits while logging
  807. //
  808. configure_signal_handlers(argv[0]);
  809. // Make an initial attempt to get in touch with the interprocess communication hub (it may not be up yet depending on the start order)
  810. //
  811. maintain_ipc_hub_connect(argv[0]);
  812. // Register our defualt system message processing callbacks
  813. //
  814. register_system_status_callbacks();
  815. register_dispatch_callback(MAILBOX_STATUS_REQUEST, CALLBACK_USER(1), handle_status_request, NULL);
  816. register_dispatch_callback(MAILBOX_DRIVER_NOTIFY, CALLBACK_USER(2), handle_driver_notify, NULL);
  817. register_dispatch_callback(MAILBOX_PADDLE_ACK, CALLBACK_USER(3), handle_paddle_ack, NULL);
  818. register_dispatch_callback(MAILBOX_VAULT_DROP, CALLBACK_USER(4), handle_vault_drop, NULL);
  819. register_dispatch_callback(MAILBOX_TOKEN_MAG, CALLBACK_USER(5), handle_token_diag, NULL);
  820. register_dispatch_callback(MAILBOX_TOKEN_RFID, CALLBACK_USER(6), handle_token_diag, NULL);
  821. clear_diu_messages();
  822. _usec_now = get_usec_time();
  823. _usec_prv = _usec_now;
  824. // This is the main dispatch loop:
  825. //
  826. // * reset watchdog to make sure we haven't crashed/frozen
  827. // * if need be, open a connection to the DIU microcontroller, quieting all messages except for acks
  828. // * handle GPS message dispatch through IPC
  829. // * if need be, handle reload of menu.xml
  830. // * manage driver status message communication
  831. // * handle paddle change
  832. // * draw menu
  833. // * listen on the mailboxes for messages and process. This includes
  834. // - touchscreen events
  835. // - gps updates
  836. // - warning/debug/error messages
  837. //
  838. //loop until we get asked to exit.../
  839. //
  840. while( exit_request_status == EXIT_REQUEST_NONE ) {
  841. _usec_now = get_usec_time();
  842. if ((_usec_now - _usec_prv) > _usec_del) {
  843. //DEBUG
  844. printf("[%lli] diu_minder: heartbeat\n", get_usec_time());
  845. //DEBUG
  846. _usec_prv = _usec_now;
  847. //_test_ws(&mgr);
  848. }
  849. RESET_WATCHDOG();
  850. maintain_ipc_hub_connect(argv[0]);
  851. if(diu_fd < 0) {
  852. diu_fd = open_rs232_device(DRIVER_UI_PORT, USE_DEFAULT_BAUD, RS232_LINE);
  853. if(diu_fd < 0) {
  854. //fprintf(stderr, "Cannot open serial port %s for DIU!\n", DRIVER_UI_PORT);
  855. }
  856. else {
  857. write(diu_fd, "/Q:aK\r", 6); //Turn on all messages except ACKs for sent commands
  858. }
  859. }
  860. now = time(NULL);
  861. //Every second, we want to update the DIU clock (even though it only shows minutes, this covers power events...)
  862. //
  863. if((now - last_diu_clock) > 0) {
  864. if(diu_fd) {
  865. set_diu_clock(diu_fd, now);
  866. last_diu_clock = now;
  867. }
  868. // Also request a UI redraw if nothing else has, just so that status line gets redrawn
  869. //
  870. //redraw_flag |= 1;
  871. }
  872. //Every second we want to check to make sure that our GPS data have note gone stale...
  873. //
  874. if((now - last_stale_gps_check) > 0) {
  875. // If the stale check results in an update to my_gps_stat, we must update any other
  876. // modules which may be tracking GPS status via the IPC hub.
  877. //
  878. if( handle_stale_gps_condition() > 0 ) {
  879. // If we have a connection to the IPC hub
  880. //
  881. if(hub_fd >= 0) {
  882. //Go and toss the data to any other modules who happen to care about GPS
  883. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  884. send_message(hub_fd, &outgoing_msg);
  885. }
  886. }
  887. // Either way, remember that we did this stale check.
  888. //
  889. last_stale_gps_check = now;
  890. }
  891. if(hup_request_status) {
  892. //unsigned char temp_menu_checksum[MD5_DIGEST_LENGTH];
  893. hup_request_status = 0;
  894. // reserve ui if necssary ...
  895. //
  896. }
  897. //If it is time to send out a driver status update
  898. //
  899. if(update_driver_status && (hub_fd >= 0)) {
  900. //do so...
  901. //
  902. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  903. send_message(hub_fd, &outgoing_msg);
  904. update_driver_status = 0;
  905. }
  906. //If a paddle change request has resulted in a change
  907. //if(check_paddle_request(mt))
  908. //
  909. if(check_paddle_request()) {
  910. //do a redraw of the UI
  911. //redraw_flag |= 1;
  912. }
  913. //If we have to redraw the UI
  914. //if(redraw_flag && !calibration)
  915. //
  916. if(!calibration) {
  917. //Redraw the menu reflecting any changes from the last touchscreen input
  918. //or other stimulus
  919. //draw_menu(mt);
  920. //
  921. #ifdef TOUCHSCREEN_QUIET
  922. write(diu_fd, "/Q:t\r", 5); //Un-Quiet the touch screen, now that we've responded to the user we want
  923. #endif //to hear if they have any further input to give us...
  924. //redraw_flag = 0; //Clear the 'redraw required' flag
  925. }
  926. nfd = 0;
  927. if(hub_fd >= 0) {
  928. fds[nfd].fd = hub_fd;
  929. fds[nfd].events = POLLIN;
  930. fds[nfd].revents = 0;
  931. nfd++;
  932. }
  933. if(diu_fd >= 0) {
  934. fds[nfd].fd = diu_fd;
  935. fds[nfd].events = POLLIN;
  936. fds[nfd].revents = 0;
  937. nfd++;
  938. }
  939. // experimental
  940. //
  941. //for (nc = mgr.active_connections; nc != NULL; nc = nc->next) {
  942. for (nc = g_mgr.active_connections; nc != NULL; nc = nc->next) {
  943. if (nc->sock != INVALID_SOCKET) {
  944. if (nfd < 32) {
  945. fds[nfd].fd = nc->sock;
  946. fds[nfd].events = POLLIN | POLLOUT;
  947. fds[nfd].revents = 0;
  948. nfd++;
  949. }
  950. }
  951. }
  952. //printf("nfd %i\n", nfd);
  953. //if we have any file descriptors, poll them
  954. //
  955. if(nfd > 0) {
  956. poll_return = poll(fds, nfd, POLL_TIMEOUT);
  957. }
  958. //otherwise, whistle and look busy
  959. //
  960. else {
  961. // (this keeps us from buringing 100% cpu cycles if we don't have contact with either
  962. // the IPC hub or the DIU hardware).
  963. //
  964. poll_return = 0;
  965. sleep(1);
  966. }
  967. //--------------------------------------------------------------------------------------------------
  968. //if poll didn't net us any work to do,
  969. //
  970. if(poll_return < 1) {
  971. //lets try again
  972. //
  973. continue;
  974. }
  975. for(i = 0; i < nfd; i++) //Loop through all polled file descriptors
  976. {
  977. //If we're looking at the DIU...
  978. //
  979. if( fds[i].fd == diu_fd ) {
  980. //DEBUG
  981. printf("##diu_fd\n");
  982. //if poll says our serial port has become bogus...
  983. //
  984. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  985. fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
  986. close(diu_fd);
  987. diu_fd = -1;
  988. break;
  989. }
  990. if(fds[i].revents & POLLIN) {
  991. read_return = read(fds[i].fd, line, sizeof(line));
  992. if(read_return > 0) {
  993. char *trav = line;
  994. line[read_return] = '\0';
  995. strip_crlf(line);
  996. //advance until EOL or we hit our start sentinel
  997. while(*trav && (*trav != '/') ) { trav++; }
  998. //Check to see that our address header is intact...
  999. //
  1000. if( (trav[0] == '/') && (trav[2] == ':') ) {
  1001. switch(trav[1]) {
  1002. //-----------------------------------"/T:" means it's a touchscreen event
  1003. //
  1004. case 'T':
  1005. //advance past the header
  1006. //
  1007. trav += 3;
  1008. retval = sscanf(trav, "%x,%x,%x", &tz, &tx, &ty);
  1009. if(retval == 3) {
  1010. if(tz) {
  1011. if(down_time == 0) {
  1012. down_time = time(NULL);
  1013. }
  1014. else {
  1015. if( (time(NULL) - down_time) > TS_CALIB_HOLD_TIME) {
  1016. begin_touchscreen_calibration();
  1017. calibration = 1;
  1018. }
  1019. }
  1020. if(!calibration) {
  1021. /*
  1022. //printf("Touch at (%d, %d)\n", translate_ts_x(tx), translate_ts_y(ty));
  1023. if(process_pen(mt, translate_ts_x(tx), translate_ts_y(ty), 1) > 0)
  1024. {
  1025. #ifdef TOUCHSCREEN_QUIET
  1026. write(diu_fd, "/Q:T\r", 5);
  1027. #endif
  1028. //redraw_flag = 1;
  1029. }
  1030. */
  1031. }
  1032. else {
  1033. if(advance_touchscreen_calibration(tx, ty, tz)) {
  1034. calibration = 0;
  1035. //redraw_flag = 1;
  1036. }
  1037. else {
  1038. draw_touchscreen_calibration();
  1039. }
  1040. }
  1041. }
  1042. else
  1043. {
  1044. down_time = 0;
  1045. //printf("Touch Release\n");
  1046. if(!calibration) {
  1047. /*
  1048. if(process_pen(mt, 0,0,0) > 0)
  1049. {
  1050. #ifdef TOUCHSCREEN_QUIET
  1051. write(diu_fd, "/Q:T\r", 5);
  1052. #endif
  1053. //redraw_flag = 1;
  1054. }
  1055. */
  1056. }
  1057. else {
  1058. if(advance_touchscreen_calibration(tx, ty, tz)) {
  1059. calibration = 0;
  1060. //redraw_flag = 1;
  1061. }
  1062. else {
  1063. draw_touchscreen_calibration();
  1064. }
  1065. }
  1066. }
  1067. }
  1068. break;
  1069. //-----------------------------------"/G:" means it is a new GPS input
  1070. case 'G':
  1071. //advance past the header
  1072. //
  1073. trav += 3;
  1074. //If this GPS update constitutes a meaningful piece of data
  1075. //
  1076. if(update_gps(trav) > 0) {
  1077. //and we have a connection to the IPC hub
  1078. //
  1079. if(hub_fd >= 0) {
  1080. //Go and toss the data to any other modules who happen to care about GPS
  1081. //
  1082. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  1083. send_message(hub_fd, &outgoing_msg);
  1084. }
  1085. last_stale_gps_check = now; //Remember that we did a stale GPS check as part of our update.
  1086. }
  1087. break;
  1088. //handle warnings
  1089. //
  1090. case '*':
  1091. //debugs
  1092. //
  1093. case '#':
  1094. //and errors
  1095. //
  1096. case '!':
  1097. //If this DIU error/debug message has not run afoul of the rate limiting policy...
  1098. //
  1099. if( can_report_diu_error() ) {
  1100. //send them all to the log server
  1101. //
  1102. format_log_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  1103. send_message(hub_fd, &outgoing_msg);
  1104. //but in the case of errors, send them to the driver too
  1105. if(trav[1] == '!') {
  1106. format_driver_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  1107. send_message(hub_fd, &outgoing_msg);
  1108. }
  1109. }
  1110. break;
  1111. default: //ignore any message addresses that we don't know what to do with
  1112. printf("Ignoring command \"%s\"\n", trav);
  1113. break;
  1114. }
  1115. }
  1116. else {
  1117. //printf("Ignoring non-command line \"%s\"\n", trav);
  1118. }
  1119. }
  1120. else {
  1121. fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
  1122. close(diu_fd);
  1123. diu_fd = -1;
  1124. break;
  1125. }
  1126. }
  1127. }
  1128. //If we're looking at the IPC hub...
  1129. //
  1130. else if( fds[i].fd == hub_fd ) {
  1131. //if poll says our connection to the IPC hub has died...
  1132. //
  1133. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  1134. fprintf(stderr, "The connection to the IPC hub has gone away...\n");
  1135. close(hub_fd);
  1136. hub_fd = -1;
  1137. break;
  1138. }
  1139. //if we have mail in any of our mailboxes...
  1140. //
  1141. if(fds[i].revents & POLLIN) {
  1142. read_return = get_message(hub_fd, &incoming_msg);
  1143. if(read_return < 0) {
  1144. fprintf(stderr, "The connection to the IPC hub has gone away...\n");
  1145. close(hub_fd);
  1146. hub_fd = -1;
  1147. break;
  1148. }
  1149. else {
  1150. message_callback_return msg_status;
  1151. msg_status = process_message(&incoming_msg);
  1152. if (msg_status) {
  1153. //pass
  1154. }
  1155. }
  1156. }
  1157. }
  1158. else {
  1159. if (fds[i].revents & (POLLIN | POLLOUT)) {
  1160. //mg_mgr_poll(&mgr, 10);
  1161. mg_mgr_poll(&g_mgr, 10);
  1162. }
  1163. }
  1164. }
  1165. }
  1166. //set_color(255,255,255);
  1167. //cls();
  1168. //present_framebuffer();
  1169. //close_framebuffer();
  1170. if(hub_fd >= 0) {
  1171. close(hub_fd);
  1172. }
  1173. if(diu_fd >= 0) {
  1174. write(diu_fd, "/C:----\r",8);
  1175. close(diu_fd);
  1176. }
  1177. return 0;
  1178. }