Industrial Data Collection with AWS IoT Core: From ZMA Devices to Cloud

Amazeng Technical Team
5 min read
AWS IoT CoreMQTTZMAGDTModbus GatewayCloud IoTIndustrial IoT

To move data from field devices that speak Modbus RTU/TCP into AWS IoT Core, you place an IoT Gateway in between: the gateway polls the devices over Modbus, packages the values as JSON, authenticates with an X.509 certificate and publishes to IoT Core over MQTT over TLS (port 8883). Rules in IoT Core then route those messages to a database, to Lambda or to alerting services.

Moving industrial data to the cloud is the cornerstone of Industry 4.0 and predictive maintenance; however, field sensor data is usually carried over traditional protocols such as Modbus RTU or Modbus TCP and cannot connect to AWS directly.

In this article, we examine in detail how data collected via Modbus from our ZMA Data Acquisition and GDT Digital Transmitter devices is transferred to AWS IoT Core through an IoT Gateway.

How is the architecture laid out?

┌─────────────────────────────────────────────────────────────┐
│                    Factory / Field                          │
│                                                             │
│  ┌─────────┐    Modbus RTU/TCP    ┌──────────────┐        │
│  │ ZMA-4   │◄────────────────────►│              │        │
│  │ Device  │                      │  IoT Gateway │        │
│  └─────────┘                      │  (Linux Box) │        │
│                                   │              │        │
│  ┌─────────┐    Modbus RTU/TCP    │  - Modbus    │        │
│  │ GDT     │◄────────────────────►│    Client    │        │
│  │ Trans.  │                      │  - MQTT      │        │
│  └─────────┘                      │    Client    │        │
│                                   │  - TLS/SSL   │        │
│                                   └───────┬──────┘        │
└───────────────────────────────────────────┼───────────────┘
                                            │
                                            │ MQTT over TLS
                                            │ Port 8883
                                            ▼
                                   ┌────────────────┐
                                   │   AWS Cloud    │
                                   │                │
                                   │  ┌──────────┐  │
                                   │  │ IoT Core │  │
                                   │  └────┬─────┘  │
                                   │       │        │
                                   │  ┌────▼─────┐  │
                                   │  │Timestream│  │
                                   │  └──────────┘  │
                                   └────────────────┘

Why is an IoT Gateway needed?

ZMA and GDT devices communicate via Modbus RTU (RS485) and Modbus TCP (Ethernet). AWS IoT Core uses MQTT. An IoT Gateway is needed to perform protocol conversion between these two worlds.

Gateway Options

  1. Raspberry Pi / Jetson Nano: Linux-based, custom script in Python/Node.js
  2. Industrial IoT Gateways: Ready-made solutions from vendors such as Moxa, Advantech and Siemens
  3. Our HMI Panel: Can act as both HMI and gateway on embedded Linux
  4. PLC + OPC UA: Cloud connection via the PLC's OPC UA server

In this article we build a custom gateway with a Raspberry Pi 4 and Python, but the same logic applies to every platform.

AWS IoT Core Setup

1. Create a Thing (Device)

AWS Console → IoT Core → Manage → Things → Create

{
  "thingName": "amazeng-factory-gateway-01",
  "thingTypeName": "ModbusGateway",
  "attributes": {
    "location": "Istanbul-Factory-A",
    "firmware": "1.0.0"
  }
}

2. Create and Download a Certificate

Every IoT device connects to AWS with an X.509 certificate:

# Create a certificate with the AWS CLI
aws iot create-keys-and-certificate \
  --set-as-active \
  --certificate-pem-outfile gateway-cert.pem \
  --public-key-outfile gateway-public.key \
  --private-key-outfile gateway-private.key

Important: Store gateway-private.key securely; it cannot be downloaded again!

3. Define a Policy

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["iot:Connect"],
      "Resource": "arn:aws:iot:eu-west-1:123456789:client/${iot:Connection.Thing.ThingName}"
    },
    {
      "Effect": "Allow",
      "Action": ["iot:Publish"],
      "Resource": "arn:aws:iot:eu-west-1:123456789:topic/amazeng/factory/*"
    },
    {
      "Effect": "Allow",
      "Action": ["iot:Subscribe"],
      "Resource": "arn:aws:iot:eu-west-1:123456789:topicfilter/amazeng/factory/commands/*"
    }
  ]
}

