Don't just come up and choose the agreement
Every forum is asking the same question: 'Do I use Modbus or MQTT for this project?'? Do you want to go to OPC UA
The answer is always - first tell me how many devices you have on site, what physical layer you are using, and where the data is going.
Protocol selection is not about choosing which one is more advanced, but about choosing which one has the least number of problems in your scenario. Modbus was born in 1979, MQTT in 1999, OPC UA in 2006- all three protocols are still alive, indicating that each has its own job. What you need is not a 'which one is best' conclusion, but a set of engineering decision-making frameworks that allow you to come to your own conclusion within three minutes.
Three protocols, in one sentence clear
**Modbus RTU/TCP * *: The master station asks each slave station one by one, one question and one answer. The frame format is fixed, consisting of address+function code+data+CRC. The slave station cannot speak actively and must wait for the master station to call it.
For example, military training roll call. The instructor calls a student ID, and the student reports' arrived '. Call the next one again. There are 30 people in the class, one by one, in a well-organized manner. It's okay if the instructor gets tired, but what if there are 500 people? It has been twenty minutes since the last row was called.
**MQTT * *: publish/subscribe model. The device decides when to report on its own, no one needs to ask. Broker is the post office, where devices throw messages into the theme and whoever subscribes receives them.
On site analogy: WeChat group. The sensor posted a message in the group saying 'I exceeded the limit', and all systems that subscribed to this group saw it at the same time. Don't wait for anyone to ask.
**OPC UA * *: Object oriented industrial interoperability framework. Not only does it transmit data, but it also comes with a semantic model - telling you that this data is' motor current ', measured in amperes, with a value range of 0-100 and an accuracy of 0.1. There are also secure channels, authentication certificates, and method calls.
Like foreign language translators: Siemens PLC speaks German, Rockwell speaks English, Mitsubishi speaks Japanese, OPC UA is responsible for translating into common language, and comes with a detailed grammar manual.
Three agreements do not fight. They are often mixed together in real projects.
12 selection criteria, engineering hard indicators
1. Number of devices: mathematical ceiling for polling
Modbus RTU reads a hold register (function code 03) at 9600 bps, with the master station sending 8 bytes and the slave station returning 7 bytes (address+function code+byte count+2 byte data+2 byte CRC), totaling 15 bytes. Add a frame interval of 3.5 characters (approximately 4ms @ 9600) and a slave response delay (usually 10-50ms, conservatively taken as 20ms):
Single polling time per slave station=frame transmission time+frame interval+slave station response delay
Frame transmission time=15 × 11 bits ÷ 9600=17.2ms (11 bits/character: 1 start bit+8 data bits+1 check bit+1 stop bit)
Single polling ≈ 17.2+4+4+20=45.2ms
200 slave stations, each reading 10 registers (frames read from multiple registers are longer, with approximately 125 registers per frame), with an actual single polling rate of approximately 60-80ms per station.
**200 units x 70ms=14 seconds. **You are looking at the screen in the control room, and the data on the HMI only refreshes once every 14 seconds. The alarm signal took 14 seconds to be seen by you on the road.
This is still the theoretical optimal value. In practical engineering, station response timeouts, retries, and decreased line quality can all double this number.
**Conclusion: When there are less than 50 devices and the Modbus RTU polling cycle is within 2-3 seconds, it is sufficient for most monitoring scenarios. If there are more than 100 units, either use Modbus TCP (Ethernet does not suffer from the loss of serial bandwidth) or switch to MQTT. **
2. Communication Model: Polling vs. Event Driven
Modbus is polling. You ask once every N seconds, and the alarm signal may be generated between two rounds of polling, but you must wait until the next round to see it.
Scenario: At a sewage treatment plant, the pH value of the incoming water suddenly drops from 7 to 4. The polling cycle of Modbus is 5 seconds, and in the worst case scenario - the pH sensor exceeds the limit just after being asked, you have to wait for almost 5 seconds to know. 5 seconds is too long for process protection.
MQTT is event driven. The sensor detected an abnormality and immediately issued a message. Broker forwards to the monitoring system within the same second. The delay depends on network latency and Broker processing time, usually within 100ms.
OPC UA supports subscription mode (MonitoredItem). The client registers the data points of interest, sets the sampling interval and triggering conditions. Only push when the change exceeds the threshold, not blindly poll the entire quantity.
**Conclusion: If your alarm response time requirement is less than 1 second and Modbus polling cannot be achieved, choose MQTT or OPC UA subscription. **
3. Bandwidth and latency: The physical layer determines the lower limit
| physical layer | Typical speed | Suitable scenarios |
|---|---|---|
| RS-485 (Modbus RTU) | 1200-115200 bps | Local bus,<1200 meters |
| Ethernet (Modbus TCP) | 100 Mbps | Factory LAN |
| 4G Cat.1 | Upstream 5 Mbps | Remote terminal with base station coverage |
| NB-IoT | Upstream~60 kbps | Low power wide area scenario with daily data volume<1KB |
| LoRa | 0.3-50 kbps | Ultra long distance, extremely low power consumption |
I have seen that the 1200 meter limit of RS-485 can be achieved - provided it is high-quality shielded twisted pair, 9600 bps, with only one device and no frequency converter nearby. On site in the workshop, when the frequency converter is turned on, the communication error rate skyrockets, and you have to lower the baud rate, shield, and isolate.
At 9600 bps, Modbus RTU has a transmission density of approximately 800 bytes per second (excluding the overhead of start and stop bits). MQTT runs on 4G and tens of KB is not a problem. The binary encoding efficiency of OPC UA is quite good, but the certificate exchange and session negotiation during connection establishment consume several hundred KB.
**Conclusion: Local bus, bandwidth is not a bottleneck. Remote access, Modbus RTU does not directly connect to the public network - you have never seen anyone pull the RS-485 cable from Beijing to Shijiazhuang. It must pass through the gateway. **
4. Data model complexity: from registers to objects
There are only four data models for Modbus: coil (bit), discrete input (bit), hold register (16 bit word), and input register (16 bit word). There's nothing else. No floating-point numbers, no strings, no timestamps, no array structures - unless you encode on multiple registers yourself.
Data of a frequency converter: operating status (bits), set frequency (floating point number, occupying 2 registers), actual frequency (floating point number), output current (floating point number), bus voltage (integer), operating time (32 bits, 2 registers), alarm code (bit mask). All implemented with Modbus registers, you need to maintain an Excel spreadsheet to record which register corresponds to which parameter and what encoding is used. Scattered on ten frequency converters is a mapping table of hundreds of registers.
MQTT is not much better - JSON is free-form, but various manufacturers have fields for the "frequency" field called freqency, freq, Hz, and outputted. There are no standards, you can make your own agreement.
The Information Model (IM) of OPC UA solves this problem from the protocol layer: each data point has Type, Unit, Range, and EngineeringUnits. A MotorType object has Current, Temperature, Speed - built-in semantics, not bare registers.
**Conclusion: With less than 50 data points and simple types (all integers/switch values), Modbus register mapping is fully sufficient. With over 200 points and complex object models involved, OPC UA helps you save half of the document maintenance workload. **
5. Security: Who is running naked
In the design era of Modbus (1979), no one considered network security. There is no authentication field on the RTU frame, and any device connected to the RS-485 bus can issue commands such as turning off the pump, changing parameters, and writing registers. The TCP version adds an extra layer of TCP connection, but it also does not have built-in TLS.
MQTT can be transmitted through TLS encryption, authenticated with Username/Password, and the Broker side can also perform ACL to control which clients can publish/subscribe to which topics.
The security model of OPC UA consists of three components: certificate authentication (X.509), message signing, and message encryption. It also supports user tokens (username/password/certificate/anonymous). From connection establishment to data transmission, the entire link is encrypted.
Once I went to a certain water plant for investigation and found that their Modbus TCP gateway public port was open. Scanning it could directly write the frequency converter start stop register. No joke, this kind of thing is very common in small and medium-sized enterprises.
**Conclusion: Public network transmission, remote operation and maintenance, and scenarios involving critical infrastructure - do not use bare Modbus. At least pass through the gateway of MQTT+TLS. If there is already OPC UA capability, use its secure channel directly. **
6. Interoperability: Who's device to talk to
The ideal situation is that all devices run the same protocol - you Siemens, I Schneider, he AB, all use Profinet. Reality is not like that.
The advantage of Modbus lies precisely in this: almost all PLCs support Modbus RTU/TCP, whether it is the Siemens S7-1200 CM1241 module or the Mitsubishi FX series RS-485 port. Equipment manufacturers are also willing to support it - no royalties are required, implementation is simple, and it can be adjusted within a few days.
The interoperability of MQTT relies on the agreed upon topic structure and JSON format. But the agreements of each family may be different. **The Sparkplug B specification * * fills this gap by defining standard topic namespaces, data type encoding, and device birth/death messages.
The interoperability of OPC UA is built into the protocol: the Companion Specification covers robots, injection molding machines CNC、 Dozens of industries, including wind power generation. Siemens' OPC UA Server and Rockwell's OPC UA Client can communicate directly without writing mapping layer code.
But on the other hand, the supporting specifications for OPC UA are still developing and not all devices support it. Some manufacturers' OPC UA implementations are just a shell - nodes can be browsed, but the actual data update frequency cannot keep up.
**Conclusion: Interoperability with multiple brands of PLC/DCS is a hard requirement → OPC UA. All devices are domestic meters/sensors → Modbus RTU is sufficient. Cloud platform integration is required → MQTT. **
7. Development cycle and team skills
This is a severely underestimated article.
Modbus development: Find a serial port library, send 8 bytes, receive 7 bytes, tune for two days, and it works. The protocol stack has several hundred lines of code. You can use Python's Pymodbus or C #'s NModbus to load packages in the morning and read and write registers in the afternoon. There are engineers who will complete a Modbus master driver within three days.
MQTT development: Install a Paho MQTT library, connect the Broker address, port, and topic in three lines of code. Publish/subscribe on two lines each. Get started in a day. Broker deployment (Mosquitto/EMXX) can be completed in half an hour.
OPC UA development: I have to be honest - it's not easy. The learning curve for address space modeling, certificate management, security policy configuration, subscription/method invocation is much steeper than the previous two. It's one thing to connect the UAExpert client to the server, but another thing to write a complete OPC UA Server yourself. In industry, mature products such as KepServerEx and Siemens OPC UA Server are commonly used, and SDK debugging is common, with few being written from scratch. If a team lacks OPC UA experience, reserve 2-4 weeks for technical validation.
**Conclusion: 3-day development → Modbus. 1-day development → MQTT. There is a dedicated person and the project allows for learning costs → OPC UA. **
8. Hardware cost: price difference at the chip level
The batch price of RS-485 transceiver (MAX485/SP3485) is less than 1 yuan RMB. Adding two 120 Ω terminal resistors and a TVS protection tube, the BOM cost is within 3 yuan. The UART peripheral of STM32F103 microcontroller is directly driven without the need for an external PHY.
The minimum hardware requirements for MQTT are a network stack (WiFi/Ethernet/4G module) and a TCP/IP protocol stack. ESP32 comes with WiFi+BLE, and the bulk price is about 12-15 yuan. Running FreeRTOS+LwIP+Paho MQTT is effortless. If it is a 4G module (approximately 20 yuan for HeZhou Air724UG), it can also run MQTT AT commands.
OPC UA has hardware requirements. A minimum OPC UA Server (supporting security policy Basic256Sha256 and 1000 variable nodes) requires approximately 256KB RAM and 512KB Flash. You can run the embedded version of open62541 on STM32H7 (Cortex-M7,~30 blocks), but it's not as simple as "lighting a light". Industrial grade OPC UA gateways typically use ARM Cortex-A series Linux boards (such as the Quanzhi T113-i, starting from 40-50 yuan).
| agreement | MCU price range | Typical hardware platform |
|---|---|---|
| Modbus RTU | ¥3-10 | STM32F103 / GD32 |
| MQTT (WiFi) | ¥12-20 | ESP32 |
| MQTT (4G) | ¥25-40 | HeZhou Air724UG+MCU |
| OPC UA (Lightweight) | ¥30-80 | STM32H7 / i.MX RT |
| OPC UA (Complete) | ¥80-200 | Quanzhi/Ruixin Micro Linux Board |
**Conclusion: Making a Modbus RTU temperature and humidity sensor priced at 50 yuan cannot cover the hardware cost of replacing it with an OPC UA solution. Making an industrial gateway priced at 5000, the hardware cost of OPC UA is not a problem at all. **
9. Cloud Access: The Natural Gene of the Protocol
Modbus is designed for local buses. You cannot directly apply RS-485 to the Alibaba Cloud IoT platform. Must go through gateway - Modbus RTU ->gateway (for protocol conversion) ->MQTT/HTTP ->cloud.
MQTT is naturally suitable for cloud access. AWS IoT Core、 Alibaba Cloud IoT, EMQX Cloud, ThingsBoard - MQTT is the first citizen of all mainstream IoT platforms. Flexible theme routing, Last Will message solves offline device detection, and Retained message ensures that newly launched subscribers immediately receive the latest status.
The Client/Server mode of OPC UA is not very suitable for the cloud - wide area network latency is high, and UA's secure handshake and session management cannot handle it. But OPC UA has a Pub/Sub extension (released in 2018) that supports UDP multicast and MQTT Broker transport, specifically addressing cloud access issues. However, currently there are not many actual deployed OPC UA Pub/Sub cases, and more are indirect routes from OPC UA Server to edge gateway, MQTT to cloud.
**Conclusion: Your data endpoint is cloud to MQTT, don't hesitate. Local SCADA/Historian → OPC UA. Both cloud based and local monitoring → MQTT+OPC UA combination. **
10. Historical legacy: If you can't change it, don't change it
The most common scenario is a sewage treatment plant with 200 Modbus RTU meters (Weisheng/Kelu/Linyang) that have been running on the RS-485 bus for five years. You need to go to the cloud now to create an energy management platform.
Have you replaced all 200 electricity meters? unrealistic. Budgeting is one thing, the key is that they are not bad at all. The most reasonable solution is to use Modbus MQTT gateway: the meter continues to run Modbus RTU, the gateway performs polling collection, and the data is packaged into JSON and sent to MQTT for cloud transmission. The meter side is a stable Modbus, while the cloud side is a modern IoT architecture - neither side is at a disadvantage.
The same principle applies: There are 50 AB PLCs in the painting workshop of a certain automobile factory, all of which run EtherNet/IP. Do you want to add an MES system so that the data from these PLCs can be read by MES. Option A: Each PLC is equipped with a Modbus TCP module. Option B: Add a KepServer/Ignition OPC UA gateway, aggregate EtherNet/IP data, and expose the OPC UA interface. Option B does not change one wire to the on-site equipment.
**Conclusion: Respect the protocol that the existing devices are running according to. Using a gateway as a bridge, don't think about upgrading all existing devices - that would be too costly. **
11. Device discovery: Who knows what is on the bus
Modbus does not have a device discovery mechanism. Do you need to know which devices are hanging from station addresses 1 to 247? The only way is to send function codes 03 (read hold register) or 08 (diagnostic) one by one, and wait for a response. If there is no response after timeout, it is considered that there is no device. This process is called 'address scanning' - it takes several tens of seconds to scan 247 addresses at 9600 bps, and some devices may report exceptions when reading unknown registers.
MQTT itself has not been discovered by any devices. Sending a message to a specific topic when the device goes online relies on agreed upon business logic, not protocol level mechanisms. The Sparkplug B specification adds device birth/death messages, but requires the receiver to actively listen.
OPC UA has built-in Discovery Server (default port 4840). Connect to Discovery Server on the client side, ask 'Which servers have you registered below', obtain the list and endpoint URL, and then connect. Within the local area network, mDNS (multicast DNS) can also be used to automatically discover OPC UA servers.
**Conclusion: Frequent device changes and dynamic changes in network topology → OPC UA discovery services save you a lot of configuration time. The device remains fixed and does not move once installed → Manually configuring Modbus is not a problem. **
12. Firmware Upgrade and Configuration Management
Modbus only defines data read and write. Firmware upgrade? There is no standard function code. Some manufacturers use custom areas with function codes 0x41-0xFF to implement it, but each one is different and not compatible with each other.
MQTT is the same - you can transfer firmware packages, but you can choose the format and process yourself.
OPC UA has standard method calls. You can define a 'firmware upgrade' method that accepts firmware file URL and version number parameters, returns the upgrade progress and results. The Device Integration specification (DI) also defines a standard device management model.
**Conclusion: Batch device firmware upgrade is a core requirement - OPC UA method calling is more reliable than creating your own protocol. Occasionally upgrading, on-site personnel can simply connect the USB cable → Modbus is sufficient. **
Decision path, go through it once
你的项目
│
├── 设备数量 > 100?
│ ├── 是 ──→ 需要事件驱动(报警 < 1s 响应)?
│ │ ├── 是 ──→ 需要多种品牌互操作?
│ │ │ ├── 是 ──→ 【OPC UA】
│ │ │ └── 否 ──→ 【MQTT】
│ │ └── 否 ──→ 【Modbus TCP】(配高性能主站,轮询周期可接受)
│ │
│ └── 否 ──→ 需要上云?
│ ├── 是 ──→ 【MQTT】
│ └── 否 ──→ 公网传输 / 需要安全?
│ ├── 是 ──→ 【OPC UA / MQTT+TLS】
│ └── 否 ──→ 【Modbus RTU】
│ 最简单的方案永远最好Not all scenarios go to the end and choose one protocol. Most of the time, you choose a combination.
Hybrid Architecture: The Gameplay of Real Projects
Classic combination: Modbus RTU → Gateway → MQTT → Cloud
The underlying electricity meters and sensors run Modbus RTU and use an embedded gateway (such as Huawei AR650, InHand IG902, or your own Raspberry Pi+Node RED) for protocol conversion:
┌──────────┐ RS-485 ┌──────────┐ MQTT/TLS ┌─────────────┐
│ 电表 ×50 │───────────→│ Modbus- │───────────→│ 云 IoT 平台 │
│ Modbus │ Modbus RTU│ MQTT 网关│ │ (Ali/AWS) │
│ RTU │ │ │ │ │
└──────────┘ └──────────┘ └─────────────┘The gateway does two things: polling and collecting voltage/current/power/energy from 50 electricity meters, packaging them into JSON at one minute intervals, and publishing them to the cloud via MQTT. Electricity meters are not replaced, cloud computing is modern. This architecture has been validated countless times on distributed photovoltaic monitoring and energy management platforms.
OPC UA as an aggregation layer
There are 50 Modbus TCP slave stations in the factory (distributed in five workshops), and the upper level MES needs to retrieve data uniformly. Place an OPC UA Server gateway in the middle, run KepServer or write your own program using open62541:
┌────────────┐
│ MES 系统 │
└─────┬──────┘
│ OPC UA Client
▼
┌──────────────────┐
│ OPC UA Server │ ◄── 聚合网关
│ (KepServerEx等) │
└──┬───┬───┬───┬──┘
│ │ │ │ Modbus TCP
▼ ▼ ▼ ▼
50台 Modbus TCP 从站 (PLC/仪表)Benefit: MES only interfaces with one OPC UA interface, so there is no need to worry about the IP address and register mapping of each device. The gateway has conducted data aggregation and address space modeling internally.
Dual channel: MQTT reporting+Modbus TCP local control
A certain smart agricultural greenhouse: 50 LoRa temperature and humidity sensors are reported to the cloud platform for trend analysis through the LoRa gateway → MQTT. At the same time, the fans and roller shutter motors in the greenhouse are controlled directly through Modbus TCP and the local touch screen (HMI). The cloud platform can also send MQTT commands to the gateway, which converts Modbus TCP commands to control the start and stop of the fan.
┌──────────┐ LoRa ┌────────┐ MQTT ┌──────────┐
│ 传感器×50 │───────→│ LoRa │───────→│ 云平台 │ ← 数据分析
└──────────┘ │ 网关 │ └────┬─────┘
└───┬────┘ │ MQTT 控制指令
│ Modbus TCP ▼
┌───┴────────────┐
│ 本地 HMI + PLC │ ← 实时控制
│ (风机/卷帘) │
└────────────────┘Why is it designed like this? Sensors report small amounts of data but high frequency (per minute), while MQTT saves traffic. The fan control requires low latency (<500ms must respond), and Modbus TCP direct connection is the most reliable. The analysis results of the cloud platform indicate that the loop of control instructions follows MQTT, which can accept a delay of several hundred milliseconds.
When is it not necessary to mix
If your project does not exceed 30 devices, does not require cloud deployment, and does not require remote operation and maintenance - one PLC with Modbus RS-485 bus and one HMI screen, three wires (A/B/GND), is enough. Don't complicate the architecture for the sake of progressiveness. Simplicity in engineering means reliability.
Protocol Combination Quick Check Table
| Scene | number of devices | cloud migration | real-time | multi-brand | Recommended Solution |
|---|---|---|---|---|---|
| Local monitoring of sewage treatment plant | 30 instruments | 否 | Second level enough | 否 | Modbus RTU |
| Distributed photovoltaic power station | 500 inverters | Yes (4G) | Alarm in seconds | 是 | Modbus RTU+MQTT gateway |
| MES in Automotive Welding Workshop | 200 devices | 否 | 是 | Yes (mainly Siemens) | OPC UA |
| Smart agricultural greenhouse | 50 sensors+10 actuators | Yes (LoRa+4G) | Control for one hundred milliseconds | 否 | MQTT Sensor + Modbus TCP Actuator |
| Building Automation | 100 DDC controllers | Optional | Second level enough | Yes (multiple HVAC brands) | Modbus TCP / BACnet + OPC UA |
| Remote device operation and maintenance | Distributed in various places | 是 | non-real-time | 否 | MQTT + TLS |
| Single machine equipment (frequency converter+HMI) | < 10 | 否 | millisecond | 否 | Modbus RTU |
No one will tell you the truth for you
Modbus has no security mechanism, that's true. Its frames are plaintext, and CRC only handles transmission errors regardless of malicious tampering. Someone exposes the Modbus TCP port on the public network, which is no different from leaving the factory door open.
Modbus does not have event driven. Do you want an event? Find a way to poll faster on your own.
Modbus does not have a standard data model. The electricity meter in Factory A stores the voltage in the 40001 register, while Factory B stores the voltage in the 40002 register. Your code is filled with if else to determine the device model.
But Modbus has lived for over forty years not because of its strong functionality, but because it is simple enough. Can run on 8-bit microcontrollers, can run stably at minus 30 degrees Celsius, and can be debugged in an afternoon. MQTT appeared, OPC UA appeared, and it didn't die because there are still many scenarios that don't require advanced features -30 devices, one factory building, local HMI, Modbus RTU all wired to the end, what is over engineering? Hard OPC UA is called over engineering.
On the other hand, if you are facing 500 devices deployed in a distributed manner within a range of 50 kilometers, require cloud platform analysis, and demand alarm push, holding onto Modbus is causing trouble for yourself. At this point, MQTT and Modbus gateway are the most practical choices.
If you are in a factory where multiple brands of PLCs are mixed, the MES system needs to expose a unified interface to the upper layer - OPC UA is the standard answer.
No protocol is perfect, you have chosen the least bad one in your scenario. The wisdom of this profession lies in knowing when it is sufficient and when it is necessary to upgrade.
发表回复