Coverage Report

Created: 2025-08-26 06:29

/src/gpsd/gpsd-3.26.2~dev/libgps/gpsutils.c
Line
Count
Source (jump to first uncovered line)
1
/* gpsutils.c -- code shared between low-level and high-level interfaces
2
 *
3
 * This file is Copyright by the GPSD project
4
 * SPDX-License-Identifier: BSD-2-clause
5
 */
6
7
/* The strptime prototype is not provided unless explicitly requested.
8
 * We also need to set the value high enough to signal inclusion of
9
 * newer features (like clock_gettime).  See the POSIX spec for more info:
10
 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_02_01_02 */
11
12
#include "../include/gpsd_config.h"    // must be before all includes
13
14
#include <ctype.h>
15
#include <errno.h>
16
#include <math.h>
17
#include <stdbool.h>
18
#include <stdio.h>
19
#include <stdlib.h>
20
#include <string.h>
21
#include <sys/select.h>  // for to have a pselect(2) prototype a la POSIX
22
#include <sys/time.h>    // for to have a pselect(2) prototype a la SuS
23
#include <time.h>
24
25
#include "../include/gps.h"
26
#include "../include/libgps.h"
27
#include "../include/os_compat.h"
28
#include "../include/timespec.h"
29
30
#ifdef USE_QT
31
#include <QDateTime>
32
#include <QStringList>
33
#endif
34
35
// decodes for gps_fix_t
36
37
// ant_stat
38
const struct vlist_t vant_status[] = {
39
    {ANT_UNK, "UNK"},     // 0
40
    {ANT_OK, "OK"},     // 1
41
    {ANT_OPEN, "OPEN"},    // 2
42
    {ANT_SHORT, "SHORT"},   // 3
43
    {0, NULL},
44
};
45
46
// gnssId names
47
const struct vlist_t vgnssId[] = {
48
    {0, "GPS"},
49
    {1, "SBAS"},
50
    {2, "GAL"},
51
    {3, "BDS"},
52
    {4, "IMES"},
53
    {5, "QZSS"},
54
    {6, "GLO"},
55
    {7, "NavIC"},
56
    {0, NULL},
57
};
58
59
// mode val to mode string
60
const struct vlist_t vmode_str[] = {
61
    {1, "No Fix"},
62
    {2, "2D Fix"},
63
    {3, "3D Fix"},
64
    {0, NULL},
65
};
66
67
// status val to status string
68
const struct vlist_t vstatus_str[] = {
69
    {0, "UNK"},
70
    {1, "GPS"},
71
    {2, "DGPS"},
72
    {3, "RTK_FIX"},
73
    {4, "RTK_FLT"},
74
    {5, "DR"},
75
    {6, "GNSSDR"},
76
    {7, "TIME"},      // Surveyd
77
    {8, "SIM "},
78
    {0, NULL},
79
};
80
81
/* char2str(ch, vlist) - given a char, return a matching string.
82
 *
83
 * Return: pointer to string
84
 */
85
const char *char2str(unsigned char ch, const struct clist_t *clist)
86
0
{
87
0
    while (NULL != clist->str) {
88
0
        if (clist->ch == ch) {
89
0
            return clist->str;
90
0
        }
91
0
        clist++;
92
0
    }
93
0
    return "Unk";
94
0
}
95
96
/* flags2str(val, vlist) - given flags, return a matching string.
97
 *
98
 * flags the flags to find in vlist
99
 * buffer -  the buffer to return string in
100
 ( buflen - length of buffer
101
 *
102
 * Return: pointer to passed in buffer
103
 *         A string matching the flags.
104
 */
105
const char *flags2str(unsigned long flags, const struct flist_t *flist,
106
                      char *buffer, size_t buflen)
107
0
{
108
0
    buffer[0] = '\0';
109
0
    while (NULL != flist->str) {
110
0
        if (flist->val == (flist->mask & flags)) {
111
0
            if ('\0' != buffer[0]) {
112
0
                strlcat(buffer, ",", buflen);
113
0
            }
114
0
            strlcat(buffer, flist->str, buflen);
115
0
        }
116
0
        flist++;
117
0
    }
118
0
    return buffer;
119
0
}
120
121
/* sigid2str()
122
 *
123
 * given a gpsd gnssid, and gpsd sigid, return a string for the
124
 * sigid.  These are (mostly) UBX compatible.  NOT NMEA compatible.
125
 *
126
 * See sigid in include/gps.h
127
 *
128
 * return: static const string
129
 */
130
const char *sigid2str(unsigned char gnssid, unsigned char sigid)
131
0
{
132
0
    const char *rets = "Unk";
133
134
0
#define SIGID_NUM 16
135
0
    const char *xlate[GNSSID_CNT][SIGID_NUM] = {
136
       // 0 - GPS
137
0
       {"L1C", NULL,  NULL,  "L2 CL",  "L2 CM",  NULL,  "L5 I",  "L5 Q", },
138
       // 1 - SBAS
139
0
       {"L1C",},
140
       // 2 - CGalileo
141
0
       {"E1C", NULL, "E1 B", "E5 aI", "E5 aQ", "E5 bI", "E5 bQ",
142
0
        NULL, "E6 B", NULL, "E6 A",},
143
       // 3 - BeiDou
144
0
       {"B1I D1", "B1I D2", "B2I D1", "B2I D2", "B3I D1", "B1 Cp", "B1 Cd",
145
0
        "B2 ap", "B2 ad", NULL, "B3I D2",},
146
       // 4 - IMESS
147
0
       {"L5 A",},
148
       // 5 - QZSS
149
0
       {"L1C/A", "L1 S", NULL, NULL, "L2 CM", "L2 CL", NULL, "L5 I",
150
0
        NULL, "L5 Q", NULL, NULL, "L1 C/B",},
151
       // 6 - GLONASS
152
0
       {"L1 OF", NULL, "L2 OF",},
153
       // 8 - IRNSS (NavIC)
154
0
       {"L5 A",},
155
156
0
    };
157
158
0
    if (GNSSID_CNT <= gnssid) {
159
0
        rets = "GNSS-Unk";
160
0
    } else if (SIGID_NUM <= gnssid) {
161
0
        rets = "SIG-Unk";
162
0
    } else {
163
0
        rets = xlate[gnssid][sigid];
164
0
        if (NULL == rets) {
165
0
            rets = "Unk";
166
0
        }
167
0
    }
168
169
0
    return rets;
170
0
}
171
172
/* sigid2obs()
173
 *
174
 * given a gpsd gnssid, and gpsd sigid, return a string for the
175
 * RINEX observation code.  These are (mostly) UBX compatible.
176
 *  NOT NMEA compatible.
177
 *
178
 * return: static const string
179
 */
