为什么要自研网关?

做工业物联网的人都知道,网关是整个系统的”咽喉”——下面接各种设备,上面连云端平台。网关稳不稳,直接决定了整个系统稳不稳。

我们一开始也想用市面上现成的网关。试了几款,要么协议支持不全,要么二次开发能力弱,要么价格太贵,要么稳定性不行。最后决定:自己做一个。

做的过程中踩了很多坑,也积累了不少经验。今天就来聊聊,一个工业级的IoT网关,到底应该怎么设计。

整体架构:四层设计

我们的网关整体架构分四层:

┌──────────────────────────────────────┐
│           云端接入层                  │
│   MQTT / HTTP / 断点续传 / 加密       │
├──────────────────────────────────────┤
│           边缘计算层                  │
│   规则引擎 / 数据清洗 / 本地告警       │
│   脚本引擎 / 本地存储                  │
├──────────────────────────────────────┤
│           协议适配层                  │
│   Modbus / OPC UA / MQTT / 自定义     │
│   驱动框架 / 协议插件化                │
├──────────────────────────────────────┤
│           硬件抽象层                  │
│   串口 / 网口 / DI/DO / 4G / WiFi     │
│   硬件平台无关性                       │
└──────────────────────────────────────┘

下面逐层说。

硬件层:选什么平台?

硬件是网关的基础。选什么平台,决定了网关的性能、功耗、价格和稳定性。

我们试过几个方案:

方案一:树莓派

优点是便宜、生态好、开发快。但工业场景下问题很多:

  • 不是工业级,温度范围窄(0~60℃),夏天在车间里容易死机;
  • 没有硬件看门狗,死了就死了,不能自动恢复;
  • SD卡容易坏,工业环境下读写频繁的话,几个月就挂了。

结论:可以用来做原型,不能用来做产品。

方案二:ARM工控板

比如全志、瑞芯微的工业级芯片。优点是性能强、价格适中、可以跑Linux。

缺点是:

  • 工业级的板子价格不便宜;
  • 外设接口要自己扩展;
  • 生态不如树莓派,驱动要自己调。

方案三:MCU + RTOS

比如STM32 + FreeRTOS。优点是:

  • 工业级,稳定可靠;
  • 功耗低、价格便宜;
  • 实时性好。

缺点是:

  • 性能有限,跑不了复杂的边缘计算;
  • 开发难度大,生态不如Linux丰富。

我们最终的选择是双架构并行:

  • 轻量版:MCU + RTOS,适合简单的数据采集场景,价格低、稳定性高;
  • 增强版:ARM + Linux,适合需要边缘计算、协议复杂的场景,功能强、扩展性好。

两个版本共用上层的协议栈和业务逻辑,底层做硬件抽象,这样维护成本不会太高。

协议适配层:最头疼的部分

工业现场最头疼的是什么?协议太多了。

不同的设备、不同的厂家、不同的年代,用的协议都不一样。Modbus、OPC UA、Profinet、EtherNet/IP、CAN、各种私有协议……一个一个去写对接代码,能把人累死。

我们的做法是:驱动框架 + 插件化协议。

驱动框架

先抽象出一个统一的驱动接口,不管什么协议,都实现同样的接口:

  • connect():连接设备
  • disconnect():断开连接
  • read(addr, type):读数据
  • write(addr, type, value):写数据
  • subscribe(addr, callback):订阅数据变化

这样上层的业务逻辑只需要调用统一的接口,不用关心底层是什么协议。

插件化协议

每种协议实现为一个独立的插件(动态库/so文件),需要什么协议就加载什么插件。不需要的协议不加载,节省内存。

目前我们支持的协议:

  • Modbus RTU/TCP:最常用的,支持功能码01/02/03/04/05/06/15/16;
  • OPC UA:越来越多的新设备用这个,支持订阅和方法调用;
  • MQTT:有些智能设备直接出MQTT,可以直接对接;
  • TCP自定义协议:很多老设备用的是厂家自定义的TCP协议,我们提供脚本化的协议解析能力;
  • DL/T645:电表用的协议;
  • GB/T 19582:PLC用的协议。

加新协议也很方便,按照驱动接口写一个插件就行,不用改核心代码。

一个坑:协议文档和实际不一样

这是做工业协议最常踩的坑——厂家给的协议文档和实际设备对不上。

比如:

  • 文档说寄存器地址是40001开始,实际是0开始;
  • 文档说数据是大端,实际是小端;
  • 文档说有某个寄存器,实际读出来全是0;
  • 文档说支持某个功能码,实际不支持。

