-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsofabaton-server.py
More file actions
395 lines (325 loc) · 14.1 KB
/
sofabaton-server.py
File metadata and controls
395 lines (325 loc) · 14.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
#!/usr/bin/env python3
"""
SofaBaton Server - Listen for Hub Connection
"""
import socket
import sys
import time
import argparse
class SofaBatonServer:
def __init__(self, listen_port=8002, hub_ip=None, hub_id="03862a23"):
self.listen_port = listen_port
self.hub_ip = hub_ip
self.hub_id = hub_id
self.server_sock = None
self.client_sock = None
self.authenticated = False
self.running = False
def get_local_ip(self):
"""Get local IP address that can reach the hub"""
try:
# Create a socket to the hub to determine local IP
temp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
temp_sock.connect((self.hub_ip, 8102))
local_ip = temp_sock.getsockname()[0]
temp_sock.close()
return local_ip
except Exception:
# Fallback to localhost if can't determine
return "127.0.0.1"
def get_check_code(self, data: bytes) -> int:
# Sum all bytes as unsigned
total = sum(b & 0xFF for b in data)
# Return only the low byte of the sum
return total & 0xFF
def create_discovery_packet(self):
"""Create UDP discovery packet with local IP and proper checksum"""
# Get local IP that hub should connect back to
local_ip = self.get_local_ip()
print(f"🔍 Local IP for hub callback: {local_ip}")
# Parse original packet structure:
# a55a0cc3e0df03862a23c0a828551f42a9
# a55a - header
# 0c - length (12 bytes)
# c3 - command
# e0df - identifier
# 03862a23 - Device identifier (4 bytes)
# c0a82855 - IP address 192.168.40.85
# 1f42 - Port 8002 (little-endian)
# a9 - Checksum
# Build packet with our local IP
packet = bytearray()
packet.extend([0xA5, 0x5A]) # Header
packet.extend([0x0C]) # Length
packet.extend([0xC3]) # Command
packet.extend([0xE0, 0xDF]) # Identifier
# Hub identifier (configurable, default from original capture)
packet.extend(bytes.fromhex(self.hub_id))
# Convert local IP to bytes
ip_parts = [int(part) for part in local_ip.split('.')]
packet.extend(ip_parts)
# Port number (8002 = 0x1f42, big-endian)
port = self.listen_port
port_bytes = port.to_bytes(2, byteorder='big')
packet.extend(port_bytes)
# Calculate and append checksum
checksum = self.get_check_code(packet)
packet.append(checksum)
return bytes(packet)
def send_udp_discovery(self):
"""Send UDP discovery packet to hub to trigger connection"""
if not self.hub_ip:
print("❌ No hub IP provided for UDP discovery")
return False
try:
print(f"📡 Sending UDP discovery to {self.hub_ip}:8102")
# Create discovery packet with local IP
discovery_packet = self.create_discovery_packet()
# Create UDP socket
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_sock.settimeout(5)
# Send discovery packet
udp_sock.sendto(discovery_packet, (self.hub_ip, 8102))
print(f"📤 Sent UDP discovery: {discovery_packet.hex()}")
udp_sock.close()
print("✅ UDP discovery sent - hub should connect back now")
return True
except Exception as e:
print(f"❌ UDP discovery failed: {e}")
return False
def start_server(self):
"""Start listening for hub connections"""
try:
print(f"🚀 Starting SofaBaton server on port {self.listen_port}")
self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_sock.bind(('', self.listen_port))
self.server_sock.listen(1)
self.running = True
print(f"👂 Listening on 0.0.0.0:{self.listen_port} for hub connection...")
print("💡 Make sure your hub is configured to connect to this IP")
return True
except Exception as e:
print(f"❌ Failed to start server: {e}")
return False
def wait_for_hub(self, timeout=60):
"""Wait for hub to connect"""
try:
print(f"⏳ Waiting up to {timeout} seconds for hub connection...")
self.server_sock.settimeout(timeout)
self.client_sock, addr = self.server_sock.accept()
print(f"✅ Hub connected from {addr}")
# Set timeout for client socket
self.client_sock.settimeout(10)
return True
except socket.timeout:
print("⏰ Timeout waiting for hub connection")
return False
except Exception as e:
print(f"❌ Error waiting for connection: {e}")
return False
def handle_authentication(self):
"""Handle authentication when hub connects"""
if not self.client_sock:
print("❌ No client connection")
return False
try:
print("🔐 Sending authentication request to hub...")
# Send auth request to hub (we initiate)
auth_request = bytes([0xA5, 0x5A, 0x00, 0x01, 0x00])
print(f"📤 Sending auth request: {auth_request.hex()}")
self.client_sock.send(auth_request)
# Wait for auth response from hub
print("⏳ Waiting for auth response...")
data = self.client_sock.recv(1024)
if data:
print(f"📥 Received from hub: {data.hex()}")
# Check if it's an auth response (should be a55a with device info)
if len(data) >= 5 and data[0:2] == bytes([0xA5, 0x5A]):
print("🔑 Received valid auth response from hub")
print(f"📋 Response length: {len(data)} bytes")
print(f"📋 Response data: {data.hex()}")
self.authenticated = True
print("✅ Authentication completed")
return True
else:
print(f"❌ Invalid auth response format: {data.hex()}")
return False
else:
print("❌ No data received from hub")
return False
except Exception as e:
print(f"❌ Authentication failed: {e}")
return False
def send_command(self, device_id=0x02, button_code=0xB6):
"""Send command to hub with device ID and button code"""
if not self.authenticated:
print("❌ Not authenticated!")
return False
if not self.client_sock:
print("❌ No connection to hub")
return False
try:
# Command format: a55a 02 3f [device_id] [button_code] [checksum]
packet = bytearray([0xA5, 0x5A, 0x02, 0x3F, device_id, button_code])
# Calculate checksum
checksum = self.get_check_code(packet)
packet.append(checksum)
print(f"📤 Sending command - Device: {device_id:02x}, Button: {button_code:02x}")
print(f"📤 Packet: {packet.hex()}")
self.client_sock.send(bytes(packet))
# Try to get response
try:
self.client_sock.settimeout(2)
response = self.client_sock.recv(1024)
if response:
print(f"📥 Hub response: {response.hex()}")
else:
print("📥 No response from hub")
except socket.timeout:
print("📥 No response from hub (timeout)")
return True
except Exception as e:
print(f"❌ Command failed: {e}")
return False
def stop(self):
"""Stop the server"""
self.running = False
if self.client_sock:
self.client_sock.close()
self.client_sock = None
if self.server_sock:
self.server_sock.close()
self.server_sock = None
print("🔌 Server stopped")
def create_parser():
parser = argparse.ArgumentParser(
description='SofaBaton Server - Control SofaBaton Hub via TCP/UDP',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Quick commands using shortcuts (uses default device 02)
%(prog)s 192.168.40.65 --button volumeup # Volume up
%(prog)s 192.168.40.65 --button mute # Mute
%(prog)s 192.168.40.65 --button menu # Menu
%(prog)s 192.168.40.65 --button back # Back button
%(prog)s 192.168.40.65 -b nav_up # Navigation up
# Send hex commands (default device is '02')
%(prog)s 192.168.40.65 --button b6 # Volume up (hex)
%(prog)s 192.168.40.65 --device 01 --button a0 # Button a0 to device 01
%(prog)s 192.168.40.65 -d 03 -b c5 # Button c5 to device 03
# Interactive mode for testing
%(prog)s 192.168.40.65 --interactive # Interactive mode
# Button shortcuts available:
# volumeup, volumedown, mute, menu, back, nav_up, nav_down, nav_right
"""
)
# Required arguments
parser.add_argument('hub_ip',
help='SofaBaton hub IP address')
# Mode selection (optional for special modes)
parser.add_argument('--interactive', action='store_true',
help='Enter interactive mode for testing multiple commands')
# Command arguments for send mode
parser.add_argument('--device', '-d',
default='02',
help='Target device ID (hex: 01, 02, 03, etc.) (default: 02)')
parser.add_argument('--button', '-b',
help='Button code (hex: a0, b6, b9, etc.) or shortcut (volumeup, mute, menu, back, nav_up, etc.)')
# Optional arguments
parser.add_argument('--port', '-p',
type=int, default=8002,
help='TCP port (default: 8002)')
parser.add_argument('--hub-id',
default='03862a23',
help='Hub identifier for UDP discovery (default: 03862a23)')
return parser
def main():
parser = create_parser()
args = parser.parse_args()
if args.interactive:
# Interactive mode
mode = 'interactive'
device_id = None
button_code = None
elif args.button is not None:
# Send mode (default)
# Parse device ID (has default)
try:
device_id = int(args.device, 16)
if not (0 <= device_id <= 255):
parser.error("device must be valid hex value (00-FF)")
except ValueError:
parser.error("device must be valid hex value")
# Parse button code (allow shortcuts)
button_shortcuts = {
# Volume controls
'volumeup': 0xb6,
'volumedown': 0xb9,
'volume_up': 0xb6,
'volume_down': 0xb9,
'vol_up': 0xb6,
'vol_down': 0xb9,
# Navigation (conflicts with volume, so using nav_ prefix)
'nav_up': 0xb3,
'nav_down': 0xb2,
'nav_right': 0xb1,
# Common buttons
'mute': 0xb8,
'menu': 0xb5,
'back': 0xb4,
}
if args.button.lower() in button_shortcuts:
button_code = button_shortcuts[args.button.lower()]
else:
try:
button_code = int(args.button, 16)
if not (0 <= button_code <= 255):
parser.error("button must be valid hex value (00-FF)")
except ValueError:
parser.error("button must be valid hex value or shortcut (volumeup, mute, menu, back, nav_up, etc.)")
mode = 'send'
else:
parser.error("Must specify --button or --interactive")
server = SofaBatonServer(listen_port=args.port, hub_ip=args.hub_ip, hub_id=args.hub_id)
print(f"🔧 Configuration:")
print(f" Hub IP: {args.hub_ip}")
print(f" Port: {args.port}")
print(f" Hub ID: {args.hub_id}")
if mode == 'send':
print(f" Command: Device {device_id:02x}, Button {button_code:02x}")
else:
print(f" Mode: {mode}")
print()
try:
# Start server first - must be listening before UDP discovery
print("🔍 Step 1: Start TCP Server")
if not server.start_server():
return
# Give server time to fully bind and be ready for connections
print("⏳ Ensuring TCP server is ready...")
#time.sleep(1)
# Send UDP discovery for all modes (always needed)
print("\n📡 Step 2: UDP Discovery")
if not server.send_udp_discovery():
return
# Wait for hub connection (should happen quickly after UDP discovery)
print("\n👂 Step 3: Wait for Hub Connection")
if not server.wait_for_hub():
return
# Authenticate first (always needed)
print("\n🔐 Step 4: Authentication")
if server.handle_authentication():
if mode == "send":
print(f"\n📤 Step 5: Send Command - Device: {device_id:02x}, Button: {button_code:02x}")
server.send_command(device_id, button_code)
else:
print("✅ Authentication successful - ready for commands")
else:
print("❌ Authentication failed")
except KeyboardInterrupt:
print("\n⏹ Interrupted by user")
finally:
server.stop()
if __name__ == "__main__":
main()