Python 创建Modbus Server
加入软件包
import modbus_tk.modbus_tcp as mt
import modbus_tk.defines as cst
import logging
import struct
import time
创建modbus服务器
def modbusServerInit():
## 初始化Modbus
try:
## 所有设备都能访问
modbusServer = mt.TcpServer(address='0.0.0.0')
## 本地访问
## modbusServer = mt.TcpServer(address='127.0.0.1')
modbusServer.start()
modbusServerSlave = server.add_slave(1)
modbusServerSlave.add_block(
'0', cst.HOLDING_REGISTERS, 0, 200
)
except:
logger.error('[Modebus Server]创建失败')
logger.debug('[Modebus Server]创建成功')
return modbusServerSlave
完整代码
import modbus_tk.modbus_tcp as mt
import modbus_tk.defines as cst
import logging
import struct
import time
logger = logging.getLogger('my_logger')
def logInit():
## 初始化日志
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('modbusServer_app.log',encoding="utf-8")
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
def floatToModbus(float_value):
int_value = struct.unpack('<I', struct.pack('<f', float_value))[0]
values_to_write = [int_value & 0xFFFF, (int_value >> 16) & 0xFFFF]
return values_to_write
def modbusServerInit():
## 初始化Modbus
try:
## 所有设备都能访问
modbusServer = mt.TcpServer(address='0.0.0.0')
## 本地访问
## modbusServer = mt.TcpServer(address='127.0.0.1')
modbusServer.start()
modbusServerSlave = modbusServer.add_slave(1)
modbusServerSlave.add_block(
'0', cst.HOLDING_REGISTERS, 0, 200
)
except:
logger.error('[Modebus Server]创建失败')
logger.debug('[Modebus Server]创建成功')
return modbusServerSlave
logInit()
slave = modbusServerInit()
// 写数据
slave.set_values('0',0,floatToModbus(12.32))