- config.yaml: 恢复现场 IP(10.50.253.165/.181/.182)、s331_2 端口 502 - config.yaml: S331 全部 32 位量 word_order 改 CDAB,瞬时流量 scale=60 (m3/min -> m3/h) - config.yaml: 11# 电表功率/电能类型改 int32;第二路 RTU 从站 slave_id 改 10 - poller.py: 过滤 S331 无数据哨兵 -9999 与非有限值,避免污染周期基准 - rtu.py: 新增 SafeRTUFramer 支持多点半总线,忽略其它从站请求 - 新增 config.debug.yaml、README.md、wheelhouse 离线依赖 - tests: 适配新配置(ttyS7/address_offset);新增 pytest.ini 限定 testpaths
249 lines
8.6 KiB
Python
249 lines
8.6 KiB
Python
"""边缘网关主程序。
|
||
|
||
线程/任务划分:
|
||
- 采集线程:每个 TCP 设备一个(S331 #1、S331 #2、410S),指数退避重连;
|
||
- 主线程事件循环:两个独立 Modbus RTU 从站(/dev/ttyS1、/dev/ttyS2);
|
||
- 维护线程:定时 SQLite 掉电保持 + 周期状态日志。
|
||
|
||
启动:python -m gateway.app --config config/config.yaml
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import asyncio
|
||
import logging
|
||
import signal
|
||
import sys
|
||
import threading
|
||
import time
|
||
from datetime import datetime
|
||
from logging.handlers import RotatingFileHandler
|
||
from typing import Any, Iterable, Optional
|
||
|
||
from . import __version__
|
||
from .config import GatewayCfg, load_config
|
||
from .persistence import SqliteStore
|
||
from .poller import PointBinding, TcpPoller
|
||
from .rtu import run_slaves
|
||
from .store import REGISTERS_PER_MACHINE, StateStore
|
||
|
||
log = logging.getLogger("gateway")
|
||
|
||
|
||
def _setup_logging(cfg: GatewayCfg, level_override: Optional[str]) -> None:
|
||
level = getattr(logging, (level_override or cfg.log_level).upper(), logging.INFO)
|
||
handlers: list[logging.Handler] = [logging.StreamHandler()]
|
||
if cfg.log_file:
|
||
handlers.append(
|
||
RotatingFileHandler(
|
||
cfg.log_file, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||
)
|
||
)
|
||
logging.basicConfig(
|
||
level=level,
|
||
format="%(asctime)s.%(msecs)03d %(levelname)-5s [%(threadName)s] %(name)s: %(message)s",
|
||
datefmt="%Y-%m-%d %H:%M:%S",
|
||
handlers=handlers,
|
||
force=True,
|
||
)
|
||
# 第三方库日志降噪
|
||
for noisy in ("pymodbus", "pymodbus.logging", "asyncio", "serial_asyncio"):
|
||
logging.getLogger(noisy).setLevel(logging.WARNING)
|
||
|
||
|
||
def _log_register_map(compressors: Iterable[Any]) -> None:
|
||
log.info("RTU 保持寄存器映射(协议地址 0 基 / S4C 中 40001 起):")
|
||
for cfg in sorted(compressors, key=lambda c: c.register_index):
|
||
base = cfg.register_index * REGISTERS_PER_MACHINE
|
||
log.info(
|
||
" %-8s 基址 0x%04X (寄存器 %d~%d): 瞬时/小时/天/月 气电比",
|
||
cfg.name,
|
||
base,
|
||
40001 + base,
|
||
40001 + base + REGISTERS_PER_MACHINE - 1,
|
||
)
|
||
|
||
|
||
def _apply_values(store: StateStore, values: dict[tuple[int, str], Any]) -> None:
|
||
updates: dict[int, dict[str, Any]] = {}
|
||
for (machine_id, field), value in values.items():
|
||
updates.setdefault(machine_id, {})[field] = value
|
||
store.update(updates)
|
||
|
||
|
||
def _build_pollers(
|
||
cfg: GatewayCfg, store: StateStore, stop_event: threading.Event
|
||
) -> list[TcpPoller]:
|
||
per_device: dict[str, list[PointBinding]] = {}
|
||
for comp in cfg.compressors:
|
||
per_device.setdefault(comp.s331, []).extend(
|
||
[
|
||
PointBinding(comp.id, "instant_flow", comp.flow_instant),
|
||
PointBinding(comp.id, "total_flow", comp.flow_total),
|
||
]
|
||
)
|
||
per_device.setdefault(comp.meter, []).extend(
|
||
[
|
||
PointBinding(comp.id, "instant_power", comp.power_instant),
|
||
PointBinding(comp.id, "total_energy", comp.energy_total),
|
||
]
|
||
)
|
||
|
||
pollers: list[TcpPoller] = []
|
||
for device_name, bindings in per_device.items():
|
||
device = cfg.devices[device_name]
|
||
pollers.append(
|
||
TcpPoller(
|
||
device,
|
||
bindings,
|
||
lambda values, _store=store: _apply_values(_store, values),
|
||
stop_event,
|
||
)
|
||
)
|
||
return pollers
|
||
|
||
|
||
class MaintenanceWorker(threading.Thread):
|
||
"""定时落盘与状态日志。"""
|
||
|
||
def __init__(
|
||
self,
|
||
cfg: GatewayCfg,
|
||
store: StateStore,
|
||
db: SqliteStore,
|
||
pollers: list[TcpPoller],
|
||
stop_event: threading.Event,
|
||
) -> None:
|
||
super().__init__(name="maintenance", daemon=True)
|
||
self._cfg = cfg
|
||
self._store = store
|
||
self._db = db
|
||
self._pollers = pollers
|
||
self._stop_event = stop_event
|
||
|
||
def run(self) -> None:
|
||
last_persist = time.monotonic()
|
||
last_status = last_persist
|
||
while not self._stop_event.wait(1.0):
|
||
now = time.monotonic()
|
||
if now - last_persist >= self._cfg.persist_interval_s:
|
||
self.persist()
|
||
last_persist = now
|
||
if now - last_status >= self._cfg.status_interval_s:
|
||
self._log_status()
|
||
last_status = now
|
||
|
||
def persist(self) -> None:
|
||
try:
|
||
self._db.save(self._store.persist_payloads(), datetime.now())
|
||
log.debug("状态已保存到 %s", self._cfg.db_path)
|
||
except Exception: # noqa: BLE001 - 落盘失败不能影响采集与从站
|
||
log.exception("保存状态到 SQLite 失败")
|
||
|
||
def _log_status(self) -> None:
|
||
now = datetime.now()
|
||
stale = self._cfg.stale_warn_s
|
||
for row in self._store.snapshot(now):
|
||
ratios = row["ratios"]
|
||
age = row["age_s"]
|
||
log.info(
|
||
"状态 %-8s 瞬时=%-9.4f 时=%-9.4f 日=%-9.4f 月=%-9.4f | 瞬时流量=%s 累计气量=%s 瞬时功率=%s 累计电量=%s | 数据延迟=%s",
|
||
row["name"],
|
||
ratios["instant"],
|
||
ratios["hour"],
|
||
ratios["day"],
|
||
ratios["month"],
|
||
_fmt(row["instant_flow"]),
|
||
_fmt(row["total_flow"]),
|
||
_fmt(row["instant_power"]),
|
||
_fmt(row["total_energy"]),
|
||
"无数据" if age is None else f"{age:.0f}s",
|
||
)
|
||
if age is not None and age > stale:
|
||
log.warning("%s 数据已 %.0fs 未更新,寄存器继续提供最后一次计算结果", row["name"], age)
|
||
for status in (poller.status() for poller in self._pollers):
|
||
last_ok = status["last_ok_age_s"]
|
||
log.info(
|
||
"链路 %-10s %-18s 成功=%d 失败=%d 最近成功=%s 最近错误=%s",
|
||
status["name"],
|
||
status["target"],
|
||
status["ok_cycles"],
|
||
status["fail_cycles"],
|
||
"-" if last_ok is None else f"{last_ok}s",
|
||
status["last_error"],
|
||
)
|
||
|
||
|
||
def _fmt(value: Optional[float]) -> str:
|
||
if value is None:
|
||
return "-"
|
||
if abs(value) >= 10000:
|
||
return f"{value:.1f}"
|
||
return f"{value:.4f}".rstrip("0").rstrip(".")
|
||
|
||
|
||
async def _serve(cfg: GatewayCfg, store: StateStore, stop_event: threading.Event) -> None:
|
||
loop = asyncio.get_running_loop()
|
||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||
try:
|
||
loop.add_signal_handler(sig, stop_event.set)
|
||
except (NotImplementedError, RuntimeError, ValueError):
|
||
pass
|
||
await run_slaves(cfg.slaves, store, stop_event)
|
||
|
||
|
||
def _parse_args(argv: Optional[list[str]]) -> argparse.Namespace:
|
||
parser = argparse.ArgumentParser(description="空压机气电比边缘网关(EG828-CEW)")
|
||
parser.add_argument("--config", default="config/config.yaml", help="配置文件路径")
|
||
parser.add_argument("--log-level", default=None, help="覆盖日志级别,如 DEBUG")
|
||
parser.add_argument("--print-map", action="store_true", help="仅打印寄存器映射后退出")
|
||
return parser.parse_args(argv)
|
||
|
||
|
||
def main(argv: Optional[list[str]] = None) -> int:
|
||
args = _parse_args(argv)
|
||
cfg = load_config(args.config)
|
||
_setup_logging(cfg, args.log_level)
|
||
|
||
store = StateStore(cfg.compressors, cfg.register_float_order)
|
||
_log_register_map(cfg.compressors)
|
||
if args.print_map:
|
||
return 0
|
||
|
||
log.info("边缘网关启动 (version=%s, 机器数=%d)", __version__, len(cfg.compressors))
|
||
|
||
db = SqliteStore(cfg.db_path)
|
||
payloads = db.load()
|
||
if payloads:
|
||
restored = store.restore(payloads)
|
||
log.info("已从 %s 恢复 %d 台机器状态(上次保存 %s)", cfg.db_path, restored, db.last_save_time())
|
||
|
||
stop_event = threading.Event()
|
||
pollers = _build_pollers(cfg, store, stop_event)
|
||
for poller in pollers:
|
||
poller.start()
|
||
maintenance = MaintenanceWorker(cfg, store, db, pollers, stop_event)
|
||
maintenance.start()
|
||
|
||
try:
|
||
asyncio.run(_serve(cfg, store, stop_event))
|
||
except KeyboardInterrupt:
|
||
pass
|
||
finally:
|
||
stop_event.set()
|
||
maintenance.join(timeout=5)
|
||
for poller in pollers:
|
||
poller.join(timeout=2)
|
||
try:
|
||
db.save(store.persist_payloads(), datetime.now())
|
||
log.info("退出前状态已保存到 %s", cfg.db_path)
|
||
except Exception: # noqa: BLE001
|
||
log.exception("退出前保存状态失败")
|
||
log.info("边缘网关已退出")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|