gps_main.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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 <ctype.h>
  30. #include <string.h>
  31. #include "../common/common_defs.h"
  32. #include "../commhub/commhub.h"
  33. #include "../commhub/client_utils.h"
  34. int gps_fd = -1;
  35. int hub_fd = -1;
  36. time_t last_hub_try = 0;
  37. time_t last_diu_clock = 0;
  38. gps_status my_gps_stat={0};
  39. time_t mkgmtime(struct tm *tm);
  40. // This function takes a GPS timestamp (in gross GPS float format + gross integer date) and
  41. // makes it into a sane UTC timestamp. If we are more than MAX_GPS_CLOCK_DRIFT seconds off
  42. // from GPS time, it sets the system clock to GPS time.
  43. //
  44. int handle_gps_time(float gtime, int date) {
  45. int day,month,year;
  46. int hour,min,sec,frac;
  47. int n = 0;
  48. time_t utc,now;
  49. char buffer[32] = {0};
  50. struct message_record outgoing_msg;
  51. now = time(NULL);
  52. day = month = year = 0;
  53. hour = min = sec = frac = 0;
  54. // Just to be *ahem* clear, as per NMEA standard the date is encoded DDMMYY, and the time of day
  55. // is encoded HHMMSS[.frac] where there is an optional fractional second field denoted by a decimal point.
  56. // we must be able to decode the fractional seconds field but we discard the information since it is not
  57. // reliable enough to be worth the bother.
  58. //
  59. // Start out with zero parsed fields
  60. //
  61. n = 0;
  62. // Construct and then re-parse the time from its icky format to discrete values (this should result
  63. // in at least three (possibly four) fields.
  64. //
  65. sprintf(buffer,"%010.3f", gtime);
  66. n += sscanf(buffer,"%02d%02d%02d.%d", &hour, &min, &sec, &frac);
  67. // Construct and then re-parse the date from its icky format to discrete values. This should result in three fields.
  68. //
  69. sprintf(buffer,"%06d", date);
  70. n += sscanf(buffer,"%02d%02d%02d", &day, &month, &year);
  71. if(n >= 6) //if we scanned at all required fields
  72. {
  73. struct tm gpstm = {0};
  74. // GPS date only uses two digits for year, so we must assume the century
  75. //
  76. year += GPS_DATE_CENTURY;
  77. // tm.tm_year is based on the year 1900
  78. //
  79. gpstm.tm_year = year - 1900;
  80. // January = month 0 in struct tm.tm_mon whereas January = month 1 in an NMEA GPS date.
  81. //
  82. gpstm.tm_mon = month - 1;
  83. gpstm.tm_mday = day;
  84. gpstm.tm_hour = hour;
  85. gpstm.tm_min = min;
  86. gpstm.tm_sec = sec;
  87. // Go and turn the struct tm we've just populated into an utc time stamp (seconds since epoch)
  88. //
  89. utc = mkgmtime(&gpstm);
  90. // Most importantly... Remember what the self-reported GPS time stamp is.
  91. //
  92. my_gps_stat.gpstime = utc;
  93. // printf("%02d-%02d-%04d %02d:%02d:%02d\n",day,month,year,hour,min,sec);
  94. // printf("CALCULATED: %d\nSYSTEM : %d\n\n",(int)utc,(int)time(NULL));
  95. // if we have more than MAX_GPS_CLOCK_DRIFT seconds of clock drift
  96. //
  97. if(abs(utc - now) > MAX_GPS_CLOCK_DRIFT) {
  98. struct timeval ts = {0};
  99. // Set the timeval struct to the calculated utc timestamp from the GPS unit.
  100. //
  101. ts.tv_sec = utc;
  102. ts.tv_usec = 0;
  103. // Set the system clock from GPS time using said timeval struct.
  104. //
  105. settimeofday(&ts, NULL);
  106. //system("/sbin/hwclock --systohc"); //Go and push the new system clock value into the hardware realtime clock chip.
  107. // If we have a valid connection to the IPC hub
  108. //
  109. if( hub_fd >= 0) {
  110. // Stick a message into the diagnostic log to record the fact that we've set the system clock from GPS
  111. //
  112. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "Set syatem clock from previous value (%d) to GPS time (%d).", (int)now, (int)utc );
  113. send_message(hub_fd, &outgoing_msg);
  114. }
  115. }
  116. }
  117. return 0;
  118. }
  119. #ifdef CLEAR_GPS_ON_STALE
  120. static inline void clear_stale_gps_data() {
  121. my_gps_stat.lat = my_gps_stat.lon = my_gps_stat.heading = my_gps_stat.velocity = 0;
  122. my_gps_stat.num_sats = 0;
  123. }
  124. #else
  125. static inline void clear_stale_gps_data() { }
  126. #endif
  127. static int handle_stale_gps_condition() {
  128. // This return code will be > 0 if this function generates a status change that
  129. // will then need to be communicated to other modules in the system via a message to
  130. // MAILBOX_GPS_STATUS.
  131. //
  132. int return_code = 0;
  133. // This will hold the gps_good flag as it stood at the beginning of this subroutine
  134. // previous to any adjustments we make.
  135. //
  136. int previous_good_flag = my_gps_stat.gps_good;
  137. int stale_time = 0;
  138. time_t now = time(NULL);
  139. stale_time = (now - my_gps_stat.stamp);
  140. // If we have entered this function with the impression that we have a valid GPS fix...
  141. //
  142. if(previous_good_flag > 0) {
  143. // If it has been at least GPS_STALE_THRESHOLD seconds since the last fix
  144. //
  145. if( stale_time >= GPS_STALE_THRESHOLD ) {
  146. clear_stale_gps_data();
  147. my_gps_stat.gps_good = 0;
  148. return_code |= 1;
  149. }
  150. }
  151. // If we have determined that we need to declare the GPS data stale and invalid and
  152. // we have a valid connection to the IPC hub we should use that IPC hub connection to
  153. // add a note to the diagnostic log indicating that we've declared the GPS data stale.
  154. //
  155. if( return_code && (hub_fd >= 0) ) {
  156. struct message_record outgoing_msg;
  157. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix has been stale for %d seconds, setting GPS = NO.", stale_time);
  158. send_message(hub_fd, &outgoing_msg);
  159. }
  160. return return_code;
  161. }
  162. int update_gps(char *in) {
  163. // This will hold the number of matched variables populated by sscanf().
  164. //
  165. int num = 0;
  166. // This will allow us to know if we have made a transition from an invalid
  167. // GPS fix to a valid one so that we can log this information.
  168. //
  169. int previous_good_flag = my_gps_stat.gps_good;
  170. // This return code will be > 0 if this function generates a status change that
  171. // will then need to be communicated to other modules in the system via a message to
  172. // MAILBOX_GPS_STATUS.
  173. //
  174. int return_code = 0;
  175. if(!strncmp(in,"$GPRMC",6)) {
  176. float f1=0;
  177. char f2=0;
  178. float f3=0;
  179. char f4=0;
  180. float f5=0;
  181. char f6=0;
  182. float f7=0;
  183. float f8=0;
  184. int f9=0;
  185. float f10=0;
  186. char f11=0;
  187. //DEBUG
  188. printf(">> gprmc\n");
  189. 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);
  190. // If we have a full GPRMC sentence we can consider setting the time
  191. //
  192. if(num == 11) {
  193. // Require at least MIN_SATS_FOR_TIME satellites to accept a new system clock value from the GPS unit.
  194. // This is to keep a crummy GPS fix from generating a bogus or unstable system time.
  195. //
  196. if(my_gps_stat.num_sats >= MIN_SATS_FOR_TIME) {
  197. // Pass the time field (f1) and the date field (f9) in to the routine that sets the system clock if needed.
  198. // (this routine also stores the utc timestamp derived from the GPS date and time fields so it can be passed to
  199. // other modules that may have a need for this information).
  200. //
  201. handle_gps_time(f1,f9);
  202. }
  203. }
  204. if(num > 0) {
  205. // update snapshot with latitude
  206. //
  207. my_gps_stat.lat = f3 * ((f4 == 'N')?(1):(-1));
  208. // longitude
  209. //
  210. my_gps_stat.lon = f5 * ((f6 == 'E')?(1):(-1));
  211. // meters per second (converted from knots)
  212. //
  213. my_gps_stat.velocity = f7 / 1.94384449f;
  214. // course
  215. //
  216. my_gps_stat.heading = f8;
  217. // update snapshot's staledate
  218. //
  219. my_gps_stat.stamp = time(NULL);
  220. return_code |= 1;
  221. }
  222. }
  223. else if(!strncmp(in,"$GPGGA",6)) {
  224. int f1=0;
  225. float f2=0;
  226. char f3=0;
  227. float f4=0;
  228. char f5=0;
  229. int f6=0;
  230. int f7=0;
  231. float f8=0;
  232. float f9=0;
  233. char f10=0;
  234. float f11=0;
  235. char f12=0;
  236. //DEBUG
  237. printf(">> gpgga\n");
  238. 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);
  239. if(num == 12) {
  240. // require 3 satellites minimum
  241. //
  242. if ( f7 >= 3 ) {
  243. // store GPS valid flag in snapshot
  244. //
  245. my_gps_stat.gps_good = f6;
  246. // store number of satellites in view in snapshot
  247. //
  248. my_gps_stat.num_sats = f7;
  249. // Do NOT store the timestamp since we only want to remember timestamps of position
  250. // fixes and the GPGGA message is all metadata (number of satellites, fix quality, etc...).
  251. // It is worth noting that GPGGA does report altitude, but that is not a piece of information
  252. // we track because the road is where the road is, and if a bus becomes airborn we have much
  253. // bigger problems than figuring out how far off the ground it is...
  254. //
  255. return_code |= 1;
  256. }
  257. }
  258. }
  259. return_code |= handle_stale_gps_condition();
  260. // If we have a connection to the IPC hub and we had previously not had a valid
  261. // GPS fix but we now do, make a note of it in the diagnostic log.
  262. //
  263. if( (previous_good_flag == 0) && (my_gps_stat.gps_good != 0) && (hub_fd >= 0) ) {
  264. struct message_record outgoing_msg;
  265. format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix is now valid with %d satellites. Setting GPS = YES.", my_gps_stat.num_sats);
  266. send_message(hub_fd, &outgoing_msg);
  267. }
  268. return return_code;
  269. }
  270. void maintain_ipc_hub_connect(char *progname) {
  271. struct message_record outgoing_msg;
  272. // if we have no connection to the IPC hub
  273. //
  274. if(hub_fd < 0) {
  275. // if we haven't tried the hub in a few seconds
  276. //
  277. if( (time(NULL) - last_hub_try) > HUB_RETRY_TIME ) {
  278. // retry it
  279. //
  280. last_hub_try = time(NULL);
  281. // try and get one
  282. //
  283. hub_fd = connect_to_message_server(progname);
  284. if(hub_fd >= 0) {
  285. //Subscribe to the default status messages
  286. //
  287. subscribe_to_default_messages(hub_fd);
  288. // Ask for a status update
  289. //
  290. prepare_message(&outgoing_msg, MAILBOX_STATUS_REQUEST, "", 0);
  291. send_message(hub_fd,&outgoing_msg);
  292. }
  293. else {
  294. fprintf(stderr, "Cannot connect to IPC hub!\n");
  295. }
  296. }
  297. }
  298. }
  299. //----------------------------------
  300. int main(int argc, char **argv) {
  301. char line[LINE_BUFFER_SIZE] = {0};
  302. struct message_record incoming_msg;
  303. struct message_record outgoing_msg;
  304. struct pollfd fds[2];
  305. int nfd;
  306. int poll_return;
  307. int read_return;
  308. int i;
  309. time_t now;
  310. //int retval = 0;
  311. time_t last_stale_gps_check = 0;
  312. // Configure our signal handlers to deal with SIGINT, SIGTERM, etc...
  313. // and make graceful exits while logging
  314. //
  315. configure_signal_handlers(argv[0]);
  316. // Make an initial attempt to get in touch with the
  317. // interprocess communication hub (it may not be up yet depending on the start order)
  318. //
  319. maintain_ipc_hub_connect(argv[0]);
  320. // Register our defualt system message processing callbacks
  321. //
  322. register_system_status_callbacks();
  323. // This is the main dispatch loop:
  324. //
  325. // * reset watchdog to make sure we haven't crashed/frozen
  326. // * if need be, open a connection to the DIU microcontroller, quieting all messages except for acks
  327. // * handle GPS message dispatch through IPC
  328. // * if need be, handle reload of menu.xml
  329. // * manage driver status message communication
  330. // * handle paddle change
  331. // * draw menu
  332. // * listen on the mailboxes for messages and process. This includes
  333. // - touchscreen events
  334. // - gps updates
  335. // - warning/debug/error messages
  336. //
  337. while( exit_request_status == EXIT_REQUEST_NONE ) //loop until we get asked to exit...
  338. {
  339. //DEBUG
  340. printf("[%lli] gps_minder: heartbeat\n", get_usec_time());
  341. //DEBUG
  342. RESET_WATCHDOG();
  343. maintain_ipc_hub_connect(argv[0]);
  344. if(gps_fd < 0) {
  345. gps_fd = open_rs232_device(GPS_PORT, GPS_DEFAULT_BAUD, RS232_LINE);
  346. if(gps_fd < 0) {
  347. fprintf(stderr, "Cannot open serial port %s for GPS!\n", GPS_PORT);
  348. }
  349. }
  350. //---
  351. now = time(NULL);
  352. // Every second we want to check to make sure that our GPS data have note gone stale...
  353. //
  354. if((now - last_stale_gps_check) > 0) {
  355. // If the stale check results in an update to my_gps_stat, we must update any other
  356. // modules which may be tracking GPS status via the IPC hub.
  357. //
  358. if( handle_stale_gps_condition() > 0 ) {
  359. // If we have a connection to the IPC hub
  360. //
  361. if(hub_fd >= 0) {
  362. // Go and toss the data to any other modules who happen to care about GPS
  363. //
  364. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  365. send_message(hub_fd, &outgoing_msg);
  366. }
  367. }
  368. // Either way, remember that we did this stale check.
  369. //
  370. last_stale_gps_check = now;
  371. }
  372. //---
  373. if (hup_request_status) {
  374. fprintf(stderr, "gps_minder: hup request\n");
  375. hup_request_status = 0;
  376. }
  377. //---
  378. nfd = 0;
  379. if(hub_fd >= 0)
  380. {
  381. fds[nfd].fd = hub_fd;
  382. fds[nfd].events = POLLIN;
  383. fds[nfd].revents = 0;
  384. nfd++;
  385. }
  386. if(gps_fd >= 0)
  387. {
  388. fds[nfd].fd = gps_fd;
  389. fds[nfd].events = POLLIN;
  390. fds[nfd].revents = 0;
  391. nfd++;
  392. }
  393. // if we have any file descriptors, poll them
  394. //
  395. if(nfd > 0) {
  396. poll_return = poll(fds, nfd, POLL_TIMEOUT);
  397. }
  398. // otherwise, whistle and look busy
  399. //
  400. else {
  401. poll_return = 0; //(this keeps us from buringing 100% cpu cycles if we don't have contact with either
  402. sleep(1); //the IPC hub or the DIU hardware).
  403. }
  404. //--------------------------------------------------------------------------------------------------
  405. // if poll didn't net us any work to do,
  406. //
  407. if(poll_return < 1) {
  408. // lets try again
  409. //
  410. continue;
  411. }
  412. // Loop through all polled file descriptors
  413. //
  414. for(i = 0; i < nfd; i++) {
  415. // If we're looking at the DIU...
  416. //
  417. if( fds[i].fd == gps_fd ) {
  418. // if poll says our serial port has become bogus...
  419. //
  420. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  421. fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
  422. // close it, flag as invalid,
  423. // and break out of the for loop to allow the while to cycle
  424. //
  425. close(gps_fd);
  426. gps_fd = -1;
  427. break;
  428. }
  429. if(fds[i].revents & POLLIN) {
  430. read_return = read(fds[i].fd, line, sizeof(line));
  431. if(read_return > 0) {
  432. char *trav = line;
  433. line[read_return] = '\0';
  434. strip_crlf(line);
  435. // advance until EOL or we hit our start sentinel
  436. //
  437. while(*trav && (*trav != '$') ) {
  438. trav++;
  439. }
  440. // Check to see that our address header is intact...
  441. //
  442. if (trav[0] == '$') {
  443. switch(trav[1]) {
  444. case 'G': //-----------------------------------"/G:" means it is a new GPS input
  445. // If this GPS update constitutes a meaningful piece of data
  446. //
  447. if(update_gps(trav) > 0) {
  448. //and we have a connection to the IPC hub
  449. //
  450. if(hub_fd >= 0) {
  451. // Go and toss the data to any other modules who happen to care about GPS
  452. //
  453. prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
  454. send_message(hub_fd, &outgoing_msg);
  455. }
  456. // Remember that we did a stale GPS check as part of our update.
  457. //
  458. last_stale_gps_check = now;
  459. }
  460. break;
  461. // ignore any message addresses that we don't know what to do with
  462. //
  463. default:
  464. printf("Ignoring command \"%s\"\n", trav);
  465. break;
  466. }
  467. }
  468. else { }
  469. }
  470. else {
  471. fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
  472. // close it, flag it invalid and break out of the
  473. // for loop to allow for the while to cycle.
  474. //
  475. close(gps_fd);
  476. gps_fd = -1;
  477. break;
  478. }
  479. }
  480. }
  481. // If we're looking at the IPC hub...
  482. //
  483. else if( fds[i].fd == hub_fd ) {
  484. // if poll says our connection to the IPC hub has died...
  485. //
  486. if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
  487. fprintf(stderr, "The connection to the IPC hub has gone away...\n"); //complain
  488. // close it, flag it invalid and break out of the
  489. // for loop to allow for the while to cycle.
  490. //
  491. close(hub_fd);
  492. hub_fd = -1;
  493. break;
  494. }
  495. // if we have mail in any of our mailboxes...
  496. //
  497. if(fds[i].revents & POLLIN) {
  498. read_return = get_message(hub_fd, &incoming_msg);
  499. if(read_return < 0) {
  500. fprintf(stderr, "The connection to the IPC hub has gone away...\n"); //complain
  501. // close it, flag it invalid and break out of the
  502. // for loop to allow for the while to cycle.
  503. //
  504. close(hub_fd);
  505. hub_fd = -1;
  506. break;
  507. }
  508. else {
  509. message_callback_return msg_status;
  510. msg_status = process_message(&incoming_msg);
  511. if (msg_status) { }
  512. }
  513. }
  514. }
  515. }
  516. }
  517. if(hub_fd >= 0) {
  518. close(hub_fd);
  519. }
  520. if(gps_fd >= 0) {
  521. close(gps_fd);
  522. }
  523. return 0;
  524. }