#include "uart.h"
#include <QSerialPortInfo>
#include <QSerialPort>
#include <QList>
#include <QDebug>
#include <stdio.h>
#include <QObject>
#include <QDebug>
#include "communications.h"
#include <QWidget>
#include  "MCU_ARM.h"
#include <stdio.h>
#include "QSharedMemory"
#include <QBuffer>
#include <QTime>
#include <QTimer>
uint16_t CRC;
QSerialPortInfo *SerialPortInfo;
QSerialPort SerialPort;
QByteArray UART_READ_DATA;
MCU_ARM *ARM;
uint16_t uart0_ini = 0;
uint16_t uart1_ini = 0;
uint8_t UART_Enable = 0;
QByteArray ttt;
struct UU_data uui;

void UART::Delay_MSec(unsigned int msec)
{
    QEventLoop eventloop;
    QTimer::singleShot((int)msec, &eventloop, SLOT(quit()));
    eventloop.exec();
}

void UART::creat_file()
{
    QFile file("/home/data/incident.txt");
    if(file.open(QFile::WriteOnly))
    {
        QTextStream set_wifi_connect(&file);
    }
    file.close();
}

UART::UART(QObject *parent): QObject(parent)
{

}

UART::~UART()
{
    SerialPort.close();
    SerialPort.deleteLater();
    my_thread->quit();
    my_thread->wait();
    my_thread->deleteLater();
}


void UART::openserial(QString COM/*QString COM2*/)
{
    QList<QSerialPortInfo> list3;
    list3=QSerialPortInfo::availablePorts();
    for(int i=0;i<list3.size();i++)
        qDebug()<<list3[i].portName();
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        if(info.portName()==COM)
        {

            QSerialPortInfo SerialPortInfo= info;
            SerialPort.setPort(info);
            setserial();
        }
    }
}

void UART::uart_init(QString COM,uint8_t Enable)
{
    openserial(COM);
    ARM->testSerialPort(1);
    UART_Enable = Enable;
}

void UART::ShuJu_Read()//读取数据
{
    if(SerialPort.isOpen())
    {
        UART_READ_DATA = SerialPort.readAll();
    }
    else
    {
    }
}

void UART::ShuJu_Write(QByteArray data)
{
    SerialPort.write(data);

}

void UART::setserial()
{
    SerialPort.open(QIODevice::ReadWrite);
    SerialPort.setBaudRate(QSerialPort::Baud115200);
    SerialPort.setDataBits(QSerialPort::Data8);
    SerialPort.setParity(QSerialPort::NoParity);
    SerialPort.setStopBits(QSerialPort::OneStop);
    SerialPort.setFlowControl(QSerialPort::NoFlowControl);

    if(SerialPort.isOpen())
    connect(&SerialPort,SIGNAL(readyRead()),this,SLOT(receverDataFromSerialPort()));
}

void UART::serial_close()
{
    SerialPort.close();
}

void UART::ModBusCRC16(QByteArray data)
{
    int len = data.size();
    uint16_t rc=0xffff;
    int i, j;
    uint8_t temp;
    for(i=0; i<len; i++)
    {
        temp=data.at(i);
        rc^=temp;
        for(j=0;j<8;j++){
            if(rc&0X0001){
                rc>>=1;
                rc^=0XA001;
            }
            else
                rc>>=1;
        }
    }
    CRC = rc;
}

/*0a 43 43 11 22 33 aa aa*/
void UART::memcpySerialData(char *data,QByteArray &A,uint16_t len)
{
    if(A.isEmpty() != 0)
    {
        A = 0;
    }
    A = QByteArray(data,len);
}

void UART::happenInfoError(QByteArray data){
    switch (data.at(2)) {
    case 0x20:
        printf("Concentrator set fail...\n");
        break;
    case 0x21:
        printf("this function unable to use, now...%d\n");
        break;
    case 0x22:
        printf("fan start T set fail...\n");
        break;
    case 0x23:
        printf("fan state set fail...\n");
        break;
    case 0x24:
        printf("fan timing set fail...\n");
        break;
    case 0x25:
        printf("buzzer state set fail...\n");
        break;
    }
}


void UART::receverDataFromSerialPort(){
    SerialPort.waitForReadyRead(100);
    QByteArray data = SerialPort.readAll();
    if(data.toStdString()!="")
    {
        QByteArray data1;
        data1[0]=0xAA;
        data1[1]=0x55;
        QByteArray Sec_len;
        uint32_t dataLen = 0;
        uint32_t result = 0;
        bool ok;
        uint8_t lower_CRC = 0;
        char Check[2] = {0};
        QByteArray CrcCheck = data.left(data.size()-2);

        if((data[0] == data1[0])&&(data[1]==data1[1]))
        {
            ModBusCRC16(CrcCheck);
            lower_CRC = CRC;
            CRC = CRC>>8;
            Check[0] = lower_CRC;
            Check[1] = CRC;
            if((Check[0] == data[data.size()-2])&&(Check[1] == data[data.size()-1]))
            {
                if(data.at(2) >= 0x20)
                {
                    dataLen = data.size();
                    result = data.at(dataLen - 3);
                    if(result == 0)
                    {
                        printf("success...\n");
                    }
                    else
                    {
                        happenInfoError(data);
                    }
                    return ;
                }
                else
                {
                    char *temp = data.data();
                    temp = temp + 5;
                    char *Sec = data.data();
                    Sec = Sec + 4;
                    char *adress = data.data();
                    adress = adress + 6;
                    char *sec = data.data();
                    sec = sec + 6;
                    switch (data.at(2))
                    {
                    case 0x06:
                        Sec_len[0] = data[4];
                        Sec_len[1] = data[5];
                        dataLen =Sec_len.toHex().toInt(&ok,16);
                        uui.SecData.clear();
                        memcpySerialData(Sec,uui.SecData,dataLen+2);
                        //qDebug()<<"SecData:"<<uui.SecData<<endl;
                        temp = NULL;
                        break;

                    case 0x08:
                        Sec_len[0] = data[4];
                        Sec_len[1] = data[5];
                        dataLen =Sec_len.toHex().toInt(&ok,16);
                        uui.Incident.clear();
                        memcpySerialData(Sec,uui.Incident,dataLen+2);
                        creat_file();
                        temp = NULL;
                        break;


                    case 0x10:
                        ARM->testSerialPort(1);
                        uart0_ini = 1;
                        break;

                    }
                }
            }
        }
    }
}

