Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1251

Python • Python serial programing

$
0
0
Hi,
I'm not a programmer; I just occasionally code a bit. I thought this task wouldn't be too complicated, but...

I have an old device that sends reports via a serial port in the form of SMS. Normally, a Siemens C35i phone was connected to it, and it handled the message sending. Unfortunately, it's an old phone, and I would like to replace it somehow. I decided to write a simple emulator in Python that will receive SMS messages from the device on a Raspberry Pi and, for example, send them as an email. Everything works almost fine, but unfortunately, it's acting strangely: when the device sends the first SMS, I don’t see it, even though everything appears to be correct. This SMS only appears when the device sends the second SMS, but then I don’t see the second one, and so on. I'm not a professional and I don’t really know what I’m doing wrong :( I’m attaching my simple initial code and the program log.

Code:

 import serialimport signalimport sysimport time# Serial port configurationPORT = "/dev/serial0"  # Use 'serial0' port instead of 'ttyS0'BAUDRATE = 19200       # Set baud rate 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 data is available on the serial port        if ser.in_waiting > 0:            # Decode the line using latin-1 encoding            line = ser.readline().decode('latin-1').strip()                        # Debugging - display the received 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 acknowledgment                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                # Ready for receiving PDU data                ser.write(b"> ")                print("Response: > (Ready for PDU input)")                                # Wait for PDU data                pdu_data = ""                while True:                    if ser.in_waiting > 0:                        # Read the next PDU line                        pdu_line = ser.readline().decode('latin-1').strip()                        data = ser.readline()  # Read a single line                        print(data.decode('latin-1').strip())                        # Check if it's the end (Ctrl+Z) - ASCII code 26                        if pdu_line == chr(26):                            break  # End PDU data reception                                                # Add the PDU line to the data                        pdu_data += pdu_line                # 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}")                                # Acknowledge receipt and send SMS                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()
example of output:

Code:

 Response: OK (Echo off)Received: AT+CMGS=75Response: > (Ready to receive PDU)SMS saved to sms.dat:Response: +CMGS: 1, OKReceived:--------------this is where the first read ends, but PDU is missing----------------on the next line, there is first SMS PDU data, but it only appears when the second SMS is sent, though as you can see, the PDU of the second SMS doesn’t appear despite the messages indicating it was received-----------------------------------------------------------------------------------0011PDU DATA PDU DATA PDU DATA 00000000ATE0Response: ERROR - unknown command——second SMS——Received: ATE0Response: OK (Echo off)Received: AT+CMGS=75Response: > (Ready to receive PDU)SMS saved to sms.dat:Response: +CMGS: 1, OK
I suspect that the data is being stored in some sort of buffer, but how can I make it display immediately after reading, rather than only when the next SMS is added to the buffer? I’m not very familiar with this type of communication; this is my first program of this kind.

summary:

I would like the script to emulate a Siemens phone in terms of receiving messages sent by an external device. The device uses AT commands sent to the phone, and my script should receive these commands and send back the correct responses, just like an old phone would. The SMS is sent in PDU format, but that's not a problem, I have scripts for it. The messages are also being received, but the only frustrating issue is the lack of the current message content in the script's output. The message only appears when the device sends another SMS, but even then, the current one is missing and only the previous one shows up.

Best Regards Jack

Statistics: Posted by dojnikowski — Thu Nov 07, 2024 4:29 pm



Viewing all articles
Browse latest Browse all 1251

Trending Articles