# MODBUS RTU 上位机 **Repository Path**: BUG_MAKER_KING/ModbusRTU_Master_Slave ## Basic Information - **Project Name**: MODBUS RTU 上位机 - **Description**: 基于QT python的MODBUS RTU上位机,可以实现master以及slave模式切换功能 - **Primary Language**: Python - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-05-07 - **Last Updated**: 2026-10-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # MODBUS RTU Master / Slave Tool > Current version: **V2.0** A **PyQt5 + pymodbus** based MODBUS RTU debug tool supporting both **Master** and **Slave** modes. It loads multiple Excel register-definition workbooks for batch read/write, live monitoring and data logging. --- ## Features ### Dual Mode - **Master mode** — set target device ID; supports "Read Selected", "Read All", "Periodic Read", "Write Selected", "Write All" - **Slave mode** — set local device ID; starts a slave server waiting for master requests; the "Current Value" column is directly editable ### Serial Port Configuration - Automatic port scanning with manual refresh - Configurable baud rate (1200 ~ 115200), data bits, stop bits and parity - A dedicated "Open / Close Port" button gates the configuration to prevent accidental operations ### Excel Register Management (Multiple Lists) - Loads `.xlsx` / `.xls`, **multi-select**, up to **10 register lists**; each file becomes one list (tab) - List name = the first `【…】` text in the file name; otherwise `List1/2/3…`; duplicates get a `(2)`/`(3)` suffix - Register type is derived from the file name: if the `【…】` text contains `04` → **Input Register (FC04)**; otherwise (contains `03`, or no `【】`) → **Holding Register (FC03)** - All master operations (read / write / periodic read) apply **only to the currently selected list**; asynchronous results are written back to the originating list - Columns are located **by header name**, so different column orders are supported ```mermaid flowchart LR F["File name
【系统数据04】SysDataWithPV.xlsx"] --> N["List name = 系统数据04"] F --> T{"【】contains '04' ?"} T -- Yes --> I["Input Register FC04"] T -- No --> H["Holding Register FC03"] ``` See [`docs/快速使用指南.md`](docs/快速使用指南.md) (Chinese) for the full naming rules and column reference. ### Engineering Values & Signed 16-bit Handling - Raw 16-bit register values are interpreted as **signed integers**: `raw ≥ 32768` is converted to the corresponding negative value - All displayed values are **engineering values**: `display = raw × coefficient`; writing reverses it as `raw = display / coefficient` (rounded) - Excel supports "范围值" (Range), "系数" (Coefficient) and "单位" (Unit) columns, shown as read-only grey text ### Special Data Processing (Function Command / Info Parsing) - **`ASCII_x` string concatenation** — group addresses must increase consecutively, sequence starts at `ASCII_1`; the concatenated string is shown on the `ASCII_1` row, max 32 characters (truncated with a warning if exceeded) - **`DATA_H` / `DATA_L` 32-bit merge** — adjacent pair combined into a signed 32-bit value, displayed on the `DATA_H` row; `DATA_L` is not shown separately - **Info parsing (bit-change events)** — the symbol in the definition sheet's "信息解析" column must exactly match a column name in the `信息解析` sheet; `BIT0~BIT15` texts are read and `{text}_出现` / `{text}_消失` is printed on bit transitions (never on the first reception) - At most **32** info-parse registers are registered - The "功能命令处理" and "信息解析" columns are **parse-only** — no UI control is created; if the column is missing, the corresponding feature is disabled ### Smart Batch Reading - Consecutive addresses are merged into a single request and automatically split by the protocol per-frame limit: **125** registers per read frame, **123** per write frame - `sleep 50ms` between segments; logs mark "segment N/M" ### Periodic Read - Periodically reads the **currently selected list** in master mode - Interval **50 ~ 60000 ms**, default **1000 ms**, adjustable via `QSpinBox` - Overlap protection: a new round is skipped while the previous one is still running ### Direct Slave Editing - In slave mode, double-click the "Current Value" cell to enter a new value and press Enter - A 500 ms poll synchronizes values written by the master into the slave context back to the table - New lists can be loaded while the slave is running, but **master reads are disabled**; a new list takes effect on the bus only after **restarting the slave service** ### Data Logging - Every visible register row has a **checkbox** at the end; check/uncheck takes effect immediately without reloading - The initial check state comes from the Excel "默认记录选项" column (`1` = checked, `0`/empty = unchecked) - "Start Data Logging" creates a time-stamped CSV in `datalog/` (`yyyy-MM-dd_HH-mm-ss.csv`); the header is `记录时间` plus `address-description` of all visible registers - At a **1 ~ 500 s** interval, only the checked registers are sampled and appended as new rows; unchecked columns are left empty - Switching tabs / reloading a workbook while logging shows a confirmation dialog; the file is saved and closed on exit ### Interaction Log Window - Shows live serial interaction status - Thread-safe **ring buffer** keeping up to **10000** entries - Export to CSV (saved under `./record/`) and one-click clear --- ## Requirements | Dependency | Version | | ---------- | ------------------------ | | Python | 3.8+ | | PyQt5 | 5.15+ | | pymodbus | 2.5+ (v2.x / v3.x) | | pyserial | 3.5+ | | openpyxl | 3.0+ | ## Installation ```bash pip install -r requirements.txt ``` ## Quick Start ```bash # 1. Generate a sample Excel register workbook (optional) python generate_sample_excel.py # 2. Launch the application python modbus_rtu_app.py ``` ### Master Mode Workflow ``` Open port → Load Excel (multi-select) → Set target device ID → "Read Selected / Read All" or "Start Periodic Read" ``` ### Slave Mode Workflow ``` Switch to Slave mode → Load Excel → Set local device ID → Click "Start Slave Service" → Double-click the "Current Value" column to edit → Values written by the master refresh automatically ``` --- ## Excel File Format A workbook may contain two sheets: - **`寄存器定义` (Register Definition, required)** — the register list; if missing, the import fails with a dialog - **`信息解析` (Info Parsing, optional)** — the bit-definition mapping; if missing, the info-parsing feature is disabled silently `寄存器定义` supported columns (located by header name; order may vary): | Column | Required | Description | | --- | --- | --- | | 寄存器地址 | ✅ | Row identity | | 物理量含义 | — | Display name, also used in the data-log header | | 范围值 | — | Text note only, not used by read/write logic | | 系数 | — | Engineering scaling; missing/empty = 1.0; 0 or negative → 1.0 | | 单位 | — | Unit text, display only | | 读写权限 | — | `R`/`READ`, `W`/`WRITE`, `RW`/`R/W`/`READ/WRITE`; default read-only | | 初始值 | — | **Slave-mode** initial value only; the master never writes it | | 是否可见 | — | `Y` = visible, `N` = fully hidden; default/empty = `Y` | | 功能命令处理 | — | `ASCII_x` / `DATA_H` / `DATA_L`, parse-only | | 信息解析 | — | Identity symbol matched against `信息解析` sheet columns, parse-only | | 默认记录选项 | — | `1` = checked for logging, `0`/empty = unchecked; missing column → all unchecked | Example: | 寄存器地址 | 物理量含义 | 范围值 | 系数 | 单位 | 读写权限 | 初始值 | 是否可见 | | ---------- | ---------- | ------ | ---- | ---- | -------- | ------ | -------- | | 100 | Temperature | 0~100 | 0.1 | °C | R | 0 | Y | | 200 | Setpoint | 0~100 | 0.1 | °C | RW | 250 | Y | - **Row 1** is the header; data starts at **row 2** - Read/write permission accepts: `R`/`READ`, `W`/`WRITE`, `RW`/`R/W`/`READ/WRITE` --- ## Directory Layout ``` ModbusRTU/ ├── modbus_rtu_app.py # Main application ├── generate_sample_excel.py # Sample Excel generator ├── requirements.txt # Python dependencies ├── sample_registers.xlsx # Sample register workbook (both sheets, all columns) ├── docs/ # Documentation ├── icon/ # Application icon resources ├── record/ # Exported log CSV directory (auto-created) ├── datalog/ # Data-log CSV directory (auto-created) └── dist/ # Build output (standalone exe) ``` --- ## Packaging as a Standalone EXE ```bash python -m PyInstaller --clean --noconfirm --onefile --windowed ^ --name "ModbusRTU上位机V2.0" --icon "icon\Image.ico" ^ --add-data "icon\Image.ico;icon" ^ --hidden-import pymodbus.client --hidden-import pymodbus.server ^ --hidden-import pymodbus.simulator --hidden-import pymodbus.datastore ^ --hidden-import pymodbus.transaction --hidden-import pymodbus.framer ^ --hidden-import serial.tools.list_ports --hidden-import openpyxl.cell._writer ^ modbus_rtu_app.py ``` - Produces a **single-file** executable; the target machine needs no Python or dependencies - At runtime `record/` and `datalog/` are created **next to the exe**, so the whole folder can be copied --- ## Author **BugMaker** ## License MIT License