180
const char *sigid2obs(unsigned char gnssid, unsigned char sigid)
181
0
{
182
0
    const char *rets = "Unk";
183
184
0
#define SIGID_NUM 16
185
0
    const char *xlate[GNSSID_CNT][SIGID_NUM] = {
186
       // 0 - gep
187
0
       {"C1C", NULL,  NULL,  "C2L",  "C2S",  NULL,  "C5I",  "C5Q", },
188
       // 1 - SBAS
189
0
       {"C1C",},
190
       // 2 - Galileo
191
0
       {"C1C", NULL, "C1B", "C5I", "C5Q", "C7I", "C7Q", NULL, "C6B",
192
0
        NULL, "C6A",},
193
       // 3 - BeiDou
194
0
       {"C2I", "C2I", "C7I", "C7I", "C6I", "C1P", "C1D", "C5P", "C5D",
195
0
        NULL, "C6I",},
196
       // 4 - IMESS
197
0
       {NULL,},
198
       // 5 - QZSS
199
0
       {"C1C", "C1Z", NULL, NULL, "C2S", "C2L", NULL, "C5I", NULL,
200
0
        "C5Q", NULL, NULL, "C1E",},
201
       // 6 - GLONASS
202
0
       {"L1C", NULL, "C2C",},
203
       // 8 - IRNSS (NavIC)
204
0
       {"L5A",},
205
206
0
    };
207
208
0
    if (GNSSID_CNT <= gnssid) {
209
0
        rets = "GNSS-Unk";
210
0
    } else if (SIGID_NUM <= gnssid) {
211
0
        rets = "SIG-Unk";
212
0
    } else {
213
0
        rets = xlate[gnssid][sigid];
214
0
        if (NULL == rets) {
215
0
            rets = "Unk";
216
0
        }
217
0
    }
218
219
0
    return rets;
220
0
}
221
222
/* val2str(val, vlist) - given a value, return a matching string.
223
 *
224
 * val the value to find in vlist
225
 *
226
 * Return: pointer to static string
227
 *         The string matching val, or "Unk".
228
 */
229
const char *val2str(unsigned long val, const struct vlist_t *vlist)
230
0
{
231
0
    while (NULL != vlist->str) {
232
0
        if (vlist->val == val) {
233
0
            return vlist->str;
234
0
        }
235
0
        vlist++;
236
0
    }
237
0
    return "Unk";
238
0
}
239
240
/*
241
 * Berkeley implementation of strtod(), inlined to avoid locale problems
242
 * with the decimal point and stripped down to an atof()-equivalent.
243
 */
244
245
/* Takes a decimal ASCII floating-point number, optionally
246
 * preceded by white space.  Must have form "SI.FE-X",
247
 * S may be ither of the signs may be "+", "-", or omitted.
248
 * I is the integer part of the mantissa,
249
 * F is the fractional part of the mantissa,
250
 * X is the exponent.
251
 * Either I or F may be omitted, or both.
252
 * The decimal point isn't necessary unless F is
253
 * present.  The "E" may actually be an "e".  E and X
254
 * may both be omitted (but not just one).
255
 *
256
 * returns NaN if:
257
 *    *string is zero length,
258
 *    the first non-white space is not negative sign ('-'), positive sign ('_')
259
 *    or a digit
260
 */
