

物联网 · 盛世宏博 · 以太网温湿度变送器、多协议适配、数据标准化、终端接入
以太网温湿度变送器标榜"即插即用",但到了多品牌混装的现场,协议差异能把集成工程师逼疯。同样是 RJ45 接口、同样走 TCP/IP,不同厂商的数据组织方式天差地别:
{"temp":23.5,"hum":52.1,"sn":"TH2023-001"},端口 80 factory/c/001 主题,payload 为二进制 4 字节(温度 float + 湿度 float) .1.3.6.1.4.1.12345.1.1.1.0 取温度,.1.3.6.1.4.1.12345.1.1.2.0 取湿度 某园区项目 8 个配电室、3 个档案库房,共采购 5 个品牌的以太网温湿度变送器 67 台。集成商最初打算"每个品牌写一套采集程序",结果光协议对接就耗了 3 周,还频繁出现字节序搞反导致温度显示 -12℃ 的乌龙。最终引入协议适配层 + 统一数据模型,将 5 种协议归一化为标准 JSON 上送,后续新增品牌只需加一个适配器,不影响上层业务。
所有协议适配器最终输出统一结构,上层系统只认这一种格式:
{
"device_id": "TH-A01-001",
"device_type": "ethernet_th",
"vendor": "vendor_a",
"protocol": "modbus_tcp",
"zone": "archive_zone_1",
"location": "密集架区A-3",
"timestamp": 1728643200,
"values": {
"temperature": 22.6,
"humidity": 51.3,
"dewpoint": 11.8
},
"quality": {
"signal_strength": -42,
"sample_interval": 15,
"status": "OK",
"error_code": 0
},
"raw": null
}status | 含义 | 上层处理 |
|---|---|---|
OK | 正常 | 参与聚合计算 |
STALE | 数据超时(超过 2 个采样周期未更新) | 降权,触发告警 |
READ_ERR | 读取失败 | 标记异常,启动重试 |
CALIBRATING | 校准中 | 暂不参与控制 |
OFFLINE | 设备离线 | 权重置 0,插值替代 |
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass
class StandardReading:
device_id: str
temperature: float
humidity: float
timestamp: float
status: str = "OK"
raw: dict = None
class ProtocolAdapter(ABC):
@abstractmethod
async def connect(self) -> bool: ...
@abstractmethod
async def read(self) -> StandardReading: ...
@abstractmethod
async def disconnect(self): ...
@abstractmethod
def get_poll_interval(self) -> int: ...class ModbusTCPAdapter(ProtocolAdapter):
def __init__(self, config: dict):
self.ip = config['ip']
self.port = config.get('port', 502)
self.slave = config.get('slave', 1)
self.temp_reg = config.get('temp_reg', 0)
self.hum_reg = config.get('hum_reg', 1)
self.scale = config.get('scale', 10)
self.byte_order = config.get('byte_order', 'big')
self.client = None
async def connect(self) -> bool:
self.client = AsyncModbusTcpClient(self.ip, port=self.port, timeout=3)
return await self.client.connect()
async def read(self) -> StandardReading:
rr = await self.client.read_holding_registers(
self.temp_reg, 2, slave=self.slave
)
if rr.isError():
return StandardReading(self.ip, 0, 0, time.time(), "READ_ERR")
temp_raw, hum_raw = rr.registers[0], rr.registers[1]
if self.byte_order == 'little':
temp_raw = ((temp_raw & 0xFF) << 8) | (temp_raw >> 8)
hum_raw = ((hum_raw & 0xFF) << 8) | (hum_raw >> 8)
return StandardReading(
device_id=f"TH-{self.ip}",
temperature=temp_raw / self.scale,
humidity=hum_raw / self.scale,
timestamp=time.time(),
status="OK"
)
async def disconnect(self):
if self.client:
await self.client.close()
def get_poll_interval(self) -> int:
return 15import aiohttp
class HttpJsonAdapter(ProtocolAdapter):
def __init__(self, config: dict):
self.url = config['url']
self.timeout = config.get('timeout', 5)
self.temp_path = config.get('temp_path', 'temp')
self.hum_path = config.get('hum_path', 'hum')
self.session = None
async def connect(self) -> bool:
self.session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout))
return True
async def read(self) -> StandardReading:
try:
async with self.session.get(self.url) as resp:
if resp.status != 200:
return StandardReading(self.url, 0, 0, time.time(), "READ_ERR")
data = await resp.json()
return StandardReading(
device_id=data.get('sn', self.url),
temperature=data[self.temp_path],
humidity=data[self.hum_path],
timestamp=time.time(),
status="OK",
raw=data
)
except Exception as e:
return StandardReading(self.url, 0, 0, time.time(), "READ_ERR", raw={'err': str(e)})
async def disconnect(self):
if self.session:
await self.session.close()
def get_poll_interval(self) -> int:
return 30import asyncio_mqtt
import struct
class MqttAdapter(ProtocolAdapter):
def __init__(self, config: dict):
self.broker = config['broker']
self.topic = config['topic']
self.port = config.get('port', 1883)
self._latest = None
self._client = None
async def connect(self) -> bool:
self._client = asyncio_mqtt.Client(self.broker, port=self.port)
await self._client.connect()
await self._client.subscribe(self.topic)
asyncio.create_task(self._listen())
return True
async def _listen(self):
async with self._client.messages() as messages:
async for msg in messages:
if msg.topic == self.topic:
payload = msg.payload
temp, hum = struct.unpack('>ff', payload[:8])
self._latest = {
'temp': temp, 'hum': hum, 'ts': time.time()
}
async def read(self) -> StandardReading:
if not self._latest:
return StandardReading(self.topic, 0, 0, time.time(), "STALE")
return StandardReading(
device_id=f"MQTT-{self.topic}",
temperature=self._latest['temp'],
humidity=self._latest['hum'],
timestamp=self._latest['ts'],
status="OK"
)
async def disconnect(self):
if self._client:
await self._client.disconnect()
def get_poll_interval(self) -> int:
return 0 # 被动接收,不主动轮询from pysnmp.hlapi.asyncio import *
class SnmpAdapter(ProtocolAdapter):
def __init__(self, config: dict):
self.ip = config['ip']
self.community = config.get('community', 'public')
self.temp_oid = config.get('temp_oid', '1.3.6.1.4.1.12345.1.1.1.0')
self.hum_oid = config.get('hum_oid', '1.3.6.1.4.1.12345.1.1.2.0')
async def connect(self) -> bool:
return True
async def read(self) -> StandardReading:
# SNMP GET 温度
error_indication, error_status, _, var_binds = await get_cmd(
SnmpEngine(),
CommunityData(self.community),
UdpTransportTarget((self.ip, 161), timeout=3),
ContextData(),
ObjectType(ObjectIdentity(self.temp_oid)),
ObjectType(ObjectIdentity(self.hum_oid)),
)
if error_indication or error_status:
return StandardReading(self.ip, 0, 0, time.time(), "READ_ERR")
temp = float(var_binds[0][1])
hum = float(var_binds[1][1])
return StandardReading(
device_id=f"SNMP-{self.ip}",
temperature=temp,
humidity=hum,
timestamp=time.time(),
status="OK"
)
async def disconnect(self): pass
def get_poll_interval(self) -> int:
return 30class PrivateTcpAdapter(ProtocolAdapter):
def __init__(self, config: dict):
self.ip = config['ip']
self.port = config.get('port', 9000)
self.frame_header = config.get('header', 0xAA)
self.reader = None
self.writer = None
async def connect(self) -> bool:
try:
self.reader, self.writer = await asyncio.open_connection(self.ip, self.port)
return True
except Exception:
return False
async def read(self) -> StandardReading:
# 发送读取命令帧: 0xAA 0x01 0x00 0x00 CRC16
cmd = bytes([self.frame_header, 0x01, 0x00, 0x00, 0x00, 0x00])
cmd = cmd[:-2] + struct.pack('<H', crc16(cmd[:-2]))
self.writer.write(cmd)
await self.writer.drain()
# 读取响应帧: 0xAA 0x02 len temp_hi temp_lo hum_hi hum_lo CRC16
resp = await asyncio.wait_for(self.reader.read(12), timeout=3)
if len(resp) < 8 or resp[0] != self.frame_header:
return StandardReading(self.ip, 0, 0, time.time(), "READ_ERR")
temp = struct.unpack('>h', resp[4:6])[0] / 10
hum = struct.unpack('>h', resp[6:8])[0] / 10
return StandardReading(
device_id=f"PRI-{self.ip}",
temperature=temp,
humidity=hum,
timestamp=time.time(),
status="OK"
)
async def disconnect(self):
if self.writer:
self.writer.close()
await self.writer.wait_closed()
def get_poll_interval(self) -> int:
return 15class AdapterFactory:
_registry = {}
@classmethod
def register(cls, protocol: str, adapter_class):
cls._registry[protocol] = adapter_class
@classmethod
def create(cls, config: dict) -> ProtocolAdapter:
protocol = config['protocol']
if protocol not in cls._registry:
raise ValueError(f"Unsupported protocol: {protocol}")
return cls._registry[protocol](config)
# 注册所有适配器
AdapterFactory.register('modbus_tcp', ModbusTCPAdapter)
AdapterFactory.register('http_json', HttpJsonAdapter)
AdapterFactory.register('mqtt', MqttAdapter)
AdapterFactory.register('snmp', SnmpAdapter)
AdapterFactory.register('private_tcp', PrivateTcpAdapter)
class AdapterScheduler:
def __init__(self, devices: list):
self.adapters = []
for d in devices:
adapter = AdapterFactory.create(d)
self.adapters.append({
'config': d,
'adapter': adapter,
'interval': adapter.get_poll_interval(),
'last_read': 0
})
async def start_all(self):
for a in self.adapters:
await a['adapter'].connect()
async def poll_loop(self, callback):
while True:
now = time.time()
for a in self.adapters:
if a['interval'] > 0 and now - a['last_read'] >= a['interval']:
reading = await a['adapter'].read()
a['last_read'] = now
callback(reading)
await asyncio.sleep(1)
async def stop_all(self):
for a in self.adapters:
await a['adapter'].disconnect()原始数据 → 适配器读取 → 统一 StandardReading → 质量评估 → 标准化 JSON → 输出
处理环节:
① 字节序校正(大端/小端/混合)
② 量程换算(×10 / ×0.1 / float 直接取)
③ 单位统一(华氏→摄氏、ppm→%RH)
④ 时间戳对齐(设备时间→NTP 校准→统一 UTC+8)
⑤ 质量码标注(OK/STALE/READ_ERR/OFFLINE)
⑥ 异常值过滤(温度<-40℃ 或 >85℃ 标记为无效)
⑦ 输出标准化 JSONdef validate_reading(r: StandardReading) -> StandardReading:
if r.temperature < -40 or r.temperature > 85:
r.status = "READ_ERR"
elif r.humidity < 0 or r.humidity > 100:
r.status = "READ_ERR"
elif abs(r.temperature) < 0.01 and abs(r.humidity) < 0.01:
r.status = "READ_ERR" # 全零通常是通信异常
return rdevices:
- id: TH-A01-001
protocol: modbus_tcp
ip: 172.20.10.11
port: 502
slave: 1
temp_reg: 0
hum_reg: 1
scale: 10
byte_order: big
zone: archive_zone_1
location: 密集架区A-3
- id: TH-B02-001
protocol: http_json
url: http://172.20.10.12/data
temp_path: temp
hum_path: hum
zone: archive_zone_1
location: 门口缓冲区
- id: TH-C03-001
protocol: mqtt
broker: 172.20.10.100
topic: factory/c/001
zone: power_room_a
- id: TH-D04-001
protocol: snmp
ip: 172.20.10.14
community: archive_ro
temp_oid: 1.3.6.1.4.1.12345.1.1.1.0
hum_oid: 1.3.6.1.4.1.12345.1.1.2.0
zone: ancient_zone
- id: TH-E05-001
protocol: private_tcp
ip: 172.20.10.15
port: 9000
header: 0xAA
zone: power_room_b项目 | 标准 |
|---|---|
协议支持 | ≥5 种(Modbus TCP/HTTP/MQTT/SNMP/私有TCP) |
标准化输出 | 100% 统一 JSON 格式 |
字节序兼容 | 大端/小端/混合均正确解析 |
异常值过滤 | 温度<-40℃/>85℃、湿度<0/>100% 自动标记 |
质量码标注 | 4 种状态准确反映设备健康度 |
新增品牌接入 | ≤0.5 天(只需加适配器+配置) |
采集周期 | 15~30s 可配 |
数据到达率 | ≥99.9%(含重试机制) |
多品牌以太网温湿度变送器混装的现场,协议适配层是"翻译官"也是"过滤器"——把 Modbus、HTTP、MQTT、SNMP、私有 TCP 五种方言翻译成同一种标准语言,让上层系统只管"用数据"而不用管"怎么拿到的"。适配器工厂 + 统一数据模型 + 质量码体系,三步解决协议碎片化问题。
关键词:以太网温湿度变送器、多协议适配、数据标准化、Modbus TCP、HTTP JSON、MQTT、SNMP、私有TCP、适配器模式、统一数据模型、质量码、字节序、异常过滤
标签:#以太网温湿度变送器 #多协议适配 #数据标准化 #ModbusTCP #HTTPJSON #MQTT #SNMP #私有协议 #适配器模式 #统一数据模型 #质量码 #字节序 #异常过滤
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。