diu_main.c 47 KB

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