七、Modbus工具

先安装modbus_tk和serial.感谢梁工替我写的这个工具

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

from modbus_tk import defines as funCode
from modbus_tk.modbus_rtu import RtuServer
import serial
import time
from modbus_tk import hooks

#
server = RtuServer(serial.Serial(port='/dev/tty.wchusbserial1420', baudrate=115200, bytesize=8, parity='N', stopbits=1, xonxoff=0))
# server = RtuServer(serial.Serial(port=0, baudrate=38400, bytesize=8, parity='N', stopbits=1, xonxoff=0))
slave = server.add_slave(1)

def before_handle_request_hook(argument):
#     print('modbus_rtu.RtuServer.before_write')    
    data = argument[1]
    strData = 'RX: '
    for i in argument[1]:
        strData = strData + '0x%02x ' %(i)
    print(strData)

def after_handle_request_hook(argument):
#     print('modbus_rtu.RtuServer.after_read')  
    strData = 'TX: '
    for i in argument[1]:
        strData = strData + '0x%02x ' %(i)
    print(strData)


def slave_init():
    slave.add_block('holdingReg', funCode.HOLDING_REGISTERS, 0x2000, 20)
    hooks.install_hook('modbus.Server.before_handle_request', before_handle_request_hook)
    hooks.install_hook('modbus.Server.after_handle_request', after_handle_request_hook)

def slave_poll():
    server.start()
    print('server.start....')
    while True:
        data = slave.get_values('holdingReg', 0x2000, 20)
        #print(type(data))
        data = data
        time.sleep(1)


def slave_stop():
    server.stop()



if __name__ == '__main__':
    slave_init()
    try:
        slave_poll()
    except KeyboardInterrupt:
        slave_stop()

你可能感兴趣的:(python,modbus,slave,poll,python)