261
double safe_atof(const char *string)
262
5.10k
{
263
5.10k
    static int maxExponent = 511;   /* Largest possible base 10 exponent.  Any
264
                                     * exponent larger than this will already
265
                                     * produce underflow or overflow, so there's
266
                                     * no need to worry about additional digits.
267
                                     */
268
    /* Table giving binary powers of 10.  Entry is 10^2^i.
269
     * Used to convert decimal exponents into floating-point numbers. */
270
5.10k
    static double powersOf10[] = {
271
5.10k
        10.,
272
5.10k
        100.,
273
5.10k
        1.0e4,
274
5.10k
        1.0e8,
275
5.10k
        1.0e16,
276
5.10k
        1.0e32,
277
5.10k
        1.0e64,
278
5.10k
        1.0e128,
279
5.10k
        1.0e256
280
5.10k
    };
281
282
5.10k
    bool sign = false, expSign = false;
283
5.10k
    double fraction, dblExp, *d;
284
5.10k
    const char *p;
285
5.10k
    int c;
286
5.10k
    int exp = 0;                // Exponent read from "EX" field.
287
5.10k
    int fracExp = 0;            /* Exponent that derives from the fractional
288
                                 * part.  Under normal circumstatnces, it is
289
                                 * the negative of the number of digits in F.
290
                                 * However, if I is very long, the last digits
291
                                 * of I get dropped (otherwise a long I with a
292
                                 * large negative exponent could cause an
293
                                 * unnecessary overflow on I alone).  In this
294
                                 * case, fracExp is incremented one for each
295
                                 * dropped digit. */
296
5.10k
    int mantSize;               // Number of digits in mantissa.
297
5.10k
    int decPt;                  /* Number of mantissa digits BEFORE decimal
298
                                 * point. */
299
5.10k
    const char *pExp;           /* Temporarily holds location of exponent
300
                                 * in string. */
301
302
    /*
303
     * Strip off leading blanks and check for a sign.
304
     */
305
306
5.10k
    p = string;
307
5.10k
    while (isspace((int)*p)) {
308
0
        p += 1;
309
0
    }
310
5.10k
    if (isdigit((int)*p)) {
311
        // ignore
312
3.03k
    } else if ('-' == *p) {
313
391
        sign = true;
314
391
        p += 1;
315
1.67k
    } else if ('+' == *p) {
316
198
        p += 1;
317
1.47k
    } else if ('.' == *p) {
318
        // ignore
319
799
    } else {
320
675
        return NAN;
321
675
    }
322
323
    /*
324
     * Count the number of digits in the mantissa (including the decimal
325
     * point), and also locate the decimal point.
326
     */
327
328
4.42k
    decPt = -1;
329
21.8k
    for (mantSize = 0; ; mantSize += 1) {
330
21.8k
        c = *p;
331
21.8k
        if (!isdigit((int)c)) {
332
5.45k
            if ((c != '.') || (decPt >= 0)) {
333
4.42k
                break;
334
4.42k
            }
335
1.02k
            decPt = mantSize;
336
1.02k
        }
337
17.4k
        p += 1;
338
17.4k
    }
339
340
    /*
341
     * Now suck up the digits in the mantissa.  Use two integers to
342
     * collect 9 digits each (this is faster than using floating-point).
343
     * If the mantissa has more than 18 digits, ignore the extras, since
344
     * they can't affect the value anyway.
345
     */
346
347
4.42k
    pExp  = p;
348
4.42k
    p -= mantSize;
349
4.42k
    if (decPt < 0) {
350
3.40k
        decPt = mantSize;
351
3.40k
    } else {
352
1.02k
        mantSize -= 1;                  // One of the digits was the point.
353
1.02k
    }
354
4.42k
    if (mantSize > 18) {
355
227
        fracExp = decPt - 18;
356
227
        mantSize = 18;
357
4.20k
    } else {
358
4.20k
        fracExp = decPt - mantSize;
359
4.20k
    }
360
4.42k
    if (mantSize == 0) {
361
985
        fraction = 0.0;
362
        // p = string;
363
985
        goto done;
364
3.44k
    } else {
365
3.44k
        int frac1, frac2;
366
367
3.44k
        frac1 = 0;
368
6.77k
        for ( ; mantSize > 9; mantSize -= 1) {
369
3.33k
            c = *p;
370
3.33k
            p += 1;
371
3.33k
            if ('.' == c) {
372
202
                c = *p;
373
202
                p += 1;
374
202
            }
375
3.33k
            frac1 = 10*frac1 + (c - '0');
376
3.33k
        }
377
3.44k
        frac2 = 0;
378
14.0k
        for (; mantSize > 0; mantSize -= 1) {
379
10.6k
            c = *p;
380
10.6k
            p += 1;
381
10.6k
            if ('.' == c) {
382
202
                c = *p;
383
202
                p += 1;
384
202
            }
385
10.6k
            frac2 = 10*frac2 + (c - '0');
386
10.6k
        }
387
3.44k
        fraction = (1.0e9 * frac1) + frac2;
388
3.44k
    }
389
390
    /*
391
     * Skim off the exponent.
392
     */
393
394
3.44k
    p = pExp;
395
3.44k
    if (('E' == *p) ||
396
3.44k
        ('e' == *p)) {
397
1.76k
        p += 1;
398
1.76k
        if ('-' == *p) {
399
409
            expSign = true;
400
409
            p += 1;
401
1.35k
        } else {
402
1.35k
            if ('+' == *p) {
403
206
                p += 1;
404
206
            }
405
1.35k
            expSign = false;
406
1.35k
        }
407
2.98k
        while (isdigit((int) *p)) {
408
2.98k
            exp = exp * 10 + (*p - '0');
409
2.98k
            if (1024 < exp) {
410
396
                if (true == expSign) {
411
                    // exponent underflow!
412
194
                    return 0.0;
413
194
                } // else  exponent overflow!
414
202
                return INFINITY;
415
396
            }
416
2.58k
            p += 1;
417
2.58k
        }
418
1.76k
    }
419
3.04k
    if (expSign) {
420
215
        exp = fracExp - exp;
421
2.83k
    } else {
422
2.83k
        exp = fracExp + exp;
423
2.83k
    }
424
425
    /*
426
     * Generate a floating-point number that represents the exponent.
427
     * Do this by processing the exponent one bit at a time to combine
428
     * many powers of 2 of 10. Then combine the exponent with the
429
     * fraction.
430
     */
431
432
3.04k
    if (0 > exp) {
433
414
        expSign = true;
434
414
        exp = -exp;
435
2.63k
    } else {
436
2.63k
        expSign = false;
437
2.63k
    }
438
3.04k
    if (exp > maxExponent) {
439
258
        exp = maxExponent;
440
258
        errno = ERANGE;
441
258
    }
442
3.04k
    dblExp = 1.0;
443
7.71k
    for (d = powersOf10; exp != 0; exp >>= 1, d += 1) {
444
4.66k
        if (exp & 01) {
445
3.73k
            dblExp *= *d;
446
3.73k
        }
447
4.66k
    }
448
3.04k
    if (expSign) {
449
414
        fraction /= dblExp;
450
2.63k
    } else {
451
2.63k
        fraction *= dblExp;
452
2.63k
    }
453
454
4.03k
done:
455
4.03k
    if (sign) {
456
391
        return -fraction;
457
391
    }
458
3.64k
    return fraction;
459
4.03k
}
460
461
2.86k
#define MONTHSPERYEAR   12      // months per calendar year
462
463
// clear a baseline_t
464
static void gps_clear_base(struct baseline_t *base)
465
0
{
466
0
    base->status = STATUS_UNK;
467
0
    base->east = NAN;
468
0
    base->north = NAN;
469
0
    base->up = NAN;
470
0
    base->length = NAN;
471
0
    base->course = NAN;
472
0
    base->ratio = NAN;
473
0
}
474
475
// stuff a fix structure with recognizable out-of-band values
476
void gps_clear_fix(struct gps_fix_t *fixp)
477
0
{
478
0
    memset(fixp, 0, sizeof(struct gps_fix_t));
479
0
    fixp->altitude = NAN;        // DEPRECATED, undefined
480
0
    fixp->altHAE = NAN;
481
0
    fixp->altMSL = NAN;
482
0
    fixp->climb = NAN;
483
0
    fixp->depth = NAN;
484
0
    fixp->epc = NAN;
485
0
    fixp->epd = NAN;
486
0
    fixp->eph = NAN;
487
0
    fixp->eps = NAN;
488
0
    fixp->ept = NAN;
489
0
    fixp->epv = NAN;
490
0
    fixp->epx = NAN;
491
0
    fixp->epy = NAN;
492
0
    fixp->latitude = NAN;
493
0
    fixp->longitude = NAN;
494
0
    fixp->magnetic_track = NAN;
495
0
    fixp->magnetic_var = NAN;
496
0
    fixp->mode = MODE_NOT_SEEN;
497
0
    fixp->sep = NAN;
498
0
    fixp->speed = NAN;
499
0
    fixp->track = NAN;
500
    // clear ECEF too
501
0
    fixp->ecef.x = NAN;
502
0
    fixp->ecef.y = NAN;
503
0
    fixp->ecef.z = NAN;
504
0
    fixp->ecef.vx = NAN;
505
0
    fixp->ecef.vy = NAN;
506
0
    fixp->ecef.vz = NAN;
507
0
    fixp->ecef.pAcc = NAN;
508
0
    fixp->ecef.vAcc = NAN;
509
0
    fixp->NED.relPosN = NAN;
510
0
    fixp->NED.relPosE = NAN;
511
0
    fixp->NED.relPosD = NAN;
512
0
    fixp->NED.velN = NAN;
513
0
    fixp->NED.velE = NAN;
514
0
    fixp->NED.velD = NAN;
515
0
    fixp->geoid_sep = NAN;
516
0
    fixp->dgps_age = NAN;
517
0
    fixp->dgps_station = -1;
518
0
    fixp->temp = NAN;
519
0
    fixp->wanglem = NAN;
520
0
    fixp->wangler = NAN;
521
0
    fixp->wanglet = NAN;
522
0
    fixp->wspeedr = NAN;
523
0
    fixp->wspeedt = NAN;
524
0
    fixp->wtemp = NAN;
525
0
    gps_clear_base(&fixp->base);
526
0
}
527
528
// stuff an attitude structure with recognizable out-of-band values
529
void gps_clear_att(struct attitude_t *attp)
530
0
{
531
0
    memset(attp, 0, sizeof(struct attitude_t));
532
0
    attp->acc_len = NAN;
533
0
    attp->acc_x = NAN;
534
0
    attp->acc_y = NAN;
535
0
    attp->acc_z = NAN;
536
0
    attp->depth = NAN;
537
0
    attp->dip = NAN;
538
0
    attp->gyro_temp = NAN;
539
0
    attp->gyro_x = NAN;
540
0
    attp->gyro_y = NAN;
541
0
    attp->gyro_z = NAN;
542
0
    attp->heading = NAN;
543
0
    attp->mheading = NAN;
544
0
    attp->mag_len = NAN;
545
0
    attp->mag_x = NAN;
546
0
    attp->mag_y = NAN;
547
0
    attp->mag_z = NAN;
548
0
    attp->pitch = NAN;
549
0
    attp->roll = NAN;
550
0
    attp->rot = NAN;
551
0
    attp->temp = NAN;
552
0
    attp->yaw = NAN;
553
0
    gps_clear_base(&attp->base);
554
0
}
555
556
// Clear a dop_t structure
557
void gps_clear_dop( struct dop_t *dop)
558
0
{
559
0
    dop->xdop = dop->ydop = dop->vdop = dop->tdop = dop->hdop = dop->pdop =
560
0
        dop->gdop = NAN;
561
0
}
562
563
// Clear a gst structure
564
void gps_clear_gst( struct gst_t *gst)
565
0
{
566
0
    memset(&gst->utctime, 0, sizeof(gst->utctime));
567
0
    gst-> rms_deviation =  NAN;
568
0
    gst-> smajor_deviation =  NAN;
569
0
    gst-> sminor_deviation =  NAN;
570
0
    gst-> smajor_orientation =  NAN;
571
0
    gst-> lat_err_deviation =  NAN;
572
0
    gst-> lon_err_deviation =  NAN;
573
0
    gst-> alt_err_deviation =  NAN;
574
0
    gst-> ve_err_deviation =  NAN;
575
0
    gst-> vn_err_deviation =  NAN;
576
0
    gst-> vu_err_deviation =  NAN;
577
0
}
578
579
// stuff a log structure with recognizable out-of-band values
580
void gps_clear_log(struct gps_log_t *logp)
581
0
{
582
0
    memset(logp, 0, sizeof(struct gps_log_t));
583
0
    logp->lon = NAN;
584
0
    logp->lat = NAN;
585
0
    logp->altHAE = NAN;
586
0
    logp->altMSL = NAN;
587
0
    logp->gSpeed = NAN;
588
0
    logp->heading = NAN;
589
0
    logp->tAcc = NAN;
590
0
    logp->hAcc = NAN;
591
0
    logp->vAcc = NAN;
592
0
    logp->sAcc = NAN;
593
0
    logp->headAcc = NAN;
594
0
    logp->velN = NAN;
595
0
    logp->velE = NAN;
596
0
    logp->velD = NAN;
597
0
    logp->pDOP = NAN;
598
0
    logp->distance = NAN;
599
0
    logp->totalDistance = NAN;
600
0
    logp->distanceStd = NAN;
601
0
    logp->fixType = -1;
602
0
}
603
604
/* merge new data (from) into current fix (to)
605
 * Being careful not to lose information */
