#include "eqptcontrol.h"
#include <QThread>
#include <QDebug>
#include <QTimer>
EqptControl::EqptControl(QObject *parent) : QObject(parent)
{

}

void EqptControl::setComm(QString ComName, long baudRate)
{
    qDebug()<<"硬件控制子线程:"<< QThread::currentThreadId()<<ComName<<baudRate;
    SerialPort = new QSerialPort(this);
    // 设置串口号
    SerialPort->setPortName(ComName);
    // 打开串口
    if(SerialPort->open(QIODevice::ReadWrite))
    {
        // 设置波特率
        SerialPort->setBaudRate(baudRate);
        SerialPort->setDataBits(QSerialPort::Data8);
        SerialPort->setParity(QSerialPort::NoParity);
        // 设置流控制
        SerialPort->setFlowControl(QSerialPort::NoFlowControl);
        SerialPort->setStopBits(QSerialPort::OneStop);
        qDebug()<<"打开RFID";
        emit SendRFIDStatus(true);
    }else {
        qDebug()<<"打开道闸控制失败";
        emit SendRFIDStatus(false);
    }
    connect(SerialPort,&QSerialPort::readyRead,this,[=](){
        QByteArray data = SerialPort->readAll();
        //QString str(SerialPort.readAll());
        //qDebug()<<"接收到的初始数据:"<<data;
        emit SendToBridge(data);
    });
    connect(this,&EqptControl::SendToSelf_Close,this,[=](){
        SerialPort->close();
        emit SendRFIDStatus(false);
    });
    ///控制信号触发
    connect(this,&EqptControl::SendToSelf_HeadTrunkUp,this,[=](){
        //抬起门禁道闸
        SerialPort->write(WriteData(m_head_trunk_up));
        QTimer *m_headTimer = new QTimer(this);
        m_headTimer->start(300);
        connect(m_headTimer,&QTimer::timeout,this,[=](){
            //抬起前道闸释放
            m_headTimer->stop();
            SerialPort->write(WriteData(m_head_trunk_up2));
        });
    });
    ///落道闸信号
    connect(this,&EqptControl::SendToSelf_HeadTrunkDown,this,[=](){
        //落下门禁道闸
        SerialPort->write(WriteData(m_head_trunk_down));
        QTimer *m_lastTimer = new QTimer(this);
        m_lastTimer->start(300);
        connect(m_lastTimer,&QTimer::timeout,this,[=](){
            //落下前道闸释放
            m_lastTimer->stop();
            SerialPort->write(WriteData(m_head_trunk_down2));
        });
    });
    connect(this,&EqptControl::SendToSelf_SnapByHand,this,[=](){
        SerialPort->write(WriteData(m_snap));
        QTimer *m_SnapTimer = new QTimer(this);
        m_SnapTimer->start(300);
        connect(m_SnapTimer,&QTimer::timeout,this,[=](){
            //落下前道闸释放
            m_SnapTimer->stop();
            SerialPort->write(WriteData(m_snap_r));
        });
    });
}

QByteArray EqptControl::WriteData(QString order)
{
    QByteArray Data_1;
    QString Data = order;
    Data_1 = QByteArray::fromHex (Data.toLatin1().data());
    return Data_1;
}