4. Attach the Policy to the Certificate

aws iot attach-policy \
  --policy-name amazeng-gateway-policy \
  --target arn:aws:iot:eu-west-1:123456789:cert/xxxxx

IoT Gateway Software (Python)

Required Libraries

pip install "pymodbus<3" awsiotsdk

The example below uses the pymodbus 2.x API. In pymodbus 3.x the import path (pymodbus.client) and the name of the unit/slave parameter have changed, so adapt the code to the version you use.

Modbus Client Configuration

config.json

{
  "modbus_devices": [
    {
      "name": "ZMA-Tank1",
      "type": "tcp",
      "host": "192.168.1.101",
      "port": 502,
      "unit_id": 1,
      "registers": [
        { "address": 0, "count": 2, "type": "float", "name": "channel_1" },
        { "address": 2, "count": 2, "type": "float", "name": "channel_2" },
        { "address": 4, "count": 2, "type": "float", "name": "channel_3" },
        { "address": 6, "count": 2, "type": "float", "name": "channel_4" }
      ]
    },
    {
      "name": "GDT-Loadcell",
      "type": "tcp",
      "host": "192.168.1.102",
      "port": 502,
      "unit_id": 1,
      "registers": [
        { "address": 0, "count": 2, "type": "float", "name": "net_weight" },
        { "address": 2, "count": 2, "type": "float", "name": "gross_weight" }
      ]
    }
  ],
  "aws_iot": {
    "endpoint": "xxxxx-ats.iot.eu-west-1.amazonaws.com",
    "port": 8883,
    "cert_path": "/etc/iot-gateway/certs/",
    "thing_name": "amazeng-factory-gateway-01",
    "topic_prefix": "amazeng/factory"
  },
  "polling_interval": 1.0
}

Main Gateway Application

gateway.py

#!/usr/bin/env python3

import json
import time
import struct
from pymodbus.client.sync import ModbusTcpClient, ModbusSerialClient
from awscrt import io, mqtt
from awsiot import mqtt_connection_builder

