#ifndef RS485CONTROLLER_H
#define RS485CONTROLLER_H

#include <QObject>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QThread>
#include <QMutex>
#include <QQueue>
#include <QTimer>
#include <QWaitCondition>

class RS485Controller : public QObject
{
    Q_OBJECT
public:
    explicit RS485Controller(QObject *parent = nullptr);
    ~RS485Controller();

    bool openPort(const QString& portName = "/dev/ttys2",
                  qint32 baudRate = QSerialPort::Baud9600,
                  QSerialPort::DataBits dataBits = QSerialPort::Data8,
                  QSerialPort::Parity parity = QSerialPort::NoParity,
                  QSerialPort::StopBits stopBits = QSerialPort::OneStop,
                  QSerialPort::FlowControl flowControl = QSerialPort::NoFlowControl);

    void closePort();
    void sendData(const QByteArray& data);
    bool sendData(const QByteArray& data, int timeout); // 新增带超时的发送接口

signals:
    void dataReceived(const QByteArray& data);
    void errorOccurred(const QString& errorString);
    void responseReceived(const QByteArray& data); // 新增响应接收信号

private slots:
    void handleReadRead();
    void handleError(QSerialPort::SerialPortError error);
    void handleTimeout(); // 新增超时处理槽函数

private:
    void processSendQueue();
    void setupResponseTimer(); // 初始化响应定时器

private:
    QSerialPort *m_serialPort;
    QThread *m_workerThread;
    QMutex m_mutex;
    QQueue<QByteArray> m_sendQueue;
    QWaitCondition m_queueNotEmpty;
    bool m_stopped = false;

    // 新增响应等待相关成员
    QTimer *m_responseTimer;
    bool m_waitingResponse;
    QMutex m_responseMutex;
    QWaitCondition m_responseCondition;
};

#endif // RS485CONTROLLER_H