经验:不要完全相信文档,一定要拿真实设备测。而且要做好容错——读不到的数据不要崩,要记录日志、继续跑。

边缘计算层:为什么网关也要”计算”?

很多人觉得网关就是个”数据透传”的东西——把设备数据收上来,传到云端就行了。

但实际项目中,纯透传的问题很多:

  • 流量成本高:如果数据量大,全传到云端,4G流量费很贵;
  • 实时性差:告警要等数据传到云端再判断,延迟高;
  • 网络依赖强:断网了就什么都干不了;
  • 云端压力大:设备多了,海量数据全传到云端,云端处理压力大。

所以我们在网关里做了边缘计算,把一部分计算任务下沉到网关本地。

1. 数据清洗和降采样

不是所有数据都需要传到云端。比如温度数据,一秒钟采一次,但一分钟传一次平均值就够了。

网关本地先做处理:

  • 降采样:高频采集,低频上报;
  • 异常值过滤:明显不合理的数据(比如温度突然跳到1000度)直接丢掉;
  • 变化上报:数据没变化就不上报,变化超过阈值才上报。

这样能把上报的数据量降到原来的1/10甚至更低,大大节省流量和云端成本。

2. 规则引擎

网关本地可以跑规则引擎,做实时判断和告警。

比如:

  • 温度超过80度 → 触发告警,本地声光报警,同时推送到云端;
  • 设备连续5分钟没数据 → 判定为离线,记录日志;
  • 电流突然增大 → 预判设备故障,提前告警。

这些判断在本地做,毫秒级响应,完全实时,不依赖网络。

3. 本地存储 + 断点续传

工业现场网络不稳定是常态。网关本地必须能存数据,断网了继续存,网络恢复了再补传。

我们的网关用SQLite做本地存储,能存3个月以上的数据。断点续传做了幂等处理,不会重复上报。

4. 脚本引擎

有些客户有特殊的计算逻辑,比如:

  • 把几个寄存器的值组合起来,算一个指标;
  • 根据某些条件做复杂的判断;
  • 跟本地的其他设备做联动。

这些逻辑每个客户都不一样,不可能都做到固件里。所以我们做了一个脚本引擎,支持用Lua脚本写自定义逻辑。客户可以自己写脚本,上传到网关上运行。

这样网关的灵活性就大大提高了,很多定制化需求不用改固件,写个脚本就行。

云端接入层:怎么保证数据可靠传输?

网关和云端之间的通信,看起来就是发个MQTT消息,但里面的门道也不少。

1. 为什么选MQTT?

MQTT是物联网场景的事实标准,优点很明显:

  • 轻量,开销小;
  • 支持QoS,保证消息可靠送达;
  • 发布订阅模式,灵活;
  • 长连接,实时性好。

我们用MQTT做主要的通信协议,HTTP做辅助(比如固件升级、配置下发)。

2. 可靠传输的几个关键点

  • QoS 1:重要数据用QoS 1,保证至少送达一次;不重要的数据用QoS 0,节省带宽。
  • 心跳机制:定时发心跳包,检测连接是否正常。断了自动重连,指数退避,避免频繁重连把服务器打挂。
  • 消息缓存:发不出去的消息先存在本地,等连接恢复了再发。
  • 数据加密:TLS加密传输,保证数据安全。政企项目里这是硬性要求。

3. 一个坑:运营商NAT超时

4G网络下,运营商的NAT表有超时时间——如果连接空闲太久,NAT表项会被删掉,连接就断了,但MQTT客户端可能还不知道。

解决方法:心跳间隔要设得比NAT超时时间短。一般设60秒比较保险。太短了费电费流量,太长了容易断。

远程管理:怎么管成百上千个网关?

项目做大了,网关数量一多,管理就成了问题。总不能每个网关都跑现场去配置吧?

所以远程管理功能很重要。

1. 远程配置

所有配置都可以远程下发:采集哪些点、采集频率是多少、上报频率是多少、告警规则是什么……都可以在云端改,改了网关自动生效。

2. 远程诊断

网关出问题了,不用跑现场,远程就能诊断:

  • 看网关的运行状态:CPU、内存、磁盘、网络;
  • 看设备连接状态:哪些设备在线、哪些离线;
  • 看日志:远程拉取网关的日志,排查问题;
  • 远程调试:甚至可以远程登录到网关的命令行,直接调试。

3. OTA升级

固件升级是刚需。发现bug了、加新功能了,总不能一个个网关去现场刷固件吧?

