#!/usr/bin/env python3 # -*- coding: utf-8 -*- # BFi53ER0 免電池 Bluetooth 閘道 — 範例:第一次 Modbus TCP 讀取。 # # python3 modbus_identify.py bfi53er0-xxxx.local # 標籤上的名稱 # python3 modbus_identify.py 192.168.1.20 # python3 modbus_identify.py 192.168.1.20 0 # 指定單元 ID(預設 255) # # 請先開啟 Modbus TCP:設定頁 → 轉送(Forwarding)→ Modbus TCP。閘道本身回應 # 單元 ID 255(或 0;若已在保持暫存器 207 改過閘道自己的單元 ID,請用 0 或新值)。 # 本程式讀取設備識別(功能碼 43/14),以及暫存器對照表版本與韌體版本 # (功能碼 04,輸入暫存器 0–3)。完整的暫存器對照表——每個開關與感測器的解碼值、 # 端子、RS-485——見《系統整合指南》第 3 章起。 # # Python 3,只用標準函式庫;任何 Modbus TCP 用戶端函式庫也都可以使用。 # # © 2026 譜羅科技(股)公司 BANFi Semiconductor Co., Ltd. 與 FL Semiconductor LLC。 # 您可以使用、複製及修改本範例,以整合 BFi53ER0 產品。 import socket import struct import sys if len(sys.argv) < 2: sys.exit("用法:modbus_identify.py 閘道名稱或位址 [單元ID]") UNIT = int(sys.argv[2]) if len(sys.argv) > 2 else 255 def recv_exact(s, n): """讀取 n 個位元組;閘道先關閉連線時結束。""" b = b"" while len(b) < n: chunk = s.recv(n - len(b)) if not chunk: raise SystemExit("閘道關閉了連線") b += chunk return b def request(s, tid, pdu): """送出一個 Modbus TCP 請求,傳回回應的 PDU。""" s.sendall(struct.pack(">HHHB", tid, 0, len(pdu) + 1, UNIT) + pdu) head = recv_exact(s, 7) n = struct.unpack(">H", head[4:6])[0] - 1 body = recv_exact(s, n) if body[0] & 0x80: if body[1] == 11 and UNIT == 255: raise SystemExit("閘道回傳例外碼 11(找不到單元 ID 255):閘道自己的單元 ID 可能已改過," "請改用:modbus_identify.py %s 0" % sys.argv[1]) raise SystemExit("閘道回傳例外碼 %d" % body[1]) return body with socket.create_connection((sys.argv[1], 502), timeout=5) as s: a = request(s, 1, bytes([43, 14, 1, 0])) # 設備識別(基本) objs, i = {}, 7 for _ in range(a[6]): objs[a[i]] = a[i + 2:i + 2 + a[i + 1]].decode() i += 2 + a[i + 1] print("廠商 %s\n產品 %s\n版本 %s" % (objs.get(0), objs.get(1), objs.get(2))) a = request(s, 2, struct.pack(">BHH", 4, 0, 4)) # 輸入暫存器 0–3 v = struct.unpack(">4H", a[2:10]) print("暫存器對照表版本 %d,韌體 %d.%d.%d" % v)