606
void gps_merge_fix(struct gps_fix_t *to,
607
                   gps_mask_t transfer,
608
                   struct gps_fix_t *from)
609
0
{
610
0
    if ((NULL == to) ||
611
0
        (NULL == from)) {
612
0
        return;
613
0
    }
614
0
    if (0 != (transfer & TIME_SET)) {
615
0
        to->time = from->time;
616
0
    }
617
0
    if (0 != (transfer & LATLON_SET)) {
618
0
        to->latitude = from->latitude;
619
0
        to->longitude = from->longitude;
620
0
    }
621
0
    if (0 != (transfer & MODE_SET)) {
622
        // FIXME?  Maybe only upgrade mode, not downgrade it
623
0
        to->mode = from->mode;
624
0
    }
625
    /* Some messages only report mode, some mode and status, some only status.
626
     * Only upgrade status, not downgrade it */
627
0
    if (0 != (transfer & STATUS_SET)) {
628
0
        if (to->status < from->status) {
629
0
            to->status = from->status;
630
0
        }
631
0
    }
632
0
    if ((transfer & ALTITUDE_SET) != 0) {
633
0
        if (0 != isfinite(from->altHAE)) {
634
0
            to->altHAE = from->altHAE;
635
0
        }
636
0
        if (0 != isfinite(from->altMSL)) {
637
0
            to->altMSL = from->altMSL;
638
0
        }
639
0
        if (0 != isfinite(from->depth)) {
640
0
            to->depth = from->depth;
641
0
        }
642
0
    }
643
0
    if (0 != (transfer & TRACK_SET)) {
644
0
        to->track = from->track;
645
0
    }
646
0
    if (0 != (transfer & MAGNETIC_TRACK_SET)) {
647
0
        if (0 != isfinite(from->magnetic_track)) {
648
0
            to->magnetic_track = from->magnetic_track;
649
0
        }
650
0
        if (0 != isfinite(from->magnetic_var)) {
651
0
            to->magnetic_var = from->magnetic_var;
652
0
        }
653
0
    }
654
0
    if (0 != (transfer & SPEED_SET)) {
655
0
        to->speed = from->speed;
656
0
    }
657
0
    if (0 != (transfer & CLIMB_SET)) {
658
0
        to->climb = from->climb;
659
0
    }
660
0
    if (0 != (transfer & TIMERR_SET)) {
661
0
        to->ept = from->ept;
662
0
    }
663
0
    if (0 != isfinite(from->epx) &&
664
0
        0 != isfinite(from->epy)) {
665
0
        to->epx = from->epx;
666
0
        to->epy = from->epy;
667
0
    }
668
0
    if (0 != isfinite(from->epd)) {
669
0
        to->epd = from->epd;
670
0
    }
671
0
    if (0 != isfinite(from->eph)) {
672
0
        to->eph = from->eph;
673
0
    }
674
0
    if (0 != isfinite(from->eps)) {
675
0
        to->eps = from->eps;
676
0
    }
677
    // spherical error probability, not geoid separation
678
0
    if (0 != isfinite(from->sep)) {
679
0
        to->sep = from->sep;
680
0
    }
681
    // geoid separation, not spherical error probability
682
0
    if (0 != isfinite(from->geoid_sep)) {
683
0
        to->geoid_sep = from->geoid_sep;
684
0
    }
685
0
    if (0 != isfinite(from->epv)) {
686
0
        to->epv = from->epv;
687
0
    }
688
0
    if (0 != (transfer & SPEEDERR_SET)) {
689
0
        to->eps = from->eps;
690
0
    }
691
0
    if (0 != (transfer & ECEF_SET)) {
692
0
        to->ecef.x = from->ecef.x;
693
0
        to->ecef.y = from->ecef.y;
694
0
        to->ecef.z = from->ecef.z;
695
0
        to->ecef.pAcc = from->ecef.pAcc;
696
0
    }
697
0
    if (0 != (transfer & VECEF_SET)) {
698
0
        to->ecef.vx = from->ecef.vx;
699
0
        to->ecef.vy = from->ecef.vy;
700
0
        to->ecef.vz = from->ecef.vz;
701
0
        to->ecef.vAcc = from->ecef.vAcc;
702
0
    }
703
0
    if (0 != (transfer & NED_SET)) {
704
0
        to->NED.relPosN = from->NED.relPosN;
705
0
        to->NED.relPosE = from->NED.relPosE;
706
0
        to->NED.relPosD = from->NED.relPosD;
707
0
        if ((0 != isfinite(from->NED.relPosH)) &&
708
0
            (0 != isfinite(from->NED.relPosL))) {
709
0
            to->NED.relPosH = from->NED.relPosH;
710
0
            to->NED.relPosL = from->NED.relPosL;
711
0
        }
712
0
    }
713
0
    if (0 != (transfer & VNED_SET)) {
714
0
        to->NED.velN = from->NED.velN;
715
0
        to->NED.velE = from->NED.velE;
716
0
        to->NED.velD = from->NED.velD;
717
0
    }
718
0
    if ('\0' != from->datum[0]) {
719
0
        strlcpy(to->datum, from->datum, sizeof(to->datum));
720
0
    }
721
0
    if (0 != isfinite(from->dgps_age) &&
722
0
        0 <= from->dgps_station) {
723
        // both, or neither
724
0
        to->dgps_age = from->dgps_age;
725
0
        to->dgps_station = from->dgps_station;
726
0
    }
727
728
0
    if (ANT_UNK != from->ant_stat) {
729
0
        to->ant_stat = from->ant_stat;
730
0
    }
731
0
    if (0 < from->jam) {
732
0
        to->jam = from->jam;
733
0
    }
734
    // navdata stuff.  just wind angle and angle for now
735
0
    if (0 != (transfer & NAVDATA_SET)) {
736
0
        if (0 != isfinite(from->wanglem)) {
737
0
            to->wanglem = from->wanglem;
738
0
        }
739
0
        if (0 != isfinite(from->wangler)) {
740
0
            to->wangler = from->wangler;
741
0
        }
742
0
        if (0 != isfinite(from->wanglet)) {
743
0
            to->wanglet = from->wanglet;
744
0
        }
745
0
        if (0 != isfinite(from->wspeedr)) {
746
0
            to->wspeedr = from->wspeedr;
747
0
        }
748
0
        if (0 != isfinite(from->wspeedt)) {
749
0
            to->wspeedt = from->wspeedt;
750
0
        }
751
0
    }
752
0
    if (0 != isfinite(from->temp)) {
753
0
        to->temp = from->temp;
754
0
    }
755
0
    if (0 != isfinite(from->wtemp)) {
756
0
        to->wtemp = from->wtemp;
757
0
    }
758
0
}
759
760
/* mkgmtime(tm)
761
 * convert struct tm, as UTC, to seconds since Unix epoch
762
 * This differs from mktime() from libc.
763
 * mktime() takes struct tm as localtime.
764
 *
765
 * The inverse of gmtime(time_t)
766
 *
767
 * Return: -1 on error, set errno to EOVERFLOW
768
 */
