-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
617 lines (470 loc) · 19.1 KB
/
main.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
import os, signal
import sys
import argparse
# noinspection PyUnresolvedReferences
import time
def kill_siblings():
# Ask user for the name of process
name = "StnMate2/main.py"
try:
# iterating through each instance of the process
for line in os.popen("ps -ef | grep " + name + " | grep -v grep"):
fields = line.split()
# extracting Process ID from the output
pid = fields[1]
_ppid = fields[2]
if int(pid) == os.getpid(): # Avoid suicide
continue
# if fields[-1].endswith("debugging"):
# continue
# terminating process
while True:
try:
os.kill(int(pid), signal.SIGTERM)
# os.kill(int(ppid), signal.SIGSTOP)
print("Sent kill signal to process %d" % int(pid))
time.sleep(1)
except Exception as ex:
print ("Process %s is now dead: %s" % (int(pid), ex))
break
except Exception as ex:
print("Error %s Encountered while running script"%ex)
parser = argparse.ArgumentParser(
prog='StnMate2',
description='This program helps me remote controlling my ham station and aid in the finding VHF/UHF Dx and logging QSOs',
epilog='SM6FBQ 2021-2023')
parser.add_argument("--debugging", action="store_true",
help="Run a debugging session, kills any simultaneously running sibling instances")
parsed_args=parser.parse_args()
if parsed_args.debugging:
kill_siblings()
import socket
address = ("", 8878)
s = socket.socket()
try:
s.bind(address)
except OSError as e:
print("Another instance of StnMate2 is running. Quitting: %s" % e)
sys.exit(1)
from flask import Flask, render_template, request
import psycopg2
from config import DevelopmentConfig
from flask_socketio import SocketIO, emit
from flask_socketio.namespace import Namespace
from morsetx import *
import threading
import atexit
import logging
logger=logging.getLogger(__name__)
if parsed_args.debugging:
logger.setLevel("DEBUG")
else:
logger.setLevel("INFO")
hdlr = logging.StreamHandler()
hdlr.setFormatter(logging.Formatter('%(asctime)s %(levelname)8s %(filename)20s:%(lineno)-5s %(message)s'))
logger.addHandler(hdlr)
logger.info("Starting stnMate")
socket_io = SocketIO(async_mode="eventlet", logger=False, engineio_logger=False, ping_timeout=60, ping_interval=4)
class MyApp(Flask):
def __init__(self, import_name, **kwargs):
super().__init__(import_name, **kwargs)
self.config.from_object(DevelopmentConfig)
with open("etc/google_api.txt") as f:
api_key = f.readline()
self.config['GOOGLEMAPS_API_KEY'] = api_key
socket_io.init_app(self)
self.socket_io = socket_io
self._db = psycopg2.connect(dbname='ham_station')
from hamop import HamOp
self.ham_op = HamOp(self, logger, self._db)
from clientmgr import ClientMgr
self.client_mgr = ClientMgr(self, logger, socket_io)
from azel import AzelController
self.azel = AzelController(self, logger, socket_io, hysteresis=14)
from aircraft_tracker import AircraftTracker
self.aircraft_tracker = AircraftTracker(self, logger, socket_io, url="http://192.168.1.129:8754")
from station_tracker import StationTracker
self.station_tracker = StationTracker(self, logger, socket_io)
rows = self.ham_op.fetch_my_current_data("144")
self.my_data = {x["key"]: x["value"] for x in rows}
self.keyer = Morser(logger, speed=None, p20=self.azel.p20)
self.keyer_thread = threading.Thread(target=self.keyer.background_thread, args=())
self.keyer_thread.daemon = True # Daemonize keyer_thread
self.keyer_thread.start()
app=MyApp(__name__)
class WsjtxNamespace(Namespace):
"""
:class:`WsjtxNamespace` is a class that extends the `Namespace` class from the `SocketIO` library. It handles events related to WSJT-X
message exchanger py-wsjtx.
Methods:
- `on_connect()`:
- This method is called when the WSJT-X message exchanger connects.
- It logs a message that the exchanger has connected.
- then emits a `server_response` event with data `{'data': 'Connected', 'count': 0}`.
- `on_disconnect()`:
- This method is called when yhr WSJT-X message exchanger disconnects.
- It logs a message that the exchanger has disconnected.
- `on_my_event(sid, data)`:
- This method is called when a custom event `my_event` is triggered.
- It emits a `my_response` event with the given data.
- `on_set_dx_note(json)`:
- This method is called when a `set_dx_note` event is triggered with some JSON data.
- It logs a message that the DX note is being filled with the given JSON data.
- It retrieves the callsign and locator from the JSON data and sets them using the `set_dx_call` method from the `app.client_mgr`.
- It emits a `fill_dx_note` event with the JSON data, broadcasting it to all clients.
- `on_set_dx_grid(grid)`:
- Emits a `fill_dx_grid` event with the `grid`, broadcasting it to all clients.
- `on_set_trx70(json)`:
- This method is called when a `set_trx70` event is triggered with some JSON data.
- It logs a message that the TRX70 is being set.
- It sets the TRX70 using the `set_trx70` method from the `app.ham_op`.
- `on_commit_wsjtx_qso(json)`:
- This method is called when a `commit_wsjtx_qso` event is triggered with some JSON data.
- It retrieves the necessary fields from the JSON data and creates a `qso` dictionary with the following keys:
- `callsign`: The DX call from the JSON data.
- `band`: The dial frequency divided by 1,000,000.
- `txmode`: The transmit mode from the JSON data.
- `tx`: The report sent from the JSON data.
- `rx`: The report received from the JSON data.
- `locator`: The DX grid from the JSON data.
- `frequency`: The dial frequency divided by 1,000,000.
- `date`: The date from the `date_time_on` field of the JSON data.
- `time`: The time from the `date_time_on` field of the JSON data.
- `complete`: True.
- `propmode`: The propagation mode from the JSON data.
- If the `dx_call` and `dx_grid` are provided, it looks up any known full locator using the `lookup_locator` method from the `app.ham_op` and adds it to the `qso` dictionary
* as `augmented_locator`.
- It calculates the bearing, distance, contest points, and square count using the `distance_to` method from the `app.ham_op` and adds them to the `qso` dictionary.
- It logs a message that the QSO from WSJT-X is being committed with the `qso` dictionary.
- It commits the QSO using the `do_commit_qso` method from the `app.ham_op` and retrieves the new QSO ID.
- It adds the QSO ID to the `qso` dictionary.
- It emits a `commit_qso` event with the `qso` dictionary, broadcasting it to all clients.
Note: Please refer to the relevant code implementation for further details on the methods and their usage.
"""
@staticmethod
def on_connect():
logger.info("WSJTX exchanger connected")
emit('server_response', {'data': 'Connected', 'count': 0})
@staticmethod
def on_disconnect():
logger.info("WSJTX exchanger disconnected")
pass
@staticmethod
def on_my_event(sid, data):
emit('my_response', (sid,data))
@staticmethod
def on_set_dx_note(json):
logger.info("Fill DX note %s" % json)
callsign = json["callsign"]
locator = json["locator"]
app.client_mgr.set_dx_call(callsign, locator)
emit("fill_dx_note", json, namespace="/", broadcast=True)
@staticmethod
def on_set_dx_grid(grid):
logger.info("Set DX grid to %s" % grid)
emit("fill_dx_grid", grid, namespace="/", broadcast=True)
@staticmethod
def on_set_trx70(json):
logger.info("Set TRX70")
app.ham_op.set_trx70(json)
@staticmethod
def on_commit_wsjtx_qso(json):
dt = json["date_time_on"] # type: str
fq = int(json["dial_frequency"])
qso = {
"callsign": json["dx_call"],
"band": "%f" % (fq / 1000000),
"txmode": json["txmode"],
"tx": json["report_sent"],
"rx": json["report_received"],
"locator": json["dx_grid"],
"frequency": "%f" % (fq / 1000000),
"date": dt[:10],
"time": dt[11:13] + dt[14:16],
"complete": True,
"propmode": json["propmode"]
}
# If given only the square, look up any known full locator if previously known
found_loc = app.ham_op.lookup_locator(json["dx_call"], json["dx_grid"])
if found_loc:
qso["augmented_locator"] = found_loc
bearing, distance, points, square_count = app.ham_op.distance_to(qso["locator"], qso["date"], qso["time"])
qso["distance"] = "%4.1f" % distance
qso["points"] = points
# "dx_grid": p.dx_grid,
# "dx_call": p.dx_call,
# "dial_frequency": p.dial_frequency,
# "mode": p.mode,
# "comments": p.comments,
# "date_time_off": p.date_time_off,
# "date_time_on": p.date_time_on,
# "exch_received": p.exch_received,
# "exch_sent": p.exch_sent,
# "my_call": p.my_call,
# "my_grid": p.my_grid,
# "name": p.name,
# "op_name": p.op_name,
# "propmode": p.propmode,
# "report_received": p.report_received,
# "report_sent": p.report_send,
# "tx_power": p.tx_power
logger.info("Commit QSO from WSJT-X %s", qso)
new_qso_id = app.ham_op.do_commit_qso(qso)
qso["id"] = new_qso_id
# app.client_mgr.add_qso(qso) # do_commit_qso does this.
socket_io.on_namespace(WsjtxNamespace('/wsjtx'))
@app.route('/')
def index():
with open("etc/g16e.txt") as f:
key=f.readline()
return render_template('sm6fbq.html', gapikey=key, async_mode=socket_io.async_mode)
@app.route('/az')
def get_azimuth():
return "Az=%d ticks" % app.azel.az
@app.route("/help")
def cmd_help():
help_text = """
<table>
<tr><td>/</td><td>Start antenna and log view</td></tr>
<tr><td>/help</td><td>See this help text</td></tr>
<tr><td>/az</td><td>Return current antenna azimuth in ticks</td></tr>
<tr><td>/translate_qras</td><td>Translate all legacy QRA locators in the log to Maidenhead locators</td></tr>
<tr><td>/recompute_distances</td><td>Recompute all distances in the log and add distances where missing</td></tr>
<tr><td>/status</td><td>Return rig status</td></tr>
<tr><td>/paon</td><td>Turn on the power supply to the transmitter power amplifiers</td></tr>
<tr><td>/paoff</td><td>Turn off the power supply to the transmitter power amplifiers</td></tr>
<tr><td>/qroon</td><td>Enable high power transmission</td></tr>
<tr><td>/qrooff</td><td>Disable high power transmission</td></tr>
<tr><td>/rx70</td><td>Configure core station for 70cm reception (Just causes RX disconnect from the antenna)</td></tr>
<tr><td>/tx70</td><td>Configure core station for 70cm transmission.</td></tr>
<tr><td>/rx2</td><td>Opposite of rx70</td></tr>
<tr><td>/tx2</td><td>Opposite of tx70</td></tr>
<tr><td>/wsjtx_upload</td><td>Upload a wsjt-x log file to the station log.</td></tr>
<tr><td>/az_scan</td><td>Sweep the antenna azimuth. Requires parameters</td></tr>
<tr><td>/commit_qso</td><td>Commit a qso to the station log. Requires parameters</td></tr></table>
"""
return help_text
@app.route("/myqth")
def my_qth():
return app.ham_op.my_qth()
@app.route("/translate_qras") # Maintenance entry, converts all legacy QRA locators to maidenhead locators.
def translate_qras():
return app.ham_op.translate_qras()
@app.route("/recompute_distances") # Maintenance entry, recomputes all distances
def recompute_distances():
return app.ham_op.recompute_distances()
@app.route("/status")
def my_status():
return app.ham_op.my_status()
@app.route("/paon")
def my_pa_on():
return app.ham_op.my_pa_on()
@app.route("/paoff")
def my_pa_off():
return app.ham_op.my_pa_off()
@app.route("/qroon")
def my_qro_on():
return app.ham_op.my_qro_on()
@app.route("/qrooff")
def my_qro_off():
return app.ham_op.my_qro_off()
@app.route("/rx70")
def my_rx70_on():
return app.ham_op.my_rx70_on()
@app.route("/rx2")
def my_rx70_off():
return app.ham_op.my_rx70_off()
@app.route("/tx70")
def my_tx70_on():
return app.ham_op.my_tx70_on()
@app.route("/tx2")
def my_tx70_off():
return app.ham_op.my_tx70_off()
@app.route('/wsjtx_upload', methods=['POST'])
def my_wsjtx_upload():
return app.ham_op.my_wsjtx_upload(request)
@app.route('/az_scan', defaults={"az_start":0,"az_stop":180, "period":30, "sweeps":2, "increment":15})
def az_scan(az_start,az_stop,period,sweeps, increment):
logger.info("AZ_scan start=%d, az_stop=%d, period=%d, sweeps=%d increment=%d" % (az_start,az_stop,period,sweeps, increment))
return app.azel.sweep(az_start,az_stop,period,sweeps,increment)
# @app.route('/commit_qso', methods=['POST'])
# def commit_qso():
# return commit_qso(request)
##############
@socket_io.event()
def connect():
app.client_mgr.connect()
@socket_io.on('connect', namespace="/stats")
def connect():
app.client_mgr.connect(namespace="/stats")
@socket_io.event
def calibrate(_json):
app.azel.calibrate()
return "Azimuth calibration done"
@socket_io.event
def set_map_mh_length(json):
length = int(json["length"])
app.client_mgr.set_locator_precision_used_on_map(length)
@socket_io.event
def set_log_scope(json):
scope = json["scope"]
app.client_mgr.set_log_scope(scope)
@socket_io.event
def set_az(json):
print("Pointing at %d" % json["az"])
app.azel.set_az(json["az"])
app.client_mgr.send_azel(force=True)
@socket_io.event
def set_az(json):
print("Pointing at %d" % json["az"])
app.azel.set_az(json["az"])
app.client_mgr.send_azel(force=True)
@socket_io.event
def manual(what):
# print("Manual event %s" % what)
app.azel.manual(what)
@socket_io.on("get_azel")
def get_azel():
ret=app.azel.get_azel()
return ret
@socket_io.event
def add_az(json):
print("Adjusting az target %d" % json["diff"])
app.azel.add_az(json["diff"])
app.client_mgr.send_azel(force=True)
@socket_io.event
def stop(_json):
app.azel.stop()
app.client_mgr.status_update()
@socket_io.event
def lookup_locator(qso):
app.client_mgr.lookup_locator(qso)
@socket_io.event
def untrack(_json):
app.azel.untrack()
return "Stopped tracking"
@socket_io.event
def transmit_cw(json):
speed = json.get("speed", None)
if speed:
app.keyer.set_speed(speed)
repeat = json.get("repeat", 1)
# keyer.send_message(json["msg"], repeat=repeat)
while repeat:
app.keyer.txq.put(json["msg"])
repeat -= 1
pass
@socket_io.event
def make_log(json):
app.ham_op.make_log(json)
@socket_io.event
def band_select(json):
app.client_mgr.band_select(json)
@socket_io.event
def set_cw_speed(json):
speed = int(json.get("speed", None))
app.keyer.set_speed(speed)
def message_received():
logger.debug('message was received!!!')
@socket_io.on('my event')
def handle_my_custom_event(json):
logger.debug('received my event: ' + str(json))
emit('my response', json, callback=message_received)
app.client_mgr.send_azel(force=True)
app.station_tracker.refresh()
@socket_io.on("track_wind")
def handle_track_wind(_json):
app.azel.track_wind()
@socket_io.on("track_moon")
def handle_track_moon(_json):
app.azel.track_moon()
@socket_io.on("track_sun")
def handle_track_sun(_json):
app.azel.track_sun()
@socket_io.on("pop_target")
def handle_pop_target(_json):
#logger.debug("Handle pop_target")
return app.azel.pop_target()
@socket_io.on("toggle_qro")
def handle_toggle_qro(_json):
app.ham_op.toggle_qro()
@socket_io.on("toggle_pa")
def handle_toggle_pa(_json):
app.ham_op.toggle_pa()
@socket_io.on("toggle_tx70")
def handle_toggle_tx70(_json):
app.ham_op.toggle_tx70()
@socket_io.on("toggle_auto_track")
def handle_toggle_auto_track(_json):
app.client_mgr.toggle_auto_track()
@socket_io.on("toggle_antenna_freeze")
def handle_toggle_auto_track(_json):
app.client_mgr.toggle_antenna_freeze()
@socket_io.on("toggle_rx70")
def handle_toggle_rx70(_json):
app.ham_op.toggle_rx70()
@socket_io.on("toggle_distinct")
def handle_toggle_rx70(_json):
app.client_mgr.toggle_distinct()
@socket_io.on("toggle_hide_logged_stations")
def handle_toggle_hide_logged_stations(_json):
app.client_mgr.toggle_hide_logged_stations()
@socket_io.on("toggle_aircraft_layer")
def handle_toggle_aircraft_layer(_json):
app.client_mgr.toggle_aircraft_layer()
@socket_io.on("toggle_station_layer")
def handle_toggle_station_layer(_json):
app.client_mgr.toggle_station_layer()
@socket_io.on("toggle_beacon_layer")
def handle_toggle_beacon_layer(_json):
app.client_mgr.toggle_beacon_layer()
@socket_io.on("track_az")
def handle_track_az(_json):
logger.debug('received track_az: ' + str(_json))
app.ham_op.az_track(_json["az"].upper())
@socket_io.event()
def commit_qso(qso):
new_qso_id = app.ham_op.do_commit_qso(qso)
qso["id"] = new_qso_id
emit("qso_committed", qso)
app.station_tracker.refresh()
@socket_io.event()
def delete_qso(qso):
app.ham_op.do_delete_qso(qso)
app.station_tracker.refresh()
@socket_io.on('disconnect')
def test_disconnect():
logger.info('Client %s disconnected', request.host)
@socket_io.event()
def az_scan_go(json):
logger.info("Run AZ scan using %s" % json)
return app.azel.sweep(int(json["start"]), int(json["stop"]), int(json["period"]), int(json["sweeps"]), int(json["increment"]))
@socket_io.event()
def plane_click(plane_id):
logger.info("Plane click on %s" % plane_id)
return app.aircraft_tracker.track_plane(plane_id)
@socket_io.event()
def station_click(callsign):
logger.info("Station click on %s" % callsign)
emit("fill_dx_grid", callsign, namespace="/", broadcast=True)
return app.station_tracker.track_station(app.azel, callsign)
@socket_io.event()
def map_settings(settings):
app.client_mgr.map_settings(settings)
@atexit.register
def goodbye():
logger.info("Goodbye!!")
app.azel.az_stop()
app.azel.GPIO_cleanup() # clean up GPIO on exit
logger.info("Starting antenna tracker")
app.azel.startup()
logger.info("Starting aircraft tracker")
app.aircraft_tracker.startup()
logger.info("Starting stations tracker")
app.station_tracker.startup()
if __name__ == '__main__':
try:
socket_io.run(app, host='0.0.0.0', port=8877, log_output=False, debug=False, use_reloader=False)
finally:
app.azel.az_stop()
pass