'pySerial 2.6: specify end-of-line in readline()
I am sending commands to Eddie using pySerial. I need to specify a carriage-return in my readline, but pySerial 2.6 got rid of it... Is there a workaround?
Here are the Eddie command set is listed on the second and third pages of this PDF. Here is a backup image in the case where the PDF is inaccessible.
General command form:
Input: <cmd>[<WS><param1>...<WS><paramN>]<CR>
Response (Success): [<param1>...<WS><paramN>]<CR>
Response (Failure): ERROR[<SP>-<SP><verbose_reason>]<CR>
As you can see all responses end with a \r. I need to tell pySerial to stop.
What I have now:
def sendAndReceive(self, content):
logger.info('Sending {0}'.format(content))
self.ser.write(content + '\r')
self.ser.flush();
response = self.ser.readline() # Currently stops reading on timeout...
if self.isErr(response):
logger.error(response)
return None
else:
return response
Solution 1:[1]
From pyserial 3.2.1 (default from debian Stretch) read_until is available. if you would like to change cartridge from default ('\n') to '\r', simply do:
import serial
ser=serial.Serial('COM5',9600)
ser.write(b'command\r') # sending command
ser.read_until(b'\r') # read until '\r' appears
b'\r' could be changed to whatever you will be using as carriadge return.
Solution 2:[2]
from pyserial's documentation:
(sic)
Note:
The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module io is available.
EOL
To specify the EOL character for readline() or to use universal newline mode, it is advised to use io.TextIOWrapper:
import serial
import io
ser = serial.serial_for_url('loop://', timeout=1)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
sio.write(unicode("hello\n"))
sio.flush() # it is buffering. required to get the data out *now*
hello = sio.readline()
print hello == unicode("hello\n")
Solution 3:[3]
reading 10 data from port 3 with board rate 38400, The data is separated with \n character when comes in the incoming data
import serial as self
ser=self.Serial("COM3", 38400)
buffer = []
count = 0.0
c = "\0"
while count < 10:
c = "\0"
if ser.inWaiting():
while True:
val = ser.read(1)
if "\n" in val:
break
else:
c += val
buffer.append(c) # stores all data received into a list
count += 1
print buffer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Antony Hatchkins |
| Solution 2 | zmo |
| Solution 3 | sajin |
