好的,这是一份详细的Cursor自动化代码生成提示词,它基于您提供的Qt工程师任务分解,旨在引导Cursor生成实现所述功能的Qt Modbus上位机应用代码。
Prompt for Cursor:
Please generate a Qt C++ application project that acts as a Modbus RTU master (client) to communicate with an industrial chiller via RS-485 serial port.
The application should implement the following features based on the provided requirements:
Project Setup:
- Create a standard Qt Widgets application project.
- Use C++17 or later.
- Structure the code logically with appropriate classes for UI, serial communication, Modbus protocol handling, and data management.
Core Communication (Modbus RTU over Serial):
- Serial Port Configuration:
- Utilize
QSerialPort to manage the serial connection.
- Implement a configuration dialog or section in the main window to allow selecting the serial port name (e.g., COM1, /dev/ttyUSB0).
- Configure the port programmatically upon connection with the fixed parameters:
- Baud Rate: 9600
- Data Bits: 8
- Parity: None
- Stop Bits: 1
- Flow Control: None
- Handle opening and closing the serial port.
- Modbus RTU Implementation:
- Implement a custom Modbus RTU client/master logic. Do not rely on a separate
QModbus library unless specifically requested (the requirement implies a byte-level implementation).
- CRC-16 Calculation: Implement the Modbus standard CRC-16 algorithm for appending to outbound frames and verifying inbound frames.
- Frame Building: Create functions to construct Modbus request frames for the specified function codes:
01 (Read Coils): For reading output switch states.
02 (Read Discrete Inputs): For reading input switch states.
03 (Read Holding Registers): For reading analog values (temperatures, flow, run times, fault codes) and configuration registers (system status, device address).
06 (Write Single Holding Register): For writing single registers (e.g., system status, device address, factory reset trigger).
16 (Write Multiple Holding Registers): Although 06 is sufficient for the specified writes (status, address, factory reset), implement 16 as well for completeness as it's a standard write function (could be used for writing multiple parameters later).
- Frame Parsing: Create functions to parse incoming Modbus response frames:
- Verify CRC-16.
- Check for valid response structure (slave address, function code, data length).
- Extract data based on the function code and requested addresses/lengths.
- Handle potential Modbus exception responses (function code + 0x80).
- Communication Flow Management:
- Implement a polling mechanism to periodically request data from the chiller (e.g., every 1-5 seconds).
- Manage a request queue or state machine to send one request at a time and wait for a response before sending the next.
- Implement a timeout mechanism for responses (e.g., 500ms - 1 second). If a timeout occurs, handle it (e.g., log error, mark data as stale, potentially retry).
- Handle
QSerialPort::readyRead() signal to receive incoming data byte by byte or in chunks. Buffer incoming data until a complete Modbus frame (with valid CRC) is received.
Functionality and Data Processing:
- Data Model:
- Create a C++ class or structure (
ChillerData or similar) to hold the current state and values read from the chiller. This should include:
- Discrete Inputs (bools or bits): Represent states like flow switch.
- Coils (bools or bits): Represent states like alarm, compressor status.
- Holding Registers (integers): Raw values for temperatures, flow, run times, fault codes, system status, device address, etc.
- Processed values (floats for temps/flow, translated strings for states/faults).
- Implement methods to update this model based on parsed Modbus responses.
- Data Processing & Interpretation:
- Bit Parsing (01, 02): For coils/discrete inputs received in byte form, extract individual bit states (e.g., byte
0x05 -> Bit0 is 1, Bit2 is 1). Map these bits to meaningful boolean states (Alarm Active, Compressor Running, Flow OK, etc.).
- Analog Value Scaling (04, 03): For registers representing temperatures and flow, divide the received integer value by 10.0 to get the actual float value.
- Fault Code Mapping (03): Read the fault code register value. Implement a mapping (e.g.,
QMap<int, QString>) to translate integer fault codes (like 1) into user-friendly string descriptions ("Environment Temperature Sensor Fault"). If the fault code is 0, it means no fault.
- Run Time Parsing (03): Read run time registers as unsigned integers.
- System Status/Device Address (03): Read and store these register values.
- Parameter Writing (06/16):
- Implement functions to construct and send write commands for:
- System Status (Register 25): Allow writing specific values (e.g., 0=Standby, 1=Running, 2=Fault - though writing 2 might not be standard). A common approach is writing values like 0 (Stop) or 1 (Run).
- Device Address (Register 37): Allow writing a new Modbus slave address.
- Factory Reset (Register 15): Write the value
1 to this register to trigger the reset. Add a confirmation dialog for this action.
- Implement input validation before sending writes (e.g., validate device address range, system status values).
- Handle responses to write commands (they typically echo the request).
User Interface Design (using Qt Widgets):
- Main Window:
- Display the connection status (e.g., connected/disconnected indicator).
- Status Indicators: Use colored labels or indicator widgets for key boolean states (Alarm, Compressor, Flow Switch, System Status).
- Real-time Data Display: Use labels or a
QTableWidget to show current values:
- Media Temperature (float)
- Environment Temperature (float)
- Flow Rate (float)
- System Status (translated string: Standby, Running, Fault)
- Current Fault Code (translated string or "No Fault")
- System Run Time (unsigned integer, maybe formatted as HH:MM:SS)
- Compressor Run Time (unsigned integer, maybe formatted as HH:MM:SS)
- Device Address (integer)
- (Optional but good): Add a simple logging area (e.g.,
QTextEdit) to show communication events (sent/received frames, errors, timeouts).
- (Optional for trends): Mention the possibility of adding charts (e.g.,
Qt Charts) for temperature/flow trends, but focus on the table/label display first.
- Configuration/Control Section (can be in main window or separate dialog):
- Serial Port Selection (ComboBox).
- Connect/Disconnect button.
- Input field and button to set System Status (e.g., dropdown or buttons for Standby/Run).
- Input field and button to set Device Address.
- Button to trigger Factory Reset (with confirmation).
- (Optional): Polling rate setting.
- Alarm Handling:
- When an alarm state (from Coils or Fault Code) is detected, display a prominent visual indicator on the main window.
- Pop up a
QMessageBox or a custom notification window describing the active alarm (using the translated fault description or a pre-defined alarm message for specific coil bits).
- Maintain a list or table of active alarms.
- (Optional): Implement an alarm history list/table displaying timestamp and description.
- Safety/Maintenance:
- Add a prominent
QLabel on the main window with a warning message like: "Maintenance Warning: Ensure power is disconnected for at least 3 minutes before servicing."
Concurrency and Robustness:
- Threading: Implement the serial communication and Modbus polling logic in a separate thread (
QThread) to keep the main UI thread responsive. Use signals and slots with Qt::QueuedConnection to communicate between the worker thread and the UI thread (e.g., thread emits dataReady(ChillerData) signal, UI slot updates display).
- Error Handling:
- Display communication errors (timeout, CRC error, invalid response) in the log area and/or status bar.
- Implement a retry mechanism for communication failures (e.g., 2-3 retries before declaring device offline).
- Gracefully handle serial port errors (e.g., port disconnected).
- Prevent sending write commands with invalid data.
Code Structure and Notes:
- Create classes like:
MainWindow (UI management)
SerialWorker (Manages QSerialPort and runs in a separate thread)
ModbusRTUClient (Implements Modbus frame building/parsing, sends/receives via SerialWorker)
ChillerData (Data model)
CRC16 (Helper class/functions for CRC)
- Add comments explaining key logic, especially Modbus frame structure and data parsing.
- Provide a basic address mapping placeholder in the code (e.g., constants or a map) based on the description (Address 0/Coil 0 = Alarm, Address 0/DI 0 = Flow Switch, Register 25 = System Status, Register 37 = Device Address, Register 15 = Factory Reset Trigger, Registers for temps/flow/run times/faults).
- The code should be runnable (though it will require a serial port or simulator).
Key Implementation Hints to Follow:
- Use the user's provided snippets for frame building and float scaling (
/ 10.0) as examples of the required logic.
- Focus on getting the core read/write Modbus logic and serial communication working first, then integrate with the UI and error handling.
Please generate the initial project structure and core classes (MainWindow, SerialWorker, ModbusRTUClient, ChillerData), including placeholder UI elements and the basic Modbus frame handling and serial communication setup within the worker thread. Provide explanations for the key parts of the code and how the components interact using signals and slots.
This detailed prompt covers all the points from your task breakdown, providing Cursor with a clear roadmap to generate the required Qt application code. It specifies the technologies, architecture, required functionalities, UI elements, and even includes hints and structure suggestions.