Tcp To Serial Python

Posted by admin
Permalink

/usr/bin/python # (C) 2002-2006 Chris Liechti # redirect data from a TCP/IP connection to a serial port and vice versa # requires Python 2.2 'cause socket.sendall is used import sys, os, serial, threading, socket try: True except NameError: True = 1 False = 0 class Redirector: def __init__(self, serial,. This module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX, Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automatically selects the appropriate backend.

Join GitHub today

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Sign up
Find file Copy path
1 contributor
Tcp To Serial Python
#!/usr/bin/env python
#
# Redirect data from a TCP/IP connection to a serial port and vice versa.
#
# (C) 2002-2016 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier: BSD-3-Clause
import sys
import socket
import serial
import serial.threaded
import time
classSerialToNet(serial.threaded.Protocol):
''serial->socket''
def__init__(self):
self.socket =None
def__call__(self):
returnself
defdata_received(self, data):
ifself.socket isnotNone:
self.socket.sendall(data)
if__name__'__main__': # noqa
import argparse
parser = argparse.ArgumentParser(
description='Simple Serial to Network (TCP/IP) redirector.',
epilog=''
NOTE: no security measures are implemented. Anyone can remotely connect
to this service over the network.
Only one connection at once is supported. When the connection is terminated
it waits for the next connect.
'')
parser.add_argument(
'SERIALPORT',
help='serial port name')
parser.add_argument(
'BAUDRATE',
type=int,
nargs='?',
help='set baud rate, default: %(default)s',
default=9600)
parser.add_argument(
'-q', '--quiet',
action='store_true',
help='suppress non error messages',
default=False)
parser.add_argument(
'--develop',
action='store_true',
help='Development mode, prints Python internals on errors',
default=False)
group = parser.add_argument_group('serial port')
group.add_argument(
'--bytesize',
choices=[5, 6, 7, 8],
type=int,
help='set bytesize, one of {5 6 7 8}, default: 8',
default=8)
group.add_argument(
'--parity',
choices=['N', 'E', 'O', 'S', 'M'],
type=lambdac: c.upper(),
help='set parity, one of {N E O S M}, default: N',
default='N')
group.add_argument(
'--stopbits',
choices=[1, 1.5, 2],
type=float,
help='set stopbits, one of {1 1.5 2}, default: 1',
default=1)
group.add_argument(
'--rtscts',
action='store_true',
help='enable RTS/CTS flow control (default off)',
default=False)
group.add_argument(
'--xonxoff',
action='store_true',
help='enable software flow control (default off)',
default=False)
group.add_argument(
'--rts',
type=int,
help='set initial RTS line state (possible values: 0, 1)',
default=None)
group.add_argument(
'--dtr',
type=int,
help='set initial DTR line state (possible values: 0, 1)',
default=None)
group = parser.add_argument_group('network settings')
exclusive_group = group.add_mutually_exclusive_group()
exclusive_group.add_argument(
'-P', '--localport',
type=int,
help='local TCP port',
default=7777)
exclusive_group.add_argument(
'-c', '--client',
metavar='HOST:PORT',
help='make the connection as a client, instead of running a server',
default=False)
args = parser.parse_args()
# connect to serial port
ser = serial.serial_for_url(args.SERIALPORT, do_not_open=True)
ser.baudrate = args.BAUDRATE
ser.bytesize = args.bytesize
ser.parity = args.parity
ser.stopbits = args.stopbits
ser.rtscts = args.rtscts
ser.xonxoff = args.xonxoff
if args.rts isnotNone:
ser.rts = args.rts
if args.dtr isnotNone:
ser.dtr = args.dtr
ifnot args.quiet:
sys.stderr.write(
'--- TCP/IP to Serial redirect on {p.name}{p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---n'
'--- type Ctrl-C / BREAK to quitn'.format(p=ser))
try:
ser.open()
except serial.SerialException as e:
sys.stderr.write('Could not open serial port {}: {}n'.format(ser.name, e))
sys.exit(1)
ser_to_net = SerialToNet()
serial_worker = serial.threaded.ReaderThread(ser, ser_to_net)
serial_worker.start()
ifnot args.client:
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(('', args.localport))
srv.listen(1)
try:
intentional_exit =False
whileTrue:
if args.client:
host, port = args.client.split(':')
sys.stderr.write('Opening connection to {}:{}..n'.format(host, port))
client_socket = socket.socket()
try:
client_socket.connect((host, int(port)))
except socket.error as msg:
sys.stderr.write('WARNING: {}n'.format(msg))
time.sleep(5) # intentional delay on reconnection as client
continue
sys.stderr.write('Connectedn')
client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
#~ client_socket.settimeout(5)
else:
sys.stderr.write('Waiting for connection on {}..n'.format(args.localport))
client_socket, addr = srv.accept()
sys.stderr.write('Connected by {}n'.format(addr))
# More quickly detect bad clients who quit without closing the
# connection: After 1 second of idle, start sending TCP keep-alive
# packets every 1 second. If 3 consecutive keep-alive packets
# fail, assume the client is gone and close the connection.
try:
client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1)
client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
exceptAttributeError:
pass#XXX not available on windows
client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
try:
ser_to_net.socket = client_socket
# enter network <-> serial loop
whileTrue:
try:
data = client_socket.recv(1024)
ifnot data:
break
ser.write(data) # get a bunch of bytes and send them
except socket.error as msg:
if args.develop:
raise
sys.stderr.write('ERROR: {}n'.format(msg))
# probably got disconnected
break
exceptKeyboardInterrupt:
intentional_exit =True
raise
except socket.error as msg:
if args.develop:
raise
sys.stderr.write('ERROR: {}n'.format(msg))
finally:
ser_to_net.socket =None
sys.stderr.write('Disconnectedn')
client_socket.close()
if args.client andnot intentional_exit:
time.sleep(5) # intentional delay on reconnection as client
exceptKeyboardInterrupt:
pass
sys.stderr.write('n--- exit ---n')
serial_worker.stop()
  • Copy lines
  • Copy permalink

