|
- #ifndef MODBUSSIMULATOR_H
- #define MODBUSSIMULATOR_H
-
- #include <QObject>
- #include <QModbusRtuSerialMaster>
- #include <QSet>
- #include <QMutex>
- #include <QThread>
- #include <atomic>
-
- class PollingWorker; // 前向声明
-
- class ModbusSimulator : public QObject
- {
- Q_OBJECT
-
- public:
- explicit ModbusSimulator(QObject *parent = nullptr);
- ~ModbusSimulator();
-
- void startSimulation();
- void stopSimulation();
- bool isRunning() const;
-
- void setCoilAddresses(const QSet<int> &addresses);
- void writeCoil(int address, bool state);
-
- signals:
- void coilStatusRead(int address, bool state);
- void errorOccurred(const QString &message);
-
- private:
- QModbusRtuSerialMaster *m_modbusClient;
- QSet<int> m_coilAddresses;
- std::atomic<bool> m_running;
- QMutex m_mutex;
- QThread *m_workerThread;
- PollingWorker *m_worker;
- };
-
- // 轮询工作线程类
- class PollingWorker : public QObject
- {
- Q_OBJECT
- public:
- void stop() { m_stop = true; } // 新增公共接口
- explicit PollingWorker(QModbusRtuSerialMaster *client,
- QMutex *mutex,
- QSet<int> *addresses,
- std::atomic<bool> *runningFlag,
- QObject *parent = nullptr);
-
- public slots:
- void startPolling(int interval);
-
- signals:
- void coilReadResult(int address, bool state);
- void errorOccurred(const QString &message);
-
- private:
- void performCoilReading();
-
- QModbusRtuSerialMaster *m_modbusClient;
- QMutex *m_mutex;
- QSet<int> *m_coilAddresses;
- std::atomic<bool> *m_runningFlag;
- std::atomic<bool> m_stop;
- };
-
- #endif // MODBUSSIMULATOR_H
|