modbus_rtu.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. from typing import Optional
  2. # ========== 地址配置协议 ==========
  3. def build_broadcast_query() -> bytes:
  4. """构建广播查询指令
  5. DTU定时发送广播指令查询未配置地址的从机
  6. 格式: 00 40 00 40 00 (无CRC, 固定5字节)
  7. """
  8. return bytes([0x00, 0x40, 0x00, 0x40, 0x00])
  9. def parse_device_response(data: bytes) -> Optional[dict]:
  10. """解析从机应答
  11. 从机应答格式: 00 + 41 + 12个UID + CRC_L + CRC_H
  12. 例如: 00 41 18 00 40 00 14 00 00 59 59 54 30 56 AE 34
  13. """
  14. if len(data) < 16:
  15. return {'error': '数据长度不足', 'raw_data': data.hex()}
  16. if data[1] != 0x41:
  17. return {'error': f"非预期功能码: {data[1]:#x}", 'raw_data': data.hex()}
  18. uid_bytes = data[2:14]
  19. uid_hex = uid_bytes.hex()
  20. # CRC 校验失败则拒绝
  21. if not verify_crc16(data[:14]):
  22. return {'error': 'CRC校验失败', 'raw_data': data.hex()}
  23. # UID 有效性检查:拒绝明显是噪声或碰撞产生的数据
  24. zero_count = uid_bytes.count(0)
  25. if zero_count > 6:
  26. return {'error': f"UID中零字节过多({zero_count}/12)", 'raw_data': data.hex()}
  27. # 检查碰撞:UID 中不应有大量重复字节
  28. from collections import Counter
  29. counts = Counter(uid_bytes)
  30. if counts.most_common(1)[0][1] > 8:
  31. return {'error': f"UID中单字节重复过多({counts.most_common(1)})", 'raw_data': data.hex()}
  32. return {
  33. 'function_code': 0x41,
  34. 'uid': uid_hex,
  35. 'uid_readable': ':'.join(f'{b:02x}' for b in uid_bytes),
  36. 'source_address': data[0],
  37. 'raw_data': data.hex()
  38. }
  39. def build_confirm_address(device_address: int, uid: bytes) -> bytes:
  40. """构建确认地址指令
  41. DTU遍历已存储的UID和地址,如果存在匹配的UID则发送确认指令
  42. 格式: add + 44 + 00 + 12个UID + CRC_L + CRC_H
  43. """
  44. if len(uid) != 12:
  45. raise ValueError(f"UID长度必须是12字节,当前: {len(uid)}")
  46. data = bytes([device_address, 0x44, 0x00]) + uid
  47. return data + calculate_crc16(data)
  48. def build_assign_address(uid: bytes, address: int) -> bytes:
  49. """构建分配地址指令
  50. 如果DTU中没有该UID的记录,则分配新地址
  51. 格式: 00 + 42 + 12个UID + add + CRC_L + CRC_H
  52. """
  53. if len(uid) != 12:
  54. raise ValueError(f"UID长度必须是12字节,当前: {len(uid)}")
  55. if address < 1 or address > 247:
  56. raise ValueError(f"设备地址必须在1-247之间,当前: {address}")
  57. data = bytes([0x00, 0x42]) + uid + bytes([address])
  58. return data + calculate_crc16(data)
  59. def parse_address_assignment_response(data: bytes) -> dict:
  60. """解析地址分配响应
  61. 模块应答格式: add + 43 + 00 + CRC_L + CRC_H
  62. 例如: 01 43 00 11 30
  63. """
  64. if len(data) < 5:
  65. return {'error': '数据长度不足', 'raw_data': data.hex()}
  66. device_address = data[0]
  67. if data[1] != 0x43:
  68. return {'error': f"非预期功能码: {data[1]:#x}", 'raw_data': data.hex()}
  69. if not verify_crc16(data):
  70. logger.warning(f"CRC校验失败: {data.hex()}")
  71. return {
  72. 'device_address': device_address,
  73. 'function_code': 0x43,
  74. 'raw_data': data.hex()
  75. }
  76. class AddressConfigProtocol:
  77. """地址配置协议处理器"""
  78. def __init__(self, serial_port):
  79. self.serial = serial_port
  80. self.default_timeout = 2.0
  81. self.stored_devices = {}
  82. def add_stored_device(self, uid: str, address: int):
  83. """添加已存储的设备"""
  84. self.stored_devices[uid] = address
  85. def get_stored_devices(self) -> dict:
  86. """获取已存储的设备列表"""
  87. return self.stored_devices.copy()
  88. def broadcast_query(self, timeout: float = None) -> list:
  89. """send broadcast query and collect all valid 00 41 responses"""
  90. import time
  91. request = build_broadcast_query()
  92. logger.info(f"send broadcast: {request.hex()}")
  93. timeout = timeout or self.default_timeout
  94. response = self.serial.send_and_wait(request, timeout=timeout, min_response_bytes=16)
  95. responses = []
  96. if response and len(response) >= 16:
  97. logger.info(f"got raw response ({len(response)}B): {response.hex()}")
  98. # RS485 半双工会回显已发送的数据,导致 response 开头可能有 5 字节回显
  99. # 在 response 中搜索所有 00 41 标记,尝试从中提取 16 字节帧解析
  100. for i in range(len(response) - 15):
  101. if response[i] == 0x00 and response[i + 1] == 0x41:
  102. chunk = response[i:i + 16]
  103. if len(chunk) >= 16:
  104. parsed = parse_device_response(chunk)
  105. if "error" not in parsed:
  106. if not any(p.get('uid') == parsed['uid'] for p in responses):
  107. responses.append(parsed)
  108. else:
  109. logger.info(f"no response or too short: {len(response) if response else 0}B")
  110. logger.info(f"broadcast done, got {len(responses)} valid unique responses")
  111. return responses
  112. def process_responses(self, responses: list) -> list:
  113. """处理广播查询响应,发送确认或分配地址指令"""
  114. import time
  115. results = []
  116. for resp in responses:
  117. if 'error' in resp:
  118. results.append({'status': 'error', 'message': resp['error']})
  119. continue
  120. uid = resp['uid']
  121. src_addr = resp.get('source_address', 0)
  122. device_address = self.stored_devices.get(uid)
  123. if device_address and src_addr != 0:
  124. logger.info(f"UID={uid} 地址={device_address} 源地址={src_addr},发送确认指令")
  125. request = build_confirm_address(device_address, bytes.fromhex(uid))
  126. self.serial.flush_input()
  127. success, msg = self.serial.send_raw(request)
  128. if success:
  129. results.append({
  130. 'status': 'confirmed',
  131. 'uid': uid,
  132. 'address': device_address,
  133. 'request': request.hex()
  134. })
  135. else:
  136. new_address = device_address or (len(self.stored_devices) + 1)
  137. if new_address > 247:
  138. new_address = 1
  139. logger.info(f"UID={uid} 未配置或源地址=0,分配新地址={new_address}")
  140. request = build_assign_address(bytes.fromhex(uid), new_address)
  141. self.serial.flush_input()
  142. time.sleep(0.05)
  143. success, msg = self.serial.send_raw(request)
  144. if success:
  145. self.stored_devices[uid] = new_address
  146. results.append({
  147. 'status': 'assigned',
  148. 'uid': uid,
  149. 'address': new_address,
  150. 'request': request.hex()
  151. })
  152. return results
  153. def auto_configure(self, timeout: float = None) -> dict:
  154. """自动配置所有未配置的设备"""
  155. logger.info("开始自动配置设备...")
  156. responses = self.broadcast_query(timeout)
  157. if not responses:
  158. return {
  159. 'success': True,
  160. 'message': '未发现任何从机设备',
  161. 'discovered': 0,
  162. 'configured': 0,
  163. 'results': []
  164. }
  165. results = self.process_responses(responses)
  166. confirmed = sum(1 for r in results if r.get('status') == 'confirmed')
  167. assigned = sum(1 for r in results if r.get('status') == 'assigned')
  168. errors = sum(1 for r in results if r.get('status') == 'error')
  169. return {
  170. 'success': errors == 0,
  171. 'discovered': len(responses),
  172. 'confirmed': confirmed,
  173. 'assigned': assigned,
  174. 'errors': errors,
  175. 'results': results,
  176. 'stored_devices': self.get_stored_devices()
  177. }
  178. def save_config(self, filepath: str) -> bool:
  179. """保存配置到文件"""
  180. import json
  181. try:
  182. with open(filepath, 'w') as f:
  183. json.dump(self.stored_devices, f, indent=2)
  184. return True
  185. except Exception as e:
  186. logger.error(f"保存配置失败: {e}")
  187. return False
  188. def load_config(self, filepath: str) -> bool:
  189. """从文件加载配置"""
  190. import json
  191. try:
  192. with open(filepath, 'r') as f:
  193. self.stored_devices = json.load(f)
  194. return True
  195. except Exception as e:
  196. logger.error(f"加载配置失败: {e}")
  197. return False
  198. # ========== Modbus RTU Client ==========
  199. # 天线地址映射表(天线编号 -> Modbus寄存器地址)
  200. ANTENNA_ADDRESSES = {i: 0x0001 + (i - 1) for i in range(1, 25)}
  201. import struct
  202. import logging
  203. logger = logging.getLogger('serial_mqtt_gateway')
  204. def calculate_crc16(data: bytes) -> bytes:
  205. """计算Modbus CRC16校验"""
  206. crc = 0xFFFF
  207. for byte in data:
  208. crc ^= byte
  209. for _ in range(8):
  210. if crc & 0x0001:
  211. crc = (crc >> 1) ^ 0xA001
  212. else:
  213. crc >>= 1
  214. return struct.pack('<H', crc)
  215. def verify_crc16(data: bytes) -> bool:
  216. """验证Modbus CRC16校验"""
  217. if len(data) < 2:
  218. return False
  219. received_crc = struct.unpack('<H', data[-2:])[0]
  220. calculated_crc = struct.unpack('<H', calculate_crc16(data[:-2]))[0]
  221. return received_crc == calculated_crc
  222. class ModbusRTUClient:
  223. """Modbus RTU 客户端"""
  224. def __init__(self, serial_port):
  225. self.serial = serial_port
  226. self.default_timeout = 2.0
  227. def _build_request(self, device_address: int, function_code: int, data: bytes = b'') -> bytes:
  228. """构建Modbus请求帧"""
  229. pdu = bytes([device_address, function_code]) + data
  230. return pdu + calculate_crc16(pdu)
  231. def _send_receive(self, request: bytes, expected_min_len: int = 5, timeout: float = None) -> dict:
  232. """send request and receive response using sync method"""
  233. timeout = timeout or self.default_timeout
  234. if not self.serial.ser:
  235. return {"error": "serial not connected"}
  236. response = self.serial.send_and_wait(request, timeout=timeout, min_response_bytes=expected_min_len)
  237. if not response or len(response) < expected_min_len:
  238. return {"error": "response timeout or too short", "raw_data": response.hex() if response else ""}
  239. if not verify_crc16(response):
  240. logger.warning(f"CRC check failed: {response.hex()}")
  241. return {"error": "CRC check failed", "raw_data": response.hex()}
  242. return {
  243. "success": True,
  244. "device_address": response[0],
  245. "function_code": response[1],
  246. "data": response[2:-2].hex(),
  247. "raw_data": response.hex()
  248. }
  249. def read_antenna_card(self, device_address: int, antenna_num: int, timeout: float = None) -> dict:
  250. """读取天线卡号
  251. 协议: 读寄存器 0x0002+(ant-1)*4, 共4个寄存器(8字节卡号)
  252. """
  253. reg_addr = 0x0002 + (antenna_num - 1) * 4
  254. request_data = struct.pack('>HH', reg_addr, 4) # 读取4个寄存器
  255. request = self._build_request(device_address, 0x03, request_data)
  256. result = self._send_receive(request, timeout=timeout)
  257. if 'error' in result:
  258. return result
  259. data_str = result.get('data', '')
  260. data_bytes = bytes.fromhex(data_str) if isinstance(data_str, str) and data_str else b''
  261. if len(data_bytes) >= 8:
  262. # 8字节卡号, big-endian
  263. card_number = int.from_bytes(data_bytes[:8], 'big')
  264. card_str = data_bytes[:8].hex()
  265. return {
  266. 'card_number': card_number,
  267. 'card_number_hex': f'0x{card_number:016x}',
  268. 'card_number_str': card_str,
  269. 'antenna': antenna_num,
  270. 'uid': ':'.join(data_bytes[:8].hex()[i:i+2] for i in range(0, 16, 2)),
  271. **result
  272. }
  273. return {'error': f'数据长度不足({len(data_bytes)}B,需要8B)', **result}
  274. def read_holding_registers(self, device_address: int, start_address: int, quantity: int = 1, timeout: float = None) -> dict:
  275. """读取保持寄存器"""
  276. request_data = struct.pack('>HH', start_address, quantity)
  277. request = self._build_request(device_address, 0x03, request_data)
  278. result = self._send_receive(request, timeout=timeout)
  279. if 'error' in result:
  280. return result
  281. data_str = result.get('data', '')
  282. data_bytes = bytes.fromhex(data_str) if isinstance(data_str, str) and data_str else b''
  283. registers = []
  284. for i in range(0, len(data_bytes), 2):
  285. if i + 1 < len(data_bytes):
  286. registers.append(struct.unpack('>H', data_bytes[i:i+2])[0])
  287. return {'registers': registers, **result}
  288. def write_single_register(self, device_address: int, register_address: int, value: int, timeout: float = None) -> dict:
  289. """写单个寄存器"""
  290. request_data = struct.pack('>HH', register_address, value)
  291. request = self._build_request(device_address, 0x06, request_data)
  292. return self._send_receive(request, timeout=timeout)
  293. def set_rgb_led(self, device_address: int, led_number: int, color: int, timeout: float = None) -> dict:
  294. """设置RGB灯
  295. Register 0x0001, value = (led_number << 8) | color
  296. color: 0=off, 1=flashing red, 2=flashing green, 3=flashing blue
  297. """
  298. value = (led_number << 8) | (color & 0xFF)
  299. return self.write_single_register(device_address, 0x0001, value, timeout)
  300. def scan_devices(self, max_address: int = 247) -> list:
  301. """scan online devices using Modbus 03"""
  302. import time
  303. devices = []
  304. for addr in range(1, min(max_address + 1, 248)):
  305. request = self._build_request(addr, 0x03, struct.pack('>HH', 0x0000, 0x0001))
  306. response = self.serial.send_and_wait(request, timeout=0.3, min_response_bytes=5)
  307. if response and len(response) >= 5 and verify_crc16(response):
  308. devices.append(addr)
  309. return devices