OTA升级要注意几个点:

  • 差分升级:只传差异部分,节省流量;
  • 断点续传:升级包下到一半断网了,下次接着下;
  • 双分区:网关有两个系统分区,升级的时候写另一个分区,升级失败了还能切回原来的版本,保证变砖了也能救回来;
  • 灰度发布:先给少数网关升级,没问题再全量推,避免出问题全军覆没。

稳定性:工业网关的生命线

最后说最重要的一点:稳定性

工业场景下,网关可能装在没人管的地方,一跑就是几年。出了问题没人去重启,所以必须足够稳。

我们做了这些事情来保证稳定性:

  1. 硬件看门狗:程序跑飞了,硬件自动重启。软件看门狗不够可靠,必须有硬件的。
  2. 进程守护:主进程挂了,守护进程自动拉起来。
  3. 资源监控:监控CPU、内存、磁盘使用率,超过阈值自动告警、自动处理(比如清理日志、重启进程)。
  4. 容错设计:任何一个设备出问题、任何一个协议解析出错,都不能影响整个网关运行。错误要隔离,不能一个地方崩了全挂。
  5. 长时间运行测试:每个版本发布前,都要跑至少72小时的压力测试,看有没有内存泄漏、有没有性能下降。

写在最后

做工业网关,看起来不难——不就是收数据、传数据吗?但真正做起来,你会发现里面的细节特别多。

协议要全、性能要够、稳定性要强、管理要方便、价格还要便宜……每一项都不容易。

但网关是整个工业物联网系统的基石。网关稳了,上面的平台、应用才有意义。网关不稳,再漂亮的大屏、再厉害的算法,都是空中楼阁。

如果你也在做工业IoT网关,或者在选型网关,希望这篇文章能给你一些参考。

Why Build Our Own Gateway?

Anyone working in industrial IoT knows that the gateway is the “throat” of the entire system — it connects to various devices below and to the cloud platform above. Whether the gateway is stable directly determines whether the entire system is stable.

At first, we tried to use off-the-shelf gateways. We tested several — but either they didn’t support enough protocols, had weak customization capabilities, were too expensive, or lacked stability. Finally we decided: let’s build our own.

We stepped in many pitfalls along the way, and accumulated a lot of experience. Today let’s talk about how an industrial-grade IoT gateway should be designed.

Overall Architecture: Four Layers

Our gateway’s overall architecture has four layers:

┌──────────────────────────────────────┐
│        Cloud Access Layer            │
│  MQTT / HTTP / Resume / Encryption   │
├──────────────────────────────────────┤
│        Edge Computing Layer          │
│  Rule Engine / Data Cleaning /       │
│  Local Alerts / Script Engine /      │
│  Local Storage                       │
├──────────────────────────────────────┤
│        Protocol Adaptation Layer     │
│  Modbus / OPC UA / MQTT / Custom     │
│  Driver Framework / Plugin System    │
├──────────────────────────────────────┤
│        Hardware Abstraction Layer    │
│  Serial / Ethernet / DI-DO / 4G /    │
│  WiFi / Platform Independence        │
└──────────────────────────────────────┘

Let’s go through each layer.

Hardware Layer: What Platform to Choose?

Hardware is the foundation of the gateway. The platform you choose determines performance, power consumption, price, and stability.

We tried several options:

Option 1: Raspberry Pi

Advantages: cheap, great ecosystem, fast development. But in industrial scenarios, there are many problems:

  • Not industrial-grade, narrow temperature range (0~60°C), easily crashes in summer workshops.
  • No hardware watchdog — if it dies, it stays dead, no auto-recovery.
  • SD cards wear out easily — with frequent reads/writes in industrial environments, they fail in a few months.

Conclusion: Good for prototypes, not for production.

Option 2: ARM Industrial Boards

Like Allwinner or Rockchip industrial-grade chips. Advantages: strong performance, reasonable price, can run Linux.

Disadvantages:

  • Industrial-grade boards aren’t cheap.
  • Peripheral interfaces need to be expanded yourself.
  • Ecosystem isn’t as good as Raspberry Pi, drivers need tuning.

Option 3: MCU + RTOS

Like STM32 + FreeRTOS. Advantages:

  • Industrial-grade, stable and reliable.
  • Low power consumption, cheap.
  • Good real-time performance.

Disadvantages:

  • Limited performance, can’t run complex edge computing.
  • Harder development, less rich ecosystem than Linux.

