diu_main.c 48 KB

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