-
-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathhelpers.py
More file actions
1505 lines (1201 loc) · 37.2 KB
/
Copy pathhelpers.py
File metadata and controls
1505 lines (1201 loc) · 37.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
helpers.py
Collection of helper methods and tkinter class extensions.
Created on 17 Apr 2021
:author: semuadmin (Steve Smith)
:copyright: 2020 semuadmin
:license: BSD 3-Clause
"""
import re
from datetime import datetime, timedelta
from math import (
asin,
atan,
atan2,
cos,
degrees,
pi,
radians,
sin,
sqrt,
trunc,
)
from os import path
from socket import AF_INET, SOCK_DGRAM, socket
from time import strftime
from tkinter import (
BooleanVar,
DoubleVar,
Entry,
IntVar,
Spinbox,
StringVar,
Tk,
font,
)
from types import FunctionType, MethodType, NoneType
from typing import Any, Literal
from pygnssutils import version as PGVERSION
from pynmeagps import WGS84_SMAJ_AXIS, NMEAMessage, haversine
from pynmeagps import version as NMEAVERSION
from pynmeagps import wnotow2utc
from pyqgc import version as QGCVERSION
from pyrtcm import version as RTCMVERSION
from pysbf2 import version as SBFVERSION
from pyspartn import version as SPARTNVERSION
from pyubx2 import (
SET,
SET_LAYER_RAM,
TXN_NONE,
UBX_CLASSES,
UBX_MSGIDS,
UBXMessage,
attsiz,
atttyp,
)
from pyubx2 import version as UBXVERSION
from pyunigps import version as UNIVERSION
from requests import get
from pygpsclient._version import __version__ as VERSION
from pygpsclient.globals import (
BSR,
ERRCOL,
FIXLOOKUP,
GPSEPOCH0,
M2FT,
M2KM,
M2MIL,
M2NMIL,
MAX_SNR,
MAXFLOAT,
MINFLOAT,
MPS2KNT,
MPS2KPH,
MPS2MPH,
OVERSCAN,
PUBLICIP_URL,
ROMVER_NEW,
TIME0,
UI,
UIK,
UMK,
VALBLANK,
VALBOOL,
VALCUSTOM,
VALDMY,
VALFLOAT,
VALHEX,
VALINT,
VALLEN,
VALNONBLANK,
VALNONSPACE,
VALREGEX,
VALURL,
Area,
Point,
)
from pygpsclient.strings import NA
# validation type flags
MAXPORT = 65535
MAXALT = 10000.0 # meters arbitrary
LIBVERSIONS = {
"PyGPSClient": VERSION,
"pygnssutils": PGVERSION,
"pynmeagps": NMEAVERSION,
"pyqgc": QGCVERSION,
"pyrtcm": RTCMVERSION,
"pysbf2": SBFVERSION,
"pyspartn": SPARTNVERSION,
"pyubx2": UBXVERSION,
"pyunigps": UNIVERSION,
}
def validate(
self: Entry,
valmode: int,
low: int | float = MINFLOAT,
high: int | float = MAXFLOAT,
regex: str | NoneType = None,
func: MethodType | FunctionType | NoneType = None,
args: tuple = (),
) -> bool:
"""
Extends tkinter.Entry class to add parameterised validation
and error highlighting.
:param Entry self: tkinter entry widget instance
:param int valmode: int representing validation type - can be OR'd
:param int | float low: optional min value
:param int | float high: optional max value
:param str | NoneType regex: regex expression
:param MethodType | FunctionType | NoneType func: custom validation function
:param Any args: optional function arguments
:return: True/False
:rtype: bool
"""
valid = False
try:
val = self.get()
if valmode == VALBLANK and val == "":
valid = True # blank ok
elif valmode == VALNONBLANK: # non-blank
valid = val != "" and not val.isspace()
elif valmode == VALNONSPACE: # non-blank
valid = not val.isspace()
elif valmode == VALINT: # int in range
valid = low < int(val) < high
elif valmode == VALBOOL: # boolean
valid = val in ("0", "1", 1, 0)
elif valmode == VALFLOAT: # float in range
valid = low < float(val) < high
elif valmode == VALURL: # valid URL
# none of the clever RFC 3986 regexes
# seem to work 100% of the time
valid = val != "" and not val.isspace()
elif valmode == VALHEX: # valid hexadecimal
bytes.fromhex(val)
valid = True
elif valmode == VALDMY: # valid date YYYYMMDD
datetime(int(val[0:4]), int(val[4:6]), int(val[6:8]))
valid = True
elif valmode == VALLEN: # valid length
valid = low <= len(val) <= high
elif valmode == VALREGEX and regex is not None: # matches given regex
valid = re.compile(regex).search(val) is not None
elif valmode == VALCUSTOM and func is not None: # custom validation function
valid = func(val, *args)
except ValueError:
valid = False
if valid:
self.configure(highlightthickness=0)
else:
self.configure(
highlightthickness=2, highlightbackground=ERRCOL, highlightcolor=ERRCOL
)
return valid
for wdg in (Entry, Spinbox):
wdg.validate = validate
def trace_update(
self: IntVar | StringVar | DoubleVar | BooleanVar,
mode: Literal["array", "read", "write", "unset"],
callback: object,
add: bool = True,
) -> str:
"""
Extends tkinter.*Var classes with trace_update method.
:param str mode: 'array', 'read', 'write' or 'unset'
:param function callback: callback
:param bool add: add (True) or remove (False) trace
:return: status
:rtype: str
"""
if add:
return self.trace_add(mode, callback)
if len(self.trace_info()) > 0:
return self.trace_remove(mode, self.trace_info()[0][1])
return None
for var in (BooleanVar, DoubleVar, IntVar, StringVar):
var.trace_update = trace_update
# ****************************************************************
# End of Custom Class Extensions
# ****************************************************************
def area_in_bounds(
bounds: Area,
extents: Area,
) -> bool:
"""
Check if extent is within bounds.
:param Area bounds: bounding box
:param Area extents: extents
:return: true/false
:rtype: bool
"""
if bounds is None:
return False
return (
extents.lat1 >= bounds.lat1
and extents.lat2 <= bounds.lat2
and extents.lon1 >= bounds.lon1
and extents.lon2 <= bounds.lon2
)
def bitsval(bitfield: bytes, position: int, length: int) -> int:
"""
Get unisgned integer value of masked bits in bitfield.
:param bytes bitfield: bytes
:param int position: position in bitfield, from leftmost bit
:param int length: length of masked bits
:return: value
:rtype: int
"""
lbb = len(bitfield) * 8
if position + length > lbb:
return None
return int.from_bytes(bitfield, "big") >> (lbb - position - length) & 2**length - 1
def brew_installed() -> bool:
"""
Check if Python installed under Homebrew.
Some Python/tkinter installations under Homebrew cause
a critical segmentation error when shell subprocesses
are invoked.
:return: yes/no
:rtype: bool
"""
return path.isfile("/opt/homebrew/bin/python3")
def bytes2unit(valb: int) -> tuple:
"""Format bytes as KB, MB, GB etc
such that value < 100.
:param int valb: bytes
:return: tuple of (value, units)
"""
if not isinstance(valb, (int, float)):
return 0, NA
BYTESUNITS = ["", "KB", "MB", "GB", "TB"]
i = 0
val = valb
valu = BYTESUNITS[i]
while val > 500:
val = valb / (2 ** (i * 10))
valu = BYTESUNITS[i]
i += 1
if i > 4:
break
return val, valu
def check_latest(name: str) -> str:
"""
Check for latest version of module on PyPi.
:param str name: name of module to check
:return: latest version e.g. "1.3.5"
:rtype: str
"""
try:
return get(f"https://pypi.org/pypi/{name}/json", timeout=3).json()["info"][
"version"
]
except Exception: # pylint: disable=broad-except
return NA
def check_for_updates() -> list[tuple[str, str, str]]:
"""
Check for updates.
:return: list of module name, current and latest version
:rtype: list[tuple[str,str,str]]
"""
updates = []
for nam, current in LIBVERSIONS.items():
updates.append((nam, current, check_latest(nam)))
return updates
def check_lowres(master: Tk, dim: tuple, overscan: float = OVERSCAN) -> tuple:
"""
Check if dialog dimensions exceed effective screen resolution.
:param tkinter.Tk master: reference to root
:param tuple dim: dialog dimensions in pixels (height, width)
:param float overscan: screen 'overscan' allowance
:return: low resolution yes/no and effective resolution
:rtype: tuple (boolean, (screen height/width))
"""
sh, sw = [int(i / overscan) for i in screenres(master)]
dh, dw = dim
maxh = min(sh, dh)
maxw = min(sw, dw)
lowres = (maxh, maxw) != dim
return lowres, (maxh, maxw)
def col2contrast(col: str) -> str:
"""
Find best contrasting color against background
using perceived luminance (human eye favors green color).
:param str col: RGB color string e.g. "#032a4e"
:return: "black' or "white"
:rtype: str
"""
r, g, b = str2rgb(col)
luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
return "black" if luminance > 0.5 else "white"
def corrage2int(code: int) -> int:
"""
Convert NAV-PVT lastCorrectionAge value to age in seconds.
:param int code: diff age code from NAV-PVT
:return: string indicating diff age in seconds
:rtype: int
"""
lookup = {
0: 0,
1: 1,
2: 2,
3: 5,
4: 10,
5: 15,
6: 20,
7: 30,
8: 45,
9: 60,
10: 90,
11: 120,
}
return lookup.get(code, 0)
def date2wnotow(dat: datetime) -> tuple:
"""
Get GPS Week number (Wno) and Time of Week (Tow)
for given datetime.
GPS Epoch 0 = 6th Jan 1980
:param datetime dat: calendar date
:return: tuple of (Wno, Tow)
:rtype: tuple
"""
wno = int((dat - GPSEPOCH0).days / 7)
tow = ((dat.weekday() + 1) % 7) * 86400
return wno, tow
def dop2str(dop: float) -> str:
"""
Convert Dilution of Precision float to descriptive string.
:param float dop: dilution of precision as float
:return: dilution of precision as string
:rtype: str
"""
if dop == 0:
dops = "N/A"
elif dop <= 1:
dops = "Ideal"
elif dop <= 2:
dops = "Excellent"
elif dop <= 5:
dops = "Good"
elif dop <= 10:
dops = "Moderate"
elif dop <= 20:
dops = "Fair"
else:
dops = "Poor"
return dops
def fitfont(
fmt: str,
maxw: int,
maxh: int,
angle: int = 0,
maxsiz: int = 10,
constraint: int = 3,
) -> tuple[font.Font, float, float, int]:
"""
Create font to fit space.
:param str format: format of string
:param int maxw: max width in pixels
:param int maxh: max height in pixels
:param int angle: font angle in degrees
:param int maxsiz: maximum font size in pixels
:param int constraint: 1 = width, 2 = height, 3 = width & height
:return: tuple of (sized font, font width, font height, font size in pixels)
:rtype: tuple[font.Font, float, float, int]
"""
fw, fh = maxw + 1, maxh + 1
rw, rh = fw, fh
siz = maxsiz
fnt = font.Font(size=-siz)
while (
(rw > maxw and constraint & 1) or (rh > maxh and constraint & 2)
) and siz > 0:
fnt = font.Font(size=-siz)
rw, rh = fontdim(fmt, fnt, angle)
siz -= 1
return fnt, fw, fh, siz
def fix2desc(msgid: str, fix: object) -> str:
"""
Get integer fix value for given message fix status.
:param str msgid: UBX or NMEA message identity
:param object fix: value representing fix type
:return: descriptive fix status e.g. "3D"
:rtype: str
"""
return FIXLOOKUP.get(msgid + str(fix), "NO FIX")
def ft2m(feet: float) -> float:
"""
Convert feet to meters.
:param float feet: feet
:return: elevation in meters
:rtype: float
"""
if not isinstance(feet, (float, int)):
return 0
return feet / 3.28084
def fontdim(fmt: str, fnt: font.Font, angle: int = 0) -> tuple[float, float]:
"""
Get x,y pixel dimensions of string in given rotated font.
:param str fmt: format string e.g. "000"
:param font.Font fnt: font
:param int angle: rotation angle in degrees (0 = horizontal)
:return: tuple of (width, height)
:rtype: tuple[float, float]
"""
theta = radians(angle)
fw = fnt.measure(fmt)
fh = fnt.metrics("linespace")
rw = abs(fw * cos(theta)) + abs(fh * sin(theta))
rh = abs(fh * cos(theta)) + abs(fw * sin(theta))
return rw, rh
def get_mp_distance(lat: float, lon: float, mp: list) -> float:
"""
Get distance to mountpoint from current location (if known).
The sourcetable mountpoint entry is a list where index [0]
is the name and indices [8] & [9] are the lat/lon. Not all
sourcetable entries provide this information.
:param float lat: current latitude
:param float lon: current longitude
:param list mp: sourcetable mountpoint entry
:return: distance to mountpoint in km, or None if n/a
:rtype: float or None
"""
dist = None
try:
if len(mp) > 9: # if location provided for this mountpoint
lat2 = float(mp[8])
lon2 = float(mp[9])
dist = haversine(lat, lon, lat2, lon2)
except (ValueError, TypeError):
pass
return dist
def get_mp_info(srt: list) -> dict:
"""
Get mountpoint information from sourcetable entry.
:param list srt: sourcetable entry as list
:return: dictionary of mountpoint info
:rtype: dict or None if not available
"""
try:
return {
"name": srt[0],
"identifier": srt[1],
"format": srt[2],
"messages": srt[3],
"carrier": srt[4],
"navs": srt[5],
"network": srt[6],
"country": srt[7],
"lat": srt[8],
"lon": srt[9],
"gga": srt[10],
"solution": srt[11],
"generator": srt[12],
"encrypt": srt[13],
"auth": srt[14],
"fee": srt[15],
"bitrate": srt[16],
}
except IndexError:
return {"name": NA, "gga": 0}
def get_point_at_vector(
start: Point,
dist: float,
bearing: float,
radius: float = WGS84_SMAJ_AXIS,
) -> Point:
"""
Get new point at vector from start position.
:param Point start: starting position
:param float dist: vector distance
:param float bearing: vector bearing (true)
:param float radius: optional radius of sphere, defaults to mean radius of earth
:return: new position as lat/lon
:rtype: Point
"""
phi1 = radians(start.lat)
lambda1 = radians(start.lon)
br = radians(bearing)
phi2 = asin(
sin(phi1) * cos(dist / radius) + cos(phi1) * sin(dist / radius) * cos(br)
)
lambda2 = lambda1 + atan2(
sin(br) * sin(dist / radius) * cos(phi1),
cos(dist / radius) - sin(phi1) * sin(phi2),
)
return Point(degrees(phi2), degrees(lambda2))
def get_range(val: float, rng: tuple):
"""
Find first value in range which exceeds specified value.
:param float val: value
:param tuple rng: range
"""
return rng[next(x[0] for x in enumerate(rng) if x[1] > val)]
def get_track_bounds(track: list) -> tuple:
"""
Get bounds and centre point of track list.
:param list track: list of TrackPoints
:return: bounds of track, center point
:rtype: (Area, Point)
"""
minlat = minlon = 400
maxlat = maxlon = -400
for pnt in track:
minlat = min(minlat, pnt.lat)
minlon = min(minlon, pnt.lon)
maxlat = max(maxlat, pnt.lat)
maxlon = max(maxlon, pnt.lon)
return Area(minlat, minlon, maxlat, maxlon), Point(
(maxlat + minlat) / 2, (maxlon + minlon) / 2
)
def get_units(units: str) -> tuple:
"""
Get speed and elevation units and conversions.
Default is metric - meters and meters per second.
:param str unit: unit
:return: tuple of (dst_u, dst_c, ele_u, ele_C, spd_u, spd_c)
:rtype: tuple
"""
if units == UI:
dst_u = "miles"
dst_c = M2MIL
ele_u = "ft"
ele_c = M2FT
spd_u = "mph"
spd_c = MPS2MPH
elif units == UIK:
dst_u = "naut miles"
dst_c = M2NMIL
ele_u = "ft"
ele_c = M2FT
spd_u = "knt"
spd_c = MPS2KNT
elif units == UMK:
dst_u = "km"
dst_c = M2KM
ele_u = "m"
ele_c = 1
spd_u = "kph"
spd_c = MPS2KPH
else: # UMM
dst_u = "m"
dst_c = 1
ele_u = "m"
ele_c = 1
spd_u = "m/s"
spd_c = 1
return dst_u, dst_c, ele_u, ele_c, spd_u, spd_c
def hdg2yaw(heading: float) -> float:
"""
Convert heading (0 - 360) to yaw (-180 - 180)
:param float heading: heading in range 0 - 360
:return: yaw in range -180 to 180
:rtype: float
"""
heading %= 360
if heading > 180:
heading -= 360
return heading
def hsv2rgb(h: float, s: float, v: float) -> str:
"""
Convert HSV values (in range 0-1) to RGB color string.
:param float h: hue (0-1)
:param float s: saturation (0-1)
:param float v: value (0-1)
:return: RGB color string e.g. "#032a4e"
:rtype: str
"""
r = g = b = 0
v = int(v * 255)
if s == 0.0:
return rgb2str(v, v, v)
i = int(h * 6.0)
f = (h * 6.0) - i
p = int(v * (1.0 - s))
q = int(v * (1.0 - s * f))
t = int(v * (1.0 - s * (1.0 - f)))
i %= 6
if i == 0:
r, g, b = v, t, p
if i == 1:
r, g, b = q, v, p
if i == 2:
r, g, b = p, v, t
if i == 3:
r, g, b = p, q, v
if i == 4:
r, g, b = t, p, v
if i == 5:
r, g, b = v, p, q
return rgb2str(r, g, b)
def isot2dt(tim: str) -> float:
"""
Format datetime from ISO time element.
:param str tim: iso time from trackpoint
:return: timestamp
:rtype: float
"""
if tim[-1] == "Z": # strip timezone label
tim = tim[0:-1]
if tim[-4] == ".": # has milliseconds
tfm = "%Y-%m-%dT%H:%M:%S.%f"
elif tim[-7] == ".": # has microseconds
tfm = "%Y-%m-%dT%H:%M:%S.%f"
else:
tfm = "%Y-%m-%dT%H:%M:%S"
return datetime.strptime(tim, tfm).timestamp()
def kmph2ms(kmph: float) -> float:
"""
Convert kilometers per hour to meters per second.
:param float kmph: kmph
:return: speed in m/s
:rtype: float
"""
if not isinstance(kmph, (float, int)):
return 0
return kmph * 0.2777778
def knots2ms(knots: float) -> float:
"""
Convert knots to meters per second.
:param float knots: knots
:return: speed in m/s
:rtype: float
"""
if not isinstance(knots, (float, int)):
return 0
return knots * 0.5144447324
def lanip() -> str:
"""
Get LAN IP address via socket connection info.
:return: LAN IP address as string, or "N/A' if not available.
"""
with socket(AF_INET, SOCK_DGRAM) as sck:
try:
sck.connect(("8.8.8.8", 80))
return sck.getsockname()[0]
except Exception: # pylint: disable=broad-exception-caught
return "N/A"
def ll2xy(width: int, height: int, bounds: Area, position: Point) -> tuple:
"""
Convert lat/lon to canvas x/y.
:param int width: canvas width
:param int height: canvas height
:param Area bounds: lat/lon bounds of canvas
:param Point coordinate: lat/lon
:return: x,y canvas coordinates
:rtype: tuple
"""
lw = bounds.lon2 - bounds.lon1
lh = bounds.lat2 - bounds.lat1
x = (position.lon - bounds.lon1) / (lw / width)
y = height - (position.lat - bounds.lat1) / (lh / height)
return x, y
def makeval(val: Any, default: Any = 0.0) -> Any:
"""
Force value to be same type as default
(used in sqlite database insertions).
:param object val: value
:param Any default: default value
:return: value or default
:rtype: Any
"""
if (not isinstance(val, type(default))) or (
val == "" and default != val and isinstance(default, str)
):
return default
return val
def m2ft(meters: float) -> float:
"""
Convert meters to feet.
:param float meters: meters
:return: feet
:rtype: float
"""
if not isinstance(meters, (float, int)):
return 0
return meters * 3.28084
def ms2kmph(ms: float) -> float:
"""
Convert meters per second to kilometers per hour.
:param float ms: m/s
:return: speed in kmph
:rtype: float
"""
if not isinstance(ms, (float, int)):
return 0
return ms * 3.6
def ms2knots(ms: float) -> float:
"""
Convert meters per second to knots.
:param float ms: m/s
:return: speed in knots
:rtype: float
"""
if not isinstance(ms, (float, int)):
return 0
return ms * 1.94384395
def ms2mph(ms: float) -> float:
"""
Convert meters per second to miles per hour.
:param float ms: m/s
:return: speed in mph
:rtype: float
"""
if not isinstance(ms, (float, int)):
return 0
return ms * 2.23693674
def ned2vector(n: float, e: float, d: float) -> tuple:
"""
Convert N,E,D relative position to 2D heading and distance.
:param float n: north coordinate
:param float e: east coordinate
:param float d: down coordinate
:return: tuple of distance, heading
:rtype: tuple
"""
dis = sqrt(n**2 + e**2 + d**2)
if n == 0 or e == 0:
hdg = 0
else:
hdg = atan(e / n) * 180 / pi
if hdg > 0:
hdg += 180
else:
hdg += 360
return dis, hdg
def nmea2preset(
msgs: NMEAMessage | tuple[NMEAMessage] | list[NMEAMessage], desc: str = ""
) -> str:
"""
Convert one or more NMEAMessages to format suitable for adding to user-defined
preset list `nmeapresets_l` in PyGPSClient .json configuration files.
The format is:
"<description>; <talker>; <msgID>; <payload as comma separated list>; <msgmode>"
e.g. "Configure Signals; P; QTMCFGSIGNAL; W,7,3,F,3F,7,1; 1"
:param NMEAMessage | tuple[NMEAMessage] | list[NMEAMessage] msgs: NMEAmessage(s)
:param str desc: preset description
:return: preset string
:rtype: str
"""
desc = desc.replace(";", " ")
if not isinstance(msgs, (tuple, list)):
msgs = (msgs,)
preset = (
f"{msgs[0].identity} {['GET','SET','POLL'][msgs[0].msgmode]}"
if desc == ""
else desc
)
for msg in msgs:
preset += f"; {msg.talker}; {msg.msgID}; {','.join(msg.payload)}; {msg.msgmode}"
return preset
def normalise_area(points: tuple) -> Area:
"""
Convert 4 points to Area in correct order (minlat, minlon, maxlat, maxlon).
:param tuple points: tuple of lat1, lon1, lat2, lon2
:return: area
:rtype: Area
:raises TypeError: if less than 4 points provided
"""
if len(points) != 4:
raise ValueError("Exactly 4 points required")
minlat = min(points[0], points[2])
maxlat = max(points[0], points[2])
minlon = min(points[1], points[3])
maxlon = max(points[1], points[3])
return Area(minlat, minlon, maxlat, maxlon)
def parse_rxmspartnkey(msg: UBXMessage) -> list:
"""
Extract dates and keys from RXM-SPARTNKEY message.
:param UBXMessage msg: RXM-SPARTNKEY message
:return: list of (key, valid from date) tuples
:rtype: list
"""
keys = []
pos = 0
for i in range(msg.numKeys):
lkey = getattr(msg, f"keyLengthBytes_{i+1:02}")
wno = getattr(msg, f"validFromWno_{i+1:02}")
tow = getattr(msg, f"validFromTow_{i+1:02}")
dat = wnotow2utc(wno, int(tow * 1000), None, "G", True)
key = ""
for n in range(0 + pos, lkey + pos):
keyb = getattr(msg, f"key_{n+1:02}")
key += f"{keyb:02x}"
keys.append((key, dat))
pos += lkey
return keys