class ModbusToMQTTGateway:
    def __init__(self, config_file):
        with open(config_file, 'r') as f:
            self.config = json.load(f)

        self.modbus_clients = {}
        self.mqtt_connection = None

        # Create Modbus clients
        for device in self.config['modbus_devices']:
            if device['type'] == 'tcp':
                client = ModbusTcpClient(device['host'], port=device['port'])
            elif device['type'] == 'rtu':
                client = ModbusSerialClient(
                    method='rtu',
                    port=device['port'],
                    baudrate=device.get('baudrate', 9600),
                    timeout=device.get('timeout', 1)
                )

            client.connect()
            self.modbus_clients[device['name']] = {
                'client': client,
                'config': device
            }

        # AWS IoT MQTT connection
        self._setup_mqtt()

    def _setup_mqtt(self):
        """Set up the AWS IoT Core MQTT connection"""
        aws_config = self.config['aws_iot']
        cert_path = aws_config['cert_path']

        # Secure connection with mutual TLS
        self.mqtt_connection = mqtt_connection_builder.mtls_from_path(
            endpoint=aws_config['endpoint'],
            port=aws_config['port'],
            cert_filepath=f"{cert_path}gateway-cert.pem",
            pri_key_filepath=f"{cert_path}gateway-private.key",
            ca_filepath=f"{cert_path}AmazonRootCA1.pem",
            client_id=aws_config['thing_name'],
            clean_session=False,
            keep_alive_secs=30
        )

        # Connect
        connect_future = self.mqtt_connection.connect()
        connect_future.result()
        print(f"✓ Connected to AWS IoT Core: {aws_config['endpoint']}")

    def read_modbus_device(self, device_name):
        """Read all registers from a Modbus device"""
        device = self.modbus_clients[device_name]
        client = device['client']
        config = device['config']

        data = {
            'device_name': device_name,
            'timestamp': int(time.time() * 1000),
            'values': {}
        }

        for register in config['registers']:
            try:
                # Read holding registers
                result = client.read_holding_registers(
                    address=register['address'],
                    count=register['count'],
                    unit=config['unit_id']
                )

                if not result.isError():
                    # Float conversion (IEEE 754)
                    if register['type'] == 'float' and register['count'] == 2:
                        raw = (result.registers[0] << 16) | result.registers[1]
                        value = struct.unpack('f', struct.pack('I', raw))[0]
                    elif register['type'] == 'int':
                        value = result.registers[0]

                    data['values'][register['name']] = round(value, 3)
                else:
                    print(f"✗ Modbus read error: {device_name} @ {register['address']}")
                    data['values'][register['name']] = None

            except Exception as e:
                print(f"✗ Error: {device_name} - {e}")
                data['values'][register['name']] = None

        return data

    def publish_to_aws(self, device_name, data):
        """Publish data to AWS IoT Core"""
        topic = f"{self.config['aws_iot']['topic_prefix']}/{device_name}/data"
        payload = json.dumps(data)

        self.mqtt_connection.publish(
            topic=topic,
            payload=payload,
            qos=mqtt.QoS.AT_LEAST_ONCE
        )

        print(f"→ Published to {topic}: {payload}")

    def run(self):
        """Main loop: read from Modbus, publish to MQTT"""
        interval = self.config['polling_interval']

        print(f"Gateway started. Polling interval: {interval}s")

        try:
            while True:
                for device_name in self.modbus_clients.keys():
                    # Read from Modbus
                    data = self.read_modbus_device(device_name)

                    # Send to AWS
                    self.publish_to_aws(device_name, data)

                time.sleep(interval)

        except KeyboardInterrupt:
            print("\nStopping gateway...")
            self.shutdown()

    def shutdown(self):
        """Close connections"""
        for device in self.modbus_clients.values():
            device['client'].close()

        disconnect_future = self.mqtt_connection.disconnect()
        disconnect_future.result()
        print("✓ All connections closed")

if __name__ == "__main__":
    gateway = ModbusToMQTTGateway('/etc/iot-gateway/config.json')
    gateway.run()

Running as a systemd Service

/etc/systemd/system/iot-gateway.service

[Unit]
Description=Amazeng Modbus to AWS IoT Gateway
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/iot-gateway
ExecStart=/usr/bin/python3 /opt/iot-gateway/gateway.py
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
sudo systemctl enable iot-gateway
sudo systemctl start iot-gateway
sudo systemctl status iot-gateway

Data Flow in AWS IoT Core

Writing to Timestream with the Rules Engine

AWS IoT Core → Act → Rules → Create

SELECT
  device_name,
  timestamp,
  values.channel_1 as ch1,
  values.channel_2 as ch2,
  values.channel_3 as ch3,
  values.channel_4 as ch4
FROM 'amazeng/factory/+/data'
WHERE device_name = 'ZMA-Tank1'

Action: Write to Amazon Timestream

{
  "roleArn": "arn:aws:iam::123456789:role/IoTTimestreamRole",
  "databaseName": "AmazengFactory",
  "tableName": "SensorData",
  "dimensions": [{ "name": "device", "value": "${device_name}" }],
  "timestamp": {
    "value": "${timestamp}",
    "unit": "MILLISECONDS"
  }
}

Note: AWS closed Amazon Timestream for LiveAnalytics to new customers as of June 20, 2025; existing accounts can keep using it. For new projects, consider Amazon Timestream for InfluxDB, which AWS recommends, or another destination supported by IoT rules (for example your own database via Lambda, or S3). See our Amazon Timestream article for details.

Monitoring with CloudWatch

IoT Core publishes CloudWatch metrics in the AWS/IoT namespace (for example PublishIn.Success for successful inbound publishes). By putting an alarm on this metric, you can, for instance, email the maintenance team if no messages arrive for 5 minutes. For per-device monitoring, have the gateway publish a periodic "heartbeat" message.

Real-Time Alarm Scenario

Lambda Function for Threshold Control

alarm_handler.py

import json
import boto3

