diu_main.c 43 KB

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