Repository navigation
Expand file tree
/
Copy pathcontrol.py
More file actions
3659 lines (3062 loc) · 153 KB
/
Copy pathcontrol.py
File metadata and controls
3659 lines (3062 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
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
"""
General-purpose radiod control interface via TLV command protocol
This module provides a complete interface to radiod's control protocol using
TLV (Type-Length-Value) encoding, based on ka9q-radio's status.c/status.h.
ARCHITECTURE:
- This module exposes ALL radiod capabilities and parameters
- Application-specific defaults should be implemented in higher-level modules
or configuration files
- Reusable for any application needing radiod channel control
USAGE:
1. Create RadiodControl instance with status address
2. Use granular setters (set_frequency, set_preset, etc.) OR
3. Use create_and_configure_channel() for common channel creation patterns
PARAMETERS:
- All StatusType enum values from ka9q-radio/status.h are supported
- See individual methods for parameter descriptions and valid ranges
"""
import socket
import select
import struct
import secrets
import logging
import threading
import hashlib
import re
import time
from dataclasses import dataclass, field
from typing import Optional, Dict, Union
from .types import StatusType, CMD, Encoding, DemodType
from .discovery import discover_channels
from .exceptions import ConnectionError, CommandError, ValidationError
from .utils import resolve_multicast_address
logger = logging.getLogger(__name__)
@dataclass
class Metrics:
"""Metrics for monitoring RadiodControl operations"""
commands_sent: int = 0
commands_failed: int = 0
status_received: int = 0
last_error: str = ""
last_error_time: float = 0.0
errors_by_type: Dict[str, int] = field(default_factory=dict)
def to_dict(self) -> dict:
"""Convert metrics to dictionary for easy inspection"""
total = max(1, self.commands_sent) # Avoid division by zero
return {
'commands_sent': self.commands_sent,
'commands_failed': self.commands_failed,
'commands_succeeded': self.commands_sent - self.commands_failed,
'success_rate': (self.commands_sent - self.commands_failed) / total,
'status_received': self.status_received,
'last_error': self.last_error,
'last_error_time': self.last_error_time,
'errors_by_type': dict(self.errors_by_type),
}
# SSRC allocation function - compatible with signal-recorder
# Preset -> demodulator, mirroring the `demod =` line of each preset in
# ka9q-radio's share/presets.conf. LINEAR is the default because radio.h
# defines it as "everything else"; defaulting to FM (as this once did) puts
# an FM demodulator behind sam/ame/dsb/cwu/cwl/wspr/nam/amsq as well as wfm.
_FM_PRESETS = frozenset({"fm", "nfm", "pm", "npm"})
_WFM_PRESETS = frozenset({"wfm"})
_SPECTRUM_PRESETS = frozenset({"spectrum"})
def demod_type_for_preset(preset: str) -> int:
"""Return the DEMOD_TYPE that matches a radiod preset name.
radiod sets the demodulator from the preset, but clients that also send
DEMOD_TYPE override it -- so the value has to agree with the preset or
the channel runs a demodulator the caller never asked for.
"""
name = (preset or "").strip().lower()
if name in _WFM_PRESETS:
return DemodType.WFM_DEMOD
if name in _FM_PRESETS:
return DemodType.FM_DEMOD
if name in _SPECTRUM_PRESETS:
return DemodType.SPECT_DEMOD
return DemodType.LINEAR_DEMOD
def allocate_ssrc(
frequency_hz: float,
preset: str = "iq",
sample_rate: int = 16000,
agc: bool = False,
gain: float = 0.0,
destination: Optional[str] = None,
encoding: int = 0,
radiod_host: Optional[str] = None
) -> int:
"""
Allocate a deterministic SSRC from channel parameters.
This function generates a consistent SSRC for a given set of channel
parameters. The same parameters will always produce the same SSRC,
enabling stream sharing and coordination between applications.
The algorithm matches signal-recorder's StreamSpec.ssrc_hash() for
cross-library compatibility.
Args:
frequency_hz: Center frequency in Hz
preset: Demodulation mode ("iq", "usb", "lsb", "am", "fm", "cw")
sample_rate: Output sample rate in Hz
agc: Automatic gain control enabled
gain: Manual gain in dB
destination: RTP destination multicast address (optional)
encoding: Output encoding type
radiod_host: Optional radiod hostname or address. When provided the
hash includes the radiod identity so the same client parameters
talking to different radiod instances produce distinct SSRCs.
Returns:
Deterministic 31-bit positive SSRC value
Example:
>>> ssrc = allocate_ssrc(10.0e6, "iq", 16000)
>>> print(f"SSRC for 10 MHz IQ @ 16kHz: {ssrc}")
# Same parameters always give same SSRC
>>> ssrc2 = allocate_ssrc(10.0e6, "iq", 16000)
>>> assert ssrc == ssrc2
"""
# Create a stable string key from parameters
# The format and rounding match signal-recorder's StreamSpec hash logic.
key_str = (
f"{round(frequency_hz)}|" # Frequency rounded to nearest Hz
f"{preset.lower()}|" # Preset normalized to lowercase
f"{sample_rate}|" # Sample rate
f"{'1' if agc else '0'}|" # AGC as 1/0
f"{round(gain, 1)}|" # Gain rounded to 0.1 dB
f"{destination or ''}|" # Destination (empty string if None)
f"{encoding}|" # Encoding type
f"{radiod_host or ''}" # Radiod instance identity
)
# Use SHA-256 for a stable, platform-independent hash
h = hashlib.sha256(key_str.encode()).digest()
# Convert first 4 bytes to integer (big-endian)
# Keep positive and 31 bits to match signal-recorder's SSRC range
ssrc_full = int.from_bytes(h[:4], byteorder='big')
return ssrc_full & 0x7FFFFFFF
# Input validation functions
def _validate_ssrc(ssrc: int) -> None:
"""Validate SSRC fits in 32-bit unsigned integer"""
if not isinstance(ssrc, int):
raise ValidationError(f"SSRC must be an integer, got {type(ssrc).__name__}")
if not (0 <= ssrc <= 0xFFFFFFFF):
raise ValidationError(f"Invalid SSRC: {ssrc} (must be 0-4294967295)")
def _validate_frequency(freq_hz: float) -> None:
"""Validate frequency is within reasonable SDR range"""
if not isinstance(freq_hz, (int, float)):
raise ValidationError(f"Frequency must be a number, got {type(freq_hz).__name__}")
if not (0 < freq_hz < 10e12): # 10 THz max
raise ValidationError(f"Invalid frequency: {freq_hz} Hz (must be 0 < freq < 10 THz)")
def _validate_sample_rate(rate: int) -> None:
"""Validate sample rate is positive and reasonable"""
if not isinstance(rate, int):
raise ValidationError(f"Sample rate must be an integer, got {type(rate).__name__}")
if not (1 <= rate <= 100e6): # 100 MHz max
raise ValidationError(f"Invalid sample rate: {rate} Hz (must be 1-100000000)")
def _validate_timeout(timeout: float) -> None:
"""Validate timeout is positive"""
if not isinstance(timeout, (int, float)):
raise ValidationError(f"Timeout must be a number, got {type(timeout).__name__}")
if timeout <= 0:
raise ValidationError(f"Timeout must be positive, got {timeout}")
def _validate_gain(gain_db: float) -> None:
"""Validate gain is within reasonable range"""
if not isinstance(gain_db, (int, float)):
raise ValidationError(f"Gain must be a number, got {type(gain_db).__name__}")
if not (-100 <= gain_db <= 100): # Reasonable range for most SDRs
raise ValidationError(f"Invalid gain: {gain_db} dB (must be -100 to +100)")
def _validate_positive(value: float, name: str) -> None:
"""Validate that a value is positive"""
if not isinstance(value, (int, float)):
raise ValidationError(f"{name} must be a number, got {type(value).__name__}")
if value <= 0:
raise ValidationError(f"{name} must be positive, got {value}")
def _validate_preset(preset: str) -> None:
"""
Validate preset name is safe and within reasonable bounds
Args:
preset: Preset name to validate
Raises:
ValidationError: If preset name is invalid
"""
if not isinstance(preset, str):
raise ValidationError(f"Preset must be a string, got {type(preset).__name__}")
if not preset:
raise ValidationError("Preset name cannot be empty")
if len(preset) > 32:
raise ValidationError(f"Preset name too long: {len(preset)} chars (max 32)")
# Check control characters FIRST (before regex)
if any(ord(c) < 32 or ord(c) == 127 for c in preset):
raise ValidationError(f"Preset name contains control characters")
# Allow alphanumeric, dash, underscore only
if not re.match(r'^[a-zA-Z0-9_-]+$', preset):
raise ValidationError(f"Invalid preset name '{preset}': only alphanumeric, dash, and underscore allowed")
def _validate_string_param(value: str, param_name: str, max_length: int = 256) -> None:
"""
Validate a generic string parameter
Args:
value: String value to validate
param_name: Name of parameter (for error messages)
max_length: Maximum allowed length
Raises:
ValidationError: If string is invalid
"""
if not isinstance(value, str):
raise ValidationError(f"{param_name} must be a string, got {type(value).__name__}")
if not value:
raise ValidationError(f"{param_name} cannot be empty")
if len(value) > max_length:
raise ValidationError(f"{param_name} too long: {len(value)} chars (max {max_length})")
# Check null bytes FIRST
if '\x00' in value:
raise ValidationError(f"{param_name} contains null bytes")
# Then check other control characters (except newline/tab if needed)
if any(ord(c) < 32 and c not in '\n\t' for c in value):
raise ValidationError(f"{param_name} contains control characters")
def _validate_multicast_address(address: str) -> None:
"""
Validate multicast address format
Args:
address: Multicast address (IP or hostname)
Raises:
ValidationError: If address format is invalid
"""
if not isinstance(address, str):
raise ValidationError(f"Multicast address must be a string, got {type(address).__name__}")
if not address:
raise ValidationError("Multicast address cannot be empty")
# Try to parse as IP address
try:
# Simple validation - socket.inet_aton will catch malformed addresses
socket.inet_aton(address)
except OSError:
# Not a valid IP, could be hostname - allow it
# radiod will resolve it or hash it to generate multicast address
if len(address) > 255:
raise ValidationError(f"Hostname too long: {len(address)} chars (max 255)")
if '\x00' in address:
raise ValidationError("Multicast address contains null bytes")
def encode_int64(buf: bytearray, type_val: int, x: int) -> int:
"""
Encode a 64-bit integer in TLV format
Format: [type:1][length:1][value:variable]
Value is big-endian, with leading zeros compressed
Args:
buf: Buffer to write to
type_val: TLV type identifier
x: Integer value (must be 0 <= x <= 2^64-1)
Raises:
ValidationError: If x is negative or too large
"""
if x < 0:
raise ValidationError(f"Cannot encode negative integer: {x}")
if x >= 2**64:
raise ValidationError(f"Integer too large for 64-bit encoding: {x}")
buf.append(type_val)
if x == 0:
# Compress zero to zero length
buf.append(0)
return 2
# Convert to bytes and remove leading zeros
x_bytes = x.to_bytes(8, byteorder='big')
# Find first non-zero byte
start = 0
while start < len(x_bytes) and x_bytes[start] == 0:
start += 1
value_bytes = x_bytes[start:]
length = len(value_bytes)
buf.append(length)
buf.extend(value_bytes)
return 2 + length
def encode_int(buf: bytearray, type_val: int, x: int) -> int:
"""
Encode an integer in TLV format (alias for encode_int64)
Args:
buf: Buffer to write to
type_val: TLV type identifier
x: Integer value (must be 0 <= x <= 2^64-1)
Returns:
Number of bytes written (2 + value length)
Raises:
ValidationError: If x is negative or too large
"""
return encode_int64(buf, type_val, x)
def encode_double(buf: bytearray, type_val: int, x: float) -> int:
"""
Encode a double-precision float (float64) in TLV format
Converts the float to IEEE 754 double-precision format, then encodes
it as a 64-bit integer in TLV format.
Args:
buf: Buffer to write to
type_val: TLV type identifier
x: Float value to encode
Returns:
Number of bytes written (2 + value length)
Example:
>>> buf = bytearray()
>>> encode_double(buf, StatusType.RADIO_FREQUENCY, 14.074e6)
10
"""
# Pack as double, unpack as uint64
packed = struct.pack('>d', x) # big-endian double
value = struct.unpack('>Q', packed)[0] # big-endian uint64
return encode_int64(buf, type_val, value)
def encode_float(buf: bytearray, type_val: int, x: float) -> int:
"""
Encode a single-precision float (float32) in TLV format
Converts the float to IEEE 754 single-precision format, then encodes
it as a 32-bit integer in TLV format.
Args:
buf: Buffer to write to
type_val: TLV type identifier
x: Float value to encode
Returns:
Number of bytes written (2 + value length)
Note:
Single-precision floats have less precision than doubles.
Use encode_double() for better precision when needed.
"""
# Pack as float, unpack as uint32
packed = struct.pack('>f', x) # big-endian float
value = struct.unpack('>I', packed)[0] # big-endian uint32
return encode_int64(buf, type_val, value)
def encode_string(buf: bytearray, type_val: int, s: str) -> int:
"""
Encode a UTF-8 string in TLV format
Strings are encoded with variable-length encoding:
- Length < 128: single-byte length
- Length >= 128: multi-byte length (0x80 | high_byte, low_byte)
Args:
buf: Buffer to write to
type_val: TLV type identifier
s: String to encode (will be converted to UTF-8)
Returns:
Number of bytes written (2 + string length)
Raises:
ValueError: If string is longer than 65535 bytes
Example:
>>> buf = bytearray()
>>> encode_string(buf, StatusType.PRESET, "usb")
5
"""
buf.append(type_val)
s_bytes = s.encode('utf-8')
length = len(s_bytes)
if length < 128:
buf.append(length)
elif length < 65536:
# Multi-byte length encoding
buf.append(0x80 | (length >> 8))
buf.append(length & 0xff)
else:
raise ValueError(f"String too long: {length} bytes")
buf.extend(s_bytes)
return 2 + length
def encode_socket(buf: bytearray, type_val: int, address: str, port: int = 5004) -> int:
"""
Encode a socket address (IPv4) in TLV format
Format matches radiod's decode_socket expectations:
- Address: 4 bytes (IPv4 address in network order)
- Port: 2 bytes (big-endian)
Total: 6 bytes for IPv4
Note: Family (AF_INET/AF_INET6) is inferred from length by radiod:
- length 6 = IPv4
- length 10 = IPv6 (not currently supported)
Args:
buf: Buffer to write to
type_val: TLV type identifier
address: IP address as string (e.g., "239.1.2.3")
port: Port number (default: 5004 for RTP)
Returns:
Number of bytes written (8 = type + length + 6 bytes data)
Raises:
ValidationError: If address format is invalid
Example:
>>> buf = bytearray()
>>> encode_socket(buf, StatusType.OUTPUT_DATA_DEST_SOCKET, "239.1.2.3", 5004)
8
"""
buf.append(type_val)
# Encode the socket address
try:
# Convert string IP to 4 bytes (already in network order)
addr_bytes = socket.inet_aton(address)
except OSError as e:
raise ValidationError(f"Invalid IP address '{address}': {e}")
# Validate port range
if not (0 <= port <= 65535):
raise ValidationError(f"Invalid port {port} (must be 0-65535)")
# Format: address(4 bytes) + port(2 bytes, network order)
# This matches radiod's decode_socket() expectations
buf.append(6) # length for IPv4
buf.extend(addr_bytes) # 4 bytes address (already in network order from inet_aton)
buf.extend(struct.pack('>H', port)) # 2 bytes port (big-endian)
return 2 + 6 # type + length + data
def encode_eol(buf: bytearray) -> int:
"""
Encode end-of-list marker
Every TLV command must end with an EOL marker to signal
the end of the parameter list.
Args:
buf: Buffer to write to
Returns:
Number of bytes written (always 1)
"""
buf.append(StatusType.EOL)
return 1
# Decode functions for parsing TLV responses
def decode_int(data: bytes, length: int) -> int:
"""
Decode an integer from TLV response
Args:
data: Bytes to decode (variable length, big-endian)
length: Number of bytes
Returns:
Integer value
Raises:
ValidationError: If length is negative or data is insufficient
"""
# Validate length
if length < 0:
raise ValidationError(f"Negative length in decode_int: {length}")
if length == 0:
return 0
if length > 8:
logger.warning(f"Integer length {length} exceeds 8 bytes, truncating")
length = 8
if len(data) < length:
raise ValidationError(f"Insufficient data: need {length} bytes, have {len(data)}")
value = 0
for i in range(length):
value = (value << 8) | data[i]
return value
def decode_int32(data: bytes, length: int) -> int:
"""
Decode a 32-bit integer from TLV response (alias for decode_int)
Args:
data: Bytes to decode (variable length, big-endian)
length: Number of bytes
Returns:
Integer value
"""
return decode_int(data, length)
def decode_int64(data: bytes, length: int) -> int:
"""
Decode a 64-bit integer from TLV response (alias for decode_int)
Args:
data: Bytes to decode (variable length, big-endian)
length: Number of bytes
Returns:
Integer value (up to 64-bit)
"""
return decode_int(data, length)
def decode_float(data: bytes, length: int) -> float:
"""
Decode a float (float32) from TLV response
Args:
data: Bytes to decode (big-endian IEEE 754)
length: Number of bytes (should be 4 or less with leading zeros stripped)
Returns:
Float value
Raises:
ValidationError: If length is negative or data is insufficient
"""
# Validate length
if length < 0:
raise ValidationError(f"Negative length in decode_float: {length}")
if length > 4:
logger.warning(f"Float length {length} exceeds 4 bytes, truncating")
length = 4
if len(data) < length:
raise ValidationError(f"Insufficient data: need {length} bytes, have {len(data)}")
# Reconstruct 4-byte big-endian representation
value_bytes = b'\x00' * (4 - length) + data[:length]
return struct.unpack('>f', value_bytes)[0]
def decode_double(data: bytes, length: int) -> float:
"""
Decode a double (float64) from TLV response
Args:
data: Bytes to decode (big-endian IEEE 754)
length: Number of bytes (should be 8 or less with leading zeros stripped)
Returns:
Float value
Raises:
ValidationError: If length is negative or data is insufficient
"""
# Validate length
if length < 0:
raise ValidationError(f"Negative length in decode_double: {length}")
if length > 8:
logger.warning(f"Double length {length} exceeds 8 bytes, truncating")
length = 8
if len(data) < length:
raise ValidationError(f"Insufficient data: need {length} bytes, have {len(data)}")
# Reconstruct 8-byte big-endian representation
value_bytes = b'\x00' * (8 - length) + data[:length]
return struct.unpack('>d', value_bytes)[0]
def decode_bool(data: bytes, length: int) -> bool:
"""
Decode a boolean value from TLV response
Args:
data: Bytes to decode
length: Number of bytes
Returns:
True if non-zero, False if zero
"""
return decode_int(data, length) != 0
def decode_string(data: bytes, length: int) -> str:
"""
Decode a UTF-8 string from TLV response
Args:
data: Bytes to decode
length: String length in bytes
Returns:
Decoded string
Raises:
ValidationError: If length is negative or data is insufficient
"""
# Validate length
if length < 0:
raise ValidationError(f"Negative length in decode_string: {length}")
if length > 65535:
logger.warning(f"String length {length} exceeds maximum, truncating to 65535")
length = 65535
if len(data) < length:
logger.warning(f"String data truncated: expected {length} bytes, have {len(data)}")
length = len(data)
return data[:length].decode('utf-8', errors='replace')
def decode_socket(data: bytes, length: int) -> dict:
"""
Decode a socket address from TLV response
Args:
data: Bytes containing socket address
length: Length of socket data
Returns:
Dictionary with 'family', 'address', and 'port' keys
Note:
Handles two formats:
- With family field: 2 bytes family + 2 bytes port + N bytes address (length 8 for IPv4, 18 for IPv6)
- Without family field: N bytes address + 2 bytes port (length 6 for IPv4, 10 for IPv6)
"""
if length == 8:
# Format WITH family field: family(2) + port(2) + address(4) for IPv4
family = struct.unpack('>H', data[0:2])[0]
port = struct.unpack('>H', data[2:4])[0]
# Check if it's actually IPv4 (AF_INET = 2)
if family == 2:
address = socket.inet_ntoa(data[4:8])
return {'family': 'IPv4', 'address': address, 'port': port}
else:
# Unknown family
return {'family': f'unknown (family={family})', 'address': '', 'port': port}
elif length == 6:
# Format WITHOUT family field: address(4) + port(2) for IPv4
address = socket.inet_ntoa(data[0:4])
port = struct.unpack('>H', data[4:6])[0]
return {'family': 'IPv4', 'address': address, 'port': port}
elif length == 10:
# Format WITHOUT family field: address(8) + port(2) for IPv6 (truncated)
# Note: This is a truncated IPv6 address (only 8 bytes instead of 16)
address_bytes = data[0:8]
port = struct.unpack('>H', data[8:10])[0]
# Format as hex string since it's truncated
address = ':'.join(f'{address_bytes[i]:02x}{address_bytes[i+1]:02x}'
for i in range(0, 8, 2))
return {'family': 'IPv6', 'address': address, 'port': port}
else:
return {'family': 'unknown', 'address': '', 'port': 0}
# SSRCs already warned about for TTL=0, so the warning fires once per
# channel per process instead of once per poll. See decode_status_dict().
_TTL_ZERO_WARNED: set = set()
def decode_status_dict(buffer: bytes) -> dict:
"""Decode a radiod STATUS packet into a flat dictionary.
Standalone module-level decoder — does NOT require a RadiodControl
instance, so it's safe to call from contexts that should not open
a control socket (notably :class:`ka9q.status_listener.StatusListener`,
which would otherwise drag in a full control session just to parse
bytes).
Returns an empty dict for non-STATUS packets (first byte != 0).
Unknown TLV tags are silently skipped.
Used by :meth:`RadiodControl._decode_status_response` (which adds a
metric bump on top of the same parse) and by the status listener.
"""
status: dict = {}
if len(buffer) == 0 or buffer[0] != 0:
return status # Not a status response
cp = 1 # Skip packet type byte
while cp < len(buffer):
if cp >= len(buffer):
break
type_val = buffer[cp]
cp += 1
if type_val == StatusType.EOL:
break
if cp >= len(buffer):
break
optlen = buffer[cp]
cp += 1
# Handle extended length encoding
if optlen & 0x80:
length_of_length = optlen & 0x7f
optlen = 0
for _ in range(length_of_length):
if cp >= len(buffer):
break
optlen = (optlen << 8) | buffer[cp]
cp += 1
if cp + optlen > len(buffer):
break
data = buffer[cp:cp + optlen]
# Decode based on type
if type_val == StatusType.COMMAND_TAG:
status['command_tag'] = decode_int32(data, optlen)
elif type_val == StatusType.GPS_TIME:
status['gps_time'] = decode_int64(data, optlen)
elif type_val == StatusType.RTP_TIMESNAP:
status['rtp_timesnap'] = decode_int32(data, optlen)
elif type_val == StatusType.RADIO_FREQUENCY:
status['frequency'] = decode_double(data, optlen)
elif type_val == StatusType.OUTPUT_SSRC:
status['ssrc'] = decode_int32(data, optlen)
elif type_val == StatusType.AGC_ENABLE:
status['agc_enable'] = decode_bool(data, optlen)
elif type_val == StatusType.GAIN:
status['gain'] = decode_float(data, optlen)
elif type_val == StatusType.RF_GAIN:
status['rf_gain'] = decode_float(data, optlen)
elif type_val == StatusType.RF_ATTEN:
status['rf_atten'] = decode_float(data, optlen)
elif type_val == StatusType.RF_AGC:
status['rf_agc'] = decode_int(data, optlen)
elif type_val == StatusType.PRESET:
status['preset'] = decode_string(data, optlen)
# ⛔ The two fields that say how to READ the samples. status.py has
# always decoded them; this decoder -- the one discovery.py builds
# ChannelInfo from -- did not, so every consumer holding a
# ChannelInfo had to fall back to the preset STRING to decide
# complex-versus-real. Phil Karn, 2026-09-21: "the individual
# parameters [are] definitive, with a preset just being a convenient
# shorthand"; a preset can be tweaked out of truth (PRESET USB then
# filters -3000,-50 yields LSB) and, from the nopreset branch on,
# may not arrive at all.
elif type_val == StatusType.DEMOD_TYPE:
status['demod_type'] = decode_int(data, optlen)
elif type_val == StatusType.OUTPUT_CHANNELS:
status['output_channels'] = decode_int(data, optlen)
elif type_val == StatusType.LOW_EDGE:
status['low_edge'] = decode_float(data, optlen)
elif type_val == StatusType.HIGH_EDGE:
status['high_edge'] = decode_float(data, optlen)
elif type_val == StatusType.NOISE_DENSITY:
status['noise_density'] = decode_float(data, optlen)
elif type_val == StatusType.BASEBAND_POWER:
status['baseband_power'] = decode_float(data, optlen)
elif type_val == StatusType.OUTPUT_SAMPRATE:
status['sample_rate'] = decode_int(data, optlen)
elif type_val == StatusType.OUTPUT_ENCODING:
status['encoding'] = decode_int(data, optlen)
elif type_val == StatusType.OUTPUT_DATA_DEST_SOCKET:
status['destination'] = decode_socket(data, optlen)
elif type_val == StatusType.OUTPUT_TTL:
status['ttl'] = decode_int(data, optlen)
if status['ttl'] == 0:
# Warn ONCE per SSRC, not once per poll. TTL=0 is a static
# property of the channel, but every client re-reads status
# for every SSRC on every poll -- on a 36-channel single-host
# station that was hundreds of identical WARNING lines per
# minute in psk-recorder and wspr-recorder, which is enough
# to bury the decode/anchor diagnostics an operator actually
# needs. (It is also the *intended* config there: sigmond
# generates radiod with ttl=0 as the safe single-host
# default. This library can't know the deployment intent,
# so the warning stays -- it just stops repeating.)
ssrc = status.get('ssrc', 'unknown')
msg = (f"Radiod reporting TTL=0 for SSRC {ssrc}: "
f"Multicast data restricted to localhost loopback only!")
if ssrc in _TTL_ZERO_WARNED:
logger.debug(msg)
else:
_TTL_ZERO_WARNED.add(ssrc)
logger.warning(msg)
elif type_val == StatusType.FILTER_DROPS:
# radiod's count of output blocks this channel's demod thread
# lapped. Since ka9q-radio 55d9048d each lapped block is
# counted here AND emitted as a block of zeros, so the sample
# timeline stays intact and the loss shows up in the data --
# which makes this counter cross-checkable against
# ``PacketResequencer``'s zero-block detection rather than
# something a client has to take on trust.
#
# ``decode_status_packet`` has decoded it into
# ``ChannelStatus.filter_drops`` all along; this lightweight
# decoder -- the one ``StatusListener`` runs on every
# broadcast -- silently skipped it, so the per-channel drop
# count was invisible to every long-running client.
status['filter_drops'] = decode_int(data, optlen)
elif type_val == StatusType.LIFETIME:
status['lifetime'] = decode_int(data, optlen)
elif type_val == StatusType.DESCRIPTION:
status['description'] = decode_string(data, optlen)
cp += optlen
# Calculate SNR if we have the necessary data
if all(k in status for k in
['baseband_power', 'low_edge', 'high_edge', 'noise_density']):
import math
bandwidth = abs(status['high_edge'] - status['low_edge'])
if bandwidth > 0:
try:
noise_power_db = (
status['noise_density'] + 10 * math.log10(bandwidth)
)
signal_plus_noise_db = status['baseband_power']
noise_power = 10 ** (noise_power_db / 10)
signal_plus_noise = 10 ** (signal_plus_noise_db / 10)
if noise_power > 0:
snr_linear = signal_plus_noise / noise_power - 1
if snr_linear > 0:
status['snr'] = 10 * math.log10(snr_linear)
except (ValueError, ZeroDivisionError, OverflowError):
pass
return status
def _encoding_name(value: Optional[int]) -> str:
"""Render an encoding value as 'NAME(n)' for log messages."""
if value is None:
return "unknown"
for name, val in vars(Encoding).items():
if not name.startswith("_") and val == value:
return f"{name}({value})"
return f"UNKNOWN({value})"
#: Bounds on `RadiodControl._drain_status_socket`. Comfortably above a full
#: receive buffer's worth of status packets (~26k for a 5 MB queue), while
#: guaranteeing the drain terminates even if the group refills as fast as it
#: is read -- or if the socket is a test double that never raises.
_DRAIN_MAX_PACKETS = 50000
_DRAIN_MAX_SEC = 0.25
class RadiodControl:
"""
Control interface for radiod
Sends TLV-encoded commands to radiod's control socket to create
and configure channels.
"""
def __init__(self, status_address: str, max_commands_per_sec: int = 100,
interface: Optional[str] = None,
client_id: Optional[str] = None):
"""
Initialize radiod control
Args:
status_address: mDNS name or IP:port of radiod status stream
max_commands_per_sec: Maximum commands per second (rate limiting)
interface: IP address of network interface for multicast (e.g., '192.168.1.100').
Required on multi-homed systems. If None, uses INADDR_ANY (0.0.0.0).
client_id: Identity string for this client application
(e.g. ``"psk-recorder"``, ``"hf-timestd"``). When set,
:py:meth:`ensure_channel` derives a per-(client, radiod)
multicast destination via
:py:func:`ka9q.generate_multicast_ip` whenever the
caller does not supply an explicit ``destination=``.
Same client_id + same radiod -> same destination
(all of that client's channels share one multicast
group); different client_id OR different radiod ->
distinct destinations (peer clients on one station
never collide; one client targeting two radiods
sees one destination per radiod). ``None`` (default):
if the caller also omits ``destination=`` on
create_channel()/ensure_channel(), ValidationError is
raised — there is no config-file fallback client-side
(audit finding F5; before 3.22 this silently fell
through to radiod, which created nothing).
client_id is the SUPPORTED way to obtain channel
destinations: create_channel()/ensure_channel()
derive a deterministic per-(client, radiod) multicast
group from it whenever destination= is omitted;
passing destination= explicitly is the legacy path
(audit finding F5).
"""
self.status_address = status_address
self.interface = interface
self.client_id = client_id
self.socket = None
self._status_sock = None # Cached status listener socket for tune()
self._status_sock_lock = None # Will be initialized when needed
self._socket_lock = threading.RLock() # Protect control socket operations
# Encoding requested per SSRC, so the keepalive can re-assert it and
# verify_channel() can tell a granted encoding from a silently lost one.
# radiod takes OUTPUT_ENCODING only as a follow-up command (see
# create_channel), which makes the grant easy to drop and impossible to
# notice; HamSCI/ka9q-python#3.
self._requested_encoding: Dict[int, int] = {}
# Optional continuous STATUS listener (live timing anchor refresh).
# Lazily created by start_status_listener(); see ka9q.status_listener.
self._status_listener = None
# Rate limiting
self.max_commands_per_sec = max_commands_per_sec
self._command_count = 0
self._command_window_start = time.time()
self._rate_limit_lock = threading.Lock()
# Metrics tracking
self.metrics = Metrics()
self._connect()
def __enter__(self):
"""Context manager entry"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit - ensure cleanup"""
try:
self.close()
except Exception as e:
logger.warning(f"Error during cleanup in context manager: {e}")
return False # Don't suppress exceptions
def _connect(self):
"""Connect to radiod control socket"""
try:
# Resolve the status address using shared utility
mcast_addr = resolve_multicast_address(self.status_address, timeout=5.0)
# Create UDP socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Allow multiple sockets to bind to the same port