tk如何獲得客戶端信息?
利用 Python modbus工具實現(xiàn)modbus從站的數(shù)據(jù)采集,很方便簡單。python Modbus 協(xié)議工具目前有下面三種:
pymodbus
MinimalModbus
Modbus-tk
modbus_tk :完整modbus協(xié)議棧的實現(xiàn),支持modbus tcp/rtu{1.提供slave模擬器,即模擬modbus server:502), web-based hmi master支持}
pymodbus:使用twisted實現(xiàn)的modbus完整協(xié)議(支持異步通訊)
MinimalModbus :只支持modbusrtu
至于那個更好,可以參考stack overflaw上的一個回答http://stackoverflow.com/questions/17081442/python-modbus-library
Modbus_tk是很簡單易用的工具。相關(guān)資料查看:https://pypi.python.org/pypi/modbus_tk
Modbsu_tk庫使用
execute(slave,功能代碼,開始地址,quantity_of_x=0,output_value=0,data_format="",指定長度=-1)
實現(xiàn)數(shù)據(jù)讀與寫,用功能碼很容易實現(xiàn)。
READ_COILS = 1 讀線圈READ_DISCRETE_INPUTS = 2 讀離散輸入READ_HOLDING_REGISTERS = 3 【讀保持寄存器】READ_INPUT_REGISTERS = 4 讀輸入寄存器WRITE_SINGLE_COIL = 5 寫單一線圈WRITE_SINGLE_REGISTER = 6 寫單一寄存器WRITE_MULTIPLE_COILS = 15 寫多個線圈 【強制多點線圈】WRITE_MULTIPLE_REGISTERS = 16 寫多寄存器 【寫乘法寄存器】
master.execute(1,cst.READ_HOLDING_REGISTERS, 0, 3)
1—從設(shè)備地址
cst.READ_HOLDING_REGISTERS—讀保持寄存器
0—開始地址
3—讀三個字節(jié)
下面來一個簡單的例子。
[python] view plain copy#!/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 serial import modbus_tk import modbus_tk.defines as cst from modbus_tk import modbus_rtu #PORT = 1 PORT = "/dev/ttyUSB0" def main(): """main""" logger = modbus_tk.utils.create_logger("console") try: #Connect to the slave master = modbus_rtu.RtuMaster( serial.Serial(port=PORT, baudrate=9600, bytesize=8, parity='N', stopbits=1, xonxoff=0) ) master.set_timeout(5.0) master.set_verbose(True) logger.info("connected") logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 1, 1)) #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()用modsim在window下充當slave設(shè)置如下:
在樹莓派下運行結(jié)果如下: