This repository has been archived by the owner on Mar 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathradio-daemon.py
1199 lines (941 loc) · 33.7 KB
/
radio-daemon.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
# Base libraries
#from cmath import asin
#from datetime import datetime
#from inspect import trace
import sys
import glob
import os
import argparse
import platform
import time
from datetime import datetime, timedelta
#import time
import json
#import queue
#import audioop
import ssl
#from typing_extensions import runtime
# TCP Socket Server
import websockets
import websockets.exceptions
import asyncio
# HTTP server stuff
import ssl
# WebRTC Stuff
from aiortc import MediaStreamTrack, RTCPeerConnection, RTCSessionDescription, logging
from aiortc.contrib.media import MediaBlackhole, MediaPlayer, MediaRecorder, MediaRelay, AudioFrame
import uuid
# Sound stuff
from av.audio.frame import AudioFrame
# Numpy (used for sound processing)
#import numpy as np
# Serial stuff
import serial
import serial.tools.list_ports
# Radio class
from radioClass import Radio
# Radio State
from radioState import RadioState
# Logger
from logger import Logger
# Used for loading config and sending messages
import json
# CPU profiling (don't fail if user doesn't have yappi installed)
try:
import yappi
except ImportError:
pass
# Memory profiling
try:
import tracemalloc
import gc
#from pympler import summary, muppy
except ImportError:
pass
# Config class (loaded from JSON)
class Config():
# Init
def __init__(self):
# List of radio configs
self.Radio = None
# Create new config
configFile = ""
config = Config()
# AIORTC recorder & player (for mic & speaker tracks)
micRecorder = None
spkrPlayer = None
# Local recording config
recDirectory = None
recHangtime = None
recFormat = None
recorder = None
recording = False
recTimeout = None
recTimeoutTask = None
recChannel = None
recState = None
# Create a relay for the incoming mic track
micRelay = None
spkrRelay = None
# FFMPEG device format (alsa for linux, dshow for windows, loaded at runtime)
ffmpegFormat = None
# Flag that says when we got the first track from the client (which would be the mic track)
gotMicTrack = False
# Argument parser
parser = argparse.ArgumentParser()
# Global variables
verbose = False
address = None
serverport = None
webguiport = None
noreset = False
cpuProfiling = False
memProfiling = False
gcProfiling = False
# Muppy tracker
sumThread = None
sumStop = False
sumInterval = 300 # seconds
# SSL globals
certfile = 'certs/localhost.crt'
keyfile = 'certs/localhost.key'
# Asyncio routines and event loop
wsServer = None
eventLoop = None
# WebRTC variables
rtcPeer = None
# Message queue for sending to client
messageQueue = asyncio.Queue()
# Audio globals
audioSampleRate = 48000 # this must match the WebRTC settings on the client
# Test input & output audio streams
micStream = None
spkrStream = None
# WebRTC Tracks
micTrack = None
spkrTrack = None
blackHole = None
# Sound device lists
inputs = []
outputs = []
hostapis = []
# Detect operating system
osType = platform.system()
# Create logger object
logger = Logger()
logger.initLogs()
"""-------------------------------------------------------------------------------
Command Line Argument Functions
-------------------------------------------------------------------------------"""
def addArguments():
"""
Add command line arguments
"""
parser.add_argument("-a","--address", help="Server address to bind to")
parser.add_argument("-c","--config", help="Config file to load", metavar="config.json")
parser.add_argument("-ls","--list-sound", help="List available sound devices", action="store_true")
parser.add_argument("-lp","--list-ports", help="List available com ports", action="store_true")
parser.add_argument("-nr","--no-reset", help="Don't reset connected radios on start", action="store_true")
parser.add_argument("-sp","--serverport", help="Websocket server port")
parser.add_argument("-v","--verbose", help="Enable verbose logging", action="store_true")
parser.add_argument("-vv","--verbose2", help="Debug verbosity in logging", action="store_true")
parser.add_argument("-cp", "--cpu-profiling", help="Enable yappi CPU profiling", action="store_true")
parser.add_argument("-mp","--memory-profiling", help="Enable memory profiling", action="store_true")
parser.add_argument("-gp","--garbage-profiling", help="Enable garbage collector debug", action="store_true")
return
def parseArguments():
global verbose
global address
global serverport
global webguiport
global noreset
global cpuProfiling
global memProfiling
global gcProfiling
# Parse the args
args = parser.parse_args()
# Make sure we've got a valid set of them
# Verbose logging
if args.verbose:
logger.setVerbose(args.verbose)
logger.logVerbose("Verbose logging enabled")
if args.verbose2:
logger.setVerbose(True)
logger.setDebug(True)
logger.logDebug("Debug logging enabled")
# List available serial devices
if args.list_ports:
logger.logInfo("Listing available serial ports")
getSerialDevices()
exit(0)
# List available sound devices
if args.list_sound:
print()
getSoundDevices()
printSoundDevices()
exit(0)
# Make sure port and optionally an address were specified
if not args.serverport:
logger.logError("No server port specified!")
exit(1)
else:
serverport = int(args.serverport)
if not args.address:
address = "localhost"
else:
address = args.address
if args.no_reset:
noreset = True
if args.cpu_profiling:
logger.logInfo("CPU profiling enabled")
cpuProfiling = True
if args.memory_profiling:
memProfiling = True
if args.garbage_profiling:
gcProfiling = True
# Make sure a config file was specified
if not args.config:
Logger.logWarn("No config file specified, exiting")
exit(0)
else:
loadConfig(args.config)
return
"""-------------------------------------------------------------------------------
Config Parsing Functions
-------------------------------------------------------------------------------"""
def loadConfig(filename):
"""Load JSON config file and parse to config objects
Args:
filename (string): filename/path
Returns:
bool: success or failure
"""
global certfile
global recDirectory
global recHangtime
global recFormat
global keyfile
global ffmpegFormat
try:
# make sure file is valid
if not os.path.exists(filename):
raise ValueError("Specified file does not exist")
# open and parse
with open(filename, 'r') as inp:
# Load JSON into dict
configDict = json.load(inp)
# Get and parse radio config
config.Radio = Radio.decodeConfig(configDict["Radio"], logger)
# Get globals
if "Certfile" in configDict.keys() and "Keyfile" in configDict.keys():
certfile = configDict["Certfile"]
logger.logInfo("Using SSL cerfile: {}".format(certfile))
keyfile = configDict["Keyfile"]
logger.logInfo("Using SSL keyfile: {}".format(keyfile))
# Get recording config
if "recording" in configDict.keys():
recDirectory = configDict["recording"]["directory"]
recHangtime = configDict["recording"]["hangtime"]
recFormat = configDict["recording"]["format"]
logger.logInfo("Local recording enabled, will record to {}".format(recDirectory))
logger.logDebug("Recording hangtime: {}, format: {}".format(recHangtime, recFormat))
# Print on success
logger.logInfo("Sucessfully loaded config file {}".format(filename))
logger.logVerbose(config)
# Return true
return True
except ValueError as ex:
logger.logError("Error loading config file: {}".format(ex.args[0]))
return False
def printRadios():
logger.logInfo("Loaded radio:")
print(" {} control ({})".format(config.Radio.ctrlMode, config.Radio.ctrlPort))
print(" Tx Audio dev: {}".format(config.Radio.txDev))
print(" Rx Audio dev: {}".format(config.Radio.rxDev))
return
"""-------------------------------------------------------------------------------
Radio Functions
-------------------------------------------------------------------------------"""
async def handleStatus():
global recording
global recTimeout
global recTimeoutTask
global recChannel
global recState
# Don't do anything unless our audio is connected and running, and we're configured to record
if rtcPeer and micRelay and spkrRelay and recDirectory and recHangtime and recFormat:
# See if radio is receiving or transmitting
if config.Radio.state == RadioState.Transmitting or config.Radio.state == RadioState.Receiving:
# Start recording if we weren't
if not recording:
recChannel = config.Radio.chan
recState = config.Radio.state
if recState == RadioState.Transmitting:
await startRecording(recChannel, True)
else:
await startRecording(recChannel, False)
# Restart recording if the channel changed (commented out for now since it also catched MDC IDs, TGs, etc which we don't want)
if recChannel != config.Radio.chan:
pass
#logger.logVerbose("Channel changed, restarting recording")
#await stopRecording()
#recChannel = config.Radio.chan
#recState = config.Radio.state
#if recState == RadioState.Transmitting:
# await startRecording(recChannel, True)
#else:
# await startRecording(recChannel, False)
# Channel TX/RX state change handler
elif recState != config.Radio.state:
logger.logVerbose("Channel switched TX/RX state, restarting recording")
await stopRecording()
recChannel = config.Radio.chan
recState = config.Radio.state
if recState == RadioState.Transmitting:
await startRecording(recChannel, True)
else:
await startRecording(recChannel, False)
else:
if recording and not recTimeout:
logger.logVerbose("Radio idle, starting recorder timeout timer")
recTimeout = datetime.now()
# Start recorder timeout monitoring
recTimeoutTask = asyncio.create_task(checkRecTimer())
def connectRadio():
"""
Connect to the configured radio
"""
# Log
logger.logInfo("Connecting to radio {}".format(config.Radio.name))
# Connect
config.Radio.connect(radioStatusUpdate, reset = not noreset)
return
def radioStatusUpdate():
"""
Status callback the radio interface calls when it has a new status
"""
# Add the message to the queue
eventLoop.call_soon_threadsafe(messageQueue.put_nowait,"status")
return
def setTransmit(transmit):
"""
Set transmit state of the radio
Args:
transmit (bool): state of transmit
"""
config.Radio.transmit(transmit)
return
def changeChannel(down):
"""
Changes the channel up or down on the radio
Args:
down ([type]): whether to go down or not
"""
config.Radio.changeChannel(down)
return
def toggleSoftkey(softkeyidx):
"""
Toggles softkey on radio
Args:
softkeyidx (int): Index of softkey (1-5)
"""
config.Radio.toggleSoftkey(softkeyidx)
return
def pressSoftkey(softkeyidx):
"""
Depresses softkey on radio
Args:
softkeyidx (int): Index of softkey (1-5)
"""
config.Radio.pressSoftkey(softkeyidx)
return
def releaseSoftkey(softkeyidx):
"""
Releases softkey on radio
Args:
softkeyidx (int): Index of softkey (1-5)
"""
config.Radio.releaseSoftkey(softkeyidx)
return
def leftArrow():
"""
Presses left arrow button (for softkey scrolling)
"""
config.Radio.leftArrow()
return
def rightArrow():
"""
Presses right arrow button (for softkey scrolling)
"""
config.Radio.rightArrow()
return
def toggleMute(state):
"""
Set state of mute for radio
Args:
state (bool): state of mute
"""
config.Radio.setMute(state)
return
def getRadioStatusJson():
"""
Gets status of radio and returns a json string
Returns:
string: JSON of radio status
"""
# Get the status of the specified radio
status = config.Radio.encodeClientStatus()
logger.logDebug(status)
return json.dumps(status)
"""-------------------------------------------------------------------------------
WebRTC Functions
-------------------------------------------------------------------------------"""
async def gotRtcDescription(desc):
"""
Called when we receive a WebRTC offer from the client
Args:
offerObj (dict): WebRTC description object
"""
global rtcPeer
global spkrPlayer
global micRecorder
global micRelay
global spkrRelay
logger.logVerbose("Got WebRTC description")
logger.logDebug(desc)
# Create peer connection if it doesn't already exist
if not rtcPeer:
rtcPeer = RTCPeerConnection()
# If offer, do offer-related things
if desc["type"] == "offer":
# Create SDP offer and peer connection objects
offer = RTCSessionDescription(sdp=desc["sdp"], type=desc["type"])
# Create speaker track
if not spkrPlayer:
logger.logInfo("Creating RTC speaker track for radio {}, device {}".format(config.Radio.name, config.Radio.rxDev))
# Create speaker track
spkrPlayer = MediaPlayer(config.Radio.rxDev, format=ffmpegFormat)
# Create speaker relay
if not spkrRelay:
spkrRelay = MediaRelay()
# Connect
rtcPeer.addTrack(spkrRelay.subscribe(spkrPlayer.audio))
else:
logger.logVerbose("RTC speaker track already exists")
# Create callbacks
# ICE connection state callback
@rtcPeer.on("iceconnectionstatechange")
async def onIceConnectionStateChange():
logger.logVerbose("Ice connection state is now {}".format(rtcPeer.iceConnectionState))
if rtcPeer.iceConnectionState == "failed":
await rtcPeer.close()
logger.logError("WebRTC peer connection failed")
# Audio track callback when we get the mic track from the client
@rtcPeer.on("track")
async def onTrack(track):
global micRelay
global micTrack
global micRecorder
global ffmpegFormat
logger.logVerbose("Got {} track from peer".format(track.kind))
micTrack = track
# make sure it's audio
if track.kind != "audio":
logger.logError("Got non-audio track from peer")
return
# Discard the mic track if we're RX only
if config.Radio.rxOnly:
logger.logWarn("Radio is configured as RX only, mic track will be discarded")
micRecorder = MediaBlackhole()
# Only open the mic recorder if it's not already open (from previous config or above rx only catch)
if not micRecorder:
logger.logInfo("Opening TX audio device stream: {}".format(config.Radio.txDev))
micRecorder = MediaRecorder(config.Radio.txDev, format=ffmpegFormat)
# Create a mic relay
if not micRelay:
micRelay = MediaRelay()
# Connect the mic track to the recorder via the relay
micRecorder.addTrack(micRelay.subscribe(track))
await micRecorder.start()
# Track ended handler (don't really do anything here for now)
@track.on("ended")
async def onEnded():
logger.logVerbose("Audio track from peer ended")
# Send RTC resposne back to console
await doRtcAnswer(offer)
logger.logVerbose("done")
return
async def stopRtc():
global rtcPeer
global spkrPlayer
global micRecorder
global micRelay
global micTrack
global spkrRelay
# Stop the peer if it's open
logger.logInfo("Stopping RTC connection")
if rtcPeer:
await rtcPeer.close()
rtcPeer = None
# Stop and clear mic track
if micTrack:
logger.logVerbose("Stopping Mic track")
micTrack = None
# Stop and clear recorder
if micRecorder:
logger.logVerbose("Stopping TX audio recorder")
await micRecorder.stop()
micRecorder = None
# Stop and clear player
if spkrPlayer:
logger.logVerbose("Stopping RX audio player")
spkrPlayer = None
# Stop and clear the mic relay
if micRelay:
logger.logVerbose("Clearing mic relay")
micRelay = None
# Stop and clear the speaker relay
if spkrRelay:
logger.logVerbose("Clearing speaker relay")
spkrRelay = None
return
async def doRtcAnswer(offer):
# Handle the received offer
logger.logVerbose("Creating remote description from offer")
await rtcPeer.setRemoteDescription(offer)
# Create answer
logger.logVerbose("Creating WebRTC answer")
answer = await rtcPeer.createAnswer()
# Set local description
logger.logVerbose("setting local SDP")
await rtcPeer.setLocalDescription(answer)
# Send answer
logger.logVerbose("sending SDP answer")
message = '{{ "webRtcAnswer": {{ "type": "{}", "sdp": {} }} }}'.format(rtcPeer.localDescription.type, json.dumps(rtcPeer.localDescription.sdp))
logger.logDebug(message.replace("\\r\\n", "\r\n"))
messageQueue.put_nowait(message)
return
async def startRecording(channelName, tx):
global recorder
global recording
global recTimeout
if not os.path.exists(recDirectory):
os.mkdir(recDirectory)
timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
if tx:
# Record TX stream
filename = "{}/{}_{}_TX.{}".format(recDirectory, channelName, timestamp, recFormat)
recorder = MediaRecorder(filename)
logger.logVerbose("Starting recording TX to file {}".format(filename))
recorder.addTrack(micRelay.subscribe(micTrack))
else:
# Record RX stream
filename = "{}/{}_{}_RX.{}".format(recDirectory, channelName, timestamp, recFormat)
recorder = MediaRecorder(filename)
logger.logVerbose("Starting recording RX to file {}".format(filename))
recorder.addTrack(spkrRelay.subscribe(spkrPlayer.audio))
# Start
await recorder.start()
recording = True
recTimeout = None
return
async def stopRecording():
global recording
global recTimeout
await recorder.stop()
logger.logVerbose("Stopped recording")
recording = False
recTimeout = None
return
# this runs in a thread
async def checkRecTimer():
while recTimeout:
if datetime.now() - recTimeout > timedelta(seconds=recHangtime):
logger.logVerbose("Recorder hangtime expired, stopping!")
await stopRecording()
else:
await asyncio.sleep(0.01)
logger.logVerbose("Recording timeout cleared")
return
"""-------------------------------------------------------------------------------
Sound Device Functions
-------------------------------------------------------------------------------"""
def getSoundDevices():
"""
Get available system sound devices
"""
global inputs
global outputs
global hostapis
return
def printSoundDevices():
"""
Print queried sound devices
"""
# Print inputs first
logger.logInfo("Available input devices:")
print()
return
"""-------------------------------------------------------------------------------
Serial Port Functions
-------------------------------------------------------------------------------"""
def getSerialDevices():
"""
Gets a list of avaialble serial devices based on operating system
"""
# Windows
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
# Linux
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
ports = glob.glob('/dev/tty[A-Za-z]*')
# Fallback
else:
logger.logError("Unknown OS detected!")
exit(1)
# Find which ports are valid
results = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
results.append(port)
except (OSError, serial.SerialException):
pass
# Print the result
for port in results:
logger.logInfo("Port {}".format(port))
return
"""-------------------------------------------------------------------------------
Websocket Server Functions
-------------------------------------------------------------------------------"""
async def websocketHandler(websocket, path):
"""
Sets up handlers for websocket
"""
consumer_task = asyncio.ensure_future(consumer_handler(websocket, path))
producer_task = asyncio.ensure_future(producer_hander(websocket, path))
done, pending = await asyncio.wait(
[consumer_task, producer_task],
return_when=asyncio.FIRST_COMPLETED,
)
for task in pending:
task.cancel()
return
async def consumer_handler(websocket, path):
"""
Websocket handler for data received from client
Args:
websocket (websocket): websocket object
path (path): not sure what this does, we don't use it
"""
try:
# Old way - just a while True infinite loop
#while True:
# New way - proper asyncio consumer per documentation
async for msg in websocket:
logger.logDebug("Got data from websocket:")
logger.logDebug(msg)
obj = json.loads(msg)
# Iterate through the received command keys (there should only ever be one, but it's possible to recieve multiple)
for key in obj.keys():
#
# Radio Query Command
#
if key == "radio" and obj[key]["command"] == "query":
await messageQueue.put("status")
#
# Radio Control Commands
#
elif key == "radioControl":
# Get object inside
params = obj[key]
command = params["command"]
options = params["options"]
# Start PTT
if command == "startTx":
logger.logVerbose("Starting TX on radio")
setTransmit(True)
# Stop PTT
elif command == "stopTx":
logger.logVerbose("Stopping TX on radio")
setTransmit(False)
# Channel Up
elif command == "chanUp":
changeChannel(False)
# Channel Down
elif command == "chanDn":
changeChannel(True)
# Buttons
elif command == "buttonToggle":
# Get button
button = options
# Toggle a softkey
if "softkey" in button:
softkeyidx = int(button[7])
toggleSoftkey(softkeyidx)
# Left/right arrow keys
elif button == "left":
leftArrow()
elif button == "right":
rightArrow()
elif command == "buttonPress":
button = options
if "softkey" in button:
softkeyidx = int(button[7])
pressSoftkey(softkeyidx)
elif command == "buttonRelease":
button = options
if "softkey" in button:
softkeyidx = int(button[7])
releaseSoftkey(softkeyidx)
else:
logger.logWarn("Unknown radio control command {}".format(command))
#
# Audio Control Messages
#
elif key == "audioControl":
# Get params
params = obj[key]
command = params["command"]
# Start audio command
if command == "startAudio":
logger.logWarn("Deprecated command: startAudio")
# Mute commands
elif command == "mute":
toggleMute(True)
elif command == "unmute":
toggleMute(False)
#
# WebRTC Messages
#
elif key == "webRtc":
# Get params
rtcObj = obj[key]
logger.logVerbose("Got webRtc object from console")
logger.logDebug(rtcObj)
# Determine if we have a candidate or a description
if 'desc' in rtcObj:
await gotRtcDescription(rtcObj['desc'])
if 'cand' in rtcObj:
logger.logWarn("Got WebRTC candidate, but we don't handle those yet")
#
# NACK if command wasn't handled above
#
else:
logger.logError("Unknown command from console: {}".format(obj))
# Send NACK
await messageQueue.put('NACK')
# Handle connection closing event (stop audio devices)
except websockets.exceptions.ConnectionClosed:
logger.logWarn("Client disconnected!")
# stop sound devices and exit
asyncio.ensure_future(stopRtc(),loop=eventLoop)
return
async def producer_hander(websocket, path):
"""
Websocket handler for sending data to client
Args:
websocket (websocket): socket object
path (path): still not sure what this does
"""
try:
while True:
# Wait for new data in queue
message = await messageQueue.get()
# Send WebRTC SDP answer
if "webRtcAnswer" in message:
logger.logInfo("sending WebRTC answer to {}".format(websocket.remote_address[0]))
await websocket.send(message)
# send status update for specific radio
elif "status" in message:
# Format JSON response
response = '{{ "status": {} }}'.format(getRadioStatusJson())
# Send
await websocket.send(response)
# Handle status message (for local recording, etc)
await handleStatus()
# send NACK to unknown command
elif "NACK" in message:
logger.logWarn("invalid command received from {}".format(websocket.remote_address[0]))
await websocket.send('{{"nack": {{ }} }}')
except websockets.exceptions.ConnectionClosed:
# The consumer handler should already cover this
logger.logWarn("Websocket connection closed!")
return
def startWsServer():
"""
Start the websocket server
"""
global wsServer
global eventLoop
global config
logger.logInfo("Starting websocket server on address {}, port {}".format(address, serverport))
# use ssl on the web socket
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(certfile, keyfile)
# create server object
wsServer = websockets.serve(websocketHandler, address, serverport, ssl=ssl_context)
# add websocket server to event loop
eventLoop.run_until_complete(wsServer)
#asyncio.run(wsServer)
"""-------------------------------------------------------------------------------
Utility Functions
-------------------------------------------------------------------------------"""