sns = boto3.client('sns')

def lambda_handler(event, context):
    # Data from IoT Core
    device = event['device_name']
    weight = event['values'].get('net_weight', 0)

    # Threshold check
    if weight > 5000:  # Over 5 tonnes
        message = f"ALARM: {device} - Weight limit exceeded: {weight} kg"

        sns.publish(
            TopicArn='arn:aws:sns:eu-west-1:123456789:factory-alarms',
            Subject='Tank Capacity Alarm',
            Message=message
        )

        return {'statusCode': 200, 'body': 'Alarm sent'}

    return {'statusCode': 200, 'body': 'Normal'}

Security Best Practices

1. Certificate Rotation

Renew certificates periodically (for example every 90 days, per your organisation's policy). The CSR method is preferred so the private key never leaves the device:

openssl req -new -newkey rsa:2048 -nodes \
  -keyout gateway-private.key -out gateway.csr -subj "/CN=amazeng-factory-gateway-01"

aws iot create-certificate-from-csr \
  --certificate-signing-request file://gateway.csr \
  --certificate-pem-outfile gateway-cert.pem \
  --set-as-active

2. IoT Policies - Least Privilege

Let the gateway publish only to its own topic:

{
  "Resource": "arn:aws:iot:*:*:topic/amazeng/factory/${iot:Connection.Thing.ThingName}/*"
}

3. VPN/Firewall

Limit the gateway's outbound internet access to what it needs:

# Deny all outbound traffic by default, then open only what is required
sudo ufw default deny outgoing
sudo ufw allow out 53        # DNS (to resolve the endpoint)
sudo ufw allow out 123/udp   # NTP (TLS certificate validation needs correct time)
sudo ufw allow out 8883/tcp  # MQTT over TLS

Remember to also open port 502 for Modbus TCP devices, restricted to the field subnet only.

Cost Analysis

AWS IoT Core Pricing (eu-west-1)

Scenario: 1 gateway with 2 Modbus devices behind it, 1 message per device per second (under 5 KB), 30 days.

ComponentUnit priceCalculationMonthly
Connectivity$0.08 / million connection-minutes1 connection × 43,200 min = 0.0432 M min≈ $0.003
Messaging$1.00 / million messages (first 1 billion)2 × 86,400 × 30 = 5.18 M messages≈ $5.18
Rules EnginePer rule triggered and per action5.18 M rules + 5.18 M actionsSee regional price

Points to note:

  • Messages are metered in 5 KB increments; a 6 KB message counts as 2 messages. The maximum size of a single message is 128 KB.
  • The connectivity charge is per MQTT connection, not per device. Connecting every device through one gateway makes this item almost zero.
  • Message count drives the real cost: combining both devices' readings into one JSON halves the number of messages and rule executions.
  • The destination database (Timestream, InfluxDB, S3, etc.) is billed separately.

Prices can change; check the AWS IoT Core pricing page for current values.

Alternative Gateway Solutions

1. Gateway Integrated into an HMI Panel

Because our HMI Industrial Display Solutions run on embedded Linux, they can serve as both the operator interface and the gateway:

# The same gateway.py script running on the HMI panel
# + a local Qt/QML user interface

2. Off-the-Shelf Industrial IoT Gateway

Industrial gateways from vendors such as Moxa and Advantech come with DIN-rail mounting, a wide operating temperature range, and serial (RS232/485) and Ethernet ports. When choosing a model, verify port count, temperature range and AWS IoT support in the vendor's datasheet.

3. No-Code Gateway with Node-RED

Install Node-RED on a Raspberry Pi and build the gateway with drag and drop:

[Modbus] → [Function] → [MQTT out]

Summary: Moving ZMA and GDT Data to AWS

Our ZMA and GDT products can easily connect to AWS IoT Core through an IoT Gateway thanks to Modbus RTU/TCP support. This enables:

✅ Real-time data monitoring (Grafana/QuickSight)
✅ Long-term data storage (time-series database)
✅ Predictive maintenance (AI/ML models)
✅ Remote alarms and notifications

For more information about our Cloud & IoT Data Collection Solutions, contact us.