#!/usr/bin/env python
# -*- coding: utf_8 -*-
"""
Modbus TestKit: Implementation of Modbus protocol in python
(C)2009 - Luc Jean - luc.jean@gmail.com
(C)2009 - Apidev - http://www.apidev.fr
This is distributed under GNU LGPL license, see license.txt
"""
import sys
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp
def main():
"""main"""
logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")
try:
#Create the server
server = modbus_tcp.TcpServer()
logger.info("running...")
logger.info("enter 'quit' for closing the server")
server.start()
slave_1 = server.add_slave(1)
slave_1.add_block('0', cst.HOLDING_REGISTERS, 0, 100)
while True:
cmd = sys.stdin.readline()
args = cmd.split(' ')
if cmd.find('quit') == 0:
sys.stdout.write('bye-bye\r\n')
break
elif args[0] == 'add_slave':
slave_id = int(args[1])
server.add_slave(slave_id)
sys.stdout.write('done: slave %d added\r\n' % slave_id)
elif args[0] == 'add_block':
slave_id = int(args[1])
name = args[2]
block_type = int(args[3])
starting_address = int(args[4])
length = int(args[5])
slave = server.get_slave(slave_id)
slave.add_block(name, block_type, starting_address, length)
sys.stdout.write('done: block %s added\r\n' % name)
elif args[0] == 'set_values':
slave_id = int(args[1])
name = args[2]
address = int(args[3])
values = []
for val in args[4:]:
values.append(int(val))
slave = server.get_slave(slave_id)
slave.set_values(name, address, values)
values = slave.get_values(name, address, len(values))
sys.stdout.write('done: values written: %s\r\n' % str(values))
elif args[0] == 'get_values':
slave_id = int(args[1])
name = args[2]
address = int(args[3])
length = int(args[4])
slave = server.get_slave(slave_id)
values = slave.get_values(name, address, length)
sys.stdout.write('done: values read: %s\r\n' % str(values))
else:
sys.stdout.write("unknown command %s\r\n" % args[0])
finally:
server.stop()
if __name__ == "__main__":
main()
服务端启动
#!/usr/bin/env python
# -*- coding: utf_8 -*-
"""
Modbus TestKit: Implementation of Modbus protocol in python
(C)2009 - Luc Jean - luc.jean@gmail.com
(C)2009 - Apidev - http://www.apidev.fr
This is distributed under GNU LGPL license, see license.txt
"""
from __future__ import print_function
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp, hooks
import logging
def main():
"""main"""
logger = modbus_tk.utils.create_logger("console", level=logging.DEBUG)
def on_after_recv(data):
master, bytes_data = data
logger.info(bytes_data)
hooks.install_hook('modbus.Master.after_recv', on_after_recv)
try:
def on_before_connect(args):
master = args[0]
logger.debug("on_before_connect {0} {1}".format(master._host, master._port))
hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect)
def on_after_recv(args):
response = args[1]
logger.debug("on_after_recv {0} bytes received".format(len(response)))
hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv)
# Connect to the slave
master = modbus_tcp.TcpMaster()
master.set_timeout(5.0)
logger.info("connected")
# logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3))
# logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='f'))
# Read and write floats
master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[3.14], data_format='>f')
logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='>f'))
master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=2, output_value=[3.14], data_format='>f')
logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 2, 2, data_format='>f'))
# # send some queries
# logger.info(master.execute(1, cst.READ_COILS, 0, 10))
# logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8))
# logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3))
# logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12))
# logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1))
# logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54))
# logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1]))
# logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12)))
#
except modbus_tk.modbus.ModbusError as exc:
logger.error("%s- Code=%d", exc, exc.get_exception_code())
if __name__ == "__main__":
main()
写入值:写入两个float值
使用modbusscan进行展示