-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfreq_cycler.py
executable file
·1405 lines (1061 loc) · 36.4 KB
/
freq_cycler.py
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
#!/usr/bin/python -u
# coding=utf8
# by Wojtek SP9WPN
# v1.16.1 (22.08.2023)
# BSD licence
import os
import sys
import re
import subprocess
import socket
import time
import sqlite3
import argparse
try:
import ConfigParser as configparser #py2
except ImportError:
import configparser #py3
try:
import Queue as queue #py2
except ImportError:
import queue #py3
import signal
try:
from urllib.request import urlopen #py3
except ImportError:
from urllib2 import urlopen #py2
import csv
import email.utils
from datetime import datetime
import calendar
import codecs
from math import sin, cos, sqrt, atan2, radians
from threading import Thread
from threading import Event
def verbose(t):
if args.v or args.vv:
vprint(t)
def vprint(t):
if args.vv:
print("%s %s" % (datetime.now().strftime("%d.%m.%Y %H:%M:%S"), t) )
else:
print(t)
default_external_urls = [
'http://api.wettersonde.net/sonde_csv.php'
]
argparser = argparse.ArgumentParser(description='Smart frequency cycler for dxlAPRS radiosonde decoder.')
mut_excl_group1 = argparser.add_mutually_exclusive_group()
mut_excl_group1.add_argument('-csv', metavar='<url>', action='append', help='URL of data from external server (default: see readme)')
mut_excl_group1.add_argument('-no-external-csv', action='store_true', help='disable reading CSV from external sites')
argparser.add_argument('-udplog', metavar='<file>', help='read APRS data udpgate4 log')
argparser.add_argument('-aprslog', metavar='<IP:port>', action='append', help='read sondes APRS data from TCP connection')
argparser.add_argument('-remote', metavar='<url>', help='URL of remote control (override) file')
argparser.add_argument('-slave', action='store_true', help='do not read file/web/APRS data (for multi-SDR operation)')
argparser.add_argument('-aprsscan', action='store_true', help='enable extra 70cm APRS reception cycles, see readme')
argparser.add_argument('-c', metavar='<num>', help='RTL max open channels (default: 4)', default=4)
argparser.add_argument('-bc', metavar='<num|percent%>', help='channels reserved for blind-scanning (default: 25%% of max channels')
argparser.add_argument('-no-blind', action='store_true', help='disable blind-scanning')
argparser.add_argument('-f', metavar='<kHz>', nargs=2, type=int, help='frequency range (for multi-SDR operation, default 400000 406000)')
argparser.add_argument('-bflush', action='store_true', help='enable buffer flush cycles, see readme')
argparser.add_argument('-ppm', metavar='<ppm>', type=int, help='RTL PPM correction')
argparser.add_argument('-agc', metavar='<0|1>', help='RTL AGC switch (default: 1 - enabled)', choices=('0','1'), default=1)
argparser.add_argument('-gain', metavar='<gain|auto>', help='RTL gain setting')
argparser.add_argument('-bw', metavar='<kHz>', type=int, help='RTL max badwidth (default: 1900)', default=1900)
mut_excl_group3 = argparser.add_mutually_exclusive_group()
mut_excl_group3.add_argument('-v', action='store_true', help='verbose mode')
mut_excl_group3.add_argument('-vv', action='store_true', help='verbose with timestamps')
mut_excl_group3.add_argument('-q', action='store_true', help='quiet mode (show only errors)')
argparser.add_argument('config', help='configuration file (input)')
argparser.add_argument('output', help='sdrtst config file to write to')
args=argparser.parse_args()
if not os.path.isfile(args.config):
vprint("ERROR: config file not found: " + args.config)
sys.exit()
try:
config = configparser.ConfigParser()
config.read(args.config)
except:
vprint("ERROR: error reading config file: " + args.config)
sys.exit()
if os.access (args.output, os.F_OK) and not os.access(args.output, os.W_OK):
vprint("ERROR: access denied to output file: " + args.output)
sys.exit()
if config.has_option('main','Database') and config.get('main','Database'):
dbfile = config.get('main','Database')
verbose("using "+dbfile+" as database")
else:
if args.slave:
vprint("ERROR: -slave requires Database defined (check "+args.config+")")
sys.exit()
dbfile = ":memory:"
sonde_types = { 0: 'sonde_standard', # RS41, RS92, DFM, MP3
1: 'sonde_pilotsonde',
2: 'sonde_m10',
3: 'sonde_atms'
}
# status:
# 0 - blind scanning freq
# 1 - known possible sondes
# 2 - nearby flying (external data)
# 3 - heard by us
aprs_interval = 0
remote_control_last_check = 0
q = queue.Queue()
exit_script = Event()
def thread_external_sondelist(url):
while not exit_script.is_set():
read_csv(url)
exit_script.wait(180)
def thread_read_udpgate_log(filename):
while not exit_script.is_set():
try:
file = open(filename,'rb')
file.seek(0,2)
while not exit_script.is_set():
try:
line = file.readline()
if not line:
if file.tell() != os.stat(filename)[6]:
break
time.sleep(1)
else:
APRS_decode(line,filename)
except:
break
try:
file.close()
except:
pass
except:
pass
vprint("ERROR: error accessing "+str(filename)+", trying to reopen in 20s")
exit_script.wait(20)
def thread_read_APRS(ip,port):
port = int(port)
need_connect = True
verbose ("Connecting to APRS: "+ip+":"+str(port))
while not exit_script.is_set():
try:
if need_connect:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip,port))
need_connect = False
# APRS login
s.sendall(("user N0CALL -1 filter r/%.4f/%.4f/%d\n" %
( config.getfloat('main','QTHlat'),
config.getfloat('main','QTHlon'),
config.getint('main','Range') ) ).encode() )
line = s.recv(1200)
if line:
APRS_decode(line,'aprs')
else:
vprint("APRS connection error, reconnecting in 20s")
need_connect = True
exit_script.wait(20)
except (socket.timeout, socket.error) as e:
vprint("APRS connection error, reconnecting in 20s")
verbose(e)
need_connect = True
s.close()
exit_script.wait(20)
def roundF(f,r):
f = round(float(f)/r)
f = f * r
return int(f)
def init(z1,z2):
global config,freq_range,qth,aprs_last_cycle,aprs_interval,sdrtst_templates,l_sdrtst_templates,l_freq_spread
if not os.path.isfile(args.config):
print("ERROR: config file not found: " + args.config)
sys.exit()
verbose("reading config: " + args.config)
try:
config = configparser.ConfigParser()
config.read(args.config)
except:
print("ERROR: error reading config file: " + args.config)
sys.exit()
for t,t_name in dict(sonde_types).items():
if not config.has_section(t_name):
sonde_types.pop(t)
if len(sonde_types) == 0:
print("ERROR: need definitions for sonde types in config file")
sys.exit()
sdrtst_templates={}
l_sdrtst_templates={}
for t,t_name in dict(sonde_types).items():
temp = set()
ltemp = set()
section_items = config.items(t_name)
for key,val in section_items:
if key[:14].lower() == 'sdrtsttemplate':
temp.add(' '.join(val.strip('"').split()))
if key[:17].lower() == 'ldgsdrtsttemplate':
ltemp.add(' '.join(val.strip('"').split()))
if len(temp) > 0:
sdrtst_templates[t] = temp
else:
print("ERROR: no SdrtstTemplate defined for %s, ignoring this type" % t_name)
time.sleep(1)
sonde_types.pop(t)
if len(ltemp) > 0:
l_sdrtst_templates[t] = ltemp
else:
l_sdrtst_templates[t] = sdrtst_templates[t]
l_freq_spread={}
for t,t_name in dict(sonde_types).items():
_spread = {0}
if config.has_option(t_name,'LdgModeFreqSpread'):
try:
(_low, _high, _step) = list(map(int, config.get(t_name,'LdgModeFreqSpread').strip('\"').split(" ")))
for _freq_diff in range (_low, _high+1, _step):
_spread.add(_freq_diff)
except:
print("ERROR: bad LdgModeFreqSpread definition for %s" % t_name)
l_freq_spread[t] = _spread
if args.f:
freq_range = (args.f[0],args.f[1])
else:
freq_range = (400000,406000) # default
qth=(config.getfloat('main','QTHlat'),config.getfloat('main','QTHlon'))
aprs_last_cycle = time.time()
try:
aprs_interval=config.getint('aprs_cycles','AprsInterval')
except:
aprs_interval=180
pass
def set_blind_channels():
global channels,blind_channels
if args.bc: # number of channels reserved for blind-scanning
if args.bc[-1] == '%':
blind_channels = int(max(1,channels * float(args.bc[:-1])/100))
else:
blind_channels = min(int(args.bc),channels)
elif channels == 1:
blind_channels = 0
else:
blind_channels = int(max(1,channels * 0.25))
if args.no_blind:
blind_channels = 0
def count_sel_freqs(f):
have=0
for (freq, type, landing) in f:
if not landing:
have += len(sdrtst_templates[type])
else:
have += len(l_sdrtst_templates[type]) * len(l_freq_spread[type])
return have
def add_freqs(flist,landing = False):
global channels,blind_channels
channels = max(1,channels)
for f in flist:
have_channels = count_sel_freqs(selected_freqs)
if have_channels >= channels:
break
# no free channels for all templates
if have_channels + len(sdrtst_templates[f[1]]) > channels:
continue
if ( not landing
and have_channels >= channels-blind_channels+1
and f[2] != 0 ):
continue
if args.no_blind and f[2]==0:
continue
if f[0] < freq_range[0] or f[0] > freq_range[1]:
continue
if have_channels > 0:
if ( f[0] - args.bw >= min([t[0] for t in selected_freqs])
or f[0] + args.bw <= max([t[0] for t in selected_freqs]) ):
continue
# remove non-landing duplicates (this shouldn't happen)
if landing:
for _xx in selected_freqs:
if [roundF(_xx[0],50),_xx[1],_xx[2]] == [roundF(f[0],50),f[1],False]:
selected_freqs.remove(_xx)
# skip duplicates (as rounded to 50kHz)
if [roundF(f[0],50),f[1]] in [[roundF(x[0],50),x[1]] for x in selected_freqs]:
continue
selected_freqs.add((f[0],f[1],landing))
def mark_freqs_checked(freqs):
for f in freqs:
dbc.execute("""UPDATE freqs SET last_checked = datetime('now')
WHERE freq = ? and type = ?""",(f[0],f[1]))
db.commit()
def mark_landing_mode(freqs):
for f in freqs:
dbc.execute("""UPDATE freqs SET landing_mode = ?
WHERE freq = ?
AND type = ?
AND landing_mode = '/:/AVAIL/:/' """,(args.output,f[0],f[1]))
if ( dbc.rowcount > 0
and not args.q ):
vprint("Entering landing mode: (%.3f)" % (f[0]/1000.0))
db.commit()
def flush_sdrtst_buffers(n):
if n < 1 or not args.bflush:
return 0
oldmask = os.umask (000)
try:
tmp=open(args.output+'.tmp','w')
except:
os.umask (oldmask)
vprint("ERROR: error writing tmp file: " + args.output + ".tmp")
return 0
for f in range (0, n):
tmp.write("f 511.111 0 1 1\n")
os.umask (oldmask)
tmp.close()
try:
os.rename(args.output+'.tmp',args.output)
except:
vprint("ERROR: error writing file: " + args.output)
return 0
time.sleep(1.3)
def write_sdrtst_config(freqs):
if count_sel_freqs(freqs) < count_sel_freqs(old_selected_freqs):
flush_sdrtst_buffers(count_sel_freqs(old_selected_freqs))
oldmask = os.umask (000)
try:
tmp=open(args.output+'.tmp','w')
if args.ppm != None:
tmp.write('p 5 '+str(args.ppm)+"\n")
tmp.write('p 8 '+str(args.agc)+"\n")
if args.gain:
if args.gain == 'auto':
tmp.write('p 3 1'+"\n")
else:
tmp.write('p 3 0'+"\n")
tmp.write('p 4 '+ "%d" % (float(args.gain) * 10) +"\n")
except:
os.umask (oldmask)
vprint("ERROR: error writing tmp file: " + args.output + ".tmp")
return 0
new_freqs = set()
for f in sorted(freqs):
if f[1] not in sonde_types:
continue
_count = 0
if not f[2]:
for template in sdrtst_templates[f[1]]:
tmp.write("f %.3f" % (int(f[0])/1000.0))
tmp.write(" "+template+"\n")
_count += 1
else:
for template in l_sdrtst_templates[f[1]]:
for _freq_diff in l_freq_spread[f[1]]:
tmp.write("f %.3f" % ( (int(f[0])+_freq_diff)/1000.0) )
tmp.write(" "+template+"\n")
_count += 1
if (_count > 0):
new_freqs.add((f[0],f[1],_count,f[2]))
os.umask (oldmask)
tmp.close()
try:
os.rename(args.output+'.tmp',args.output)
except:
vprint("ERROR: error writing file: " + args.output)
return 0
if not args.q:
txt = "New freqs:"
for nf in sorted(new_freqs):
status = dbc.execute("""SELECT status, landing_mode, serial
FROM freqs
WHERE freq = ?
AND type = ?
AND ( status_expire IS NULL
OR status_expire >= datetime('now') )
ORDER BY landing_mode DESC, status DESC
LIMIT 1""",
(nf[0],nf[1])).fetchone()
if nf[3] == True or status[1] != None:
txt += ' !'
elif status[0] == 3:
txt += ' ^'
elif status[0] == 2:
txt += ' #'
elif status[0] == 1:
txt += ' +'
else:
txt += ' '
txt += "%.3f" % (int(nf[0])/1000.0)
if sonde_types[nf[1]] == 'sonde_pilotsonde':
txt += 'p'
elif sonde_types[nf[1]] == 'sonde_m10':
txt += 'm'
elif sonde_types[nf[1]] == 'sonde_atms':
txt += 'a'
else:
txt += ''
if (nf[2] > 1):
txt += "*%d" % nf[2]
vprint(txt)
def write_sdrtst_config_aprs():
flush_sdrtst_buffers(count_sel_freqs(selected_freqs))
oldmask = os.umask (000)
try:
tmp=open(args.output+'.tmp','w')
if args.ppm != None:
tmp.write('p 5 '+str(args.ppm)+"\n")
tmp.write('p 8 '+str(args.agc)+"\n")
if args.gain:
if args.gain == 'auto':
tmp.write('p 3 1'+"\n")
else:
tmp.write('p 3 0'+"\n")
tmp.write('p 4 '+ "%d" % (float(args.gain) * 10) +"\n")
except:
os.umask (oldmask)
vprint("ERROR: error writing tmp file: " + args.output + ".tmp")
return 0
tmp.write(config.get('aprs_cycles','AprsSdrtstConfig').strip('"')+"\n")
os.umask (oldmask)
tmp.close()
try:
os.rename(args.output+'.tmp',args.output)
except:
vprint("ERROR: error writing file: " + args.output)
return 0
def calc_distance(p1,p2):
r = 6373.0
lat1 = radians(float(p1[0]))
lon1 = radians(float(p1[1]))
lat2 = radians(float(p2[0]))
lon2 = radians(float(p2[1]))
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = r * c
return int(distance)
def sonde_type_from_serial(s):
if s.isdigit():
if s[0:2] == '16' or s[0:2] == '17' or s[0:2] == '18' or s[0:2] == '19' or s[0:2] == '00':
return 0 # DFM
else:
return 2 # M10/M20
elif s[0:2] == 'ME':
return 2 # M10/M20
elif s[0:2] == 'SC':
return 0 # SRSC sprawdzic, czy 0
elif s[0:3] == 'AT2':
return 3 # ATMS
elif s[0:3] == 'MRZ':
return 0 # MP3
elif s[0:3] == 'MTS':
return 0 # MTS sprawdzic, czy 0
elif s[0:3] == 'IMS':
return 0 # MEISEI
elif s[0:1] == 'P' and not s[1:2].isdigit():
return 1 # pilotSonde
elif s[0:1] == 'B' and not s[1:2].isdigit():
return 1 # pilotSonde
elif s[0:1] == 'G' and not s[1:2].isdigit():
return 1 # pilotSonde
elif s[0:2] == 'DF':
return 0 # DFM
elif s[0:1] == 'D' and s[2:4].isdigit():
return 0 # DFM
else:
return 0 # standard
def sonde_type_from_text(t):
if t == '':
return -1
elif t[0:4] == 'RS41' or t[0:4] == 'RS92':
return 0
elif t[0:3] == 'DFM':
return 0
elif t == 'MRZ' or t == 'iMET':
return 0
elif t == 'M10' or t == 'M20':
return 2
else:
return -1
def read_csv(file):
# csv_source: 0: local sonde.csv 1: external csv 2: wettersonde api
global extra_wait
if not "://" in file:
file = "file://" + file
external = True
if file[0:7] == "file://":
external = False
csv_format = 1 # sonde.csv
if file[0:27] == "http://api.wettersonde.net/":
csv_format = 2
try:
csvreader = csv.reader(codecs.iterdecode(urlopen(file), 'utf-8'), delimiter=';', quoting=csv.QUOTE_NONE)
verbose("reading "+file)
except:
return None
try:
for r in csvreader:
try:
if csv_format == 1: # sonde.csv
i_ser, i_lat, i_lon, i_alt = r[0], r[1], r[2], int(r[3])
i_qrg = int(float(r[7])*1000)
i_type = ''
try:
i_time = int(r[8])
if file[0:28] == "https://sn.skp.wodzislaw.pl/":
try:
i_time = int(r[10])
except:
i_time = int(r[8])
while i_time > time.time() + 600: # dirty fix for incorrect time zone
i_time -= 3600
except:
i_time = 0
try:
i_vs = float(r[5])
except:
i_vs=0.0
elif csv_format == 2: # wettersonde API
i_ser = r[0]
if i_ser == 'Serial':
continue
i_lat, i_lon, i_alt = r[2], r[3], int(r[4])
i_qrg = int(float(r[5])*1000)
i_type = r[6]
try:
i_time = (datetime.strptime(r[1], '%Y-%m-%dT%H:%M:%S') - datetime(1970,1,1)).total_seconds()
while i_time > time.time() + 600: # dirty fix for incorrect time zone
i_time -= 3600
except:
i_time = 0
try:
i_vs = float(r[7])
except:
i_vs=0.0
else:
raise
if i_time < time.time() - 86400 or i_time > time.time() + 86400:
i_time = 0
if external:
while i_time > time.time() + 600: # dirty fix for incorrect time zone
i_time -= 3600
except:
continue
try:
sonde_type = sonde_type_from_text(i_type)
if sonde_type not in sonde_types:
sonde_type = sonde_type_from_serial(i_ser)
if sonde_type not in sonde_types:
verbose(" ? unknown type: %s %s" % (i_type, i_ser))
continue
try:
qrg=int(float(r[7])*1000)
except:
continue
try:
if ( external == False
and i_qrg == 0
and i_time > 0
and (time.time()-i_time <= min(config.getint('main','CycleInterval'),5)) ):
extra_wait = 52
except:
pass
try:
if i_time+(config.getint('main','SignalTimeout') * 60) < time.time():
continue
status_expire = int(i_time + config.getint('main','SignalTimeout') * 60)
except:
status_expire = int(time.time() + config.getint('main','SignalTimeout') * 60)
pass
distance = calc_distance((i_lat,i_lon),qth)
if external and distance > config.getint('main','Range'):
continue
# serial, freq, type, status, last_alt, status_expire, distance, vs
if external:
q.put((i_ser,i_qrg,sonde_type,2,i_alt,status_expire,distance,i_vs))
else:
q.put((i_ser,i_qrg,sonde_type,3,i_alt,status_expire,distance,i_vs))
verbose(" ..%1d %-9s %8.5f %8.5f %5dm %5.1fm/s %.3fMHz %s" % (sonde_type, i_ser, float(i_lat), float(i_lon), i_alt, i_vs, i_qrg/1000.0, time.strftime('%H:%M:%S', time.localtime(i_time)) ) )
except:
continue
except:
vprint("ERROR: error parsing %s" % file)
pass
def APRS_decode(line,source=''):
line.strip()
try:
if (line and line.find(b":;")>-0):
line_parts=line.split(b":;")
if (source != 'aprs' and line_parts[0].find(b"U:")==-1):
return None
info=line_parts[1]
#L4340196 *220443h5120.90N/01952.39EO182/001/A=000743!wJ(!Clb=-0.6m/s f=404.50MHz BK=Off
sonde_id=info[:9].strip().decode("UTF-8")
lat=float(info[17:19])+float(info[19:21])/60+float(info[22:24])/60/100
lon=float(info[26:29])+float(info[29:31])/60+float(info[32:34])/60/100
if not ( info[25:26] == b'/' and info[35:36] == b'O' ):
return None # not /O (balloon)
m=re.search(b'(?<=A=)\w+',info)
if m:
alt=int(int(m.group(0))/3.2808)
else:
return None
qrg=0
m=re.search(b'\sf=([0-9]{3}\.[0-9]+)(MHz)?',info)
if m:
qrg=m.group(1)
if (qrg == 0):
m=re.search(b'\s([0-9\.]+)MHz',info)
if m:
qrg=m.group(1)
if (qrg == 0):
m=re.search(b'\srx=([0-9]{6})\(',info)
if m:
qrg=float(m.group(1))/1000.0
if (qrg == 0):
return None
qrg=int(float(qrg)*1000.0)
m=re.search(b'(?<=Clb=)(-?[0-9.])+',info)
if m:
vs=float(m.group(0))
else:
return None
sonde_type = sonde_type_from_serial(sonde_id)
if sonde_type not in sonde_types:
return None
distance = calc_distance((lat,lon),qth)
status_expire = int(time.time() + config.getint('main','SignalTimeout') * 60)
# serial, freq, type, status, last_alt, status_expire, distance, vs
q.put((sonde_id,qrg,sonde_type,3,alt,status_expire,distance,vs))
verbose("%s: %1d %-9s %8.5f %8.5f %5dm %5.1fm/s %.3fMHz" % (source, sonde_type, sonde_id, lat, lon, alt, vs, qrg/1000.0 ))
except:
pass
def last_aprs_log_update():
try:
aprslog = config.get('aprs_cycles','AprsLog')
if os.path.isdir(aprslog):
lastupdate=0
for file in os.listdir(aprslog):
if os.path.getsize(aprslog+"/"+file) > 0:
lastupdate=max(lastupdate,os.path.getmtime(aprslog+"/"+file))
elif os.path.isfile(aprslog) and os.path.getsize(aprslog) > 0:
lastupdate=os.path.getmtime(aprslog)
else:
lastupdate=0
return int(lastupdate)
except:
return -1
def auto_channels(_landing = False):
global channels, blind_channels
if not config.has_option('auto_channels','Sensor'):
return
try:
script = config.get('auto_channels','Sensor')
if os.access(script.split()[0], os.X_OK):
data = subprocess.check_output(script.split(' '))
else:
ac_file = open(script.split()[0],'r')
data = ac_file.read(64)
ac_file.close()
m=re.search('([0-9]+)',str(data))
temp=int(m.group(1))
if temp > 1000:
temp = temp / 1000
if temp <= config.getint('auto_channels','LowTemp'):
new_channels = config.getint('auto_channels','MaxChannels')
elif temp >= config.getint('auto_channels','HighTemp'):
new_channels = config.getint('auto_channels','MinChannels')
else:
new_channels = ( config.getint('auto_channels','MaxChannels')
- ( temp - config.getint('auto_channels','LowTemp') )
/ ( ( config.getint('auto_channels','HighTemp')-float(config.getint('auto_channels','LowTemp')) )
/ ( config.getint('auto_channels','MaxChannels')-config.getint('auto_channels','MinChannels') ) ) )
if _landing:
new_channels = max(new_channels * 0.66, config.getint('auto_channels','MinChannels'))
new_channels = round(new_channels)
if new_channels != channels:
verbose("auto_channels: temp=%d'C, adjusting channels to %d" % (temp, new_channels))
channels = new_channels
set_blind_channels()
except:
pass
def vicinity_freqs(freqs):
vicinity=[]
for x in freqs:
vicinity += dbc.execute("""SELECT DISTINCT freq, type, status, ABS(freq-?) AS delta
FROM freqs
WHERE landing_mode IS NULL
AND type = ?
AND freq >= ?
AND freq <= ?
AND status > 0
AND ( status_expire IS NULL
OR status_expire >= datetime('now') )
ORDER BY status DESC, delta, random()""",(x[0],x[1],freq_range[0],freq_range[1])).fetchall()
return sorted(vicinity, key=lambda kk: kk[3])
def graceful_exit(z1,z2):
exit_script.set()
init(None,None)
signal.signal(signal.SIGUSR1,init)
for sig in ('TERM', 'INT', 'HUP'):
signal.signal(getattr(signal, 'SIG'+sig), graceful_exit);
if not args.slave:
if args.no_external_csv:
args.csv = ()
elif args.csv == None:
args.csv = default_external_urls
for url in args.csv:
t = Thread(target=thread_external_sondelist, args=(url,))
t.daemon = True
t.start()
time.sleep(0.05)
if args.aprslog:
for aprs_ip in args.aprslog:
if ':' in aprs_ip:
(ip,port) = aprs_ip.split(':')
else:
ip = aprs_ip
port = 14580
if not ip:
ip = '127.0.0.1'
t = Thread(target=thread_read_APRS, args=(ip,port))
t.daemon = True
t.start()
time.sleep(0.05)
if args.udplog:
t = Thread(target=thread_read_udpgate_log, args=(args.udplog,))
t.daemon = True
t.start()
extra_wait = False
channels = int(args.c)
set_blind_channels()
landing_freqs=set()
selected_freqs=set()
old_selected_freqs=set()
base_freq = 0
landing_lock = False
# connect / create database
try:
db = sqlite3.connect(dbfile)
except:
print("ERROR: cannot open database")
sys.exit()
finally:
dbc = db.cursor()
dbc.execute("PRAGMA journal_mode = wal")
# delete APRS flag file
try:
if config.has_option('aprs_cycles','AprsFlagFile'):
os.remove(config.get('aprs_cycles','AprsFlagFile'))
except:
pass