769
time_t mkgmtime(struct tm * t)
770
2.27k
{
771
2.27k
    int year;
772
2.27k
    time_t result;
773
2.27k
    static const int cumdays[MONTHSPERYEAR] =
774
2.27k
        { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
775
776
    // check ranges, ignore tm_isdst and max tm_year
777
2.27k
    if (0 > t->tm_sec ||
778
2.27k
        0 > t->tm_min ||
779
2.27k
        0 > t->tm_hour ||
780
2.27k
        1 > t->tm_mday ||
781
2.27k
        0 > t->tm_mon ||
782
2.27k
        0 > t->tm_year ||
783
2.27k
        0 > t->tm_wday ||
784
2.27k
        0 > t->tm_yday ||
785
2.27k
        61 < t->tm_sec ||
786
2.27k
        59 < t->tm_min ||
787
2.27k
        23 < t->tm_hour ||
788
2.27k
        31 < t->tm_mday ||
789
2.27k
        11 < t->tm_mon ||
790
2.27k
        6 < t->tm_wday ||
791
2.27k
        365 < t->tm_yday) {
792
1.06k
        errno = EOVERFLOW;
793
1.06k
        return -1;
794
1.06k
    }
795
1.21k
    errno = 0;
796
1.21k
    year = 1900 + t->tm_year + t->tm_mon / MONTHSPERYEAR;
797
1.21k
    result = (year - 1970) * 365 + cumdays[t->tm_mon % MONTHSPERYEAR];
798
1.21k
    result += (year - 1968) / 4;
799
1.21k
    result -= (year - 1900) / 100;
800
1.21k
    result += (year - 1600) / 400;
801
1.21k
    if (0 == (year % 4) &&
802
1.21k
        (0 != (year % 100) ||
803
671
         0 == (year % 400)) &&
804
1.21k
        (2 > (t->tm_mon % MONTHSPERYEAR))) {
805
206
        result--;
806
206
    }
807
1.21k
    result += t->tm_mday - 1;
808
1.21k
    result *= 24;
809
1.21k
    result += t->tm_hour;
810
1.21k
    result *= 60;
811
1.21k
    result += t->tm_min;
812
1.21k
    result *= 60;
813
1.21k
    result += t->tm_sec;
814
    /* this is UTC, no DST
815
     * if (t->tm_isdst == 1)
816
     * result -= 3600;
817
     */
818
1.21k
    return result;
819
2.27k
}
820
821
// ISO8601 UTC to Unix timespec, no leapsecond correction.
822
timespec_t iso8601_to_timespec(const char *isotime)
823
2.27k
{
824
2.27k
    timespec_t ret;
825
826
2.27k
#ifndef __clang_analyzer__
827
#ifdef USE_QT
828
    double usec = 0;
829
830
    QString t(isotime);
831
    QDateTime d = QDateTime::fromString(isotime, Qt::ISODate);
832
    QStringList sl = t.split(".");
833
    if (1 < sl.size()) {
834
        usec = sl[1].toInt() / pow(10., (double)sl[1].size());
835
    }
836
    ret.tv_sec = d.toTime_t();
837
    ret.tv_nsec = usec * 1e9;
838
#else  // USE_QT
839
2.27k
    double usec = 0;
840
2.27k
    struct tm tm = {0};
841
842
2.27k
    {
843
2.27k
        char *dp = NULL;
844
2.27k
        dp = strptime(isotime, "%Y-%m-%dT%H:%M:%S", &tm);
845
2.27k
        if (NULL != dp &&
846
2.27k
            '.' == *dp) {
847
195
            usec = strtod(dp, NULL);
848
195
        }
849
2.27k
    }
850
851
    /*
852
     * It would be nice if we could say mktime(&tm) - timezone + usec instead,
853
     * but timezone is not available at all on some BSDs. Besides, when working
854
     * with historical dates the value of timezone after an ordinary tzset(3)
855
     * can be wrong; you have to do a redirect through the IANA historical
856
     * timezone database to get it right.
857
     */
858
2.27k
    ret.tv_sec = mkgmtime(&tm);
859
2.27k
    ret.tv_nsec = usec * 1e9;
860
2.27k
#endif  // USE_QT
861
2.27k
#endif  // __clang_analyzer__
862
863
2.27k
#if 4 < SIZEOF_TIME_T
864
2.27k
    if (253402300799LL < ret.tv_sec) {
865
        // enforce max "9999-12-31T23:59:59.999Z"
866
194
        ret.tv_sec = 253402300799LL;
867
194
    }
868
2.27k
#endif
869
2.27k
    return ret;
870
2.27k
}
871
872
/* Convert POSIX timespec to ISO8601 UTC, put result in isotime.
873
 * no timezone adjustment
874
 * Return: pointer to isotime.
875
 * example: 2007-12-11T23:38:51.033Z */
876
char *timespec_to_iso8601(timespec_t fixtime, char isotime[], size_t len)
877
0
{
878
0
    struct tm when;
879
0
    char timestr[30];
880
0
    long fracsec;
881
882
0
    if (0 > fixtime.tv_sec) {
883
        // Allow 0 for testing of 1970-01-01T00:00:00.000Z
884
0
        strlcpy(isotime, "NaN", len);
885
0
        return isotime;
886
0
    }
887
0
    if (999499999 < fixtime.tv_nsec) {
888
        // round up
889
0
        fixtime.tv_sec++;
890
0
        fixtime.tv_nsec = 0;
891
0
    }
892
893
0
#if 4 < SIZEOF_TIME_T
894
0
    if (253402300799LL < fixtime.tv_sec) {
895
        // enforce max "9999-12-31T23:59:59.999Z"
896
0
        fixtime.tv_sec = 253402300799LL;
897
0
    }
898
0
#endif
899
900
0
    (void)gmtime_r(&fixtime.tv_sec, &when);
901
902
    /*
903
     * Do not mess casually with the number of decimal digits in the
904
     * format!  Most GPSes report over serial links at 0.01s or 0.001s
905
     * precision.  Round to 0.001s
906
     */
907
0
    fracsec = (fixtime.tv_nsec + 500000) / 1000000;
908
909
0
    (void)strftime(timestr, sizeof(timestr), "%Y-%m-%dT%H:%M:%S", &when);
910
0
    (void)snprintf(isotime, len, "%s.%03ldZ",timestr, fracsec);
911
912
0
    return isotime;
913
0
}
914
915
/* return time now as ISO8601, no timezone adjustment
916
 * example: 2007-12-11T23:38:51.033Z */
917
char *now_to_iso8601(char *tbuf, size_t tbuf_sz)
918
0
{
919
0
    timespec_t ts_now;
920
921
0
    (void)clock_gettime(CLOCK_REALTIME, &ts_now);
922
0
    return timespec_to_iso8601(ts_now, tbuf, tbuf_sz);
923
0
}
924
925
0
#define Deg2Rad(n)      ((n) * DEG_2_RAD)
926
927
/* Distance in meters between two points specified in degrees, optionally
928
 * with initial and final bearings. */
929
double earth_distance_and_bearings(double lat1, double lon1,
930
                                   double lat2, double lon2,
931
                                   double *ib, double *fb)
932
0
{
933
    /*
934
     * this is a translation of the javascript implementation of the
935
     * Vincenty distance formula by Chris Veness. See
936
     * http://www.movable-type.co.uk/scripts/latlong-vincenty.html
937
     */
938
0
    double a, b, f;             // WGS-84 ellipsoid params
939
0
    double L, L_P, U1, U2, s_U1, c_U1, s_U2, c_U2;
940
0
    double uSq, A, B, d_S, lambda;
941
    // cppcheck-suppress variableScope
942
0
    double s_L, c_L, s_A, C;
943
0
    double c_S, S, s_S, c_SqA, c_2SM;
944
0
    int i = 100;
945
946
0
    a = WGS84A;
947
0
    b = WGS84B;
948
0
    f = 1 / WGS84F;
949
0
    L = Deg2Rad(lon2 - lon1);
950
0
    U1 = atan((1 - f) * tan(Deg2Rad(lat1)));
951
0
    U2 = atan((1 - f) * tan(Deg2Rad(lat2)));
952
0
    s_U1 = sin(U1);
953
0
    c_U1 = cos(U1);
954
0
    s_U2 = sin(U2);
955
0
    c_U2 = cos(U2);
956
0
    lambda = L;
957
958
0
    do {
959
0
        s_L = sin(lambda);
960
0
        c_L = cos(lambda);
961
0
        s_S = sqrt((c_U2 * s_L) * (c_U2 * s_L) +
962
0
                   (c_U1 * s_U2 - s_U1 * c_U2 * c_L) *
963
0
                   (c_U1 * s_U2 - s_U1 * c_U2 * c_L));
964
965
0
        if (0 == s_S) {
966
0
            return 0;
967
0
        }
968
969
0
        c_S = s_U1 * s_U2 + c_U1 * c_U2 * c_L;
970
0
        S = atan2(s_S, c_S);
971
0
        s_A = c_U1 * c_U2 * s_L / s_S;
972
0
        c_SqA = 1 - s_A * s_A;
973
0
        c_2SM = c_S - 2 * s_U1 * s_U2 / c_SqA;
974
975
0
        if (0 == isfinite(c_2SM)) {
976
0
            c_2SM = 0;
977
0
        }
978
979
0
        C = f / 16 * c_SqA * (4 + f * (4 - 3 * c_SqA));
980
0
        L_P = lambda;
981
0
        lambda = L + (1 - C) * f * s_A *
982
0
            (S + C * s_S * (c_2SM + C * c_S * (2 * c_2SM * c_2SM - 1)));
983
0
    } while ((fabs(lambda - L_P) > 1.0e-12) &&
984
0
             (0 < --i));
985
986
0
    if (0 == i) {
987
0
        return NAN;             // formula failed to converge
988
0
    }
989
990
0
    uSq = c_SqA * ((a * a) - (b * b)) / (b * b);
991
0
    A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
992
0
    B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
993
0
    d_S = B * s_S * (c_2SM + B / 4 *
994
0
                     (c_S * (-1 + 2 * c_2SM * c_2SM) - B / 6 * c_2SM *
995
0
                      (-3 + 4 * s_S * s_S) * (-3 + 4 * c_2SM * c_2SM)));
996
997
0
    if (NULL != ib) {
998
0
        *ib = atan2(c_U2 * sin(lambda),
999
0
                    c_U1 * s_U2 - s_U1 * c_U2 * cos(lambda));
1000
0
    }
1001
0
    if (NULL != fb) {
1002
0
        *fb = atan2(c_U1 * sin(lambda),
1003
0
                    c_U1 * s_U2 * cos(lambda) - s_U1 * c_U2);
1004
0
    }
1005
1006
0
    return (WGS84B * A * (S - d_S));
1007
0
}
1008
1009
// Distance in meters between two points specified in degrees.
1010
double earth_distance(double lat1, double lon1, double lat2, double lon2)
1011
0
{
1012
0
    return earth_distance_and_bearings(lat1, lon1, lat2, lon2, NULL, NULL);
1013
0
}
1014
1015
/* Wait for data until timeout, ignoring signals.
1016
 *
1017
 * pselect() may set errno on error
1018
 */
1019
bool nanowait(int fd, struct timespec *to)
1020
0
{
1021
0
    fd_set fdset;
1022
1023
0
    FD_ZERO(&fdset);
1024
0
    FD_SET(fd, &fdset);
1025
0
    TS_NORM(to);         // just in case
1026
0
    errno = 0;
1027
    // sigmask is NULL, so equivalent to select()
1028
0
    return pselect(fd + 1, &fdset, NULL, NULL, to, NULL) == 1;
1029
0
}
1030
1031
/* Accept a datum code, return matching string
1032
 *
1033
 * There are a ton of these, only a few are here
1034
 *
1035
 */
1036
void datum_code_string(int code, char *buffer, size_t len)
1037
0
{
1038
0
    const char *datum_str;
1039
1040
0
    switch (code) {
1041
0
    case 0:
1042
0
        datum_str = "WGS84";
1043
0
        break;
1044
0
    case 21:
1045
0
        datum_str = "WGS84";
1046
0
        break;
1047
0
    case 178:
1048
0
        datum_str = "Tokyo Mean";
1049
0
        break;
1050
0
    case 179:
1051
0
        datum_str = "Tokyo-Japan";
1052
0
        break;
1053
0
    case 180:
1054
0
        datum_str = "Tokyo-Korea";
1055
0
        break;
1056
0
    case 181:
1057
0
        datum_str = "Tokyo-Okinawa";
1058
0
        break;
1059
0
    case 182:
1060
0
        datum_str = "PZ90.11";
1061
0
        break;
1062
0
    case 999:
1063
0
        datum_str = "User Defined";
1064
0
        break;
1065
0
    default:
1066
0
        datum_str = NULL;
1067
0
        break;
1068
0
    }
1069
1070
0
    if (NULL == datum_str) {
1071
        // Fake it
1072
0
        snprintf(buffer, len, "%d", code);
1073
0
    } else {
1074
0
        strlcpy(buffer, datum_str, len);
1075
0
    }
1076
0
}
1077
1078
/* make up an NMEA 4.0 (extended) PRN based on gnssId:svId,
1079
 * This does NOT match NMEA 4.10 and 4.11 where all PRN are 1-99,
1080
 * except IMES, QZSS, and some SBAS.
1081
 *
1082
 * Ref Appendix A from u-blox ZED-F9P Interface Description
1083
 * and
1084
 * Section 1.5.3  M10-FW500_InterfaceDescription_UBX-20053845.pdf
1085
 *
1086
 * Using ST Teseo PRN fors for those not defined by UBX.
1087
 * um3407-teseo-vi-and-teseo-app2nmea-specifications-and-commands-stmicroelectronics.pdf
1088
 * Section 3.5
1089
 * But we do not use the per sigId PRNs from ST.
1090
 *
1091
 * Return PRN, less than one for error
1092
 *        -1 for GLONASS svid 255
1093
 */
1094
short ubx2_to_prn(int gnssId, int svId)
1095
0
{
1096
0
    short nmea_PRN = 0;
1097
1098
0
    if (1 > svId) {
1099
        // skip 0 svId
1100
0
        return 0;
1101
0
    }
1102
1103
0
    switch (gnssId) {
1104
0
    case 0:
1105
        // GPS, 1-32 maps to 1-32
1106
0
        if (32 >= svId) {
1107
0
            nmea_PRN = svId;
1108
0
        }
1109
0
        break;
1110
0
    case 1:
1111
        // SBAS, 120..151, 152..158 maps to 33..64, 152..158
1112
0
        if (120 <= svId &&
1113
0
            151 >= svId) {
1114
0
            nmea_PRN = svId - 87;
1115
0
        } else if (158 >= svId) {
1116
0
            nmea_PRN = svId;
1117
0
        }
1118
0
        break;
1119
0
    case 2:
1120
        // Galileo, ubx gnssid:svid 1..36 ->  301-336
1121
        // Galileo, ubx PRN         211..246 ->  301-336
1122
0
        if (36 >= svId) {
1123
0
            nmea_PRN = svId + 300;
1124
0
        } else if (211 > svId) {
1125
            // skip bad svId
1126
0
            return 0;
1127
0
        } else if (246 >= svId) {
1128
0
            nmea_PRN = svId + 90;
1129
0
        }
1130
0
        break;
1131
0
    case 3:
1132
        /* BeiDou, ubx gnssid:svid    1..37 -> to 401-437
1133
         * have seen 1-63 on F10 ProtVer 40.0, March 2025
1134
         *   ubx gnssid:svid    1..63 -> to 401-463
1135
         * BeiDou, ubx "single svid"  159..163,33..64 -> to 401-437 ?? */
1136
0
        if (63 >= svId) {
1137
0
            nmea_PRN = svId + 400;
1138
0
        } else if (159 > svId) {
1139
            // skip bad svId
1140
0
            return 0;
1141
0
        } else if (163 >= svId) {
1142
0
            nmea_PRN = svId + 242;
1143
0
        }
1144
0
        break;
1145
0
    case 4:
1146
        // IMES, ubx gnssid:svid 1-10 -> to 173-182
1147
        // IMES, ubx PRN         173-182 to 173-182
1148
0
        if (10 >= svId) {
1149
0
            nmea_PRN = svId + 172;
1150
0
        } else if (173 > svId) {
1151
            // skip bad svId
1152
0
            return 0;
1153
0
        } else if (182 >= svId) {
1154
0
            nmea_PRN = svId;
1155
0
        }
1156
0
        break;
1157
0
    case 5:
1158
        // QZSS, ubx gnssid:svid 1-10 to 193-202
1159
        // QZSS, ubx PRN         193-202 to 193-202
1160
0
        if (10 >= svId) {
1161
0
            nmea_PRN = svId + 192;
1162
0
        } else if (193 > svId) {
1163
            // skip bad svId
1164
0
            return 0;
1165
0
        } else if (202 >= svId) {
1166
0
            nmea_PRN = svId;
1167
0
        }
1168
0
        break;
1169
0
    case 6:
1170
        // GLONASS, 1-32 maps to 65-96
1171
0
        if (32 >= svId) {
1172
0
            nmea_PRN = svId + 64;
1173
0
        } else if (65 > svId) {
1174
            // skip bad svId
1175
0
            return 0;
1176
0
        } else if (96 >= svId) {
1177
0
            nmea_PRN = svId;
1178
0
        } else if (255 == svId) {
1179
            // skip bad svId, 255 == tracked, but unidentified, skip
1180
0
            nmea_PRN = -1;
1181
0
        }
1182
0
        break;
1183
0
    case 7:
1184
        // NavIC (IRNSS), 1 - 14 -> 801 - 814
1185
0
        if (14 >= svId) {
1186
0
            nmea_PRN = svId + 800;;
1187
0
        }
1188
0
        break;
1189
0
    default:
1190
        // Huh?
1191
0
        nmea_PRN = 0;
1192
0
    }
1193
1194
0
    return nmea_PRN;
1195
0
}
1196
1197
// vim: set expandtab shiftwidth=4