-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
775 lines (680 loc) · 30 KB
/
main.py
File metadata and controls
775 lines (680 loc) · 30 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
import json
import glob
import socket
import time
import threading
import subprocess
import shlex
import os
from logger_config import logger
from csclient import CSClient
cs = CSClient("lpp-client", logger=logger)
MAX_TCP_CONNECTIONS = 5
class RunProgram:
def __init__(self, cmd, name=None):
self.cmd = cmd
self.process = None
self.output_thread = None
self.name = name or "program"
def _log(self, msg):
logger.info(f"[{self.name}] {msg}")
def quit(self):
if self.process:
try:
self.process.kill()
self.process.wait(timeout=5)
except Exception:
pass
self.process = None
def interrupt(self):
if self.process:
self.process.send_signal(subprocess.signal.SIGINT)
def write(self, data):
if self.process:
self.process.stdin.write(data)
self.process.stdin.flush()
def start(self):
try:
# Start the external program and capture its output
self.process = subprocess.Popen(shlex.split(self.cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=0)
# Create a thread to read and print the program's output
def _read_output():
while True:
if not self.process:
break
try:
for line in iter(self.process.stdout.readline, ''):
self._log(line.rstrip())
if not self.process:
break
except UnicodeDecodeError as e:
logger.error(f"bad output: {e}")
continue
output_thread = threading.Thread(target=_read_output)
output_thread.daemon = True
output_thread.start()
# Wait for the program to complete and collect the return code
return_code = self.process.wait()
# Ensure all remaining output is read
remaining_output = self.process.stdout.read()
if remaining_output:
for line in remaining_output.splitlines():
self._log(line.rstrip())
self._log(f"Program exited with return code {return_code}")
# Return the return code of the program
return return_code
except Exception as e:
logger.exception(f"{e}")
return -1
finally:
self.process = None
def parse_nmea_gga(nmea):
"""Parse GPGGA sentence and return fix data in Cradlepoint format"""
try:
parts = nmea.split(',')
if not parts[0].endswith('GGA') or len(parts) < 15:
return None
# Extract time (HHMMSS.sss)
time_str = parts[1]
if time_str:
time_val = float(time_str[:2]) * 3600 + float(time_str[2:4]) * 60 + float(time_str[4:])
else:
time_val = 0
# Extract latitude (DDMM.MMMM)
lat_str = parts[2]
lat_dir = parts[3]
if lat_str and lat_dir:
lat_deg = int(lat_str[:2])
lat_min_full = float(lat_str[2:])
lat_min = int(lat_min_full)
lat_sec = (lat_min_full - lat_min) * 60
if lat_dir == 'S':
lat_deg = -lat_deg
else:
return None
# Extract longitude (DDDMM.MMMM)
lon_str = parts[4]
lon_dir = parts[5]
if lon_str and lon_dir:
lon_deg = int(lon_str[:3])
lon_min_full = float(lon_str[3:])
lon_min = int(lon_min_full)
lon_sec = (lon_min_full - lon_min) * 60
if lon_dir == 'W':
lon_deg = -lon_deg
else:
return None
# Quality and satellites
quality = int(parts[6]) if parts[6] else 0
satellites = int(parts[7]) if parts[7] else 0
# HDOP (horizontal dilution of precision)
hdop = float(parts[8]) if parts[8] else 0
# Altitude
altitude = float(parts[9]) if parts[9] else 0
return {
"accuracy": hdop,
"age": 0.0,
"altitude_meters": altitude,
"from_sentence": "GPGGA",
"ground_speed_knots": 0.0,
"heading": None,
"latitude": {
"degree": lat_deg,
"minute": lat_min,
"second": lat_sec
},
"lock": quality > 0,
"longitude": {
"degree": lon_deg,
"minute": lon_min,
"second": lon_sec
},
"satellites": satellites,
"time": time_val
}
except Exception as e:
logger.error(f"Failed to parse NMEA GGA: {e}")
return None
def handle_nmea(nmea, data=None, cs_path="/status/rtk/nmea", override_gps=False, location_output=False):
if data is None:
data = {}
t = time.time()
# prune data to last 30 seconds
data = {k: v for k, v in data.items() if (t - k) < 30}
data[t] = nmea
cs_data = list(data.values())
cs_put(cs_path, cs_data)
# Only parse GGA for fix data if location_output is disabled
if not location_output and 'GGA' in nmea:
fix_data = parse_nmea_gga(nmea)
if fix_data:
# Always write to /status/gps/rtk
cs_put("/status/gps/rtk", fix_data)
# Optionally override /status/gps/fix
if override_gps:
try:
cs_put("/status/gps/fix", fix_data)
except Exception as e:
logger.warning(f"Failed to override /status/gps/fix: {e}")
return data
def handle_location(location_json, override_gps=False):
"""Handle location format output from S3LC client"""
try:
location_data = json.loads(location_json)
if location_data.get("type") == "location":
loc = location_data.get("location", {})
# Convert to Cradlepoint GPS fix format
lat = loc.get("latitude", 0)
lon = loc.get("longitude", 0)
alt = loc.get("altitude", 0)
lat_deg = int(abs(lat))
lat_min_full = (abs(lat) - lat_deg) * 60
lat_min = int(lat_min_full)
lat_sec = (lat_min_full - lat_min) * 60
if lat < 0:
lat_deg = -lat_deg
lon_deg = int(abs(lon))
lon_min_full = (abs(lon) - lon_deg) * 60
lon_min = int(lon_min_full)
lon_sec = (lon_min_full - lon_min) * 60
if lon < 0:
lon_deg = -lon_deg
h_acc = loc.get("horizontal-accuracy", {})
accuracy = h_acc.get("uncertainty-semi-major", 0) if isinstance(h_acc, dict) else 0
fix_data = {
"accuracy": accuracy,
"age": 0.0,
"altitude_meters": alt,
"from_sentence": "LOCATION",
"ground_speed_knots": 0.0,
"heading": None,
"latitude": {
"degree": lat_deg,
"minute": lat_min,
"second": lat_sec
},
"lock": True,
"longitude": {
"degree": lon_deg,
"minute": lon_min,
"second": lon_sec
},
"satellites": 0,
"time": 0
}
# Write to /status/gps/rtk
cs_put("/status/gps/rtk", fix_data)
# Optionally override /status/gps/fix
if override_gps:
try:
cs_put("/status/gps/fix", fix_data)
except Exception as e:
logger.warning(f"Failed to override /status/gps/fix: {e}")
except json.JSONDecodeError as e:
logger.error(f"Failed to parse location JSON: {e}")
except Exception as e:
logger.error(f"Failed to handle location: {e}")
def handle_nmea_tcp(nmea, tcp_clients):
for client in list(tcp_clients):
try:
client.sendall((nmea + '\r\n').encode())
except:
tcp_clients.remove(client)
def un_thread_server(cs_path="/status/rtk/nmea", tcp_clients=[], log_messages=True, override_gps=False, location_output=False):
""" Thread for reading from unix socket and logging the output"""
socket_path = "/tmp/nmea.sock"
data = {}
if os.path.exists(socket_path):
os.unlink(socket_path)
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as unix_socket:
unix_socket.bind(socket_path)
unix_socket.listen(1)
while True:
client_socket, addr = unix_socket.accept()
with client_socket:
buffer = ""
while True:
chunk = client_socket.recv(8192)
try:
chunk = chunk.decode()
except UnicodeDecodeError:
logger.error(f"failed decoding chunk as utf-8 {chunk}")
chunk = None
if not chunk:
break
buffer += chunk
while '\r\n' in buffer:
line, buffer = buffer.split('\r\n', 1)
if line:
# Check if it's JSON location format
if line.startswith('{') and '"type"' in line and '"location"' in line:
handle_location(line, override_gps)
else:
# NMEA format
if line[0] !='$':
line = f'${line}'
if log_messages:
logger.info(line)
if cs_path:
data = handle_nmea(line, data=data, cs_path=cs_path, override_gps=override_gps, location_output=location_output)
handle_nmea_tcp(line, tcp_clients)
def location_thread_server(override_gps=False):
"""Thread for reading location JSON from separate unix socket"""
socket_path = "/tmp/location.sock"
if os.path.exists(socket_path):
os.unlink(socket_path)
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as unix_socket:
unix_socket.bind(socket_path)
unix_socket.listen(1)
while True:
client_socket, addr = unix_socket.accept()
with client_socket:
buffer = ""
while True:
chunk = client_socket.recv(8192)
try:
chunk = chunk.decode()
except UnicodeDecodeError:
logger.error(f"failed decoding location chunk as utf-8 {chunk}")
chunk = None
if not chunk:
break
buffer += chunk
while '\r\n' in buffer:
line, buffer = buffer.split('\r\n', 1)
if line and line.startswith('{'):
handle_location(line, override_gps)
def trace_cleanup_thread(max_mb):
max_bytes = max_mb * 1024 * 1024
while True:
time.sleep(60)
try:
files = sorted(glob.glob("rtkrcv_*.trace"), key=os.path.getmtime)
total = sum(os.path.getsize(f) for f in files)
while total > max_bytes and files:
oldest = files.pop(0)
size = os.path.getsize(oldest)
os.remove(oldest)
logger.info(f"Removed trace file {oldest} ({size} bytes)")
total -= size
except Exception as e:
logger.error(f"trace cleanup error: {e}")
def tcp_server_thread(port, tcp_clients):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp_socket:
tcp_socket.bind(('0.0.0.0', port))
tcp_socket.listen(MAX_TCP_CONNECTIONS)
logger.info(f"TCP server listening on port {port}")
while True:
client_socket, addr = tcp_socket.accept()
logger.info(f"TCP client connected from {addr}")
tcp_clients.append(client_socket)
def cs_get(path):
if not cs.ON_DEVICE:
return None
try:
return cs.get(path)
except Exception as e:
logger.error(f"failed getting {path} from CS: {e}")
def cs_put(path, value):
if not cs.ON_DEVICE:
return None
try:
return cs.put(path, value)
except Exception as e:
logger.error(f"failed putting to {path} in CS: {e}")
def get_appdata(key):
try:
if cs.ON_DEVICE:
return cs.get_appdata(key)
except Exception as e:
logger.error(f"failed getting appdata {key}: {e}")
def get_cellular_info(device=None):
if device is None:
device = get_appdata("lpp-client.device") or cs_get("/status/wan/primary_device")
if not (device and device.startswith("mdm")):
logger.warning(f"primary_device is not a modem: {device}")
diag = cs_get(f"/status/wan/devices/{device}/diagnostics") or {}
plmn = diag.get('CUR_PLMN') or "000000"
mcc = plmn[:3]
mnc = plmn[3:]
tac = diag.get('TAC') or '0'
imsi = diag.get('IMSI') or '0'
cell_id = diag.get('CELL_ID','').split(" ")[0] or '0'
mdn = diag.get('MDN') or '0'
nr = False
if not cell_id:
cell_id = diag.get('NR_CELL_ID') or '0'
if cell_id != '0':
nr = True
tac = plmn
current_cellular = {"mcc": mcc, "mnc": mnc, "tac": tac, "cell_id": cell_id, "imsi": imsi, "nr": nr}
# cellular overrides
current_cellular["mcc"] = get_appdata("lpp-client.mcc") or current_cellular["mcc"]
current_cellular["mnc"] = get_appdata("lpp-client.mnc") or current_cellular["mnc"]
current_cellular["tac"] = get_appdata("lpp-client.tac") or current_cellular["tac"]
current_cellular["cell_id"] = get_appdata("lpp-client.cell_id") or current_cellular["cell_id"]
current_cellular["imsi"] = get_appdata("lpp-client.imsi") or current_cellular["imsi"]
current_cellular["nr"] = get_appdata("lpp-client.nr") or current_cellular["nr"]
# mdn can only be used if explicitly requested
for use_mdn in (get_appdata("lpp-client.mdn"), get_appdata("lpp-client.msisdn")):
if use_mdn is not None:
current_cellular["mdn"] = mdn if use_mdn.lower() in ["", "true", "yes", "y"] else use_mdn
return current_cellular
def get_cmd_params():
host = get_appdata("lpp-client.host") or "129.192.82.125"
port = get_appdata("lpp-client.port") or 5431
serial = get_appdata("lpp-client.serial") or "/dev/ttyS1"
baud = get_appdata("lpp-client.baud") or 115200
output = get_appdata("lpp-client.output") or "un"
data_format = get_appdata("lpp-client.format") or "osr"
# mcc, mnc, tac, and cell_id can be statically configured as parsed by get_cellular_info(),
# or it could be dynamically updated from the momdem (default). Additionality the initial params
# can be specified explicitly, which THEN get updated dynamically by the modem. This allows the
# lpp client to start with known initial values
starting_mcc = get_appdata("lpp-client.starting_mcc") or None
starting_mnc = get_appdata("lpp-client.starting_mnc") or None
starting_tac = get_appdata("lpp-client.starting_tac") or None
starting_cell_id = get_appdata("lpp-client.starting_cell_id") or None
forwarding = get_appdata("lpp-client.forwarding") or ""
flags = get_appdata("lpp-client.flags") or ""
#flags are comma separated. For example:
# "confidence-95to39,ura-override=2,ublox-clock-correction,force-continuity,sf055-default=3,sf042-default=1,increasing-siou"
cs_path = get_appdata("lpp-client.path")
cs_path = "/status/rtk/nmea" if cs_path is None else cs_path
tokoro_flags = get_appdata("lpp-client.tokoro_flags") or ""
spartn_flags = get_appdata("lpp-client.spartn_flags") or ""
log_nmea = True
log_nmea_value = get_appdata("lpp-client.log_nmea")
if log_nmea_value is not None:
if log_nmea_value.lower() in ["", "true", "yes", "y"]:
log_nmea = True
elif log_nmea_value.lower() in ["false", "no", "n"]:
log_nmea = False
enable_rtklib = False
rtklib_mode = "client-first" # client-first: serial->client->rtklib, rtklib-first: serial->rtklib->client
enable_rtklib_value = get_appdata("lpp-client.enable_rtklib")
if enable_rtklib_value is not None:
if enable_rtklib_value.lower() in ["true", "yes", "y", "client-first"]:
enable_rtklib = True
rtklib_mode = "client-first"
elif enable_rtklib_value.lower() == "rtklib-first":
enable_rtklib = True
rtklib_mode = "rtklib-first"
override_gps = False
override_gps_value = get_appdata("lpp-client.override_gps")
if override_gps_value is not None:
if override_gps_value.lower() in ["true", "yes", "y"]:
override_gps = True
location_output = False
location_output_value = get_appdata("lpp-client.location_output")
if location_output_value is not None:
if location_output_value.lower() in ["true", "yes", "y"]:
location_output = True
rtklib_trace = 0
rtklib_trace_value = get_appdata("lpp-client.rtklib_trace")
if rtklib_trace_value is not None:
try:
rtklib_trace = int(rtklib_trace_value)
except ValueError:
pass
rtklib_trace_max_mb = 10
rtklib_trace_max_mb_value = get_appdata("lpp-client.rtklib_trace_size")
if rtklib_trace_max_mb_value is not None:
try:
rtklib_trace_max_mb = int(rtklib_trace_max_mb_value)
except ValueError:
pass
rtklib_port = None
rtklib_port_value = get_appdata("lpp-client.rtklib_port")
if rtklib_port_value is not None:
try:
rtklib_port = int(rtklib_port_value)
except ValueError:
pass
rtklib_flags = get_appdata("lpp-client.rtklib_flags") or ""
rtklib_corrections = get_appdata("lpp-client.rtklib_corrections") or "ssr"
rtklib_send_corrections = True
rtklib_send_corrections_value = get_appdata("lpp-client.rtklib_send_corrections")
if rtklib_send_corrections_value is not None:
if rtklib_send_corrections_value.lower() in ["false", "no", "n"]:
rtklib_send_corrections = False
return {
"host": host,
"port": port,
"serial": serial,
"baud": baud,
"output": output,
"cs_path": cs_path,
"format": data_format,
"starting_mcc": starting_mcc,
"starting_mnc": starting_mnc,
"starting_tac": starting_tac,
"starting_cell_id": starting_cell_id,
"forwarding": forwarding,
"flags": flags,
"tokoro_flags": tokoro_flags,
"spartn_flags": spartn_flags,
"log_nmea": log_nmea,
"enable_rtklib": enable_rtklib,
"rtklib_mode": rtklib_mode,
"override_gps": override_gps,
"location_output": location_output,
"rtklib_trace": rtklib_trace,
"rtklib_trace_max_mb": rtklib_trace_max_mb,
"rtklib_port": rtklib_port,
"rtklib_flags": rtklib_flags,
"rtklib_corrections": rtklib_corrections,
"rtklib_send_corrections": rtklib_send_corrections,
}
def build_v4_command(params, cellular):
"""Build command for v4 example-client"""
app_path = "./example-client"
# Handle additional flags
additional_flags = params["flags"].replace(',', ' ').split()
additional_flags = ' '.join(f"--{flag.lstrip('-')}" for flag in additional_flags)
tokoro_flags = params["tokoro_flags"].replace(', ', ' ').split()
tokoro_flags = ' '.join(f"--{flag.lstrip('-')}" for flag in tokoro_flags)
# Corrections mode: ssr (default, via tokoro) or osr (via lpp2rtcm)
use_tokoro = params.get("rtklib_corrections", "ssr") != "osr"
if use_tokoro:
ad_type = "--ad-type=ssr"
processors = ["--tokoro"]
additional_flags += " " + tokoro_flags
else:
ad_type = "--ad-type=osr"
processors = ["--lpp2rtcm"] # Identity specification
identity_param = ""
if cellular.get('mdn'):
identity_param = f"--msisdn {cellular['mdn']}"
else:
identity_param = f"--imsi {cellular['imsi']}"
# RTKLIB outputs (only if enabled)
rtklib_outputs = []
if params["enable_rtklib"]:
if params["rtklib_mode"] == "rtklib-first":
# rtkrcv reads serial; client gets raw GNSS from rtkrcv, sends corrections back
input_param = "--input tcp-client:host=127.0.0.1,port=10000,format=rtcm,tags=gnss"
rtklib_outputs = [
*(["--output tcp-client:host=127.0.0.1,port=40000,format=rtcm,itags=corrections"] if params["rtklib_send_corrections"] else []),
"--input tcp-client:host=127.0.0.1,port=30000,format=nmea,tags=rtk",
*(["--tkr-no-glonass", "--tkr-output-tag corrections"] if use_tokoro else ["--l2r-output-tag corrections"]),
"--ls-output-tag corrections",
]
serial_rtcm_output = ""
else:
# client-first: client reads serial, sends measurements+ephemeris and corrections separately
input_param = f"--input serial:device={params['serial']},baudrate={params['baud']},format=rtcm,tags=gnss"
rtklib_outputs = [
"--output tcp-client:host=127.0.0.1,port=10000,format=rtcm+ubx,itags=gnss",
*(["--output tcp-client:host=127.0.0.1,port=40000,format=rtcm,itags=corrections"] if params["rtklib_send_corrections"] else []),
"--input tcp-client:host=127.0.0.1,port=30000,format=nmea,tags=rtk",
*(["--tkr-no-glonass", "--tkr-output-tag corrections"] if use_tokoro else ["--l2r-output-tag corrections"]),
"--ls-output-tag corrections",
]
serial_rtcm_output = ""
else:
input_param = f"--input serial:device={params['serial']},baudrate={params['baud']},format=nmea+ubx,tags=gnss"
serial_rtcm_output = f"--output serial:device={params['serial']},baudrate={params['baud']},format=rtcm"
# Output configuration for CS path
outputs = []
if params["output"].startswith("un"):
outputs.append("--output tcp-client:path=/tmp/nmea.sock,format=nmea,itags=gnss+rtk")
if params["location_output"]:
outputs.append("--output tcp-client:path=/tmp/location.sock,format=location")
elif params["output"].startswith("tcp-server:"):
_, ip, port = params["output"]
outputs.append(f"--output tcp-server:host={ip},port={port},format=nmea,itags=gnss+rtk")
if params["location_output"]:
outputs.append(f"--output tcp-server:host={ip},port={port},format=location")
elif params["output"].startswith("tcp-client:"):
_, ip, port = params["output"]
outputs.append(f"--output tcp-client:host={ip},port={port},format=nmea,itags=gnss+rtk")
if params["location_output"]:
outputs.append(f"--output tcp-client:host={ip},port={port},format=location")
else:
ip, port = params['output'].split(':')
outputs.append(f"--output tcp-client:host={ip},port={port},format=nmea,itags=gnss+rtk")
if params["location_output"]:
outputs.append(f"--output tcp-client:host={ip},port={port},format=location")
export_param = " ".join(outputs)
control_param = "--input stdin:format=ctrl,tags=ctrl"
cmd = (
f"{app_path} "
f"{' '.join(processors)} "
f"{additional_flags} "
f"--ls-host {params['host']} "
f"--ls-port {params['port']} "
f"--mcc {params['starting_mcc'] or cellular['mcc']} "
f"--mnc {params['starting_mnc'] or cellular['mnc']} "
f"--tac {params['starting_tac'] or cellular['tac']} "
f"--ci {params['starting_cell_id'] or cellular['cell_id']} "
f"{'--nr-cell ' if cellular['nr'] else ''}"
f"{identity_param} "
f"{input_param} "
f"{serial_rtcm_output} "
f"{' '.join(rtklib_outputs)} "
f"{export_param} "
f"{control_param} "
f"{ad_type} "
)
return cmd
def main():
from configure_gnss import configure
configure()
logger.info("Starting lpp client and RTKLIB")
params = get_cmd_params()
cellular = get_cellular_info()
logger.info(params)
start_time = time.time()
# Store configuration and start time in config store
config_status = {
"config": params,
"cellular": cellular,
"start_time": start_time,
"start_time_iso": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(start_time))
}
cs_put("/status/rtk/config", config_status)
if params["cs_path"] == "/status/rtk/nmea": # the default
if cs_get("/status/rtk") is None:
cs_put("/status/rtk", {"nmea": []})
tcp_clients=[]
if params["output"].startswith("un"):
un_thread = threading.Thread(target=un_thread_server, args=(params["cs_path"], tcp_clients, params["log_nmea"], params["override_gps"], params["location_output"]))
un_thread.daemon = True
un_thread.start()
# Start location socket thread if location_output is enabled
if params["location_output"]:
location_thread = threading.Thread(target=location_thread_server, args=(params["override_gps"],))
location_thread.daemon = True
location_thread.start()
if params["output"].startswith("un-tcp"):
_, port = params["output"].split(":")
tcp_thread = threading.Thread(target=tcp_server_thread, args=(int(port), tcp_clients))
tcp_thread.daemon = True
tcp_thread.start()
logger.info("Using v4 client (example-client)")
cmd = build_v4_command(params, cellular)
logger.info(cmd)
lpp_program = RunProgram(cmd, name="example-client")
# Start RTKLIB rtkrcv with config file if enabled
rtklib_program = None
if params["enable_rtklib"]:
if params["rtklib_mode"] == "rtklib-first":
# Generate conf with serial input and logstr forwarding raw GNSS to client
with open("/lpp-client/rtklib.conf", "r") as f:
conf = f.read()
conf = conf.replace("inpstr1-type =tcpsvr", "inpstr1-type =serial")
conf = conf.replace("inpstr1-path =:10000", f"inpstr1-path ={params['serial']}:{params['baud']}:8:n:1:off")
conf = conf.replace("logstr1-type =off", "logstr1-type =tcpsvr")
conf = conf.replace("logstr1-path =", "logstr1-path =:10000")
with open("/tmp/rtklib.conf.run", "w") as f:
f.write(conf)
conf_path = "/tmp/rtklib.conf.run"
else:
conf_path = "/lpp-client/rtklib.conf"
rtklib_cmd = f"rtkrcv -s -nc -o {conf_path}"
if params["rtklib_trace"] > 0:
rtklib_cmd += f" -t {params['rtklib_trace']}"
if params["rtklib_port"]:
rtklib_cmd += f" -p {params['rtklib_port']}"
if params["rtklib_flags"]:
rtklib_cmd += f" {params['rtklib_flags']}"
logger.info(f"RTKLIB command: {rtklib_cmd}")
rtklib_program = RunProgram(rtklib_cmd, name="rtkrcv")
def rtklib_watchdog():
while True:
logger.info("rtkrcv starting...")
rtklib_program.start()
logger.warning("rtkrcv exited, restarting in 5s...")
rtklib_program.quit()
time.sleep(5)
rtklib_thread = threading.Thread(target=rtklib_watchdog)
rtklib_thread.daemon = True
rtklib_thread.start()
time.sleep(2)
if params["rtklib_trace"] > 0:
cleanup_thread = threading.Thread(target=trace_cleanup_thread, args=(params["rtklib_trace_max_mb"],))
cleanup_thread.daemon = True
cleanup_thread.start()
else:
logger.info("RTKLIB disabled via config")
# Create a control thread to handle user input (e.g., stopping the program)
def control_thread(lpp_program, rtklib_program, current_params, current_cellular):
logger.info("Periodically checking for changes")
while True:
time.sleep(10)
if lpp_program.process is None:
logger.info("example-client terminated")
break
new_params = get_cmd_params()
if new_params != current_params:
current_params = new_params
logger.info(f"params changed: {current_params}")
lpp_program.interrupt()
if rtklib_program:
rtklib_program.quit()
break
new_cellular = get_cellular_info()
logger.info(f"cell check: {new_cellular['mnc']},{new_cellular['mcc']},{new_cellular['tac']},{new_cellular['cell_id']},{new_cellular["nr"]} == {current_cellular['mnc']},{current_cellular['mcc']},{current_cellular['tac']},{current_cellular['cell_id']},{current_cellular["nr"]}")
if new_cellular != current_cellular:
current_cellular = new_cellular
logger.info("cellular info changed")
if current_cellular["nr"]:
cmd = f"/CID,N,{current_cellular['mcc']},{current_cellular['mnc']},{current_cellular['tac']},{current_cellular['cell_id']}\r\n"
else:
cmd = f"/CID,L,{current_cellular['mcc']},{current_cellular['mnc']},{current_cellular['tac']},{current_cellular['cell_id']}\r\n"
lpp_program.write(cmd)
ct = threading.Thread(target=control_thread, args=(lpp_program,rtklib_program,params,cellular))
ct.daemon = True
ct.start()
# Start both programs
lpp_thread = threading.Thread(target=lpp_program.start)
lpp_thread.start()
ct.join()
logger.info("Exiting program, hopefully restarting...")
if __name__ == "__main__":
try:
main()
except Exception as e:
logger.exception(f"{e}")
raise e