-
Notifications
You must be signed in to change notification settings - Fork 5
/
directTDoA.py
executable file
·2529 lines (2312 loc) · 128 KB
/
directTDoA.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
# -*- coding: utf-8 -*-
""" DirectTDoA python code. """
# python 2/3 compatibility
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import codecs
import glob
import json
import os
import re
import signal
import platform
import subprocess
from subprocess import PIPE
import sys
import threading
import time
import webbrowser
import shutil
from shutil import copyfile
import socket
from collections import OrderedDict
from datetime import datetime
import requests
from PIL import Image, ImageTk
# python 2/3 compatibility
if sys.version_info[0] == 2:
import tkFileDialog
import tkMessageBox
import ttk
from Tkinter import Checkbutton, END, CURRENT, NORMAL, Message, Scale, IntVar, Listbox
from Tkinter import Entry, Text, Menu, Label, Button, Frame, Tk, Canvas, PhotoImage
from tkColorChooser import askcolor
from tkSimpleDialog import askstring, askinteger
from tkFont import Font
else:
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
from tkinter import Checkbutton, END, CURRENT, NORMAL, Message, Scale, IntVar, Listbox
from tkinter import Entry, Text, Menu, Label, Button, Frame, Tk, Canvas, PhotoImage, ttk
from tkinter.colorchooser import askcolor
from tkinter.simpledialog import askstring, askinteger
from tkinter.font import Font
VERSION = "directTDoA v7.20"
class ReadKnownPointFile(object):
""" Read known location list routine (see directTDoA_knownpoints.db file). """
def __init__(self):
pass
@staticmethod
def run():
""" Read known location list routine (see directTDoA_knownpoints.db file). """
with open('directTDoA_knownpoints.db') as h:
global my_info1, my_info2, my_info3
i = 3 # skip the 3x comment lines at start of the text file database
lines = h.readlines()
my_info1 = []
my_info2 = []
my_info3 = []
while i < sum(1 for _ in open('directTDoA_knownpoints.db')):
inforegexp = re.search(r"(.*),(.*),(.*)", lines[i])
my_info1.append(inforegexp.group(1))
my_info2.append(inforegexp.group(2))
my_info3.append(inforegexp.group(3))
i += 1
class ReadCfg(object):
""" DirectTDoA configuration file read process. """
def __init__(self):
pass
@staticmethod
def read_cfg():
""" DirectTDoA configuration file read process. """
global CFG, DX0, DY0, DX1, DY1, DMAP, MAPFL, WHITELIST, BLACKLIST
global STDCOLOR, FAVCOLOR, BLKCOLOR, POICOLOR, ICONSIZE, ICONTYPE, HIGHLIGHT
global BGC, FGC, GRAD, THRES, CONS_B, CONS_F, STAT_B, STAT_F, MAP_BOX
global TCPHOST, TCPPORT, TCPTRIGGER, IQDURATION, PKJ, UC, TDOAVERSION, GUI
try:
# Read the config file and declare variables
with open('directTDoA.cfg', 'r') as config_file:
CFG = json.load(config_file, object_pairs_hook=OrderedDict)
DX0, DX1 = CFG["map"]["x0"], CFG["map"]["x1"]
DY0, DY1 = CFG["map"]["y0"], CFG["map"]["y1"]
DMAP, MAPFL, ICONSIZE = CFG["map"]["file"], CFG["map"]["mapfl"], CFG["map"]["iconsize"]
STDCOLOR, FAVCOLOR, BLKCOLOR = CFG["map"]["std"], CFG["map"]["fav"], CFG["map"]["blk"]
POICOLOR, ICONTYPE = CFG["map"]["poi"], CFG["map"]["icontype"]
WHITELIST, BLACKLIST = CFG["nodes"]["whitelist"], CFG["nodes"]["blacklist"]
HIGHLIGHT = CFG["map"]["hlt"]
BGC, FGC, GRAD = CFG["guicolors"]["main_b"], CFG["guicolors"]["main_f"], CFG["guicolors"]["grad"]
CONS_B, CONS_F = CFG["guicolors"]["cons_b"], CFG["guicolors"]["cons_f"]
STAT_B, STAT_F = CFG["guicolors"]["stat_b"], CFG["guicolors"]["stat_f"]
THRES, MAP_BOX = CFG["guicolors"]["thres"], CFG["map"]["mapbox"]
TCPHOST, TCPPORT, IQDURATION = CFG["tcp"]["host"], CFG["tcp"]["port"], CFG["tcp"]["duration"]
try:
TCPTRIGGER = CFG["tcp"]["word"]
except KeyError:
SaveCfg().save_cfg("tcp", "word", "")
TCPTRIGGER = CFG["tcp"]["word"]
try:
GUI = CFG["map"]["gui"]
except KeyError:
SaveCfg().save_cfg("map", "gui", "1200x700+150+10")
GUI = CFG["map"]["gui"]
PKJ, UC, TDOAVERSION = CFG["iq"]["pkj"], CFG["iq"]["uc"], CFG["iq"]["mode"]
except (ImportError, ValueError):
# If config file is not valid json
tkMessageBox.showinfo(title=" ¯\\_(ツ)_/¯", message="config file syntax error !")
sys.exit()
except OSError:
# If config file is not found
tkMessageBox.showinfo(title=" ¯\\_(ツ)_/¯", message="config file not found !")
sys.exit()
class SaveCfg(object):
""" DirectTDoA configuration file save process. """
def __init__(self):
pass
@staticmethod
def save_cfg(cat, field, field_value):
""" Save config routine. """
# Sets the new parameter value to the right category
CFG[cat][field] = field_value
# Now save the config file
with open('directTDoA.cfg', 'w') as config_file:
json.dump(CFG, config_file, indent=2)
class CheckUpdate(threading.Thread):
""" Check if the source is up before running the RunUpdate process. """
def __init__(self):
super(CheckUpdate, self).__init__()
def run(self):
APP.gui.writelog("Checking if http://kiwisdr.com/public is up ...")
try:
requests.get("http://kiwisdr.com/public", timeout=2)
APP.gui.writelog("Ok looks good, KiwiSDR node listing update started ...")
RunUpdate().run()
except requests.ConnectionError:
APP.gui.writelog("http://kiwisdr.com/public is not reachable. try again later.")
APP.gui.start_rec_button.configure(state="normal")
APP.gui.start_tdoa_button.configure(state="normal")
APP.gui.update_button.configure(state="normal")
APP.gui.purge_button.configure(state="normal")
class RunUpdate(threading.Thread):
""" Update map process. """
def __init__(self, parent=None):
super(RunUpdate, self).__init__()
self.parent = parent
def run(self):
try:
out = []
tdoa_id_list = []
# Get data from website source
req = requests.get("http://kiwisdr.com/public/")
# Get kiwisdr listing from kiwisdr.com/public and convert to JSON
for html in req.text.split("<div class='cl-entry'>")[1:]:
rx = {}
for m in re.finditer("<!-- (id|fixes_min|tdoa_id|gps|name|snr)=(.*) -->", html):
rx[m.group(1)] = m.group(2)
for n in re.finditer("<a href='(http|https)://(.*)' .+<br>", html):
rx['url'] = n.group(2).strip()
if rx["fixes_min"] > "20":
out.append(rx)
json_kiwisdr = json.dumps(out, ensure_ascii=False)
json_data = json.loads(json_kiwisdr)
# Analyse the kiwisdr.com/public JSON and create directTDoA db file
with codecs.open('directTDoA_server_list.tmp', 'wb', encoding='utf8') as db_file:
db_file.write("[\n")
# line by line
for i in range(len(json_data)):
# Add progress bar in the console window (* char for each node)
APP.gui.console_window.insert('end -1 lines', "*")
APP.gui.console_window.see('end')
time.sleep(0.001)
# Check if the "tdoa_id" field of the node has not been filled by the admin
if not json_data[i]['tdoa_id']:
try:
# Convert GPS data to maidenhead QRA locator, becomes the default tdoa_id
gps_data = re.search(r'([-+]?[0-9]{1,2}(\.[0-9]*)?)(,|\s) 'r'?([-+]?[0-9]{1,3}(\.[0-9]*))?',
json_data[i]['gps'][1:-1])
tdoa_id = self.to_grid(float(gps_data.group(1)), float(gps_data.group(4)))
except Exception as error:
print(error)
try:
# Try to get a Ham callsign from the name field, if success becomes the tdoa_id
hamcallfield = re.search(r"([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]{1,3})(\s|,|/|@|-)",
json_data[i]['name'])
tdoa_id = hamcallfield.group(1).upper()
except (IndexError, AttributeError):
pass
else:
tdoa_id = json_data[i]['tdoa_id']
# TDoA code is not supporting tdoa_id starting with a digit, so insert letter h at start
if tdoa_id[:1].isdigit():
tdoa_id = "h" + tdoa_id
# If tdoa_id already existing in the db, add a "/" + last digit from the port number
if tdoa_id in tdoa_id_list:
tdoa_id = tdoa_id + "/" + str(json_data[i]['url'][-1:])
tdoa_id_list.append(tdoa_id)
# Parse the geographical coordinates to get lat & lon values
try:
gpsfield = re.search(r'([-+]?[0-9]{1,2}(\.[0-9]*)?)(,|\s) 'r'?([-+]?[0-9]{1,3}(\.[0-9]*))?',
json_data[i]['gps'][1:-1])
nodelat = gpsfield.group(1)
nodelon = gpsfield.group(4)
except Exception as gps_field_error:
# For admins not respecting GPS field format (nn.nnnnnn, nn.nnnnnn)
# => nodes will be shown at 0 LAT 0 LON
print("*** Error reading <gps> field : " + str(gps_field_error))
nodelat = nodelon = "0"
# Get the SNR score: [0] is 0-30 MHz [1] is 1.8-30 MHz - default to 15 if not available
try:
snr_search = json_data[i]['snr'].rsplit(",")[1]
except KeyError:
snr_search = "15"
# Build directTDoA db by writing a dict to the .tmp file
nodeinfo = dict(mac=json_data[i]['id'], url=json_data[i]['url'], id=tdoa_id, lat=nodelat,
lon=nodelon,
snr=snr_search)
# Order the line before writing it (necessary for rest of the code)
ordered_dict = ['mac', 'url', 'id', 'snr', 'lat', 'lon']
nodelist = [(key, nodeinfo[key]) for key in ordered_dict]
nodeinfo = OrderedDict(nodelist)
json_db = json.dumps(nodeinfo, ensure_ascii=False)
db_file.write(json_db + ",\n")
db_file.seek(-2, os.SEEK_END)
db_file.truncate()
db_file.write("\n]")
db_file.close()
# Now look at db differences between before & after update process
old_kiwi_data = json.load(open('directTDoA_server_list.db', 'r'))
new_kiwi_data = json.load(open('directTDoA_server_list.tmp', 'r'))
new_node = []
for new in new_kiwi_data:
new_entry = dict(new)
new_in_old = next((old for old in old_kiwi_data if new["mac"] == old["mac"]), None)
if not new_in_old:
new_node.append(new_entry)
old_node = []
for old in old_kiwi_data:
old_entry = dict(old)
old_in_new = next((new for new in new_kiwi_data if old["mac"] == new["mac"]), None)
if not old_in_new:
old_node.append(old_entry)
gain = []
for x in range(len(new_node)):
gain.append(new_node[x]["id"])
loss = []
for y in range(len(old_node)):
loss.append(old_node[y]["id"])
# If there are differences between before and after update
if len(gain) != 0 and len(loss) != 0:
# python3 > display a YES/NO tkMessageBox window
if sys.version_info[0] == 3:
update_question = tkMessageBox.askquestion('Update ?', "added node(s): " + str(
" ".join(gain)) + "\n\nremoved node(s): " + str(" ".join(loss)) + "\n\nNew db size: " + str(
len(new_kiwi_data)) + "\nOld db size: " + str(len(old_kiwi_data)), icon='warning')
if update_question == 'yes':
APP.gui.writelog("The KiwiSDR listing update has been accepted.")
copyfile("directTDoA_server_list.tmp", "directTDoA_server_list.db")
else:
APP.gui.writelog("The KiwiSDR listing update has been aborted.")
# python2 > finish the process considering a YES answer but log infos
elif sys.version_info[0] == 2:
copyfile("directTDoA_server_list.tmp", "directTDoA_server_list.db")
else:
APP.gui.writelog("No recent change reported between db sizes.")
APP.gui.console_window.delete('end -1c linestart', END)
APP.gui.console_window.insert('end', '\n')
except Exception as update_error:
APP.gui.writelog("UPDATE FAIL - ERROR : " + str(update_error))
APP.gui.redraw()
APP.gui.update_button.configure(state="normal")
APP.gui.start_rec_button.configure(state="normal")
APP.gui.start_tdoa_button.configure(state="normal")
APP.gui.purge_button.configure(state="normal")
os.remove("directTDoA_server_list.tmp")
@staticmethod
def to_grid(dec_lat, dec_lon):
""" convert decimal lat/lon to maidenhead grid
source: Walter Underwood K6WRU @ ham.stackexchange.com """
upper = 'ABCDEFGHIJKLMNOPQRSTUVWX'
lower = 'abcdefghijklmnopqrstuvwx'
if not (-180 <= dec_lon < 180):
sys.stderr.write('longitude must be -180<=lon<180, given %f\n' % dec_lon)
sys.exit(32)
if not (-90 <= dec_lat < 90):
sys.stderr.write('latitude must be -90<=lat<90, given %f\n' % dec_lat)
sys.exit(33) # can't handle north pole, sorry, [A-R]
adj_lat = dec_lat + 90.0
adj_lon = dec_lon + 180.0
grid_lat_sq = upper[int(adj_lat / 10)]
grid_lon_sq = upper[int(adj_lon / 20)]
grid_lat_field = str(int(adj_lat % 10))
grid_lon_field = str(int((adj_lon / 2) % 10))
adj_lat_remainder = (adj_lat - int(adj_lat)) * 60
adj_lon_remainder = (adj_lon - int(adj_lon / 2) * 2) * 60
grid_lat_subsq = lower[int(adj_lat_remainder / 2.5)]
grid_lon_subsq = lower[int(adj_lon_remainder / 5)]
return grid_lon_sq + grid_lat_sq + grid_lon_field + grid_lat_field + grid_lon_subsq + grid_lat_subsq
class StartRecording(threading.Thread):
""" Recording IQ process. """
def __init__(self, parent=None):
super(StartRecording, self).__init__()
self.parent = parent
def run(self):
global PROC2_PID
CheckFileSize().start()
which_list = fulllist
which_action = "IQ Recordings in progress..."
client_type = VERSION
if (ultimate.get()) == 1:
which_action = "ultimateTDoA IQ Recordings in progress..."
proc2 = subprocess.Popen([sys.executable, 'kiwiclient' + os.sep + 'kiwirecorder.py', '-s',
','.join(str(p).rsplit('$')[0] for p in which_list), '-p',
','.join(str(p).rsplit('$')[1] for p in which_list),
'--station=' + ','.join(str(p).rsplit('$')[3] for p in which_list), '-f',
str(FREQUENCY), '-L', str(lpcut), '-H', str(hpcut), '-m', 'iq', '--tlimit', '120',
'-u', client_type.replace(' ', '_'), '-w', '-d', os.path.join('TDoA', 'iq')],
stdout=PIPE, shell=False)
self.parent.writelog(which_action)
PROC2_PID = proc2.pid
class CheckFileSize(threading.Thread):
""" The process monitoring all iq/*.wav files size. """
def __init__(self):
super(CheckFileSize, self).__init__()
def run(self):
APP.gui.purge_button.configure(state="disabled")
APP.gui.update_button.configure(state="disabled")
wav_container = []
rec_time = -1
while True:
for wavfiles in glob.glob(os.path.join('TDoA', 'iq') + os.sep + "*.wav"):
if wavfiles not in wav_container:
wav_container.append(wavfiles)
try:
APP.gui.status_window.insert('end -1 lines',
wavfiles.rsplit(os.sep, 1)[1].rsplit("_", 3)[2] + "|" + str(
os.path.getsize(wavfiles) // 1024) + "KB ")
except OSError:
APP.gui.status_window.insert('end -1 lines', "\n")
APP.gui.status_window.insert("end", "\n[" + str(len(wav_container)) + '/' + str(len(fulllist)) + "] ~" + str(rec_time) + "s")
APP.gui.status_window.see('end')
time.sleep(0.5)
rec_time += 0.5
APP.gui.status_window.delete("0.0", END)
if rec_in_progress == 0:
APP.gui.purge_button.configure(state="normal")
APP.gui.update_button.configure(state="normal")
break
class PlotIQ(threading.Thread):
""" plot_iq.py processing routine """
def __init__(self):
super(PlotIQ, self).__init__()
def run(self):
run_dir = os.path.join('TDoA', 'iq') + os.sep + starttime + tdoa_mode + str(FREQUENCY) + os.sep
with open(os.devnull, 'w') as fp:
subprocess.call([sys.executable, 'plot_iq.py'], cwd=os.path.join(run_dir), shell=False, stdout=fp)
class ComputeUltimate(threading.Thread):
""" compute_ultimate.py processing routine """
def __init__(self):
super(ComputeUltimate, self).__init__()
def run(self):
run_dir = os.path.join('TDoA', 'iq') + os.sep + starttime + tdoa_mode + str(FREQUENCY)
with open(os.devnull, 'w') as fp:
subprocess.call([sys.executable, 'compute_ultimate.py'], cwd=os.path.join(run_dir), shell=False, stdout=fp)
class OctaveProcessing(threading.Thread):
""" Octave processing routine """
def __init__(self):
super(OctaveProcessing, self).__init__()
def run(self):
global tdoa_position, PROC_PID # stdout
octave_errors = [b'index-out-of-bounds', b'< 2 good stations found', b'Octave:nonconformant - args',
b'n_stn=2 is not supported', b'resample.m: p and q must be positive integers',
b'Octave:invalid-index', b'incomplete \'data\' chunk',
b'reshape: can\'t reshape 0x0 array to 242x258 array', b'malformed filename:']
tdoa_filename = "proc_tdoa_" + HZ_FREQ + ".m"
proc = subprocess.Popen(['octave-cli', tdoa_filename], cwd=os.path.join('TDoA'), stderr=subprocess.STDOUT,
stdout=subprocess.PIPE, shell=False)
PROC_PID = proc.pid
logfile = open(os.path.join('TDoA', 'iq') + os.sep + starttime + tdoa_mode + str(
FREQUENCY) + os.sep + "TDoA_" + HZ_FREQ + "_log.txt", 'w')
if sys.version_info[0] == 2:
for octave_output in proc.stdout:
logfile.write(octave_output)
if "most likely position:" in octave_output:
tdoa_position = octave_output
if "exluding" in octave_output:
APP.gui.status_window.insert('end -1 lines', octave_output)
APP.gui.status_window.see('end')
if any(x in octave_output for x in octave_errors):
ProcessFailed(octave_output).start()
proc.terminate()
if "finished" in octave_output:
logfile.close()
ProcessFinished().start()
proc.terminate()
else:
octave_output = proc.communicate()[0]
logfile.write(str(octave_output, 'utf-8'))
if b"most likely position:" in octave_output:
tdoa_position = octave_output
if b"exluding" in octave_output:
APP.gui.status_window.insert('end -1 lines', octave_output)
APP.gui.status_window.see('end')
if any(x in octave_output for x in octave_errors):
ProcessFailed(octave_output).start()
proc.terminate()
if b"finished" in octave_output:
logfile.close()
ProcessFinished().start()
proc.terminate()
proc.wait()
class ProcessFailed(threading.Thread):
""" The actions to perform when a TDoA run has failed. """
def __init__(self, returned_error):
super(ProcessFailed, self).__init__()
self.Returned_error = returned_error
def run(self):
global tdoa_in_progress # TDoA process status
r_dir = os.path.join('TDoA', 'iq') + os.sep + starttime + tdoa_mode + str(FREQUENCY) + os.sep
if platform.system() == "Windows":
webbrowser.open(r_dir)
elif platform.system() == "Darwin":
subprocess.Popen(["open", r_dir])
else:
subprocess.Popen(["xdg-open", r_dir])
APP.gui.start_rec_button.configure(state="normal", text="Start recording")
APP.gui.start_tdoa_button.configure(state="disabled")
APP.gui.update_button.configure(state="normal")
APP.gui.purge_button.configure(state="normal")
for wavfiles in glob.glob(os.path.join('TDoA', 'iq') + os.sep + "*.wav"):
os.remove(wavfiles)
tdoa_in_progress = 0
APP.gui.status_window.insert('end -1 lines', self.Returned_error)
APP.gui.status_window.insert('end -1 lines', "Octave Process Failed. Retry")
APP.gui.status_window.see('end')
# subprocess.call(["xdg-open", 'TDoA_' + str(FREQUENCY) + '_log.txt'])
class ProcessFinished(threading.Thread):
""" The actions to perform when a TDoA run has finished. """
def __init__(self):
super(ProcessFinished, self).__init__()
def run(self):
global tdoa_in_progress # TDoA process status
r_dir = os.path.join('TDoA', 'iq') + os.sep + starttime + tdoa_mode + str(FREQUENCY) + os.sep
if auto_run_tdoa.get() == 0:
if platform.system() == "Windows":
webbrowser.open(r_dir)
elif platform.system() == "Darwin":
subprocess.Popen(["open", r_dir])
else:
subprocess.Popen(["xdg-open", r_dir])
APP.gui.start_rec_button.configure(state="normal", text="Start recording")
APP.gui.start_tdoa_button.configure(state="disabled")
APP.gui.update_button.configure(state="normal")
APP.gui.purge_button.configure(state="normal")
for wavfiles in glob.glob(os.path.join('TDoA', 'iq') + os.sep + "*.wav"):
os.remove(wavfiles)
# for pdffiles in glob.glob(os.path.join('TDoA', 'pdf') + os.sep + "*.pdf"):
# os.remove(pdffiles)
for mfiles in glob.glob(os.path.join('TDoA') + os.sep + "proc*.m"):
if mfiles != "TDoA/proc_tdoa_kiwi.m":
os.remove(mfiles)
tdoa_in_progress = 0
with open(r_dir + "proc_tdoa_" + HZ_FREQ + ".m", 'r') as read_file:
content = read_file.readlines()
with open(r_dir + "proc_tdoa_" + HZ_FREQ + ".m", 'w') as write_file:
for line in content:
write_file.write(line.replace("initial", "recomputed"))
APP.gui.writelog("TDoA process finished successfully.")
class CheckSnr(threading.Thread):
""" SNR check process. """
def __init__(self, serverport):
threading.Thread.__init__(self)
self.s_host = serverport.rsplit(":")[0]
self.s_port = serverport.rsplit(":")[1]
def run(self):
""" SNR check process. """
try:
socket2_connect = subprocess.Popen(
[sys.executable, 'kiwiclient' + os.sep + 'microkiwi_waterfall.py', '-s', self.s_host, '-p',
self.s_port], stdout=PIPE, shell=False)
APP.gui.writelog("Retrieving " + self.s_host + " waterfall, please wait")
while True:
snr_output = socket2_connect.stdout.readline()
# if b"received sample" in snr_output:
# APP.gui.console_window.insert('end -1c', '.')
if b"SNR" in snr_output:
APP.gui.console_window.delete('end -1c linestart', END)
APP.gui.console_window.insert('end', '\n')
APP.gui.writelog(snr_output.decode().replace("\n", ""))
break
except ValueError:
print ("Error: unable to retrieve datas from this node")
class StartDemodulation(threading.Thread):
""" Demodulation process. """
def __init__(self, server, port, frequency, modulation):
threading.Thread.__init__(self)
self.s_host = server
self.s_port = port
self.s_freq = frequency
self.s_mod = modulation
def run(self):
global LISTENMODE, kiwisdrclient_pid
if self.s_mod == "USB":
low_cut = "0"
hi_cut = "3600"
elif self.s_mod == "LSB":
low_cut = "-3600"
hi_cut = "0"
elif self.s_mod == "CW":
low_cut = "-500"
hi_cut = "500"
self.s_freq = str(float(self.s_freq) - 0.5)
elif self.s_mod == "AM":
low_cut = "-5000"
hi_cut = "5000"
else:
self.s_mod = "USB"
low_cut = "300"
hi_cut = "3300"
try:
client_type = VERSION
proc8 = subprocess.Popen(
[sys.executable, 'kiwiclient' + os.sep + 'kiwirecorder.py', '-s', self.s_host, '-p', self.s_port, '-f',
self.s_freq, '-m', self.s_mod, '-L', low_cut, '-H', hi_cut, '-u', client_type.replace(' ', '_'), '-q',
'-a'], stdout=PIPE, shell=False)
kiwisdrclient_pid = proc8.pid
LISTENMODE = "1"
APP.gui.writelog(
"Starting Listen mode [ " + self.s_host + " / " + self.s_freq + " kHz / " + self.s_mod.upper() + " ] - to stop: use same command from any node popup menu.")
except Exception as demodulation_Error:
print ("Unable to demodulate this node - Error: " + str(demodulation_Error))
LISTENMODE = "0"
class FillMapWithNodes(object):
""" process to display the nodes on the World Map. """
def __init__(self, parent):
self.parent = parent
def run(self):
""" DirectTDoA process to display the nodes on the World Map. """
global NODE_COUNT, NODE_COUNT_FILTER, tag_list
tag_list = []
NODE_COUNT = 0
NODE_COUNT_FILTER = 0
server_lists = ["directTDoA_server_list.db", "directTDoA_static_server_list.db"]
for server_list in server_lists:
with open(server_list) as node_db:
db_data = json.load(node_db)
for node_index in range(len(db_data)):
NODE_COUNT += 1
# Change icon color of fav, black and standards nodes and apply a gradient // SNR
perc = (int(db_data[node_index]["snr"]) - 40) * GRAD
if db_data[node_index]["mac"] in WHITELIST:
node_color = (self.color_variant(FAVCOLOR, perc))
elif db_data[node_index]["mac"] in BLACKLIST:
node_color = (self.color_variant(BLKCOLOR, perc))
else:
node_color = (self.color_variant(STDCOLOR, perc))
# Apply the map filtering
if MAPFL == 1 and db_data[node_index]["mac"] not in BLACKLIST:
NODE_COUNT_FILTER += 1
self.add_point(node_index, node_color, db_data)
elif MAPFL == 2 and db_data[node_index]["mac"] in WHITELIST:
NODE_COUNT_FILTER += 1
self.add_point(node_index, node_color, db_data)
elif MAPFL == 3 and db_data[node_index]["mac"] in BLACKLIST:
NODE_COUNT_FILTER += 1
self.add_point(node_index, node_color, db_data)
elif MAPFL == 0:
NODE_COUNT_FILTER += 1
self.add_point(node_index, node_color, db_data)
if 'APP' in globals():
APP.gui.label04.configure(text="Visible: " + str(NODE_COUNT_FILTER) + "/" + str(NODE_COUNT))
self.parent.show_image()
@staticmethod
def convert_lat(lat):
""" Convert the real node latitude coordinates to adapt to GUI window map geometry. """
# nodes are between LATITUDE 0 and 90N
if float(lat) > 0:
return 990 - (float(lat) * 11)
# nodes are between LATITUDE 0 and 60S
return 990 + (float(0 - float(lat)) * 11)
@staticmethod
def convert_lon(lon):
""" Convert the real node longitude coordinates to adapt to GUI window map geometry. """
return 1910 + ((float(lon) * 1910) / 180)
@staticmethod
def color_variant(hex_color, brightness_offset=1):
""" Process that changes the brightness (only) of a specific RGB color.
chase-seibert.github.io/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html """
rgb_hex = [hex_color[x:x + 2] for x in [1, 3, 5]]
new_rgb_int = [int(hex_value, 16) + brightness_offset for hex_value in rgb_hex]
new_rgb_int = [min([255, max([0, i])]) for i in new_rgb_int]
return "#" + "".join(["0" + hex(i)[2:] if len(hex(i)[2:]) < 2 else hex(i)[2:] for i in new_rgb_int])
def add_point(self, node_index_data, node_color, node_db_data):
""" Process that add node icons over the World map. """
global tag_list
mykeys = ['mac', 'url', 'id', 'snr', 'lat', 'lon']
node_lat = self.convert_lat(node_db_data[node_index_data]["lat"])
node_lon = self.convert_lon(node_db_data[node_index_data]["lon"])
if not any(node_db_data[node_index_data]["mac"] in s for s in tag_list):
node_tag = str('$'.join([node_db_data[node_index_data][x] for x in mykeys]))
ic_size = int(ICONSIZE)
try:
if ICONTYPE == 0:
self.parent.canvas.create_oval(node_lon - ic_size, node_lat - ic_size, node_lon + ic_size,
node_lat + ic_size, fill=node_color, tag=node_tag)
else:
self.parent.canvas.create_rectangle(node_lon - ic_size, node_lat - ic_size, node_lon + ic_size,
node_lat + ic_size, fill=node_color, tag=node_tag)
self.parent.canvas.tag_bind(node_tag, "<Button-1>", self.parent.onclickleft)
tag_list.append(node_tag)
except NameError:
print ("OOPS - Error in adding the point to the map")
def delete_point(self, map_definition):
""" Map presets deletion process. """
self.parent.canvas.delete(map_definition)
def redraw_map(self):
""" Redraw all icons on the World Map. """
for node_tag_item in tag_list:
self.parent.canvas.delete(node_tag_item)
ReadCfg().read_cfg()
FillMapWithNodes.run(self)
def node_sel_active(self, node_mac):
""" Adding additionnal highlight on node icon. """
for node_tag_item in tag_list:
if node_mac in node_tag_item:
tmp_latlon = node_tag_item.rsplit("$", 6)
tmp_lat = self.convert_lat(tmp_latlon[4])
tmp_lon = self.convert_lon(tmp_latlon[5])
is_delta = int(ICONSIZE) + 1
if ICONTYPE == 0:
self.parent.canvas.create_oval(tmp_lon - is_delta, tmp_lat - is_delta, tmp_lon + is_delta,
tmp_lat + is_delta, fill='', outline=HIGHLIGHT,
tag=node_tag_item + "$#")
else:
self.parent.canvas.create_rectangle(tmp_lon - is_delta, tmp_lat - is_delta, tmp_lon + is_delta,
tmp_lat + is_delta, fill='', outline=HIGHLIGHT,
tag=node_tag_item + "$#")
self.parent.canvas.tag_bind(node_tag_item + "$#", "<Button-1>", self.parent.onclickleft)
def node_selection_inactive(self, node_mac):
""" Removing additionnal highlight on selected node icon. """
for node_tag_item in tag_list:
if node_mac in node_tag_item:
self.parent.canvas.tag_unbind(node_tag_item + "$#", "<Button-1>")
self.parent.canvas.delete(node_tag_item + "$#")
def node_selection_inactiveall(self):
""" Removing ALL additionnal highlights on selected nodes icons. """
for node_tag_item in tag_list:
self.parent.canvas.tag_unbind(node_tag_item + "$#", "<Button-1>")
self.parent.canvas.delete(node_tag_item + "$#")
def after_update(self):
ReadCfg().read_cfg()
FillMapWithNodes.run(self)
class TcpClient(threading.Thread):
def __init__(self, trigger):
threading.Thread.__init__(self)
self.trigger = trigger
def run(self):
global TCPHOST, TCPPORT, IQDURATION
try:
s = socket.socket()
s.settimeout(1.0)
s.connect((TCPHOST, TCPPORT))
s.setblocking(False)
APP.gui.writelog("TCP client connected to " + TCPHOST + ":" + str(TCPPORT) + " | trigger word : " + str(
TCPTRIGGER) + " | duration : " + str(IQDURATION) + "s")
if self.trigger == "":
APP.gui.writelog(
"Warning, with blank trigger word the recording will start on any event appearing on TCP server side and the recordings will follow each other in a loop if TCP data flow is continuous")
except (socket.error, socket.gaierror, socket.timeout) as e:
APP.gui.writelog("TCP client connection to " + TCPHOST + ":" + str(TCPPORT) + " failed - " + str(e))
tcpclient.set(0)
return
data = b""
while True:
if not tcpclient.get():
APP.gui.writelog("TCP client disconnected from " + TCPHOST + ":" + str(TCPPORT))
break
try:
data += s.recv(2048)
except:
pass
if not rec_in_progress and data and (not self.trigger or re.search(self.trigger, data.decode('utf-8'))):
start_time = time.time()
APP.gui.writelog("### TCP data received ###")
APP.gui.start_stop_rec()
if rec_in_progress and time.time() - start_time >= IQDURATION:
try:
if "[NORMAL MODE]" in data.decode('utf-8'):
PrintALE(data, reset=0).start()
except UnicodeDecodeError:
PrintALE(data, reset=1).start()
data = b""
APP.gui.start_stop_rec()
if auto_run_tdoa.get() == 1:
APP.gui.start_stop_tdoa()
time.sleep(0.001)
class PrintALE(threading.Thread):
""" 2G ALE WORDS management. """
def __init__(self, data, reset):
threading.Thread.__init__(self)
self.ale_data = data
self.reset = reset
def run(self):
""" Get 2G ALE words or reset the buffer in case of other decoded digimodes. """
global ale_file_name, ale_file_data
if self.reset == 1:
ale_file_data = ""
else:
to_addr = tis_addr = tws_addr = ""
ale_file_name = "ALE [partial decode].txt"
ale_file_data = self.ale_data
for addr in re.findall(r'\[TO\]\[(.*?)\]', self.ale_data.decode('utf-8')):
if len(addr) > len(to_addr):
to_addr = addr
for addr in re.findall(r'\[TIS\]\[(.*?)\]', self.ale_data.decode('utf-8')):
if len(addr) > len(tis_addr):
tis_addr = addr
for addr in re.findall(r'\[TWS\]\[(.*?)\]', self.ale_data.decode('utf-8')):
if len(addr) > len(tws_addr):
tws_addr = addr
if to_addr and tis_addr and not tws_addr:
APP.gui.writelog(" ### ALE CALL ### [TO]" + to_addr + " [TIS]" + tis_addr)
ale_file_name = "ALE CALL [TO]" + to_addr + " [TIS]" + tis_addr + ".txt"
return
if to_addr and tws_addr and not tis_addr:
APP.gui.writelog(" ### ALE CLOSING ### [TO]" + to_addr + " [TWS]" + tws_addr)
ale_file_name = "ALE CLOSE [TO]" + to_addr + " [TWS]" + tws_addr + ".txt"
return
if tws_addr and not to_addr and not tis_addr:
APP.gui.writelog(" ### ALE SOUNDING ### [TWS]" + tws_addr)
ale_file_name = "ALE SOUNDING [TWS]" + tws_addr + ".txt"
class GuiCanvas(Frame):
""" Process that creates the GUI map canvas, enabling move & zoom on a picture.
source: stackoverflow.com/questions/41656176/tkinter-canvas-zoom-move-pan?noredirect=1&lq=1 """
def __init__(self, parent):
Frame.__init__(self, parent=None)
# tip: GuiCanvas is member1
parent.call('wm', 'iconphoto', parent, PhotoImage(file='icon.gif'))
global fulllist, LISTENMODE, mapboundaries_set
fulllist = []
LISTENMODE = "0"
mapboundaries_set = None
ReadCfg().read_cfg()
parent.geometry(GUI)
self.x = self.y = 0
# Create canvas and put image on it
self.canvas = Canvas(self.master, highlightthickness=0)
self.canvas.grid(row=0, column=0, sticky='nswe')
self.canvas.update() # wait till canvas is created
# Make the canvas expandable
self.master.rowconfigure(0, weight=1)
self.master.columnconfigure(0, weight=1)
# Bind events to the Canvas
self.canvas.bind('<Configure>', self.show_image) # canvas is resized
self.canvas.bind('<ButtonPress-1>', self.move_from) # map move
self.canvas.bind('<B1-Motion>', self.move_to) # map move
# self.canvas.bind_all('<MouseWheel>', self.wheel) # Windows Zoom
# self.canvas.bind('<Button-5>', self.wheel) # Linux Zoom
# self.canvas.bind('<Button-4>', self.wheel) # Linux Zoom
self.canvas.bind("<ButtonPress-3>", self.on_button_press) # red rectangle selection
self.canvas.bind("<B3-Motion>", self.on_move_press) # red rectangle selection
self.canvas.bind("<ButtonRelease-3>", self.on_button_release) # red rectangle selection
self.image = Image.open(DMAP)
self.width, self.height = self.image.size
self.imscale = 1.0 # scale for the image
self.delta = 2.0 # zoom magnitude
# Put image into container rectangle and use it to set proper coordinates to the image
self.container = self.canvas.create_rectangle(0, 0, self.width, self.height, width=0)
self.canvas.config(scrollregion=(0, 0, self.width, self.height))
self.rect = None
self.start_x = None
self.start_y = None
self.canvas.scan_dragto(-int(DX0.split('.')[0]), -int(DY0.split('.')[0]), gain=1)
self.show_image()
time.sleep(0.2)
FillMapWithNodes(self).run()
def on_button_press(self, event):
""" Red rectangle selection drawing on the World map. """
global map_preset # map_manual
if image_scale == 1:
if map_preset == 1:
self.delete_point("mappreset")
self.rect = None
map_preset = 0
self.start_x = self.canvas.canvasx(event.x)
self.start_y = self.canvas.canvasy(event.y)
# create rectangle if not yet exist
if not self.rect:
self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, outline='red', tag="mapmanual")
else:
APP.gui.writelog("ERROR : The boundaries selection is forbidden unless map un-zoomed.")
def on_move_press(self, event):
""" Get the Map boundaries red rectangle selection coordinates. """
global lat_min_map, lat_max_map, lon_min_map, lon_max_map
if image_scale == 1:
if map_preset == 1:
pass
else:
cur_x = self.canvas.canvasx(event.x)
cur_y = self.canvas.canvasy(event.y)
lonmin = round(((self.start_x - 1910) * 180) / 1910, 1)
lonmax = round(((cur_x - 1910) * 180) / 1910, 1)
latmax = round(0 - ((cur_y - 990) / 11), 1)
latmin = round((self.start_y - 990) / 11, 1)
if cur_x > self.start_x and cur_y > self.start_y:
lat_max_map = 0 - latmin
lat_min_map = latmax
lon_max_map = lonmax
lon_min_map = lonmin
if cur_x < self.start_x and cur_y > self.start_y:
lat_max_map = 0 - latmin
lat_min_map = latmax
lon_max_map = lonmin
lon_min_map = lonmax
if cur_x > self.start_x and cur_y < self.start_y:
lat_max_map = latmax
lat_min_map = 0 - latmin
lon_max_map = lonmax
lon_min_map = lonmin
if cur_x < self.start_x and cur_y < self.start_y:
lat_max_map = latmax
lat_min_map = 0 - latmin
lon_max_map = lonmin
lon_min_map = lonmax
w_canva, h_canva = self.canvas.winfo_width(), self.canvas.winfo_height()
if event.x > 0.98 * w_canva:
self.canvas.xview_scroll(1, 'units')
elif event.x < 0.02 * w_canva:
self.canvas.xview_scroll(-1, 'units')
if event.y > 0.98 * h_canva:
self.canvas.yview_scroll(1, 'units')
elif event.y < 0.02 * h_canva:
self.canvas.yview_scroll(-1, 'units')
self.canvas.coords(self.rect, self.start_x, self.start_y, cur_x, cur_y)
self.show_image()
else:
pass
def on_button_release(self, event):
""" When Mouse right button is released (map boundaries set or ultimateTDoA set). """
global mapboundaries_set, map_preset # lon_min_map, lon_max_map, lat_min_map, lat_max_map
global map_manual, fulllist, LISTENMODE
if LISTENMODE == "1":
return
if (ultimate.get()) == 1: # ultimateTDoA mode
APP.gui.purgenode()
mapboundaries_set = 1
map_manual = 1
server_lists = ["directTDoA_server_list.db", "directTDoA_static_server_list.db"]
for server_list in server_lists:
with open(server_list) as node_db2:
db_data2 = json.load(node_db2)
nodecount2 = len(db_data2)
for y in range(nodecount2):
FillMapWithNodes(self).node_selection_inactive(node_mac=db_data2[y]["mac"])
if (lat_min_map < float(db_data2[y]["lat"]) < lat_max_map) and (
lon_min_map < float(db_data2[y]["lon"]) < lon_max_map):
if ultimatefav.get() == 1 and db_data2[y]["mac"] in WHITELIST:
fulllist.append(
db_data2[y]["url"].rsplit(':')[0] + "$" + db_data2[y]["url"].rsplit(':')[1] + "$" +
db_data2[y]["mac"] + "$" + db_data2[y]["id"].replace("/", ""))
FillMapWithNodes(self).node_sel_active(node_mac=db_data2[y]["mac"])
else:
if ultimatefav.get() == 0 and db_data2[y]["mac"] not in BLACKLIST:
fulllist.append(
db_data2[y]["url"].rsplit(':')[0] + "$" + db_data2[y]["url"].rsplit(':')[
1] + "$" + db_data2[y]["mac"] + "$" + db_data2[y]["id"].replace("/", ""))
FillMapWithNodes(self).node_sel_active(node_mac=db_data2[y]["mac"])
if fulllist:
APP.gui.writelog(str(len(fulllist)) + " KiwiSDR(s) found within this area.")
APP.title(VERSION + " - ultimateTDoA nodes [" + str(len(fulllist)) + "] : " + '/'.join(
str(p).rsplit('$')[3] for p in fulllist))
else:
APP.gui.writelog("No KiwiSDR found within this area.")
APP.title(VERSION)
fulllist = []
else:
if map_preset == 1 and map_manual == 0:
pass
else:
mapboundaries_set = 1
map_manual = 1
if len(fulllist) >= 3 and APP.gui.freq_input.get() != "" and 5 < float(
APP.gui.freq_input.get()) < 30000:
APP.gui.tcpclient_checkbox.configure(state="normal")
if (ultimate.get()) == 0:
APP.gui.autorun_checkbox.configure(state="normal")
else:
APP.gui.tcpclient_checkbox.configure(state="disabled")
def create_known_point(self, y_kwn, x_kwn, n):
""" Map known place creation process, works only when self.imscale = 1.0 """
# city coordinates y & x (degrees) converted to pixels