Sean McCarthy
Sean McCarthy

Reputation: 5578

What does the integer return value mean, when I send a serial port message to my modem in Python?

How do I interpret the returned 4 in the following code, which is trying to send a basic AT message to my SIMCom 7600A modem via the serial AT port /dev/ttyUSB3?

from serial import Serial

# If a "port" is given, then the port will be opened immediately.
ser = Serial(port="/dev/ttyUSB3", timeout=2, write_timeout=2)

# The following prints as "True"
print(ser.is_open)

# Turn GPS on
ser.write(b"AT\r\n")
>>> 4

Here's another example when I request to "see GPS info", which returns 13:

ser.write(b"AT+CGPSINFO\r\n")
>>> 13

And one final example when I request to activate the GPS, which also returns 13:

ser.write(b"AT+CGPS=1,1\r\n")
>>> 13

Thanks! -Sean

Upvotes: 0

Views: 563

Answers (1)

TayTay
TayTay

Reputation: 7170

It is returning the length of the data that is written. Here is the source for the write function:

    def write(self, data):
        """Output the given string over the serial port."""
        if not self.is_open:
            raise PortNotOpenError()
        #~ if not isinstance(data, (bytes, bytearray)):
            #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
        try:
            # must call overloaded method with byte array argument
            # as this is the only one not applying encodings
            self._port_handle.Write(as_byte_array(data), 0, len(data))
        except System.TimeoutException:
            raise SerialTimeoutException('Write timeout')
        return len(data)

Upvotes: 1

Related Questions