Search code examples
pythonserial-portpyserialsocat

"AT+CGPSINFO" command works with Socat but not with PySerial


The following Socat command returns GPS data, as needed:

echo 'AT+CGPSINFO' | socat - /dev/ttyUSB3,crnl

+CGPSINFO: 5100.505778,N,11404.437214,W,031120,175538.0,1076.7,0.0,348.0

OK

Now I want to do the same thing in Python using PySerial, but I'm getting an error.

from serial import Serial
import time

def sleep_for_x_seconds(sleep_secs=0.25):
    print(f"Sleeping for {sleep_secs} seconds...")
    time.sleep(sleep_secs)

def write_to_modem(modem, to_write, sleep=True, sleep_secs=0.25, readlines=True):
    print(f"Writing {to_write}...")
    modem.write(to_write)
    if sleep:
        sleep_for_x_seconds(sleep_secs)
    if readlines:
        print(modem.readlines())

sleep_secs = 0.25
port = "/dev/ttyUSB3"
print(f"Initializing modem on port '{port}'...")
modem = Serial()
modem.port = port
modem.timeout = 1  # How long to wait when reading lines
modem.writeTimeout = 1
sleep_for_x_seconds(sleep_secs)

print("Opening modem and flushing input and output...")
modem.open()
modem.flushInput()
modem.flushOutput()
sleep_for_x_seconds(sleep_secs)

# This first command returns [b'\r\n', b'OK\r\n']
write_to_modem(modem, b"AT\r\n", sleep=True, sleep_secs=sleep_secs, readlines=True)

# This second command returns [b'\r\n', b'ERROR\r\n'] for some reason... why?
write_to_modem(modem, b"AT^CGPSINFO=1\r\n", sleep=True, sleep_secs=sleep_secs, readlines=True)

modem.flushInput()
modem.close()

Here's the full output log from running the above program (line breaks added for readability):

Initializing modem on port '/dev/ttyUSB3'...
Sleeping for 0.25 seconds...

Opening modem and flushing input and output...
Sleeping for 0.25 seconds...

Writing b'AT\r\n'...
Sleeping for 0.25 seconds...
[b'\r\n', b'OK\r\n']

Writing b'AT^CGPSINFO=1\r\n'...
Sleeping for 0.25 seconds...
[b'\r\n', b'ERROR\r\n']

Why am I getting the error "[b'\r\n', b'ERROR\r\n']" when running PySerial, when running the following command in Socat works properly?

echo 'AT+CGPSINFO' | socat - /dev/ttyUSB3,crnl

+CGPSINFO: 5100.505778,N,11404.437214,W,031120,175538.0,1076.7,0.0,348.0

OK

Solution

  • As @meuh showed in the comments, I was using ^ instead of +, so changing it to b"AT+CGPSINFO=1\r\n" solved the problem...