Important

Note This is a Major release and might affect your existing Async client implementation. Refer examples on how to use the latest async clients.

Summary

Pymodbus is a full Modbus protocol implementation using twisted for itsasynchronous communications core. It can also be used without any thirdparty dependencies (aside from pyserial) if a more lightweight project isneeded. Furthermore, it should work fine under any python version > 2.7(including python 3+)

Features

Client Features

  • Full read/write protocol on discrete and register
  • Most of the extended protocol (diagnostic/file/pipe/setting/information)
  • TCP, UDP, Serial ASCII, Serial RTU, and Serial Binary
  • asynchronous(powered by twisted/tornado/asyncio) and synchronous versions
  • Payload builder/decoder utilities
  • Pymodbus REPL for quick tests

Server Features

  • Can function as a fully implemented modbus server
  • TCP, UDP, Serial ASCII, Serial RTU, and Serial Binary
  • asynchronous(powered by twisted) and synchronous versions
  • Full server control context (device information, counters, etc)
  • A number of backing contexts (database, redis, sqlite, a slave device)

Use Cases

Although most system administrators will find little need for a Modbusserver on any modern hardware, they may find the need to query devices ontheir network for status (PDU, PDR, UPS, etc). Since the library is writtenin python, it allows for easy scripting and/or integration into their existingsolutions.

Continuing, most monitoring software needs to be stress tested againsthundreds or even thousands of devices (why this was originally written), butgetting access to that many is unwieldy at best. The pymodbus server will allowa user to test as many devices as their base operating system will allow (allowin this case means how many Virtual IP addresses are allowed).

Tcp To Serial Python

For more information please browse the project documentation:

http://riptideio.github.io/pymodbus/orhttp://readthedocs.org/docs/pymodbus/en/latest/index.html

Example Code

For those of you that just want to get started fast, here you go:

For more advanced examples, check out the examples included in therespository. If you have created any utilities that meet a specificneed, feel free to submit them so others can benefit.

Also, if you have questions, please ask them on the mailing listso that others can benefit from the results and so that I cantrace them. I get a lot of email and sometimes these requestsget lost in the noise: http://groups.google.com/group/pymodbus orat gitter: https://gitter.im/pymodbus_dev/Lobby

Pymodbus REPL (Read Evaluate Procee Loop)

Starting with Pymodbus 2.x, pymodbus library comes with handyPymodbus REPL to quickly run the modbus clients in tcp/rtu modes.

Pymodbus REPL comes with many handy features such as payload decoderto directly retrieve the values in desired format and supports allthe diagnostic function codes directly .

For more info on REPL refer Pymodbus REPL

Installing

You can install using pip or easy install by issuing the followingcommands in a terminal window (make sure you have correctpermissions or a virtualenv currently running):

Python Serial To Tcp Modbus

To Install pymodbus with twisted support run:

To Install pymodbus with tornado support run:

To Install pymodbus REPL:

Otherwise you can pull the trunk source and install from there:

Either method will install all the required dependencies(at their appropriate versions) for your current python distribution.

If you would like to install pymodbus without the twisted dependency,simply edit the setup.py file before running easy_install and commentout all mentions of twisted. It should be noted that without twisted,one will only be able to run the synchronized version as theasynchronous versions uses twisted for its event loop.

Current Work In Progress

Since I don't have access to any live modbus devices anymoreit is a bit hard to test on live hardware. However, if you wouldlike your device tested, I accept devices via mail or by IP address.

That said, the current work mainly involves polishing the library asI get time doing such tasks as:

  • Make PEP-8 compatible and flake8 ready
  • Fixing bugs/feature requests
  • Architecture documentation
  • Functional testing against any reference I can find
  • The remaining edges of the protocol (that I think no one uses)
  • Asynchronous clients with support to tornado , asyncio

Development Instructions

The current code base is compatible with both py2 and py3.Use make to perform a range of activities

Contributing

Just fork the repo and raise your PR against dev branch.

License Information

Pymodbus is built on top of code developed from/by:
Python
  • Copyright (c) 2001-2005 S.W.A.C. GmbH, Germany.
  • Copyright (c) 2001-2005 S.W.A.C. Bohemia s.r.o., Czech Republic.
  • Hynek Petrak, https://github.com/HynekPetrak
  • Twisted Matrix

Tcp To Serial Python Number

Released under the BSD License

Iruvar bgm mp3 free download. For the cost of a used paperback, we can share a book online forever. If everyone chips in $5, we can keep this going for free.