[Twisted-Python] Question about SerialPort

Jason Valenzuela jvalenzuela1977 at gmail.com
Thu Jan 20 11:34:52 EST 2011


On 1/20/2011 9:42 PM, James Y Knight wrote:
> On Jan 20, 2011, at 6:32 AM, Albert Brandl wrote:
>> The main problem seems to be the specification of Modbus RTU. RTU
>> messages are separated by time gaps that are at least 3.5 characters
>> long. Unfortunately, this is the only reliable way for separating
>> messages - there is no length header or something similar. The
>> specification does define a trailing CRC, though.
>
> I don't think you'll ever be able to do this reliably in Python. At 9600 baud, 3.5 characters is just about 275hz (9600/10/3.5). Linux schedules process at around 500hz. So, unless you use real-time scheduling, I think you have no guarantee that you'll be able to detect such a gap at all -- some other process may be running and you may completely miss it. And you can't reasonably use real-time scheduling in python...
>
> On the other hand, are you sure you need this? http://www.libmodbus.org/ seems to have code which figures out what length packets should be, and no code to detect a 3.5char delay between packets. That seems much more reliable.
>
> It also doesn't seem to have any code to ensure a 3.5char between sent packets, which indicates to me that either it's totally brokem or else that not even the hardware end actually uses a 3.5char delay to determine packet boundaries...I'd guess the second, since even on an embedded CPU, it's much trickier to ensure the appropriate serial port timing than to simply count the correct number of bytes.


Building upon James' reply a little further, I recently did a ModBus RTU 
implementation on a microcontroller and you need both a 1.5 and 3.5 
character timer for correct operation. With the micro, I used hardware 
timers with uS resolution synchronized to incoming characters via the 
UART interrupt. As James mentions, user-space Python is simply too far 
from the hardware to do this sort of thing. You'd probably have to write 
a custom UART driver and run it on a RTOS to get correct timing. That 
being said, you can probably write something that will work 99.9% of the 
time, but may not respond correctly for some weird corner case scenarios.


Jason Valenzuela



More information about the Twisted-Python mailing list