Our final choice: dual architecture:

  • Lite version: MCU + RTOS, for simple data collection scenarios — low cost, high stability.
  • Pro version: ARM + Linux, for scenarios requiring edge computing and complex protocols — powerful, extensible.

Both versions share the upper-layer protocol stack and business logic, with hardware abstraction at the bottom — so maintenance costs don’t explode.

Protocol Adaptation Layer: The Most Painful Part

What’s the biggest headache in industrial sites? Too many protocols.

Different equipment, different manufacturers, different eras — all use different protocols. Modbus, OPC UA, Profinet, EtherNet/IP, CAN, various proprietary protocols… writing integration code for each one would drive you crazy.

Our approach: driver framework + plugin-based protocols.

Driver Framework

First, abstract a unified driver interface. No matter what protocol, it implements the same interface:

  • connect(): connect to device
  • disconnect(): disconnect
  • read(addr, type): read data
  • write(addr, type, value): write data
  • subscribe(addr, callback): subscribe to data changes

This way, upper-layer business logic only calls the unified interface and doesn’t care what protocol is underneath.

Plugin-Based Protocols

Each protocol is implemented as an independent plugin (dynamic library/.so file). Load whatever protocols you need — don’t load what you don’t need, saving memory.

Currently supported protocols:

  • Modbus RTU/TCP: Most common, supports function codes 01/02/03/04/05/06/15/16.
  • OPC UA: Used by more and more new devices, supports subscriptions and method calls.
  • MQTT: Some smart devices output MQTT directly, can integrate straight away.
  • TCP custom protocols: Many old devices use manufacturer-specific TCP protocols — we provide scriptable protocol parsing.
  • DL/T645: Used by electric meters.
  • GB/T 19582: Used by PLCs.

Adding new protocols is easy — just write a plugin following the driver interface, no need to modify core code.

One Pitfall: Protocol Docs Don’t Match Reality

This is the most common pitfall in industrial protocols — the protocol documentation from the manufacturer doesn’t match the actual device.

For example:

  • Docs say register addresses start at 40001, but actually they start at 0.
  • Docs say data is big-endian, but it’s actually little-endian.
  • Docs say a register exists, but reading it returns all zeros.
  • Docs say a function code is supported, but it’s not.

Lesson: Don’t fully trust documentation — always test with real equipment. And build fault tolerance — if you can’t read some data, don’t crash. Log it and keep running.

Edge Computing Layer: Why Do Gateways Need “Computing”?

Many people think a gateway is just “data passthrough” — collect device data, send it to the cloud, done.

But in real projects, pure passthrough has many problems:

  • High traffic costs: If data volume is large and everything goes to the cloud, 4G data fees are expensive.
  • Poor real-time performance: Alerts wait for data to reach the cloud before being judged — high latency.
  • Strong network dependency: If the network goes down, nothing works.
  • Cloud pressure: With many devices, massive data all going to the cloud puts huge processing pressure on the cloud.

So we built edge computing into the gateway, offloading some computation to the gateway locally.

1. Data Cleaning and Downsampling

Not all data needs to go to the cloud. For example, temperature data sampled once per second — but reporting an average once per minute is enough.

The gateway processes locally first:

  • Downsampling: High-frequency collection, low-frequency reporting.
  • Outlier filtering: Obviously unreasonable data (like temperature suddenly jumping to 1000°C) is discarded.
  • Change-based reporting: Don’t report if data hasn’t changed — only report when change exceeds a threshold.

This reduces reported data volume to 1/10 or less of the original, drastically saving traffic and cloud costs.

2. Rule Engine

The gateway can run a rule engine locally for real-time judgment and alerts.

For example:

  • Temperature exceeds 80°C → trigger alert, local audio-visual alarm, simultaneously push to cloud.
  • Device no data for 5 consecutive minutes →判定 offline, log it.
  • Current suddenly spikes → predict equipment failure, alert in advance.

These judgments happen locally, in milliseconds — truly real-time, no network dependency.

3. Local Storage + Resume from Breakpoint

Unstable networks are the norm in industrial sites. The gateway must be able to store data locally — keep storing when offline, then upload when network is restored.

Our gateway uses SQLite for local storage, capable of storing 3+ months of data. Resume-from-breakpoint uses idempotent processing to ensure no duplicate reports.

4. Script Engine

Some customers have special calculation logic, like:

  • Combining values from several registers to calculate a metric.
  • Making complex judgments based on certain conditions.
  • Linking with other local devices.

