Following @ghp's suggestion, I modified the code to wait for the correct PDU length. The PDUs vary in length depending on the SMS content, so it's not a fixed size. I haven't tested it yet, as the device is at home; I'll test it after the weekend. Thank you all for your support, and I'll return to this topic on Monday.
Code:
import serialimport signalimport sysimport time# Serial port configurationPORT = "/dev/serial0" # Port 'serial0' instead of 'ttyS0'BAUDRATE = 19200 # Changed speed to 19200 bps# Interrupt handler function (Ctrl+C)def signal_handler(sig, frame): print("\nClosing program.") if ser.is_open: ser.close() sys.exit(0)# Register interrupt handler for Ctrl+Csignal.signal(signal.SIGINT, signal_handler)try: # Open serial port ser = serial.Serial(PORT, BAUDRATE, timeout=1) print(f"Connected to serial port {PORT} at baud rate {BAUDRATE}.") # Echo control variable echo_enabled = True while True: # Check if there is data on the serial port if ser.in_waiting > 0: # Use latin-1 encoding to decode the line line = ser.readline().decode('latin-1').strip() # Debugging - display the line print(f"Received: {line}") # Echo handling if echo_enabled: ser.write((line + "\r\n").encode('latin-1')) # AT command interpretation if line == "AT": ser.write(b"OK\r\n") # Connection confirmation print("Response: OK") elif line == "ATE0": # Disable echo echo_enabled = False ser.write(b"OK\r\n") print("Response: OK (Echo disabled)") elif line == "ATE1": # Enable echo echo_enabled = True ser.write(b"OK\r\n") print("Response: OK (Echo enabled)") elif line == "AT+CGMM": # Command to get model name ser.write(b"C35i\r\n") time.sleep(0.1) # Short delay for older devices print("Response: C35i") elif line.startswith("AT+CMGS="): # Sending SMS # Parse PDU length try: pdu_length = int(line.split('=')[1].strip()) print(f"Parsed PDU length: {pdu_length}") except ValueError: ser.write(b"ERROR\r\n") print("Response: ERROR - invalid PDU length") continue # Confirm ready to receive PDU data ser.write(b"> ") print("Response: > (Ready to receive PDU)") # Wait for PDU data of the specified length pdu_data = "" received_length = 0 while received_length < pdu_length: if ser.in_waiting > 0: # Read one byte of PDU byte = ser.read(1).decode('latin-1') pdu_data += byte received_length += 1 # Save PDU data to sms.dat file with open("sms.dat", "a") as file: file.write(f"{pdu_data}\n") print(f"SMS saved to sms.dat: {pdu_data}") # Confirm SMS reception and sending ser.write(b"\r\n+CMGS: 1\r\n") # Sent SMS ID ser.write(b"OK\r\n") print("Response: +CMGS: 1, OK") else: #ser.write(b"ERROR\r\n") print("Response: ERROR - unknown command")except serial.SerialException as e: print(f"Serial port error: {e}")finally: if ser.is_open: ser.close()
Statistics: Posted by dojnikowski — Fri Nov 08, 2024 8:36 am