作为开发者,将我们的代码运行在真实的工业硬件上,并与物理世界进行交互,是一件极具成就感的事情。本文旨在提供一个这样的实战机会。我们将跳过“Hello World”,直接构建一个有实际意义的Modbus数据监控应用,带你走通在工业边缘计算网关上进行应用开发的完整流程。

项目目标

创建一个Web应用,部署在工业边缘计算网关上,实现以下功能:

  • 通过网关的RS485串口,轮询一个Modbus从站设备。

  • 读取一个温度寄存器的值。

  • 通过一个简洁的Web页面,实时展示当前温度。

1. Python Web应用 (app.py)

我们使用轻量级的Flask框架。核心是集成minimalmodbus库来处理串口通信。

Python

from flask import Flask, jsonify
import minimalmodbus
import os
import threading
import time

# --- Configuration ---
SERIAL_PORT = os.getenv('SERIAL_PORT', '/dev/ttyS1')
SLAVE_ID = 1
REGISTER_ADDRESS = 100 # Example temperature register
app = Flask(__name__)

# --- Global variable to store temperature ---
current_temperature = {"value": "N/A"}

# --- Modbus Polling Thread ---
def poll_modbus_sensor():
    """Background thread to poll the sensor every 2 seconds."""
    instrument = minimalmodbus.Instrument(SERIAL_PORT, SLAVE_ID)
    instrument.serial.baudrate = 9600
    instrument.serial.timeout = 1
    
    while True:
        try:
            temp = instrument.read_register(REGISTER_ADDRESS, 1) # Read register, 1 decimal
            current_temperature['value'] = temp
            print(f"Read temperature: {temp}")
        except Exception as e:
            current_temperature['value'] = "Error"
            print(f"Modbus read error: {e}")
        time.sleep(2)

# --- Flask Routes ---
@app.route('/')
def index():
    # Simple HTML page with JS to auto-refresh data
    return """
    <html>
        <head><title>Edge Gateway Monitor</title></head>
        <body>
            <h1>Live Temperature</h1>
            <h2><span id="temp">--</span> &deg;C</h2>
            <script>
                function fetchTemp() {
                    fetch('/api/temperature')
                        .then(response => response.json())
                        .then(data => {
                            document.getElementById('temp').innerText = data.value;
                        });
                }
                setInterval(fetchTemp, 2000); // Refresh every 2 seconds
                fetchTemp();
            </script>
        </body>
    </html>
    """

@app.route('/api/temperature')
def get_temperature():
    return jsonify(current_temperature)

if __name__ == '__main__':
    # Start the background polling thread
    polling_thread = threading.Thread(target=poll_modbus_sensor)
    polling_thread.daemon = True
    polling_thread.start()
    
    # Start the Flask web server
    app.run(host='0.0.0.0', port=5000)

2. 依赖与Dockerfile (requirements.txt & Dockerfile)

requirements.txt:

Flask>=2.0
minimalmodbus>=2.0

Dockerfile:

Dockerfile

# Use an ARM64 compatible Python base image
FROM arm64v8/python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app.py .

# Expose the port the app runs on
EXPOSE 5000

# Run the application
CMD ["python", "app.py"]

3. 部署与运行 (docker-compose.yml)

为了方便管理和映射串口设备,我们使用docker-compose

docker-compose.yml:

YAML

version: '3.8'
services:
  modbus-web-monitor:
    build: .
    container_name: modbus_monitor
    restart: always
    ports:
      - "5000:5000"
    devices:
      - "/dev/ttyS1:/dev/ttyS1" # Map the host's serial port into the container
    environment:
      - SERIAL_PORT=/dev/ttyS1

4. 部署到边缘计算网关

  1. 打包文件:app.py, requirements.txt, Dockerfile, docker-compose.yml四个文件放在同一个目录下。

  2. 连接网关: 通过SSH登录到您的鲁邦通边缘计算网关。

  3. 上传文件: 使用scpsftp工具,将整个目录上传到网关的某个路径下(例如/home/admin/modbus_app)。

  4. 构建与运行:

    Bash

    # Navigate to the app directory
    cd /home/admin/modbus_app
    
    # Build and run the application using docker-compose
    docker-compose up --build -d
    
  5. 验证: 打开浏览器,访问http://<网关IP地址>:5000,您应该能看到实时刷新温度的Web页面。

常见问题解答 (FAQ)

  • 问题1:为什么要在容器内运行,而不是直接在宿主机上运行Python脚本?

    • 答:为了环境隔离可移植性。在容器内运行,可以确保您的应用依赖(如特定版本的Python和库)不会与系统或其他应用冲突。同时,打包成镜像后,可以非常方便地迁移到任何其他支持Docker的工业边缘计算网关上。

  • 问题2:如果我的串口不是ttyS1怎么办?

    • 答:您可以在网关的宿主机上通过dmesg | grep ttyls /dev/tty*来查找实际的串口设备文件名,然后相应地修改docker-compose.yml和环境变量即可。

  • 问题3:这个应用如何进行规模化部署?

    • 答:这正是RCMS设备管理云平台的用武之地。您可以将构建好的Docker镜像推送到镜像仓库,然后在RCMS上通过其“应用中心”功能,将这个应用批量部署到成百上千台设备上,并统一管理其配置和生命周期。

总结鲁邦通工业边缘计算网关为开发者提供了一个标准而强大的平台,让我们能够利用熟悉的Web技术栈(如Python Flask)和现代化的DevOps工具(如Docker),快速构建和部署有价值的IIoT应用。通过本文这个简单的实战项目,您已经掌握了在边缘进行数据采集、处理和可视化呈现的完整闭环,这是通往更复杂边缘智能应用的坚实第一步。

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