This logic is different for every customer — you can’t build it all into the firmware. So we built a script engine that supports custom logic written in Lua. Customers can write their own scripts and upload them to the gateway to run.

This greatly increases the gateway’s flexibility — many customization needs don’t require firmware changes, just a script.

Cloud Access Layer: How to Ensure Reliable Data Transmission?

Communication between gateway and cloud seems like just sending MQTT messages, but there’s a lot to it.

1. Why MQTT?

MQTT is the de facto standard for IoT scenarios, with clear advantages:

  • Lightweight, low overhead.
  • Supports QoS, guarantees reliable message delivery.
  • Pub-sub model, flexible.
  • Long connection, good real-time performance.

We use MQTT as the main communication protocol, with HTTP for auxiliary tasks (like firmware upgrades, configuration下发).

2. Key Points for Reliable Transmission

  • QoS 1: Important data uses QoS 1 (at least once delivery). Non-critical data uses QoS 0 to save bandwidth.
  • Heartbeat mechanism: Send heartbeat packets periodically to detect connection health. Auto-reconnect on disconnection, with exponential backoff to avoid hammering the server with frequent reconnections.
  • Message caching: Messages that can’t be sent are stored locally, then sent when connection is restored.
  • Data encryption: TLS encrypted transmission for data security. This is a hard requirement in government and enterprise projects.

3. One Pitfall: Carrier NAT Timeout

On 4G networks, carriers’ NAT tables have timeout periods — if a connection is idle too long, the NAT entry gets deleted and the connection breaks, but the MQTT client might not know.

Solution: Set the heartbeat interval shorter than the NAT timeout. Generally 60 seconds is safe. Too short wastes power and data, too long risks disconnection.

Remote Management: How to Manage Hundreds or Thousands of Gateways?

As projects grow and gateway数量 multiplies, management becomes a problem. You can’t go on-site to configure every gateway, right?

So remote management capabilities are essential.

1. Remote Configuration

All configurations can be pushed remotely: which points to collect, collection frequency, reporting frequency, alert rules… all can be changed in the cloud, and the gateway automatically applies changes.

2. Remote Diagnostics

When a gateway has issues, you don’t need to go on-site — you can diagnose remotely:

  • Check gateway status: CPU, memory, disk, network.
  • Check device connection status: which devices are online, which are offline.
  • Check logs: remotely pull gateway logs for troubleshooting.
  • Remote debugging: you can even remotely log into the gateway’s command line for direct debugging.

3. OTA Upgrades

Firmware upgrades are essential. When you find bugs or add features, you can’t go on-site to flash firmware on every gateway.

Key points for OTA upgrades:

  • Differential upgrades: Only transfer the delta, saving bandwidth.
  • Resume from breakpoint: If the upgrade package download is interrupted by network loss, resume next time.
  • Dual partitions: The gateway has two system partitions. During upgrade, write to the other partition. If upgrade fails, switch back to the original version — guarantees you can recover even if it “bricks.”
  • Gray release: Upgrade a small number of gateways first, roll out fully if no issues — avoid全军覆没 if something goes wrong.

Stability: The Lifeline of Industrial Gateways

Finally, the most important point: stability.

In industrial scenarios, gateways might be installed in无人看管 (unattended) locations, running for years at a time. If something goes wrong, nobody’s there to restart it — so it must be rock solid.

We do these things to ensure stability:

  1. Hardware watchdog: If the program crashes, hardware auto-restarts. Software watchdogs aren’t reliable enough — you must have hardware.
  2. Process supervision: If the main process dies, the supervisor process restarts it automatically.
  3. Resource monitoring: Monitor CPU, memory, disk usage. Alert and auto-handle when thresholds are exceeded (e.g., clean logs, restart processes).
  4. Fault-tolerant design: If any device has issues or any protocol parsing fails, it must not affect the entire gateway. Errors must be isolated — one failure can’t take everything down.
  5. Long-run testing: Before each release, run at least 72 hours of stress testing to check for memory leaks or performance degradation.

Closing Thoughts

Building an industrial gateway seems simple — isn’t it just collecting data and sending it? But when you actually build one, you discover there are so many details.

Full protocol support, sufficient performance, strong stability, convenient management, affordable price… none of these are easy.

But the gateway is the foundation of the entire industrial IoT system. If the gateway is stable, the platforms and applications above it matter. If the gateway isn’t stable, no matter how pretty the dashboards or how powerful the algorithms, they’re castles in the air.

If you’re also building industrial IoT gateways, or selecting one, I hope this article gives you some reference.