diu_main.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  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. ret = mg_get_http_var(&(hm->body), "param", s_param, _SLEN);
  663. if (ret<=0) { s_param[0] = '\0'; }
  664. if (hub_fd >= 0) {
  665. strncpy(dr.rulename, s_rule, DRIVER_RULECALL_LEN - 1);
  666. strncpy(dr.ruleparam, s_param, DRIVER_RULECALL_LEN - 1);
  667. prepare_message(&outgoing, MAILBOX_RULE_CALL, &dr, sizeof(dr));
  668. send_message(hub_fd, &outgoing);
  669. }
  670. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  671. (unsigned long)strlen(msg_ok), msg_ok);
  672. }
  673. // driver paddle (route) input
  674. //
  675. static void ui_handle_paddle_input(struct mg_connection *nc, struct http_message *hm) {
  676. int ret;
  677. char s_paddle[_SLEN];
  678. //char msg_fail[] = "fail .";
  679. char msg_ok[] = "ok .";
  680. int ipaddle;
  681. ret = mg_get_http_var(&(hm->body), "paddle", s_paddle, _SLEN);
  682. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  683. //DEBUG
  684. printf("#got paddle %s\n", s_paddle);
  685. ipaddle = atoi(s_paddle);
  686. make_paddle_request(ipaddle);
  687. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  688. (unsigned long)strlen(msg_ok), msg_ok);
  689. }
  690. // driver login
  691. //
  692. static void ui_handle_driver_login(struct mg_connection *nc, struct http_message *hm) {
  693. int ret;
  694. char s_driver[_SLEN], s_pin[_SLEN];
  695. int idrv=-1;
  696. char msg_fail[] = "fail driver_login";
  697. char msg_success[] = "ok driver";
  698. ret = mg_get_http_var(&(hm->body), "driver", s_driver, _SLEN);
  699. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  700. ret = mg_get_http_var(&(hm->body), "pin", s_pin, _SLEN);
  701. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  702. idrv = atoi(s_driver);
  703. ret = driver_login(idrv, s_pin);
  704. if (ret!=0) {
  705. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  706. (unsigned long)strlen(msg_fail), msg_fail);
  707. return;
  708. }
  709. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  710. (unsigned long)strlen(msg_success), msg_success);
  711. }
  712. // screen dim event
  713. //
  714. static void ui_handle_dim(struct mg_connection *nc, struct http_message *hm) {
  715. int ret;
  716. char msg_fail[] = "fail dim";
  717. char msg_success[] = "ok dim";
  718. // assuming we're running as root for now
  719. //
  720. ret = system("su - pi -c \"/usr/bin/xset -display :0 dpms force off\" &");
  721. if (ret!=0) {
  722. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  723. (unsigned long)strlen(msg_fail), msg_fail);
  724. return;
  725. }
  726. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  727. (unsigned long)strlen(msg_success), msg_success);
  728. }
  729. // set volume
  730. //
  731. static void ui_handle_volume(struct mg_connection *nc, struct http_message *hm) {
  732. int ret;
  733. char s_volume[_SLEN], _cmd[1024];
  734. float f_vol = 100.0;
  735. char msg_fail[] = "fail volume";
  736. char msg_success[] = "ok volume";
  737. ret = mg_get_http_var(&(hm->body), "volume", s_volume, _SLEN);
  738. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  739. // assuming we're running as root for now
  740. //
  741. f_vol = atof(s_volume);
  742. snprintf(_cmd, 1023, "/home/bus/bin/volumeset %04f &", f_vol);
  743. ret = system(_cmd);
  744. if (ret!=0) {
  745. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  746. (unsigned long)strlen(msg_fail), msg_fail);
  747. return;
  748. }
  749. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  750. (unsigned long)strlen(msg_success), msg_success);
  751. }
  752. // bring network interface up/down
  753. //
  754. static void ui_handle_interfaceupdown(struct mg_connection *nc, struct http_message *hm) {
  755. int ret;
  756. char s_interface[_SLEN], s_updown[_SLEN];
  757. char msg_fail[] = "fail interfaceupdown";
  758. char msg_success[] = "ok interfaceupdown";
  759. int _iface_updown = -1;
  760. ret = mg_get_http_var(&(hm->body), "interface", s_interface, _SLEN);
  761. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  762. ret = mg_get_http_var(&(hm->body), "state", s_updown, _SLEN);
  763. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  764. // only allow eth0 and up/down for now
  765. //
  766. if (strncmp(s_interface, "eth0", strlen("eth0")+1)!=0) {
  767. mg_http_send_error(nc, 404, NULL);
  768. return;
  769. }
  770. if (strncmp(s_updown, "up", strlen("up")+1)==0) {
  771. _iface_updown=1;
  772. }
  773. else if (strncmp(s_updown, "down", strlen("down")+1)==0) {
  774. _iface_updown=0;
  775. }
  776. if (_iface_updown < 0) {
  777. mg_http_send_error(nc, 404, NULL);
  778. return;
  779. }
  780. // Assuming we're running as root for now.
  781. // Bring eth0 interface up or down.
  782. //
  783. if (_iface_updown==1) {
  784. ret = system("/sbin/ip link set eth0 up &");
  785. }
  786. else if (_iface_updown==0) {
  787. ret = system("/sbin/ip link set eth0 down &");
  788. }
  789. if (ret!=0) {
  790. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  791. (unsigned long)strlen(msg_fail), msg_fail);
  792. return;
  793. }
  794. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  795. (unsigned long)strlen(msg_success), msg_success);
  796. }
  797. // get network interface information
  798. //
  799. static void ui_handle_interfaceinfo(struct mg_connection *nc, struct http_message *hm) {
  800. int n, fam, s;
  801. struct ifaddrs *_addr, *ifa;
  802. char host[NI_MAXHOST];
  803. char msg_fail[] = "fail interfaceinfo";
  804. char buf[4*_SLEN];
  805. // We're going to restrict to eth0 and only ip4
  806. //
  807. if (getifaddrs(&_addr)==-1) {
  808. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  809. (unsigned long)strlen(msg_fail), msg_fail);
  810. return;
  811. }
  812. for (ifa = _addr, n=0; ifa!=NULL; ifa = ifa->ifa_next, n++) {
  813. if (ifa->ifa_addr == NULL) { continue; }
  814. fam = ifa->ifa_addr->sa_family;
  815. if (fam != AF_INET) { continue; }
  816. if (strncmp(ifa->ifa_name, "eth0", strlen("eth0") + 1)!=0) { continue; }
  817. s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
  818. host, NI_MAXHOST,
  819. NULL, 0, NI_NUMERICHOST);
  820. if (s != 0) {
  821. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  822. (unsigned long)strlen(msg_fail), msg_fail);
  823. return;
  824. }
  825. snprintf(buf, (4*_SLEN) - 1, "ok msg=interfaceinfo\n%s=%s", ifa->ifa_name, host);
  826. }
  827. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  828. (unsigned long)strlen(buf), buf);
  829. }
  830. // run 'say' custom script for voice text to speech
  831. //
  832. static void ui_handle_say(struct mg_connection *nc, struct http_message *hm) {
  833. int ret;
  834. //char msg_fail[] = "fail say";
  835. char msg_ok[] = "ok say";
  836. char s_message[_SLEN];
  837. char buf[4*_SLEN];
  838. ret = mg_get_http_var(&(hm->body), "message", s_message, _SLEN);
  839. if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
  840. snprintf(buf, 4*_SLEN-1, "/home/bus/bin/say \"%s\" &", s_message);
  841. system(buf);
  842. mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
  843. (unsigned long)strlen(msg_ok), msg_ok);
  844. }
  845. //-----
  846. //-----
  847. //-----
  848. // api point
  849. //
  850. static void api_handle_req(struct mg_connection *nc, struct http_message *hm) {
  851. int ret;
  852. char s_action[_SLEN];
  853. ret = mg_get_http_var(&(hm->body), "action", s_action, _SLEN);
  854. if (ret==0) {
  855. mg_http_send_error(nc, 404, NULL);
  856. return;
  857. }
  858. if (strncmp(s_action, "driverlogin", strlen("driverlogin")+1)==0) {
  859. ui_handle_driver_login(nc, hm);
  860. }
  861. else if (strncmp(s_action, "paddleinput", strlen("paddleinput")+1)==0) {
  862. ui_handle_paddle_input(nc, hm);
  863. }
  864. else if (strncmp(s_action, "prevstop", strlen("prevstop")+1)==0) {
  865. ui_handle_prevstop_input(nc, hm);
  866. }
  867. else if (strncmp(s_action, "nextstop", strlen("nextstop")+1)==0) {
  868. ui_handle_nextstop_input(nc, hm);
  869. }
  870. else if (strncmp(s_action, "status", strlen("status")+1)==0) {
  871. ui_handle_status_input(nc, hm);
  872. }
  873. else if (strncmp(s_action, "logout", strlen("logout")+1)==0) {
  874. ui_handle_logout_input(nc, hm);
  875. }
  876. else if (strncmp(s_action, "fare", strlen("fare")+1)==0) {
  877. ui_handle_fare_input(nc, hm);
  878. }
  879. else if (strncmp(s_action, "dim", strlen("dim")+1)==0) {
  880. ui_handle_dim(nc, hm);
  881. }
  882. else if (strncmp(s_action, "volume", strlen("volume")+1)==0) {
  883. ui_handle_volume(nc, hm);
  884. }
  885. else if (strncmp(s_action, "interfaceupdown", strlen("interfaceupdown")+1)==0) {
  886. ui_handle_interfaceupdown(nc, hm);
  887. }
  888. else if (strncmp(s_action, "interfaceinfo", strlen("interfaceinfo")+1)==0) {
  889. ui_handle_interfaceinfo(nc, hm);
  890. }
  891. else if (strncmp(s_action, "say", strlen("say")+1)==0) {
  892. ui_handle_say(nc, hm);
  893. }
  894. else {
  895. mg_http_send_error(nc, 404, NULL);
  896. }
  897. }
  898. static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  899. struct http_message *hm = (struct http_message *) ev_data;
  900. char buf[1024];
  901. int debug_print = 0;
  902. if (debug_print) {
  903. mg_sock_addr_to_str(&(nc->sa), buf, 1023, MG_SOCK_STRINGIFY_IP);
  904. printf("%s\n", buf);
  905. }
  906. switch (ev){
  907. case MG_EV_HTTP_REQUEST:
  908. if (mg_vcmp(&hm->uri, "/req")==0) {
  909. api_handle_req(nc, (struct http_message *)ev_data);
  910. }
  911. else {
  912. mg_serve_http(nc, (struct http_message *) ev_data, s_http_server_opts);
  913. }
  914. break;
  915. case MG_EV_WEBSOCKET_HANDSHAKE_DONE:
  916. break;
  917. case MG_EV_WEBSOCKET_FRAME:
  918. process_ws_message((struct websocket_message *)ev_data);
  919. break;
  920. case MG_EV_CLOSE:
  921. if (is_websocket(nc)) {
  922. // websocket closed
  923. }
  924. break;
  925. default:
  926. break;
  927. }
  928. }
  929. //DEBUG
  930. void _test_ws(struct mg_mgr *mgr) {
  931. struct mg_connection *conn;
  932. char buf[_SLEN];
  933. snprintf(buf, _SLEN, "test message");
  934. for (conn = mg_next(mgr, NULL); conn; conn = mg_next(mgr, conn)) {
  935. if (!is_websocket(conn)) { continue; }
  936. mg_send_websocket_frame(conn, WEBSOCKET_OP_TEXT, buf, strlen(buf));
  937. }
  938. }
  939. //-------- web server functions ----
  940. int main(int argc, char **argv) {
  941. char line[LINE_BUFFER_SIZE] = {0};
  942. struct message_record incoming_msg;
  943. struct message_record outgoing_msg;
  944. struct pollfd fds[32];
  945. int nfd=0;
  946. int poll_return;
  947. int read_return;
  948. int i;
  949. time_t down_time = 0;
  950. int calibration = 0;
  951. time_t now;
  952. int retval = 0;
  953. int tz = 0;
  954. int tx = 0;
  955. int ty = 0;
  956. time_t last_stale_gps_check = 0;
  957. long long int _usec_now, _usec_prv, _usec_del;
  958. _usec_now = get_usec_time();
  959. _usec_prv = _usec_now;
  960. _usec_del = 60000000;
  961. // setup mongoose web server
  962. //
  963. struct mg_connection *nc;
  964. mg_mgr_init(&g_mgr, NULL);
  965. nc = mg_bind(&g_mgr, s_http_port, ev_handler);
  966. if (!nc) {
  967. printf("failed to create listener\n");
  968. return 1;
  969. }
  970. mg_set_protocol_http_websocket(nc);
  971. s_http_server_opts.document_root = CONFIG_FILE_PATH "/html";
  972. s_http_server_opts.enable_directory_listing = "no";
  973. // Configure our signal handlers to deal with SIGINT, SIGTERM, etc... and make graceful exits while logging
  974. //
  975. configure_signal_handlers(argv[0]);
  976. // Make an initial attempt to get in touch with the interprocess communication hub (it may not be up yet depending on the start order)
  977. //
  978. maintain_ipc_hub_connect(argv[0]);
  979. // Register our defualt system message processing callbacks
  980. //
  981. register_system_status_callbacks();
  982. register_dispatch_callback(MAILBOX_STATUS_REQUEST, CALLBACK_USER(1), handle_status_request, NULL);
  983. register_dispatch_callback(MAILBOX_DRIVER_NOTIFY, CALLBACK_USER(2), handle_driver_notify, NULL);
  984. register_dispatch_callback(MAILBOX_PADDLE_ACK, CALLBACK_USER(3), handle_paddle_ack, NULL);
  985. register_dispatch_callback(MAILBOX_VAULT_DROP, CALLBACK_USER(4), handle_vault_drop, NULL);
  986. register_dispatch_callback(MAILBOX_TOKEN_MAG, CALLBACK_USER(5), handle_token_diag, NULL);
  987. register_dispatch_callback(MAILBOX_TOKEN_RFID, CALLBACK_USER(6), handle_token_diag, NULL);
  988. clear_diu_messages();
  989. // This is the main dispatch loop:
  990. //
  991. // * reset watchdog to make sure we haven't crashed/frozen
  992. // * if need be, open a connection to the DIU microcontroller, quieting all messages except for acks
  993. // * handle GPS message dispatch through IPC
  994. // * manage driver status message communication
  995. // * handle paddle change
  996. // * listen on the mailboxes for messages and process. This includes
  997. // - gps updates
  998. // - warning/debug/error messages
  999. //
  1000. //loop until we get asked to exit.../
  1001. //
  1002. while( exit_request_status == EXIT_REQUEST_NONE ) {
  1003. _usec_now = get_usec_time();
  1004. if ((_usec_now - _usec_prv) > _usec_del) {
  1005. //DEBUG
  1006. printf("[%lli] diu_minder: heartbeat\n", get_usec_time());
  1007. //DEBUG
  1008. _usec_prv = _usec_now;
  1009. }
  1010. RESET_WATCHDOG();
  1011. maintain_ipc_hub_connect(argv[0]);
  1012. if(diu_fd < 0) {
  1013. diu_fd = open_rs232_device(DRIVER_UI_PORT, USE_DEFAULT_BAUD, RS232_LINE);
  1014. if(diu_fd < 0) {
  1015. //fprintf(stderr, "Cannot open serial port %s for DIU!\n", DRIVER_UI_PORT);
  1016. }
  1017. else {
  1018. write(diu_fd, "/Q:aK\r", 6); //Turn on all messages except ACKs for sent commands
  1019. }
  1020. }
  1021. now = time(NULL);
  1022. //Every second, we want to update the DIU clock (even though it only shows minutes, this covers power events...)
  1023. //
  1024. if((now - last_diu_clock) > 0) {
  1025. if(diu_fd) {
  1026. set_diu_clock(diu_fd, now);
  1027. last_diu_clock = now;
  1028. }
  1029. }
  1030. //Every second we want to check to make sure that our GPS data have note gone stale...
  1031. //
  1032. if((now - last_stale_gps_check) > 0) {
  1033. // If the stale check results in an update to my_gps_stat, we must update any other
  1034. // modules which may be tracking GPS status via the IPC hub.
  1035. //
  1036. if( handle_stale_gps_condition() > 0 ) {
  1037. // If we have a connection to the IPC hub
  1038. //
  1039. if(hub_fd >= 0) {
  1040. //Go and toss the data to any other modules who happen to care about GPS
  1041. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  1042. send_message(hub_fd, &outgoing_msg);
  1043. }
  1044. }
  1045. // Either way, remember that we did this stale check.
  1046. //
  1047. last_stale_gps_check = now;
  1048. }
  1049. if(hup_request_status) {
  1050. hup_request_status = 0;
  1051. // reserve ui if necssary ...
  1052. //
  1053. }
  1054. //If it is time to send out a driver status update
  1055. //
  1056. if(update_driver_status && (hub_fd >= 0)) {
  1057. //do so...
  1058. //
  1059. prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
  1060. send_message(hub_fd, &outgoing_msg);
  1061. update_driver_status = 0;
  1062. }
  1063. check_paddle_request();
  1064. //If we have to redraw the UI
  1065. //if(redraw_flag && !calibration)
  1066. //
  1067. if(!calibration) {
  1068. //Redraw the menu reflecting any changes from the last touchscreen input
  1069. //or other stimulus
  1070. //draw_menu(mt);
  1071. //
  1072. #ifdef TOUCHSCREEN_QUIET
  1073. write(diu_fd, "/Q:t\r", 5); //Un-Quiet the touch screen, now that we've responded to the user we want
  1074. #endif //to hear if they have any further input to give us...
  1075. }
  1076. nfd = 0;
  1077. if(hub_fd >= 0) {
  1078. fds[nfd].fd = hub_fd;
  1079. fds[nfd].events = POLLIN;
  1080. fds[nfd].revents = 0;
  1081. nfd++;
  1082. }
  1083. if(diu_fd >= 0) {
  1084. fds[nfd].fd = diu_fd;
  1085. fds[nfd].events = POLLIN;
  1086. fds[nfd].revents = 0;
  1087. nfd++;
  1088. }
  1089. // Add our websocket socket to the list of file descriptors
  1090. // to select on.
  1091. //
  1092. for (nc = g_mgr.active_connections; nc != NULL; nc = nc->next) {
  1093. if (nc->sock != INVALID_SOCKET) {
  1094. if (nfd < 32) {
  1095. fds[nfd].fd = nc->sock;
  1096. fds[nfd].events = POLLIN | POLLOUT;
  1097. fds[nfd].revents = 0;
  1098. nfd++;
  1099. }
  1100. }
  1101. }
  1102. //if we have any file descriptors, poll them
  1103. //
  1104. if(nfd > 0) {
  1105. poll_return = poll(fds, nfd, POLL_TIMEOUT);
  1106. }
  1107. //otherwise, whistle and look busy
  1108. //
  1109. else {
  1110. // (this keeps us from buringing 100% cpu cycles if we don't have contact with either
  1111. // the IPC hub or the DIU hardware).
  1112. //
  1113. poll_return = 0;
  1114. sleep(1);
  1115. }
  1116. //--------------------------------------------------------------------------------------------------
  1117. //if poll didn't net us any work to do,
  1118. //
  1119. if(poll_return < 1) {
  1120. //lets try again
  1121. //
  1122. continue;
  1123. }
  1124. for(i = 0; i < nfd; i++) //Loop through all polled file descriptors
  1125. {
  1126. //If we're looking at the DIU...
  1127. //
  1128. if( fds[i].fd == diu_fd ) {
  1129. //if poll says our serial port has become bogus...
  1130. //
  1131. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  1132. fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
  1133. close(diu_fd);
  1134. diu_fd = -1;
  1135. break;
  1136. }
  1137. if(fds[i].revents & POLLIN) {
  1138. read_return = read(fds[i].fd, line, sizeof(line));
  1139. if(read_return > 0) {
  1140. char *trav = line;
  1141. line[read_return] = '\0';
  1142. strip_crlf(line);
  1143. //advance until EOL or we hit our start sentinel
  1144. while(*trav && (*trav != '/') ) { trav++; }
  1145. //Check to see that our address header is intact...
  1146. //
  1147. if( (trav[0] == '/') && (trav[2] == ':') ) {
  1148. switch(trav[1]) {
  1149. //-----------------------------------"/T:" means it's a touchscreen event
  1150. //
  1151. case 'T':
  1152. //advance past the header
  1153. //
  1154. trav += 3;
  1155. retval = sscanf(trav, "%x,%x,%x", &tz, &tx, &ty);
  1156. if(retval == 3) {
  1157. if(tz) {
  1158. if(down_time == 0) {
  1159. down_time = time(NULL);
  1160. }
  1161. else {
  1162. if( (time(NULL) - down_time) > TS_CALIB_HOLD_TIME) {
  1163. begin_touchscreen_calibration();
  1164. calibration = 1;
  1165. }
  1166. }
  1167. if(!calibration) {
  1168. // calibration from here turned off...
  1169. }
  1170. else {
  1171. if(advance_touchscreen_calibration(tx, ty, tz)) {
  1172. calibration = 0;
  1173. }
  1174. else {
  1175. draw_touchscreen_calibration();
  1176. }
  1177. }
  1178. }
  1179. else
  1180. {
  1181. down_time = 0;
  1182. if(!calibration) { }
  1183. else {
  1184. if(advance_touchscreen_calibration(tx, ty, tz)) {
  1185. calibration = 0;
  1186. //redraw_flag = 1;
  1187. }
  1188. else {
  1189. draw_touchscreen_calibration();
  1190. }
  1191. }
  1192. }
  1193. }
  1194. break;
  1195. //-----------------------------------"/G:" means it is a new GPS input
  1196. //
  1197. case 'G':
  1198. //advance past the header
  1199. //
  1200. trav += 3;
  1201. //If this GPS update constitutes a meaningful piece of data
  1202. //
  1203. if(update_gps(trav) > 0) {
  1204. //and we have a connection to the IPC hub
  1205. //
  1206. if(hub_fd >= 0) {
  1207. //Go and toss the data to any other modules who happen to care about GPS
  1208. //
  1209. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  1210. send_message(hub_fd, &outgoing_msg);
  1211. }
  1212. last_stale_gps_check = now; //Remember that we did a stale GPS check as part of our update.
  1213. }
  1214. break;
  1215. //handle warnings
  1216. //
  1217. case '*':
  1218. //debugs
  1219. //
  1220. case '#':
  1221. //and errors
  1222. //
  1223. case '!':
  1224. //If this DIU error/debug message has not run afoul of the rate limiting policy...
  1225. //
  1226. if( can_report_diu_error() ) {
  1227. //send them all to the log server
  1228. //
  1229. format_log_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  1230. send_message(hub_fd, &outgoing_msg);
  1231. //but in the case of errors, send them to the driver too
  1232. if(trav[1] == '!') {
  1233. format_driver_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
  1234. send_message(hub_fd, &outgoing_msg);
  1235. }
  1236. }
  1237. break;
  1238. default: //ignore any message addresses that we don't know what to do with
  1239. printf("Ignoring command \"%s\"\n", trav);
  1240. break;
  1241. }
  1242. }
  1243. else {
  1244. //printf("Ignoring non-command line \"%s\"\n", trav);
  1245. }
  1246. }
  1247. else {
  1248. fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
  1249. close(diu_fd);
  1250. diu_fd = -1;
  1251. break;
  1252. }
  1253. }
  1254. }
  1255. //If we're looking at the IPC hub...
  1256. //
  1257. else if( fds[i].fd == hub_fd ) {
  1258. //if poll says our connection to the IPC hub has died...
  1259. //
  1260. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  1261. fprintf(stderr, "The connection to the IPC hub has gone away...\n");
  1262. close(hub_fd);
  1263. hub_fd = -1;
  1264. break;
  1265. }
  1266. //if we have mail in any of our mailboxes...
  1267. //
  1268. if(fds[i].revents & POLLIN) {
  1269. read_return = get_message(hub_fd, &incoming_msg);
  1270. if(read_return < 0) {
  1271. fprintf(stderr, "The connection to the IPC hub has gone away...\n");
  1272. close(hub_fd);
  1273. hub_fd = -1;
  1274. break;
  1275. }
  1276. else {
  1277. message_callback_return msg_status;
  1278. msg_status = process_message(&incoming_msg);
  1279. if (msg_status) {
  1280. //pass
  1281. }
  1282. }
  1283. }
  1284. }
  1285. else {
  1286. if (fds[i].revents & (POLLIN | POLLOUT)) {
  1287. mg_mgr_poll(&g_mgr, 10);
  1288. }
  1289. }
  1290. }
  1291. }
  1292. if(hub_fd >= 0) {
  1293. close(hub_fd);
  1294. }
  1295. if(diu_fd >= 0) {
  1296. write(diu_fd, "/C:----\r",8);
  1297. close(diu_fd);
  1298. }
  1299. return 0;
  1300. }