-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterlocutor.py
More file actions
2186 lines (1742 loc) · 74.1 KB
/
interlocutor.py
File metadata and controls
2186 lines (1742 loc) · 74.1 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
#!/usr/bin/env python3
"""
GPIO PTT Audio, Terminal Chat, Control Messages, and Config Files
- Voice PTT with OPUS encoding (highest priority)
- Terminal-based keyboard chat interface
- Priority queue system for message handling
- Background thread for non-voice transmission
- Debug/verbose mode for development
- UDP ports indicate data types
- Operator and Audio Device Configuration files in YAML
- Atkinson Hyperlegible font
- Audio transcription
- Specialized command dictionary (dice roller, etc)
Text Input → ChatManagerAudioDriven → AudioDrivenFrameManager.queue_text_message() → Simple Queue()
Voice Input → audio_callback → AudioDrivenFrameManager.process_voice_and_transmit() → Direct transmission
Class Organization
1. Foundation & Configuration "What do we need?"
StreamFrame - Data container for the 40ms frame system
2. Chat & User Interface Layer "How do users interact with chat?"
TerminalChatInterface - Terminal-based user interaction
ChatManagerAudioDriven - Audio-synchronized chat management
3. Stream Management & Timing "How do we manage frame timing?"
ContinuousStreamManager - Controls when the 40ms stream runs
AudioDrivenFrameManager - The heart of frame transmission logic
4. Network & Protocol "How do we connect to compouters or modems?"
MessageReceiver - Handles incoming data parsing and reassembly
5. Hardware Integration & Main System "How does it all come together?"
GPIOZeroPTTHandler - The main radio system class that orchestrates everything
Method Organization Within Classes
1. Constructor Pattern
def __init__(self) # Always first
def setup_*_methods(self) # Configuration methods
def _validate_config(self) # Private validation helpers
2. Core Operations (The Main Quest)
We put the most important method first.
They are Ordered by typical call sequence.
We group related operations together.
3. Interface Methods (Party Coordination)
Public methods other classes call.
Then, callback methods (when_, on_).
Finally, event handlers.
4. Utility & Testing (Skill Checks)
Validation methods.
Test methods.
Helper functions.
5. Status and Cleanup (Character Record Sheet)
def get_stats(self) # Status inquiry
def print_stats(self) # Status display
def stop(self) # Graceful shutdown
def cleanup(self) # Final cleanup
"""
import sys
import socket
import struct
import time
import threading
import argparse
import re
from datetime import datetime
import asyncio
from queue import PriorityQueue, Empty, Queue
#from queue import Empty, Queue
from enum import Enum
from typing import Union, Tuple, Optional, List, Dict
import select
import logging
import traceback
import random
import sounddevice
from dataclasses import dataclass
from config_manager import (
OpulentVoiceConfig,
ConfigurationManager,
create_enhanced_argument_parser,
setup_configuration
)
from audio_device_manager import (
AudioDeviceManager,
AudioManagerMode,
create_audio_manager_for_cli,
create_audio_manager_for_interactive
)
from web_interface import initialize_web_interface, run_web_server
from enhanced_receiver import integrate_enhanced_receiver
from radio_protocol import (
COBSEncoder,
SimpleFrameReassembler,
COBSFrameBoundaryManager,
OpulentVoiceProtocolWithIP,
StationIdentifier,
encode_callsign,
decode_callsign,
MessageType,
QueuedMessage,
RTPHeader,
RTPAudioFrameBuilder,
UDPHeader,
UDPAudioFrameBuilder,
UDPTextFrameBuilder,
UDPControlFrameBuilder,
IPHeader,
IPAudioFrameBuilder,
IPTextFrameBuilder,
IPControlFrameBuilder,
SimpleFrameSplitter,
SimpleFrameReassembler,
FrameType,
FramePriority,
NetworkTransmitter,
DebugConfig
)
from enhanced_receiver import integrate_enhanced_receiver
from interlocutor_commands import dispatcher as command_dispatcher
# global variable for GUI
web_interface_instance = None
# check for virtual environment
if not (hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)):
print("You need to run this code in a virtual environment:")
print(" source /LED_test/bin/activate")
sys.exit(1)
try:
import opuslib_next as opuslib
print("opuslib ready")
except ImportError:
print("opuslib is missing: pip3 install opuslib")
sys.exit()
try:
import pyaudio
print("pyaudio ready")
except ImportError:
print("pyaudio is missing: sudo apt install python3-pyaudio")
sys.exit(1)
try:
from gpiozero import Button, LED
print("gpiozero ready and standing by")
except ImportError:
print("Please install gpiozero.")
raise
# ===================================================================
# 1. FOUNDATION & CONFIGURATION
# ===================================================================
# ===================================================================
# 2. CHAT & USER INTERFACE LAYER
# ===================================================================
class TerminalChatInterface:
"""Non-blocking terminal interface with PTT-aware buffering"""
def __init__(self, station_id, chat_manager):
self.station_id = station_id
self.chat_manager = chat_manager
self.running = False
self.input_thread = None
def start(self):
"""Start the chat interface in a separate thread"""
self.running = True
self.input_thread = threading.Thread(target=self._input_loop, daemon=True)
self.input_thread.start()
print("\n" + "="*60)
print("💬 CHAT INTERFACE READY")
print("Type messages and press Enter to send")
print("📝 Messages typed during PTT will be buffered and sent after release")
print("🎤 Voice PTT takes priority - chat waits respectfully")
print("⌨️ Type 'quit' to exit, 'status' for chat stats")
print("="*60)
self._show_prompt()
def stop(self):
"""Stop the chat interface"""
self.running = False
if self.input_thread:
self.input_thread.join(timeout=1.0)
def _show_prompt(self):
"""Show the chat prompt with status"""
pending_count = self.chat_manager.get_pending_count()
if pending_count > 0:
prompt = f"[{self.station_id}] Chat ({pending_count} buffered)> "
elif self.chat_manager.ptt_active:
prompt = f"[{self.station_id}] Chat (PTT ACTIVE)> "
else:
prompt = f"[{self.station_id}] Chat> "
print(prompt, end='', flush=True)
def _input_loop(self):
"""Input loop with smart buffering"""
while self.running:
try:
# Use select for non-blocking input on Unix systems
if select.select([sys.stdin], [], [], 0.1)[0]:
message = sys.stdin.readline().strip()
if message.lower() == 'quit':
print("\nExiting chat interface...")
self.running = False
break
if message.lower() == 'status':
self._show_status()
self._show_prompt()
continue
if message.lower() == 'clear':
cleared = self.chat_manager.clear_pending()
if cleared > 0:
print(f"🗑️ Cleared {cleared} buffered messages")
else:
print("🗑️ No buffered messages to clear")
self._show_prompt()
continue
if message.lower() == '/help' or message.lower() == 'help':
print("\nAvailable commands:")
for name, help_text in command_dispatcher.list_commands():
print(f" {help_text}")
print(" status — Show chat statistics")
print(" clear — Clear buffered messages")
print(" quit — Exit chat interface")
print()
self._show_prompt()
continue
if message:
# Check for slash-commands first
cmd_result = command_dispatcher.dispatch(message)
if cmd_result is not None:
# Command recognized — display locally, don't transmit
if cmd_result.is_error:
print(f" ⚠️ {cmd_result.error}")
else:
print(f" {cmd_result.summary}")
else:
# Normal chat — send through radio pipeline
result = self.chat_manager.handle_message_input(message)
self._display_result(result)
# Show prompt again
self._show_prompt()
time.sleep(0.1) # Small delay to prevent busy waiting
except Exception as e:
print(f"Chat input error: {e}")
break
def _display_result(self, result):
"""Display result of message input"""
if result['status'] == 'sent':
DebugConfig.user_print(f"💬 Sent: {result['message']}")
elif result['status'] == 'buffered':
if self.chat_manager.ptt_active:
DebugConfig.user_print(f"📝 Buffered during PTT: {result['message']} (total: {result['count']})")
else:
DebugConfig.user_print(f"📝 Buffered: {result['message']}")
def _show_status(self):
"""Show chat status"""
pending = self.chat_manager.get_pending_count()
ptt_status = "ACTIVE" if self.chat_manager.ptt_active else "INACTIVE"
DebugConfig.user_print(f"\n📊 Chat Status:")
DebugConfig.user_print(f" PTT: {ptt_status}")
DebugConfig.user_print(f" Buffered messages: {pending}")
if pending > 0:
DebugConfig.user_print(f" 📝 Pending messages:")
for i, msg in enumerate(self.chat_manager.pending_messages, 1):
DebugConfig.user_print(f" {i}. {msg}")
def display_received_message(self, from_station, message):
"""Display received chat message"""
DebugConfig.user_print(f"\n📨 [{from_station}]: {message}")
self._show_prompt()
class ChatManagerAudioDriven:
"""
Modified chat manager for audio-driven system
"""
def __init__(self, station_id, audio_frame_manager):
self.station_id = station_id
self.audio_frame_manager = audio_frame_manager # Instead of frame_transmitter
self.ptt_active = False
self.pending_messages = []
self.tts_manager = None # Set when TTS is initialized
self.web_interface_active = False # Set to True when web interface is handling TTS
def handle_message_input(self, message_text):
"""Handle message input (same interface as before)"""
if not message_text.strip():
return {'status': 'empty', 'action': 'none'}
if self.ptt_active:
# Buffer during PTT
self.pending_messages.append(message_text.strip())
return {
'status': 'buffered',
'action': 'show_buffered',
'message': message_text.strip(),
'count': len(self.pending_messages)
}
else:
# Queue immediately for audio-driven transmission
self.queue_message_for_transmission(message_text.strip())
# Queue for TTS if enabled (for outgoing messages)
if self.tts_manager:
self.tts_manager.queue_text_message(
str(self.station_id),
message_text.strip(),
is_outgoing=True
)
return {
'status': 'queued_audio_driven',
'action': 'show_queued',
'message': message_text.strip()
}
def queue_message_for_transmission(self, message_text):
"""Queue message for audio-driven transmission"""
self.audio_frame_manager.queue_text_message(message_text)
def set_ptt_state(self, active):
"""Called when PTT state changes"""
was_active = self.ptt_active
self.ptt_active = active
# If PTT just released, flush buffered messages
if was_active and not active:
self.flush_buffered_messages()
def flush_buffered_messages(self):
"""Send all buffered messages to audio-driven system after PTT release"""
if not self.pending_messages:
return []
sent_messages = []
for message in self.pending_messages:
self.queue_message_for_transmission(message)
# Also queue for TTS readback (same as non-PTT path)
if self.tts_manager:
self.tts_manager.queue_text_message(
str(self.station_id), message, is_outgoing=True
)
sent_messages.append(message)
# Show summary
if len(sent_messages) == 1:
print(f"💬 Queued buffered message for audio-driven transmission: {sent_messages[0]}")
else:
print(f"💬 Queued {len(sent_messages)} buffered messages for audio-driven transmission")
self.pending_messages.clear()
return sent_messages
def get_pending_count(self):
"""Get number of pending messages"""
return len(self.pending_messages)
def clear_pending(self):
"""Clear pending messages"""
cleared = len(self.pending_messages)
self.pending_messages.clear()
return cleared
# ===================================================================
# 3. STREAM MANAGEMENT & TIMING
# ===================================================================
class AudioDrivenFrameManager:
'''Handles all frame logic within audio callback timing'''
def __init__(self, station_identifier, protocol, network_transmitter, config):
self.station_id = station_identifier
self.protocol = protocol
self.network_transmitter = network_transmitter
self.config = config
# Frame queues
self.control_queue = Queue()
self.text_queue = Queue()
# Voice state (no buffer needed)
self.voice_active = False
self.pending_voice_frame = None
# Non-voice transmission throttling
self.frames_since_nonvoice = 0
self.nonvoice_send_interval = 1 # Send non-voice every N frames when no voice !!!
# Keepalive management - ALWAYS initialize ALL attributes !!!
self.target_type = config.protocol.target_type
self.last_keepalive_time = 0 # Always initialize this
self.keepalive_interval = config.protocol.keepalive_interval # Always initialize this
if self.target_type == "computer":
self.send_keepalives = True
DebugConfig.debug_print(f"📡 Target: Computer - keepalives enabled every {self.keepalive_interval}s")
else:
self.send_keepalives = False
DebugConfig.debug_print(f"📻 Target: Modem - keepalives disabled, modem handles hang-time")
# Statistics
self.stats = {
'total_frames_sent': 0,
'voice_frames_sent': 0,
'control_frames_sent': 0,
'text_frames_sent': 0,
'keepalive_frames_sent': 0,
'skipped_frames': 0,
'last_frame_type': None,
'target_type': self.target_type
}
def process_voice_and_transmit(self, opus_packet, current_time):
"""
PAUL'S APPROACH: Process voice - may generate multiple frames per opus packet
"""
try:
# NEW: Create potentially multiple OV frames (Paul's approach)
ov_frames = self.protocol.create_audio_frames(opus_packet, is_start_of_transmission=False)
frames_sent = 0
for frame in ov_frames:
success = self.network_transmitter.send_frame(frame)
if success:
frames_sent += 1
self.stats['voice_frames_sent'] += 1
self.stats['total_frames_sent'] += 1
if frames_sent > 0:
self.stats['last_frame_type'] = 'VOICE'
self.frames_since_nonvoice += 1
if len(ov_frames) > 1:
DebugConfig.debug_print(f"📡 {current_time:.3f}: VOICE {frames_sent}/{len(ov_frames)} frames")
else:
DebugConfig.debug_print(f"📡 {current_time:.3f}: VOICE ({len(ov_frames[0])}B)")
return frames_sent > 0
except Exception as e:
DebugConfig.debug_print(f"✗ Voice frame transmission error: {e}")
return False
# Debugging version to find the keepalive issue:
def process_nonvoice_and_transmit(self, current_time):
"""
Process non-voice frames with target-specific behavior
"""
frames_sent_this_cycle = 0
# Priority 1: Control messages (always send immediately)
try:
ov_frame = self.control_queue.get_nowait()
success = self.network_transmitter.send_frame(ov_frame)
if success:
frames_sent_this_cycle += 1
self.stats['control_frames_sent'] += 1
self.stats['total_frames_sent'] += 1
self.stats['last_frame_type'] = 'CONTROL'
self.frames_since_nonvoice = 0
DebugConfig.debug_print(f"📡 {current_time:.3f}: CONTROL ({len(ov_frame)}B)")
return True
except Empty:
pass
except Exception as e:
DebugConfig.debug_print(f"✗ Control frame error: {e}")
# Priority 2: Text messages (send every 40ms now - no throttling)
try:
ov_frame = self.text_queue.get_nowait()
success = self.network_transmitter.send_frame(ov_frame)
if success:
frames_sent_this_cycle += 1
self.stats['text_frames_sent'] += 1
self.stats['total_frames_sent'] += 1
self.stats['last_frame_type'] = 'TEXT'
self.frames_since_nonvoice = 0
DebugConfig.debug_print(f"📡 {current_time:.3f}: TEXT ({len(ov_frame)}B)")
return True
except Empty:
pass
except Exception as e:
DebugConfig.debug_print(f"✗ Text frame error: {e}")
# DEBUG: Show keepalive decision process (commented out because it's a lot of reporting)
time_since_keepalive = current_time - self.last_keepalive_time
#DebugConfig.debug_print(f"🔍 Keepalive check: send_keepalives={self.send_keepalives}, voice_active={self.voice_active}, time_since={time_since_keepalive:.1f}s, interval={self.keepalive_interval}s")
# Priority 3: Keepalive (ONLY for computer targets AND when enabled)
if self.send_keepalives and not self.voice_active:
if time_since_keepalive >= self.keepalive_interval:
try:
keepalive_data = f"KEEPALIVE:{int(current_time)}"
ov_frames = self.protocol.create_control_frames(keepalive_data)
if ov_frames:
success = self.network_transmitter.send_frame(ov_frames[0])
if success:
self.stats['keepalive_frames_sent'] += 1
self.stats['total_frames_sent'] += 1
self.stats['last_frame_type'] = 'KEEPALIVE'
self.last_keepalive_time = current_time
self.frames_since_nonvoice = 0
DebugConfig.debug_print(f"📡 {current_time:.3f}: KEEPALIVE ({len(ov_frames[0])}B) [computer target]")
return True
except Exception as e:
DebugConfig.debug_print(f"✗ Keepalive frame error: {e}")
else:
# For modem targets: explicitly show that we're NOT sending keepalives
if time_since_keepalive >= self.keepalive_interval:
self.last_keepalive_time = current_time # Update timer but don't send
DebugConfig.debug_print(f"📻 {current_time:.3f}: Keepalive SKIPPED (target_type={self.target_type}, send_keepalives={self.send_keepalives})")
# Nothing sent this cycle
self.stats['skipped_frames'] += 1
self.frames_since_nonvoice += 1
return False
# Interface methods (compatible with existing code)
def set_voice_active(self, active):
"""Called when PTT pressed/released"""
self.voice_active = active
if not active:
self.pending_voice_frame = None
def queue_text_message(self, text_data):
"""
PAUL'S APPROACH: Queue text message - creates complete OV frames
"""
if isinstance(text_data, str):
text_data = text_data.encode('utf-8')
try:
# NEW: Create potentially multiple OV frames (Paul's approach)
ov_frames = self.protocol.create_text_frames(text_data)
# Queue all frames
for frame in ov_frames:
self.text_queue.put(frame)
if len(ov_frames) > 1:
DebugConfig.debug_print(f"📝 Text message created {len(ov_frames)} frames: {text_data.decode()[:50]}...")
else:
DebugConfig.debug_print(f"📝 Text message queued: {text_data.decode()[:50]}...")
except Exception as e:
DebugConfig.debug_print(f"✗ Error queuing text message: {e}")
def queue_control_message(self, control_data):
"""
PAUL'S APPROACH: Queue control message - creates complete OV frames
"""
if isinstance(control_data, str):
control_data = control_data.encode('utf-8')
try:
# NEW: Create potentially multiple OV frames (Paul's approach)
ov_frames = self.protocol.create_control_frames(control_data)
# Queue all frames
for frame in ov_frames:
self.control_queue.put(frame)
if len(ov_frames) > 1:
DebugConfig.debug_print(f"📋 Control message created {len(ov_frames)} frames")
else:
DebugConfig.debug_print(f"📋 Control message queued")
except Exception as e:
DebugConfig.debug_print(f"✗ Error queuing control message: {e}")
def get_transmission_stats(self):
"""Get stats (updated for simple frame splitting)"""
return {
'scheduler_stats': self.stats,
'queue_status': {
'voice_active': self.voice_active,
'control_queue': self.control_queue.qsize(),
'text_queue': self.text_queue.qsize(),
'frames_since_nonvoice': self.frames_since_nonvoice
},
'frame_info': {
'frame_size': 133,
'header_size': 12,
'payload_size': 121
},
'running': self.voice_active or not (self.control_queue.empty() and self.text_queue.empty())
}
# ===================================================================
# 4. NETWORK & PROTOCOL
# ===================================================================
class MessageReceiver:
"""Handles receiving and parsing incoming messages"""
def __init__(self, listen_port=57372, chat_interface=None):
self.listen_port = listen_port
self.chat_interface = chat_interface
self.socket = None
self.running = False
self.receive_thread = None
# Simple frame reassembler (no fragmentation headers)
self.reassembler = SimpleFrameReassembler()
self.cobs_manager = COBSFrameBoundaryManager()
# For parsing complete frames
self.protocol = OpulentVoiceProtocolWithIP(StationIdentifier("TEMP"))
def start(self):
"""Start the message receiver"""
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.bind(('', self.listen_port))
self.socket.settimeout(1.0) # Allow periodic checking of running flag
self.running = True
self.receive_thread = threading.Thread(target=self._receive_loop, daemon=True)
self.receive_thread.start()
print(f"👂 Message receiver listening on port {self.listen_port}")
except Exception as e:
print(f"✗ Failed to start receiver: {e}")
def stop(self):
"""Stop the message receiver"""
self.running = False
if self.receive_thread:
self.receive_thread.join(timeout=2.0)
if self.socket:
self.socket.close()
print("👂 Message receiver stopped")
def _receive_loop(self):
"""Main receive loop"""
while self.running:
try:
data, addr = self.socket.recvfrom(4096)
self._process_received_data(data, addr)
except socket.timeout:
continue # Normal timeout, check running flag
except Exception as e:
if self.running: # Only log errors if we're supposed to be running
print(f"Receive error: {e}")
def _process_received_data(self, data, addr):
"""
PAUL'S APPROACH: Much simpler receiver processing!
"""
try:
# Step 1: Parse Opulent Voice header
if len(data) < 12:
return
ov_header = data[:12]
fragment_payload = data[12:]
# Parse OV header
station_bytes, token, reserved = struct.unpack('>6s 3s 3s', ov_header)
if token != OpulentVoiceProtocolWithIP.TOKEN:
return # Invalid frame
# Step 2: Try to reassemble COBS frames
cobs_frames = self.reassembler.add_frame_payload(fragment_payload)
# Step 3: Process all the reassembled COBS frames
for frame in cobs_frames:
DebugConfig.debug_print(f"📥 Received COBS frame from {addr}: {len(frame)}B")
# Step 4: COBS decode to get original IP frame
try:
ip_frame, _ = self.cobs_manager.decode_frame(frame)
except Exception as e:
DebugConfig.debug_print(f"✗ COBS decode error from {addr}: {e}")
continue
self._process_complete_ip_frame(ip_frame, station_bytes, addr)
except Exception as e:
DebugConfig.debug_print(f"Error processing received data from {addr}: {e}")
def _process_complete_ip_frame(self, ip_frame, station_bytes, addr):
"""
Process a complete, decoded IP frame - much simpler now!
"""
try:
# Get station identifier
try:
from_station = StationIdentifier.from_bytes(station_bytes)
except:
from_station = f"UNKNOWN-{station_bytes.hex()[:8]}"
# Parse IP header to get protocol info
if len(ip_frame) < 20:
return
# Quick IP header parse to get UDP payload
ip_header_length = (ip_frame[0] & 0x0F) * 4
if len(ip_frame) < ip_header_length + 8: # Need at least UDP header
return
udp_payload = ip_frame[ip_header_length + 8:] # Skip IP + UDP headers
# Parse UDP header to determine port/type
udp_dest_port = struct.unpack('!H', ip_frame[ip_header_length + 2:ip_header_length + 4])[0]
# Route based on UDP port
if udp_dest_port == 57373: # Voice
DebugConfig.debug_print(f"🎤 [{from_station}] Voice: {len(udp_payload)}B")
elif udp_dest_port == 57374: # Text
try:
message = udp_payload.decode('utf-8')
print(f"\n📨 [{from_station}]: {message}")
if self.chat_interface:
# Re-display chat prompt
print(f"[{self.chat_interface.station_id}] Chat> ", end='', flush=True)
except UnicodeDecodeError:
print(f"📨 [{from_station}]: <Binary text data: {len(udp_payload)}B>")
elif udp_dest_port == 57375: # Control
try:
control_msg = udp_payload.decode('utf-8')
if not control_msg.startswith('KEEPALIVE'): # Don't spam with keepalives
print(f"📋 [{from_station}] Control: {control_msg}")
except UnicodeDecodeError:
print(f"📋 [{from_station}] Control: <Binary data: {len(udp_payload)}B>")
else:
print(f"❓ [{from_station}] Unknown port {udp_dest_port}: {len(udp_payload)}B")
except Exception as e:
print(f"Error processing IP frame: {e}")
# ===================================================================
# 5. HARDWARE INTEGRATION & MAIN SYSTEM
# ===================================================================
class GPIOZeroPTTHandler:
def __init__(self, station_identifier, config: OpulentVoiceConfig):
# cleanup flag
self._cleanup_done = False
# Store configuration
self.config = config
# Store station identifier
self.station_id = station_identifier
# GPIO setup with gpiozero using config values
self.ptt_button = Button(
config.gpio.ptt_pin,
pull_up=True,
bounce_time=config.gpio.button_bounce_time
)
self.led = LED(config.gpio.led_pin)
self.ptt_active = False
# Audio configuration from config
self.sample_rate = config.audio.sample_rate
self.bitrate = config.audio.bitrate
self.channels = config.audio.channels
self.frame_duration_ms = config.audio.frame_duration_ms
self.samples_per_frame = int(self.sample_rate * self.frame_duration_ms / 1000)
self.bytes_per_frame = self.samples_per_frame * 2
DebugConfig.debug_print(f"🎵 Audio config: {self.sample_rate}Hz, {self.frame_duration_ms}ms frames")
DebugConfig.debug_print(f" Samples per frame: {self.samples_per_frame}")
DebugConfig.debug_print(f" Bytes per frame: {self.bytes_per_frame}")
# OPUS setup with validation
try:
self.encoder = opuslib.Encoder(
fs=self.sample_rate,
channels=self.channels,
application=opuslib.APPLICATION_VOIP
)
# Set the bitrate
self.encoder.bitrate = self.bitrate
# Set CBR mode
self.encoder.vbr = 0
DebugConfig.debug_print(f"✓ OPUS encoder ready: {self.bitrate}bps CBR")
except Exception as e:
DebugConfig.system_print(f"✗ OPUS encoder error: {e}")
raise
# Network setup using config
self.protocol = OpulentVoiceProtocolWithIP(station_identifier, dest_ip=config.network.target_ip)
self.transmitter = NetworkTransmitter(config.network.encap_mode, config.network.target_ip, config.network.target_port)
# Audio-driven frame manager with config
self.audio_frame_manager = AudioDrivenFrameManager(
station_identifier,
self.protocol,
self.transmitter,
config # Pass the config object
)
# Audio-driven chat manager (evolved from the heroically retired ChatManager)
self.chat_manager = ChatManagerAudioDriven(self.station_id, self.audio_frame_manager)
# Rest of existing initialization...
self.audio = pyaudio.PyAudio()
self.audio_input_stream = None
# Statistics
self.audio_stats = {
'frames_encoded': 0,
'frames_sent': 0,
'encoding_errors': 0,
'invalid_frames': 0
}
# Chat interface - now uses ChatManager
self.chat_interface = TerminalChatInterface(self.station_id, self.chat_manager)
self.setup_gpio_callbacks()
self.setup_audio()
# Add transcription support for outgoing audio
self.transcriber = None
if hasattr(self, 'enhanced_receiver') and self.enhanced_receiver:
# Use the same transcriber as the receiver
self.transcriber = self.enhanced_receiver.transcriber
# Add TTS support
self.tts_manager = None
def setup_gpio_callbacks(self):
"""Setup PTT button callbacks"""
self.ptt_button.when_pressed = self.ptt_pressed
self.ptt_button.when_released = self.ptt_released
DebugConfig.debug_print(f"✓ GPIO setup: PTT=GPIO{self.ptt_button.pin}, LED=GPIO{self.led.pin}")
def list_audio_devices(self):
"""List all available audio devices"""
DebugConfig.debug_print("🎤 Available audio devices:")
for i in range(self.audio.get_device_count()):
info = self.audio.get_device_info_by_index(i)
if info['maxInputChannels'] > 0: # Has input capability
DebugConfig.debug_print(f" Device {i}: {info['name']} (inputs: {info['maxInputChannels']}, rate: {info['defaultSampleRate']})")
def setup_audio(self, force_device_selection=False):
"""Setup audio input and output with optional device selection"""
# create device manager with our config
device_manager = AudioDeviceManager(
mode=AudioManagerMode.INTERACTIVE,
config_file="audio_config.yaml",
radio_config=self.config
)
try:
# Device selection based on force flag or first-time setup
input_device, output_device = device_manager.setup_audio_devices(
force_selection=force_device_selection
)
# get audio parameters from device manager
params = device_manager.audio_params
# VERIFICATION: Ensure protocol requirements are met
if params['sample_rate'] != 48000:
DebugConfig.debug_print(f"⚠️ WARNING: Sample rate {params['sample_rate']} != 48000 (protocol requirement)")
params['sample_rate'] = 48000
if params['frame_duration_ms'] != 40:
DebugConfig.debug_print(f"⚠️ WARNING: Frame duration {params['frame_duration_ms']} != 40ms (protocol requirement)")
params['frame_duration_ms'] = 40
params['frames_per_buffer'] = 1920 # Recalculate
# CRITICAL: Enforce protocol requirements regardless of config
# These are protocol requirements and cannot be changed by users
protocol_sample_rate = 48000 # Protocol requirement
protocol_frame_duration_ms = 40 # Protocol requirement
protocol_frames_per_buffer = int(protocol_sample_rate * protocol_frame_duration_ms / 1000)
# Override any config values with protocol requirements
params['sample_rate'] = protocol_sample_rate
params['frame_duration_ms'] = protocol_frame_duration_ms
params['frames_per_buffer'] = protocol_frames_per_buffer
# Update our instance variables to match protocol requirements
self.sample_rate = protocol_sample_rate
self.samples_per_frame = protocol_frames_per_buffer
self.bytes_per_frame = self.samples_per_frame * 2
# # Update our instance variables to match selected params
# self.sample_rate = params['sample_rate']
# self.samples_per_frame = params['frames_per_buffer']
# self.bytes_per_frame = self.samples_per_frame * 2
DebugConfig.debug_print(f"🎵 Audio config: {params['sample_rate']}Hz, {params['frame_duration_ms']}ms frames")
DebugConfig.debug_print(f" Samples per frame: {params['frames_per_buffer']}")
DebugConfig.debug_print(f" Selected input device: {input_device}")
# set up input stream for the microphone
try:
self.audio_input_stream = self.audio.open(
format=pyaudio.paInt16,
channels=params['channels'],
rate=params['sample_rate'],
input=True,
input_device_index=input_device,
frames_per_buffer=params['frames_per_buffer'],
stream_callback=self.audio_callback
)
DebugConfig.debug_print("✓ Audio input stream ready with selected microphone")
except Exception as e:
DebugConfig.debug_print(f"✗ Audio input device setup error: {e}")
raise
# Store both devices and parameters for enhanced receiver
self.selected_input_device = input_device # For reference
self.selected_output_device = output_device # For received audio playback
self.audio_params = params
DebugConfig.debug_print("✅ Audio setup complete - input and output devices independently selected")
finally:
device_manager.cleanup()
def setup_enhanced_receiver_with_audio(self):
"""Setup enhanced receiver with audio output using independently selected output device"""
try:
from enhanced_receiver import EnhancedMessageReceiver
# Create enhanced receiver (UNCHANGED)
self.enhanced_receiver = EnhancedMessageReceiver(
listen_port=self.config.network.listen_port,
chat_interface=self.chat_interface,
block_list=[self.station_id.to_bytes()], # Block own frames only for now
)
# Setup audio output with the independently selected OUTPUT device
if hasattr(self, 'selected_output_device') and hasattr(self, 'audio_params'):
print(f"🔊 Setting up received audio playback:")
print(f" Using output device: {self.selected_output_device}")
print(f" Audio parameters: {self.audio_params['sample_rate']}Hz, {self.audio_params['channels']} channel(s)")
# Create audio output manager directly
from enhanced_receiver import AudioOutputManager
self.enhanced_receiver.audio_output = AudioOutputManager(self.audio_params)