重构目录结构:调整项目布局
This commit is contained in:
69
hardware/transmitter.py
Normal file
69
hardware/transmitter.py
Normal file
@ -0,0 +1,69 @@
|
||||
# hardware/transmitter.py
|
||||
from pymodbus.exceptions import ModbusException
|
||||
|
||||
|
||||
class TransmitterController:
|
||||
def __init__(self, relay_controller):
|
||||
self.relay_controller = relay_controller
|
||||
|
||||
# 变送器配置
|
||||
self.config = {
|
||||
1: { # 上料斗
|
||||
'slave_id': 1,
|
||||
'weight_register': 0x01,
|
||||
'register_count': 2
|
||||
},
|
||||
2: { # 下料斗
|
||||
'slave_id': 2,
|
||||
'weight_register': 0x01,
|
||||
'register_count': 2
|
||||
}
|
||||
}
|
||||
|
||||
def read_data(self, transmitter_id):
|
||||
"""读取变送器数据"""
|
||||
try:
|
||||
if transmitter_id not in self.config:
|
||||
print(f"无效变送器ID: {transmitter_id}")
|
||||
return None
|
||||
|
||||
config = self.config[transmitter_id]
|
||||
|
||||
if not self.relay_controller.modbus_client.connect():
|
||||
print("无法连接网络继电器Modbus服务")
|
||||
return None
|
||||
|
||||
result = self.relay_controller.modbus_client.read_holding_registers(
|
||||
address=config['weight_register'],
|
||||
count=config['register_count'],
|
||||
slave=config['slave_id']
|
||||
)
|
||||
|
||||
if isinstance(result, Exception):
|
||||
print(f"读取变送器 {transmitter_id} 失败: {result}")
|
||||
return None
|
||||
|
||||
# 根据图片示例,正确解析数据
|
||||
if config['register_count'] == 2:
|
||||
# 获取原始字节数组
|
||||
raw_data = result.registers
|
||||
# 组合成32位整数
|
||||
weight = (raw_data[0] << 16) + raw_data[1]
|
||||
weight = weight / 1000.0 # 单位转换为千克
|
||||
elif config['register_count'] == 1:
|
||||
weight = float(result.registers[0])
|
||||
else:
|
||||
print(f"不支持的寄存器数量: {config['register_count']}")
|
||||
return None
|
||||
|
||||
print(f"变送器 {transmitter_id} 读取重量: {weight}kg")
|
||||
return weight
|
||||
|
||||
except ModbusException as e:
|
||||
print(f"Modbus通信错误: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"数据解析错误: {e}")
|
||||
return None
|
||||
finally:
|
||||
self.relay_controller.modbus_client.close()
|
||||
Reference in New Issue
Block a user