socket testing

This commit is contained in:
Siwat Sirichai 2025-03-01 01:25:35 +07:00
parent 11c4d4acd9
commit b0790f0068
3 changed files with 177 additions and 26 deletions

View file

@ -6,7 +6,7 @@ import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Configuration for the Smart Board:
IP_ADDRESS = "10.10.4.173" # Replace with your board's IP
IP_ADDRESS = "10.10.4.58" # Replace with your board's IP
PORT = 4660
TIMEOUT = 5.0
@ -24,39 +24,29 @@ def main():
logging.debug(f"Connecting to {IP_ADDRESS}:{PORT}")
sock.connect((IP_ADDRESS, PORT))
logging.info("Connected.")
sock.settimeout(None) # disable timeout for indefinite receive
# Build "get_power" command
# Protocol: length=5, TV_ID, 'g' (get command), command_code (1 byte) and CR.
command_code = b'\x6C' # Power get command
command_code = b'\x67' # Power get command
length = 5
packet = struct.pack(">B2s1s1s1s", length, TV_ID, b'g', command_code, CR)
log_packet("Sent", packet)
sock.sendall(packet)
time.sleep(1) # Wait a bit for response
# Receive header first (expected 5 bytes):
header = sock.recv(5)
log_packet("Received", header)
if len(header) < 5:
logging.error("Incomplete header received.")
return
command_type = header[3:4]
if command_type != b'r':
logging.error(f"Unexpected response type: {command_type}")
return
# Wait a bit before reading the value bytes.
time.sleep(0.1)
value = sock.recv(3)
log_packet("Received", value)
if len(value) < 3:
logging.error("Incomplete value bytes received.")
return
power_state = value.decode()
logging.info(f"Power state: {power_state}")
time.sleep(1) # Increased delay to allow board time to respond
# Loop to receive data indefinitely:
while True:
try:
chunk = sock.recv(1024)
if chunk:
log_packet("Received", chunk)
# Do not break on empty chunk; keep the connection open
except Exception as ex:
logging.exception(f"Error receiving data: {ex}")
# Optionally break on critical errors:
# break
except Exception as ex:
logging.exception(f"Error during manual test: {ex}")
finally: