gpsutils.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. /* gpsutils.c -- code shared between low-level and high-level interfaces
  2. *
  3. * This file is Copyright 2010 by the GPSD project
  4. * SPDX-License-Identifier: BSD-2-clause
  5. */
  6. /* The strptime prototype is not provided unless explicitly requested.
  7. * We also need to set the value high enough to signal inclusion of
  8. * newer features (like clock_gettime). See the POSIX spec for more info:
  9. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_02_01_02 */
  10. #include "../include/gpsd_config.h" // must be before all includes
  11. #include <ctype.h>
  12. #include <errno.h>
  13. #include <math.h>
  14. #include <stdbool.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <sys/select.h> // for to have a pselect(2) prototype a la POSIX
  19. #include <sys/time.h> // for to have a pselect(2) prototype a la SuS
  20. #include <time.h>
  21. #include "../include/gps.h"
  22. #include "../include/libgps.h"
  23. #include "../include/os_compat.h"
  24. #include "../include/timespec.h"
  25. #ifdef USE_QT
  26. #include <QDateTime>
  27. #include <QStringList>
  28. #endif
  29. /*
  30. * Berkeley implementation of strtod(), inlined to avoid locale problems
  31. * with the decimal point and stripped down to an atof()-equivalent.
  32. */
  33. /* Takes a decimal ASCII floating-point number, optionally
  34. * preceded by white space. Must have form "SI.FE-X",
  35. * S may be ither of the signs may be "+", "-", or omitted.
  36. * I is the integer part of the mantissa,
  37. * F is the fractional part of the mantissa,
  38. * X is the exponent.
  39. * Either I or F may be omitted, or both.
  40. * The decimal point isn't necessary unless F is
  41. * present. The "E" may actually be an "e". E and X
  42. * may both be omitted (but not just one).
  43. *
  44. * returns NaN if:
  45. * *string is zero length,
  46. * the first non-white space is not negative sign ('-'), positive sign ('_')
  47. * or a digit
  48. */
  49. double safe_atof(const char *string)
  50. {
  51. static int maxExponent = 511; /* Largest possible base 10 exponent. Any
  52. * exponent larger than this will already
  53. * produce underflow or overflow, so there's
  54. * no need to worry about additional digits.
  55. */
  56. /* Table giving binary powers of 10. Entry is 10^2^i.
  57. * Used to convert decimal exponents into floating-point numbers. */
  58. static double powersOf10[] = {
  59. 10.,
  60. 100.,
  61. 1.0e4,
  62. 1.0e8,
  63. 1.0e16,
  64. 1.0e32,
  65. 1.0e64,
  66. 1.0e128,
  67. 1.0e256
  68. };
  69. bool sign = false, expSign = false;
  70. double fraction, dblExp, *d;
  71. const char *p;
  72. int c;
  73. int exp = 0; // Exponent read from "EX" field.
  74. int fracExp = 0; /* Exponent that derives from the fractional
  75. * part. Under normal circumstatnces, it is
  76. * the negative of the number of digits in F.
  77. * However, if I is very long, the last digits
  78. * of I get dropped (otherwise a long I with a
  79. * large negative exponent could cause an
  80. * unnecessary overflow on I alone). In this
  81. * case, fracExp is incremented one for each
  82. * dropped digit. */
  83. int mantSize; // Number of digits in mantissa.
  84. int decPt; /* Number of mantissa digits BEFORE decimal
  85. * point. */
  86. const char *pExp; /* Temporarily holds location of exponent
  87. * in string. */
  88. /*
  89. * Strip off leading blanks and check for a sign.
  90. */
  91. p = string;
  92. while (isspace((int)*p)) {
  93. p += 1;
  94. }
  95. if (isdigit((int)*p)) {
  96. // ignore
  97. } else if ('-' == *p) {
  98. sign = true;
  99. p += 1;
  100. } else if ('+' == *p) {
  101. p += 1;
  102. } else if ('.' == *p) {
  103. // ignore
  104. } else {
  105. return NAN;
  106. }
  107. /*
  108. * Count the number of digits in the mantissa (including the decimal
  109. * point), and also locate the decimal point.
  110. */
  111. decPt = -1;
  112. for (mantSize = 0; ; mantSize += 1) {
  113. c = *p;
  114. if (!isdigit((int)c)) {
  115. if ((c != '.') || (decPt >= 0)) {
  116. break;
  117. }
  118. decPt = mantSize;
  119. }
  120. p += 1;
  121. }
  122. /*
  123. * Now suck up the digits in the mantissa. Use two integers to
  124. * collect 9 digits each (this is faster than using floating-point).
  125. * If the mantissa has more than 18 digits, ignore the extras, since
  126. * they can't affect the value anyway.
  127. */
  128. pExp = p;
  129. p -= mantSize;
  130. if (decPt < 0) {
  131. decPt = mantSize;
  132. } else {
  133. mantSize -= 1; // One of the digits was the point.
  134. }
  135. if (mantSize > 18) {
  136. fracExp = decPt - 18;
  137. mantSize = 18;
  138. } else {
  139. fracExp = decPt - mantSize;
  140. }
  141. if (mantSize == 0) {
  142. fraction = 0.0;
  143. // p = string;
  144. goto done;
  145. } else {
  146. int frac1, frac2;
  147. frac1 = 0;
  148. for ( ; mantSize > 9; mantSize -= 1) {
  149. c = *p;
  150. p += 1;
  151. if ('.' == c) {
  152. c = *p;
  153. p += 1;
  154. }
  155. frac1 = 10*frac1 + (c - '0');
  156. }
  157. frac2 = 0;
  158. for (; mantSize > 0; mantSize -= 1) {
  159. c = *p;
  160. p += 1;
  161. if ('.' == c) {
  162. c = *p;
  163. p += 1;
  164. }
  165. frac2 = 10*frac2 + (c - '0');
  166. }
  167. fraction = (1.0e9 * frac1) + frac2;
  168. }
  169. /*
  170. * Skim off the exponent.
  171. */
  172. p = pExp;
  173. if (('E' == *p) ||
  174. ('e' == *p)) {
  175. p += 1;
  176. if ('-' == *p) {
  177. expSign = true;
  178. p += 1;
  179. } else {
  180. if ('+' == *p) {
  181. p += 1;
  182. }
  183. expSign = false;
  184. }
  185. while (isdigit((int) *p)) {
  186. exp = exp * 10 + (*p - '0');
  187. p += 1;
  188. }
  189. }
  190. if (expSign) {
  191. exp = fracExp - exp;
  192. } else {
  193. exp = fracExp + exp;
  194. }
  195. /*
  196. * Generate a floating-point number that represents the exponent.
  197. * Do this by processing the exponent one bit at a time to combine
  198. * many powers of 2 of 10. Then combine the exponent with the
  199. * fraction.
  200. */
  201. if (0 > exp) {
  202. expSign = true;
  203. exp = -exp;
  204. } else {
  205. expSign = false;
  206. }
  207. if (exp > maxExponent) {
  208. exp = maxExponent;
  209. errno = ERANGE;
  210. }
  211. dblExp = 1.0;
  212. for (d = powersOf10; exp != 0; exp >>= 1, d += 1) {
  213. if (exp & 01) {
  214. dblExp *= *d;
  215. }
  216. }
  217. if (expSign) {
  218. fraction /= dblExp;
  219. } else {
  220. fraction *= dblExp;
  221. }
  222. done:
  223. if (sign) {
  224. return -fraction;
  225. }
  226. return fraction;
  227. }
  228. #define MONTHSPERYEAR 12 /* months per calendar year */
  229. // stuff a fix structure with recognizable out-of-band values
  230. void gps_clear_fix(struct gps_fix_t *fixp)
  231. {
  232. memset(fixp, 0, sizeof(struct gps_fix_t));
  233. fixp->altitude = NAN; // DEPRECATED, undefined
  234. fixp->altHAE = NAN;
  235. fixp->altMSL = NAN;
  236. fixp->climb = NAN;
  237. fixp->depth = NAN;
  238. fixp->epc = NAN;
  239. fixp->epd = NAN;
  240. fixp->eph = NAN;
  241. fixp->eps = NAN;
  242. fixp->ept = NAN;
  243. fixp->epv = NAN;
  244. fixp->epx = NAN;
  245. fixp->epy = NAN;
  246. fixp->latitude = NAN;
  247. fixp->longitude = NAN;
  248. fixp->magnetic_track = NAN;
  249. fixp->magnetic_var = NAN;
  250. fixp->mode = MODE_NOT_SEEN;
  251. fixp->sep = NAN;
  252. fixp->speed = NAN;
  253. fixp->track = NAN;
  254. // clear ECEF too
  255. fixp->ecef.x = NAN;
  256. fixp->ecef.y = NAN;
  257. fixp->ecef.z = NAN;
  258. fixp->ecef.vx = NAN;
  259. fixp->ecef.vy = NAN;
  260. fixp->ecef.vz = NAN;
  261. fixp->ecef.pAcc = NAN;
  262. fixp->ecef.vAcc = NAN;
  263. fixp->NED.relPosN = NAN;
  264. fixp->NED.relPosE = NAN;
  265. fixp->NED.relPosD = NAN;
  266. fixp->NED.velN = NAN;
  267. fixp->NED.velE = NAN;
  268. fixp->NED.velD = NAN;
  269. fixp->geoid_sep = NAN;
  270. fixp->dgps_age = NAN;
  271. fixp->dgps_station = -1;
  272. fixp->wanglem = NAN;
  273. fixp->wangler = NAN;
  274. fixp->wanglet = NAN;
  275. fixp->wspeedr = NAN;
  276. fixp->wspeedt = NAN;
  277. }
  278. // stuff an attitude structure with recognizable out-of-band values
  279. void gps_clear_att(struct attitude_t *attp)
  280. {
  281. memset(attp, 0, sizeof(struct attitude_t));
  282. attp->acc_len = NAN;
  283. attp->acc_x = NAN;
  284. attp->acc_y = NAN;
  285. attp->acc_z = NAN;
  286. attp->depth = NAN;
  287. attp->dip = NAN;
  288. attp->gyro_temp = NAN;
  289. attp->gyro_x = NAN;
  290. attp->gyro_y = NAN;
  291. attp->gyro_z = NAN;
  292. attp->heading = NAN;
  293. attp->mag_len = NAN;
  294. attp->mag_x = NAN;
  295. attp->mag_y = NAN;
  296. attp->mag_z = NAN;
  297. attp->pitch = NAN;
  298. attp->roll = NAN;
  299. attp->temp = NAN;
  300. attp->yaw = NAN;
  301. }
  302. void gps_clear_dop( struct dop_t *dop)
  303. {
  304. dop->xdop = dop->ydop = dop->vdop = dop->tdop = dop->hdop = dop->pdop =
  305. dop->gdop = NAN;
  306. }
  307. // stuff a log structure with recognizable out-of-band values
  308. void gps_clear_log(struct gps_log_t *logp)
  309. {
  310. memset(logp, 0, sizeof(struct gps_log_t));
  311. logp->lon = NAN;
  312. logp->lat = NAN;
  313. logp->altHAE = NAN;
  314. logp->altMSL = NAN;
  315. logp->gSpeed = NAN;
  316. logp->heading = NAN;
  317. logp->tAcc = NAN;
  318. logp->hAcc = NAN;
  319. logp->vAcc = NAN;
  320. logp->sAcc = NAN;
  321. logp->headAcc = NAN;
  322. logp->velN = NAN;
  323. logp->velE = NAN;
  324. logp->velD = NAN;
  325. logp->pDOP = NAN;
  326. logp->distance = NAN;
  327. logp->totalDistance = NAN;
  328. logp->distanceStd = NAN;
  329. logp->fixType = -1;
  330. }
  331. /* merge new data (from) into current fix (to)
  332. * Being careful not to lose information */
  333. void gps_merge_fix(struct gps_fix_t *to,
  334. gps_mask_t transfer,
  335. struct gps_fix_t *from)
  336. {
  337. if ((NULL == to) ||
  338. (NULL == from)) {
  339. return;
  340. }
  341. if (0 != (transfer & TIME_SET)) {
  342. to->time = from->time;
  343. }
  344. if (0 != (transfer & LATLON_SET)) {
  345. to->latitude = from->latitude;
  346. to->longitude = from->longitude;
  347. }
  348. if (0 != (transfer & MODE_SET)) {
  349. // FIXME? Maybe only upgrade mode, not downgrade it
  350. to->mode = from->mode;
  351. }
  352. /* Some messages only report mode, some mode and status, some only status.
  353. * Only upgrade status, not downgrade it */
  354. if (0 != (transfer & STATUS_SET)) {
  355. if (to->status < from->status) {
  356. to->status = from->status;
  357. }
  358. }
  359. if ((transfer & ALTITUDE_SET) != 0) {
  360. if (0 != isfinite(from->altHAE)) {
  361. to->altHAE = from->altHAE;
  362. }
  363. if (0 != isfinite(from->altMSL)) {
  364. to->altMSL = from->altMSL;
  365. }
  366. if (0 != isfinite(from->depth)) {
  367. to->depth = from->depth;
  368. }
  369. }
  370. if (0 != (transfer & TRACK_SET)) {
  371. to->track = from->track;
  372. }
  373. if (0 != (transfer & MAGNETIC_TRACK_SET)) {
  374. if (0 != isfinite(from->magnetic_track)) {
  375. to->magnetic_track = from->magnetic_track;
  376. }
  377. if (0 != isfinite(from->magnetic_var)) {
  378. to->magnetic_var = from->magnetic_var;
  379. }
  380. }
  381. if (0 != (transfer & SPEED_SET)) {
  382. to->speed = from->speed;
  383. }
  384. if (0 != (transfer & CLIMB_SET)) {
  385. to->climb = from->climb;
  386. }
  387. if (0 != (transfer & TIMERR_SET)) {
  388. to->ept = from->ept;
  389. }
  390. if (0 != isfinite(from->epx) &&
  391. 0 != isfinite(from->epy)) {
  392. to->epx = from->epx;
  393. to->epy = from->epy;
  394. }
  395. if (0 != isfinite(from->epd)) {
  396. to->epd = from->epd;
  397. }
  398. if (0 != isfinite(from->eph)) {
  399. to->eph = from->eph;
  400. }
  401. if (0 != isfinite(from->eps)) {
  402. to->eps = from->eps;
  403. }
  404. // spherical error probability, not geoid separation
  405. if (0 != isfinite(from->sep)) {
  406. to->sep = from->sep;
  407. }
  408. // geoid separation, not spherical error probability
  409. if (0 != isfinite(from->geoid_sep)) {
  410. to->geoid_sep = from->geoid_sep;
  411. }
  412. if (0 != isfinite(from->epv)) {
  413. to->epv = from->epv;
  414. }
  415. if (0 != (transfer & SPEEDERR_SET)) {
  416. to->eps = from->eps;
  417. }
  418. if (0 != (transfer & ECEF_SET)) {
  419. to->ecef.x = from->ecef.x;
  420. to->ecef.y = from->ecef.y;
  421. to->ecef.z = from->ecef.z;
  422. to->ecef.pAcc = from->ecef.pAcc;
  423. }
  424. if (0 != (transfer & VECEF_SET)) {
  425. to->ecef.vx = from->ecef.vx;
  426. to->ecef.vy = from->ecef.vy;
  427. to->ecef.vz = from->ecef.vz;
  428. to->ecef.vAcc = from->ecef.vAcc;
  429. }
  430. if (0 != (transfer & NED_SET)) {
  431. to->NED.relPosN = from->NED.relPosN;
  432. to->NED.relPosE = from->NED.relPosE;
  433. to->NED.relPosD = from->NED.relPosD;
  434. if ((0 != isfinite(from->NED.relPosH)) &&
  435. (0 != isfinite(from->NED.relPosL))) {
  436. to->NED.relPosH = from->NED.relPosH;
  437. to->NED.relPosL = from->NED.relPosL;
  438. }
  439. }
  440. if (0 != (transfer & VNED_SET)) {
  441. to->NED.velN = from->NED.velN;
  442. to->NED.velE = from->NED.velE;
  443. to->NED.velD = from->NED.velD;
  444. }
  445. if ('\0' != from->datum[0]) {
  446. strlcpy(to->datum, from->datum, sizeof(to->datum));
  447. }
  448. if (0 != isfinite(from->dgps_age) &&
  449. 0 <= from->dgps_station) {
  450. // both, or neither
  451. to->dgps_age = from->dgps_age;
  452. to->dgps_station = from->dgps_station;
  453. }
  454. // navdata stuff. just wind angle and angle for now
  455. if (0 != (transfer & NAVDATA_SET)) {
  456. if (0 != isfinite(from->wanglem)) {
  457. to->wanglem = from->wanglem;
  458. }
  459. if (0 != isfinite(from->wangler)) {
  460. to->wangler = from->wangler;
  461. }
  462. if (0 != isfinite(from->wanglet)) {
  463. to->wanglet = from->wanglet;
  464. }
  465. if (0 != isfinite(from->wspeedr)) {
  466. to->wspeedr = from->wspeedr;
  467. }
  468. if (0 != isfinite(from->wspeedt)) {
  469. to->wspeedt = from->wspeedt;
  470. }
  471. }
  472. }
  473. /* mkgmtime(tm)
  474. * convert struct tm, as UTC, to seconds since Unix epoch
  475. * This differs from mktime() from libc.
  476. * mktime() takes struct tm as localtime.
  477. *
  478. * The inverse of gmtime(time_t)
  479. */
  480. time_t mkgmtime(struct tm * t)
  481. {
  482. int year;
  483. time_t result;
  484. static const int cumdays[MONTHSPERYEAR] =
  485. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
  486. year = 1900 + t->tm_year + t->tm_mon / MONTHSPERYEAR;
  487. result = (year - 1970) * 365 + cumdays[t->tm_mon % MONTHSPERYEAR];
  488. result += (year - 1968) / 4;
  489. result -= (year - 1900) / 100;
  490. result += (year - 1600) / 400;
  491. if (0 == (year % 4) &&
  492. (0 != (year % 100) ||
  493. 0 == (year % 400)) &&
  494. (2 > (t->tm_mon % MONTHSPERYEAR))) {
  495. result--;
  496. }
  497. result += t->tm_mday - 1;
  498. result *= 24;
  499. result += t->tm_hour;
  500. result *= 60;
  501. result += t->tm_min;
  502. result *= 60;
  503. result += t->tm_sec;
  504. /* this is UTC, no DST
  505. * if (t->tm_isdst == 1)
  506. * result -= 3600;
  507. */
  508. return (result);
  509. }
  510. // ISO8601 UTC to Unix timespec, no leapsecond correction.
  511. timespec_t iso8601_to_timespec(char *isotime)
  512. {
  513. timespec_t ret;
  514. #ifndef __clang_analyzer__
  515. #ifndef USE_QT
  516. double usec = 0;
  517. struct tm tm;
  518. memset(&tm,0,sizeof(tm));
  519. #ifdef HAVE_STRPTIME
  520. {
  521. char *dp = NULL;
  522. dp = strptime(isotime, "%Y-%m-%dT%H:%M:%S", &tm);
  523. if (NULL != dp &&
  524. '.' == *dp) {
  525. usec = strtod(dp, NULL);
  526. }
  527. }
  528. #else
  529. /* Fallback for systems without strptime (i.e. Windows)
  530. * This is a simplistic conversion for iso8601 strings only,
  531. * rather than embedding a full copy of strptime() that handles
  532. * all formats */
  533. /* Thus avoiding needing to test for (broken) negative date/time
  534. * numbers in token reading - only need to check the upper range */
  535. bool failed = false;
  536. char *isotime_tokenizer = strdup(isotime);
  537. if (isotime_tokenizer) {
  538. char *tmpbuf;
  539. char *pch = strtok_r(isotime_tokenizer, "-T:", &tmpbuf);
  540. int token_number = 0;
  541. while (NULL != pch) {
  542. double sec;
  543. unsigned int tmp;
  544. token_number++;
  545. // Give up if encountered way too many tokens.
  546. if (10 < token_number) {
  547. failed = true;
  548. break;
  549. }
  550. switch (token_number) {
  551. case 1: // Year token
  552. tmp = atoi(pch);
  553. if (9999 > tmp) {
  554. tm.tm_year = tmp - 1900; // Adjust to tm year
  555. } else {
  556. failed = true;
  557. }
  558. break;
  559. case 2: // Month token
  560. tmp = atoi(pch);
  561. if (13 > tmp) {
  562. tm.tm_mon = tmp - 1; // Month indexing starts from zero
  563. } else {
  564. failed = true;
  565. }
  566. break;
  567. case 3: // Day token
  568. tmp = atoi(pch);
  569. if (32 > tmp) {
  570. tm.tm_mday = tmp;
  571. } else {
  572. failed = true;
  573. }
  574. break;
  575. case 4: // Hour token
  576. tmp = atoi(pch);
  577. if (24 > tmp) {
  578. tm.tm_hour = tmp;
  579. } else {
  580. failed = true;
  581. }
  582. break;
  583. case 5: // Minute token
  584. tmp = atoi(pch);
  585. if (60 > tmp) {
  586. tm.tm_min = tmp;
  587. } else {
  588. failed = true;
  589. }
  590. break;
  591. case 6: // Seconds token
  592. sec = safe_atof(pch);
  593. // NB To handle timestamps with leap seconds
  594. if (0 == isfinite(sec) &&
  595. 0.0 <= sec &&
  596. 61.5 > sec) {
  597. // Truncate to get integer value
  598. tm.tm_sec = (unsigned int)sec;
  599. // Get the fractional part (if any)
  600. usec = sec - (unsigned int)sec;
  601. } else {
  602. failed = true;
  603. }
  604. break;
  605. default:
  606. break;
  607. }
  608. pch = strtok_r(NULL, "-T:", &tmpbuf);
  609. }
  610. free(isotime_tokenizer);
  611. /* Split may result in more than 6 tokens if the TZ has any t's
  612. * in it. So check that we've seen enough tokens rather than
  613. * an exact number */
  614. if (6 > token_number) {
  615. failed = true;
  616. }
  617. }
  618. if (failed) {
  619. memset(&tm,0,sizeof(tm));
  620. } else {
  621. /* When successful this normalizes tm so that tm_yday is set
  622. * and thus tm is valid for use with other functions */
  623. if ((time_t)-1 == mktime(&tm)) {
  624. // Failed mktime - so reset the timestamp
  625. memset(&tm,0,sizeof(tm));
  626. }
  627. }
  628. #endif
  629. /*
  630. * It would be nice if we could say mktime(&tm) - timezone + usec instead,
  631. * but timezone is not available at all on some BSDs. Besides, when working
  632. * with historical dates the value of timezone after an ordinary tzset(3)
  633. * can be wrong; you have to do a redirect through the IANA historical
  634. * timezone database to get it right.
  635. */
  636. ret.tv_sec = mkgmtime(&tm);
  637. ret.tv_nsec = usec * 1e9;;
  638. #else
  639. double usec = 0;
  640. QString t(isotime);
  641. QDateTime d = QDateTime::fromString(isotime, Qt::ISODate);
  642. QStringList sl = t.split(".");
  643. if (1 < sl.size()) {
  644. usec = sl[1].toInt() / pow(10., (double)sl[1].size());
  645. }
  646. ret.tv_sec = d.toTime_t();
  647. ret.tv_nsec = usec * 1e9;;
  648. #endif
  649. #endif /* __clang_analyzer__ */
  650. #if 4 < SIZEOF_TIME_T
  651. if (253402300799LL < ret.tv_sec) {
  652. // enforce max "9999-12-31T23:59:59.999Z"
  653. ret.tv_sec = 253402300799LL;
  654. }
  655. #endif
  656. return ret;
  657. }
  658. /* Convert POSIX timespec to ISO8601 UTC, put result in isotime.
  659. * no timezone adjustment
  660. * Return: pointer to isotime.
  661. * example: 2007-12-11T23:38:51.033Z */
  662. char *timespec_to_iso8601(timespec_t fixtime, char isotime[], size_t len)
  663. {
  664. struct tm when;
  665. char timestr[30];
  666. long fracsec;
  667. if (0 > fixtime.tv_sec) {
  668. // Allow 0 for testing of 1970-01-01T00:00:00.000Z
  669. strlcpy(isotime, "NaN", len);
  670. return isotime;
  671. }
  672. if (999499999 < fixtime.tv_nsec) {
  673. // round up
  674. fixtime.tv_sec++;
  675. fixtime.tv_nsec = 0;
  676. }
  677. #if 4 < SIZEOF_TIME_T
  678. if (253402300799LL < fixtime.tv_sec) {
  679. // enforce max "9999-12-31T23:59:59.999Z"
  680. fixtime.tv_sec = 253402300799LL;
  681. }
  682. #endif
  683. #ifdef HAVE_GMTIME_R
  684. (void)gmtime_r(&fixtime.tv_sec, &when);
  685. #else
  686. // Fallback to try with gmtime_s - primarily for Windows
  687. (void)gmtime_s(&when, &fixtime.tv_sec);
  688. #endif
  689. /*
  690. * Do not mess casually with the number of decimal digits in the
  691. * format! Most GPSes report over serial links at 0.01s or 0.001s
  692. * precision. Round to 0.001s
  693. */
  694. fracsec = (fixtime.tv_nsec + 500000) / 1000000;
  695. (void)strftime(timestr, sizeof(timestr), "%Y-%m-%dT%H:%M:%S", &when);
  696. (void)snprintf(isotime, len, "%s.%03ldZ",timestr, fracsec);
  697. return isotime;
  698. }
  699. char *timespec_to_unix(timespec_t fixtime, char isotime[], size_t len)
  700. {
  701. struct tm when;
  702. char timestr[30];
  703. long fracsec;
  704. if (0 > fixtime.tv_sec) {
  705. // Allow 0 for testing of 1970-01-01T00:00:00.000Z
  706. strlcpy(isotime, "NaN", len);
  707. return isotime;
  708. }
  709. if (999499999 < fixtime.tv_nsec) {
  710. // round up
  711. fixtime.tv_sec++;
  712. fixtime.tv_nsec = 0;
  713. }
  714. #if 4 < SIZEOF_TIME_T
  715. if (253402300799LL < fixtime.tv_sec) {
  716. // enforce max "9999-12-31T23:59:59.999Z"
  717. fixtime.tv_sec = 253402300799LL;
  718. }
  719. #endif
  720. #ifdef HAVE_GMTIME_R
  721. (void)gmtime_r(&fixtime.tv_sec, &when);
  722. #else
  723. // Fallback to try with gmtime_s - primarily for Windows
  724. (void)gmtime_s(&when, &fixtime.tv_sec);
  725. #endif
  726. /*
  727. * Do not mess casually with the number of decimal digits in the
  728. * format! Most GPSes report over serial links at 0.01s or 0.001s
  729. * precision. Round to 0.001s
  730. */
  731. fracsec = (fixtime.tv_nsec + 500000) / 1000000;
  732. (void)strftime(timestr, sizeof(timestr), "%s", &when);
  733. (void)snprintf(isotime, len, "%s",timestr, fracsec);
  734. return isotime;
  735. }
  736. /* return time now as ISO8601, no timezone adjustment
  737. * example: 2007-12-11T23:38:51.033Z */
  738. char *now_to_iso8601(char *tbuf, size_t tbuf_sz)
  739. {
  740. timespec_t ts_now;
  741. (void)clock_gettime(CLOCK_REALTIME, &ts_now);
  742. return timespec_to_iso8601(ts_now, tbuf, tbuf_sz);
  743. }
  744. #define Deg2Rad(n) ((n) * DEG_2_RAD)
  745. /* Distance in meters between two points specified in degrees, optionally
  746. * with initial and final bearings. */
  747. double earth_distance_and_bearings(double lat1, double lon1,
  748. double lat2, double lon2,
  749. double *ib, double *fb)
  750. {
  751. /*
  752. * this is a translation of the javascript implementation of the
  753. * Vincenty distance formula by Chris Veness. See
  754. * http://www.movable-type.co.uk/scripts/latlong-vincenty.html
  755. */
  756. double a, b, f; // WGS-84 ellipsoid params
  757. double L, L_P, U1, U2, s_U1, c_U1, s_U2, c_U2;
  758. double uSq, A, B, d_S, lambda;
  759. // cppcheck-suppress variableScope
  760. double s_L, c_L, s_A, C;
  761. double c_S, S, s_S, c_SqA, c_2SM;
  762. int i = 100;
  763. a = WGS84A;
  764. b = WGS84B;
  765. f = 1 / WGS84F;
  766. L = Deg2Rad(lon2 - lon1);
  767. U1 = atan((1 - f) * tan(Deg2Rad(lat1)));
  768. U2 = atan((1 - f) * tan(Deg2Rad(lat2)));
  769. s_U1 = sin(U1);
  770. c_U1 = cos(U1);
  771. s_U2 = sin(U2);
  772. c_U2 = cos(U2);
  773. lambda = L;
  774. do {
  775. s_L = sin(lambda);
  776. c_L = cos(lambda);
  777. s_S = sqrt((c_U2 * s_L) * (c_U2 * s_L) +
  778. (c_U1 * s_U2 - s_U1 * c_U2 * c_L) *
  779. (c_U1 * s_U2 - s_U1 * c_U2 * c_L));
  780. if (0 == s_S) {
  781. return 0;
  782. }
  783. c_S = s_U1 * s_U2 + c_U1 * c_U2 * c_L;
  784. S = atan2(s_S, c_S);
  785. s_A = c_U1 * c_U2 * s_L / s_S;
  786. c_SqA = 1 - s_A * s_A;
  787. c_2SM = c_S - 2 * s_U1 * s_U2 / c_SqA;
  788. if (0 == isfinite(c_2SM)) {
  789. c_2SM = 0;
  790. }
  791. C = f / 16 * c_SqA * (4 + f * (4 - 3 * c_SqA));
  792. L_P = lambda;
  793. lambda = L + (1 - C) * f * s_A *
  794. (S + C * s_S * (c_2SM + C * c_S * (2 * c_2SM * c_2SM - 1)));
  795. } while ((fabs(lambda - L_P) > 1.0e-12) &&
  796. (0 < --i));
  797. if (0 == i) {
  798. return NAN; // formula failed to converge
  799. }
  800. uSq = c_SqA * ((a * a) - (b * b)) / (b * b);
  801. A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
  802. B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
  803. d_S = B * s_S * (c_2SM + B / 4 *
  804. (c_S * (-1 + 2 * c_2SM * c_2SM) - B / 6 * c_2SM *
  805. (-3 + 4 * s_S * s_S) * (-3 + 4 * c_2SM * c_2SM)));
  806. if (NULL != ib) {
  807. *ib = atan2(c_U2 * sin(lambda),
  808. c_U1 * s_U2 - s_U1 * c_U2 * cos(lambda));
  809. }
  810. if (NULL != fb) {
  811. *fb = atan2(c_U1 * sin(lambda),
  812. c_U1 * s_U2 * cos(lambda) - s_U1 * c_U2);
  813. }
  814. return (WGS84B * A * (S - d_S));
  815. }
  816. // Distance in meters between two points specified in degrees.
  817. double earth_distance(double lat1, double lon1, double lat2, double lon2)
  818. {
  819. return earth_distance_and_bearings(lat1, lon1, lat2, lon2, NULL, NULL);
  820. }
  821. // Wait for data until timeout, ignoring signals.
  822. bool nanowait(int fd, struct timespec *to)
  823. {
  824. fd_set fdset;
  825. FD_ZERO(&fdset);
  826. FD_SET(fd, &fdset);
  827. TS_NORM(to); // just in case
  828. // sigmask is NULL, so equivalent to select()
  829. return pselect(fd + 1, &fdset, NULL, NULL, to, NULL) == 1;
  830. }
  831. /* Accept a datum code, return matching string
  832. *
  833. * There are a ton of these, only a few are here
  834. *
  835. */
  836. void datum_code_string(int code, char *buffer, size_t len)
  837. {
  838. const char *datum_str;
  839. switch (code) {
  840. case 0:
  841. datum_str = "WGS84";
  842. break;
  843. case 21:
  844. datum_str = "WGS84";
  845. break;
  846. case 178:
  847. datum_str = "Tokyo Mean";
  848. break;
  849. case 179:
  850. datum_str = "Tokyo-Japan";
  851. break;
  852. case 180:
  853. datum_str = "Tokyo-Korea";
  854. break;
  855. case 181:
  856. datum_str = "Tokyo-Okinawa";
  857. break;
  858. case 182:
  859. datum_str = "PZ90.11";
  860. break;
  861. case 999:
  862. datum_str = "User Defined";
  863. break;
  864. default:
  865. datum_str = NULL;
  866. break;
  867. }
  868. if (NULL == datum_str) {
  869. // Fake it
  870. snprintf(buffer, len, "%d", code);
  871. } else {
  872. strlcpy(buffer, datum_str, len);
  873. }
  874. }
  875. /* make up an NMEA 4.0 (extended) PRN based on gnssId:svId,
  876. * This does NOT match NMEA 4.10 and 4.11 where all PRN are 1-99,
  877. * except IMEA
  878. * Ref Appendix A from u-blox ZED-F9P Interface Description
  879. * and
  880. * Section 1.5.3 M10-FW500_InterfaceDescription_UBX-20053845.pdf
  881. *
  882. * Return PRN, or zero for error
  883. */
  884. short ubx2_to_prn(int gnssId, int svId)
  885. {
  886. short nmea_PRN;
  887. if (1 > svId) {
  888. // skip 0 svId
  889. return 0;
  890. }
  891. switch (gnssId) {
  892. case 0:
  893. // GPS, 1-32 maps to 1-32
  894. if (32 < svId) {
  895. // skip bad svId
  896. return 0;
  897. }
  898. nmea_PRN = svId;
  899. break;
  900. case 1:
  901. // SBAS, 120..151, 152..158 maps to 33..64, 152..158
  902. if (120 > svId) {
  903. // Huh?
  904. return 0;
  905. } else if (151 >= svId) {
  906. nmea_PRN = svId - 87;
  907. } else if (158 >= svId) {
  908. nmea_PRN = svId;
  909. } else {
  910. /* Huh? */
  911. return 0;
  912. }
  913. break;
  914. case 2:
  915. // Galileo, ubx gnssid:svid 1..36 -> 301-336
  916. // Galileo, ubx PRN 211..246 -> 301-336
  917. if (36 >= svId) {
  918. nmea_PRN = svId + 300;
  919. } else if (211 > svId) {
  920. // skip bad svId
  921. return 0;
  922. } else if (246 >= svId) {
  923. nmea_PRN = svId + 90;
  924. } else {
  925. // skip bad svId
  926. return 0;
  927. }
  928. break;
  929. case 3:
  930. // BeiDou, ubx gnssid:svid 1..37 -> to 401-437
  931. // BeiDou, ubx PRN 159..163,33..64 -> to 401-437 ??
  932. if (37 >= svId) {
  933. nmea_PRN = svId + 400;
  934. } else if (159 > svId) {
  935. // skip bad svId
  936. return 0;
  937. } else if (163 >= svId) {
  938. nmea_PRN = svId + 242;
  939. } else {
  940. // skip bad svId
  941. return 0;
  942. }
  943. break;
  944. case 4:
  945. // IMES, ubx gnssid:svid 1-10 -> to 173-182
  946. // IMES, ubx PRN 173-182 to 173-182
  947. if (10 < svId) {
  948. // skip bad svId
  949. return 0;
  950. } else if (173 > svId) {
  951. // skip bad svId
  952. return 0;
  953. } else if (182 >= svId) {
  954. nmea_PRN = svId;
  955. }
  956. nmea_PRN = svId + 172;
  957. break;
  958. case 5:
  959. // QZSS, ubx gnssid:svid 1-10 to 193-202
  960. // QZSS, ubx PRN 193-202 to 193-202
  961. if (10 >= svId) {
  962. nmea_PRN = svId + 192;
  963. } else if (193 > svId) {
  964. // skip bad svId
  965. return 0;
  966. } else if (202 >= svId) {
  967. nmea_PRN = svId;
  968. } else {
  969. // skip bad svId
  970. return 0;
  971. }
  972. break;
  973. case 6:
  974. // GLONASS, 1-32 maps to 65-96
  975. if (32 >= svId) {
  976. nmea_PRN = svId + 64;
  977. } else if (65 > svId) {
  978. // skip bad svId
  979. return 0;
  980. } else if (96 >= svId) {
  981. nmea_PRN = svId;
  982. } else {
  983. // skip bad svId, 255 == tracked, but unidentified, skip
  984. return 0;
  985. }
  986. break;
  987. case 7:
  988. // NavIC (IRNSS)
  989. FALLTHROUGH
  990. default:
  991. // Huh?
  992. return 0;
  993. }
  994. return nmea_PRN;
  995. }
  996. // vim: set expandtab shiftwidth=4