Rutger
Rutger

Reputation: 43

Python read serial (RS-232) data over TCP/IP

I am using a Moxa NPort 5110 serial-to-ethernet adapter to transfer serial data over a TCP/IP connection to my computer on port 4001.

I am able to create a socket connection on localhost:4001 to receive the data. The problem is that I can not use the data because it is not clean, it contains RS-232 bits.

This is the code I used to create the socket connection and read the unclean data:

import socket 
host = '' 
port = 4001 
backlog = 5 
size = 1024 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host,port)) 
s.listen(backlog) 
while 1: 
    client, address = s.accept() 
    data = client.recv(size) 
    if data: 
        print(data)
    client.close()

Then I tried to use pyserial to make a socket connection and let pyserial interpret the data. Code:

import serial
ser = serial.serial_for_url("socket://localhost:4001/logging=debug")
data = ser.read(8)
if data:
    print(data)
    ser.flushOutput()
ser.close()

When I use this code I receive a ConnectionRefusedError.

Any advice on how to establish a socket connection and use pyserial to read the data?

Upvotes: 4

Views: 22563

Answers (1)

Bart Friederichs
Bart Friederichs

Reputation: 33511

I have used the Moxa N-Ports a lot, and whenever garbage data arrives on the TCP socket, it was because there was a mismatch in serial settings between the N-port's serial port and the serial device you are connecting to (*). Make sure the settings of both RS-232 connected device are exactly identical.

To comment on your comment: it has nothing to do with the TCP/IP listener mis-interpreting the data, but with the N-port's UART being misconfigured. For example, when the N-port is set to receive stopbits, but the serial device isn't sending it, it will get confused and set garbage data over the TCP/IP link. The same applies to native serial ports on a computer.

(*) other possible culprits are of course electrical problems as interference or incorrect grounding.

Upvotes: 2

Related Questions