#include "widget.h"
#include "ui_form.h"
#include "common.h"
#include <QDebug>
#include <QSerialPortInfo>
#include <QByteArray>
#include <QMessageBox>
#include <QFileInfo>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent),ui(new Ui::form)
{
    ui->setupUi(this);

    on_btnRefresh_clicked();

    memset(rxbuf, 0, sizeof(rxbuf));
    rxbufLen = 0;

    memset(&clientDevInfo, 0, sizeof(clientDevInfo));

    memset(&csgConfig, 0, sizeof(csgConfig_t));

    memset(&clientRealData, 0, sizeof(realData_t));

    memset(powerFre, 0, sizeof(powerFre));

    isConnected = 0;
    upFileRecvSize = 0;
    upFileSize = 0;
    isDataRefresh = false;
    waveParam = 0;
    is_log_up = 0;
    logIndex = 0;
    waveIndex = 0;
    is_wave_up = 0;

    energyMode[0] = "未知";
    energyMode[1] = "正常模式";
    energyMode[2] = "节能模式";
    energyMode[3] = "休眠模式";

    //usartProtocol = new Protocol;

    crc32_table_init();

     /* 配置校准页面表格 */
    ui->adjustTable->horizontalHeader()->setVisible(true);
    ui->adjustTable->horizontalHeader()->resizeSection(0,20);
    ui->adjustTable->horizontalHeader()->resizeSection(1,50);

    //如下代码设置横向表格头的间隔线，有四个方向的间隔线,不需要间隔线的可以设置为0px
    ui->adjustTable->horizontalHeader()->setStyleSheet(
    "QHeaderView::section{"
                "border-top:0px solid #E5E5E5;"
                "border-left:0px solid #E5E5E5;"
                "border-right:0.5px solid #E5E5E5;"
                "border-bottom: 0.5px solid #E5E5E5;"
                "background-color:white;"
                "padding:4px;"
            "}"
    );

    /* 打开配置文件, 恢复关闭前的状态. */
    QString file = QCoreApplication::applicationDirPath()+"/CableTool.ini";
    settings = new QSettings(file, QSettings::IniFormat, this);

    
    ui->comboBaud->setCurrentIndex(settings->value("baudBoxIndex", 6).toInt());
	filePath = settings->value("updateFile", "").toString();
	adjFilePath = settings->value("adjFile", "").toString();
	waveFilePath = settings->value("waveFile", "").toString();
	QFileInfo fileinfo = QFileInfo(filePath);
	ui->fileNameEdit->setText(fileinfo.fileName());
	ui->fileNameEdit->setReadOnly(true);
	ui->fileTypeBox->setCurrentIndex(settings->value("updateFileType", 0).toInt());
	ui->freChBox->setCurrentIndex(settings->value("freChIndex", 0).toInt());

    //searchUsablePort();

}

Widget::~Widget()
{
    //delete usartProtocol;
    deinitSerial();
    delete settings;

    delete ui;
}

QString Widget::toHexadecimal(const QByteArray &byteArray)
{
    QString str;
    for(int i = 0; i< byteArray.length(); i++)
    {
        QString byteStr = QString::number(static_cast<uchar>(byteArray[i]), 16);
        if(byteStr.length() == 1) str += "0" + byteStr;
        else str += byteStr;
    }
    return str;
}

int Widget::searchUsablePort()
{
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->comboPort->addItem(serial.portName());
            QString portName = serial.portName();
            qDebug() << "usable port" << portName;
            serial.close();
            return 1;
        }
    }
    qDebug() << "无法打开串口";
    return 0;
}

/* 串口错误处理槽. */
void Widget::serialErrHandle(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError)
    {
        QMessageBox::critical(this, tr("Critical Error"), serialPort->errorString());
        //workStop(CM_usart::RV_USART);
    }
}

void Widget::serialDisconnect()
{
	deinitSerial();
	isConnected = 0;
    ui->btnConn->setText("连接");
	buttonEnable(FALSE);
}


int Widget::initSerial()
{
    serialPort = new QSerialPort;
    serialPort->setPortName(ui->comboPort->currentText());
    serialPort->setBaudRate(ui->comboBaud->currentText().toInt());
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);
    if (serialPort->open(QIODevice::ReadWrite))
    {	// open success
		connect(serialPort, &QSerialPort::errorOccurred, this, &Widget::serialErrHandle);
        connect(serialPort, &QSerialPort::readyRead, this, &Widget::readData);
    }
	else
	{	// open failed
		QMessageBox::critical(this, tr("Error"), serialPort->errorString());
	}
    //serialPort->setBaudRate(ui->comboBaud->currentText().toInt());
    qDebug() << "baudrate:" << serialPort->baudRate();

    //newTask = new QThread;
    //usartProtocol = new Protocol;
    //usartProtocol->moveToThread(newTask);
    //newTask->Start();

    //connect(worker, &WorkerThread::finished, this, &MainWindow::updateGUI);
    //connect(this, &Widget::workStart, task, &CM_usart::run);
    

    return 0;
}

int Widget::deinitSerial()
{
    if (serialPort->isOpen())
	{
		//disconnect(&serialPort, &QSerialPort::readyRead, this, &Widget::readData);
        serialPort->waitForReadyRead(500);	// Wait 0.5 second to read all the data.
        serialPort->close();
		delete serialPort;
	}
    return 0;
}


int Widget::readData()
{
    QByteArray qarry;
    qarry = serialPort->readAll();

    if (!qarry.isEmpty())
    {
        char *buf = qarry.data();
        int len = qarry.size();

        qDebug() << __FUNCTION__ << "LEN=" << len << endl;
        //HexPrint(__FUNCTION__, buf, len);

        if (len < 0 || len > USART_BUF_SIZE)
        {
        	rxbufLen = 0;
        	return -1;
        }

        if (len + rxbufLen > USART_BUF_SIZE)
        {
			rxbufLen = 0;
			return -1;
        }        

        memcpy(rxbuf + rxbufLen, buf, len);
        rxbufLen += len;

        if (rxbufLen < sizeof(proto_head_t))
        {
			return -1;
        }
        
       	proto_head_t *header = reinterpret_cast<proto_head_t*>(rxbuf);
        //qDebug() << "header->len:" << header->len << endl;
       	if (rxbufLen != header->len + 4)
       		return -1;

		/* CRC32 校验. */
	    if (crc32(rxbuf, header->len) != (*reinterpret_cast<uint32_t*>(rxbuf + header->len)))
	    {
	    	qDebug() << "Bad data,throw it away.\n";
	    	rxbufLen = 0;
	        return -1;
	    }

	    //printHexArray(__FUNCTION__, buf, len);
        HexPrint(__FUNCTION__, rxbuf, (header->len + 4));

        paraseProtocols(rxbuf);
		rxbufLen = 0;
        
    }
    qarry.clear();
    return 0;
}

int Widget::writeData(char *buf, int len)
{
    serialPort->write(buf, len);
    serialPort->flush();
    return 0;
}

int Widget::protoHeaderInit(proto_head_t * header, uint16_t len, uint32_t id, uint8_t cmd_type, uint8_t cmd)
{
    header->len = len;
    header->dev_type_m = clientDevInfo.typeM;
    header->dev_type_s = clientDevInfo.typeS;
    header->dev_id = id;
    header->cmd_type = cmd_type;
    header->cmd = cmd;
    header->pkt_id++;
    if (0 == header->pkt_id)
    {
        header->pkt_id = 0x8000;
    }
    return 0;
}

/* 按钮使能操作. */
void Widget::buttonEnable(bool flag)
{
    ui->configButton->setEnabled(flag);
    ui->waveButton->setEnabled(flag);
    ui->dataRefreshButton->setEnabled(flag);
    ui->freChBox->setEnabled(flag);
    ui->freRefreshButton->setEnabled(flag);
    ui->updateButton->setEnabled(flag);
    ui->defaultButton->setEnabled(flag);
    ui->btnReset->setEnabled(flag);
    ui->fileTypeBox->setEnabled(flag);
    ui->fileButton->setEnabled(flag);
    ui->adjButton->setEnabled(flag);
    ui->configSetButton->setEnabled(flag);
    ui->stateRefreshButton->setEnabled(flag);
    ui->waveCalButton->setEnabled(flag);
    ui->waveColButton->setEnabled(flag);
    ui->waveRefreshButton->setEnabled(flag);
    ui->ratioSetButton->setEnabled(flag);
    ui->configGetButton->setEnabled(flag);
    ui->dataRefreshAutoButton->setEnabled(flag);
    ui->stateLogButton->setEnabled(flag);
    ui->historyDataButton->setEnabled(flag);
    ui->logTextEdit->setEnabled(flag);
    ui->manualRatioSetButton->setEnabled(flag);
    ui->manualAdjButton->setEnabled(flag);
    ui->csgConfigGetButton->setEnabled(flag);
    ui->csgConfigSetButton->setEnabled(flag);
    ui->RatioParamSetButton->setEnabled(flag);
    ui->RatioParamGetButton->setEnabled(flag);
}

QString Widget::devStateWaveStateGet(uint8_t state)
{
    switch(state)
    {
    case WAVE_STATE_IDLE:
        return "空闲";
    case WAVE_STATE_START:
        return "准备";
    case WAVE_STATE_WAIT:
        return "等待";
    case WAVE_STATE_READ:
        return "读取";
    case WAVE_STATE_STOP:
        return "结束";
    case WAVE_STATE_ADC_ERROR:
    case WAVE_STATE_TIMEOUT:
        return "错误";
    case WAVE_STATE_COMPLETION:
        return "完成";
    default:
        return "未知";
    }
}


QString Widget::devStateWlStateGet(uint8_t state)
{
    switch(state)
    {
    case WL_STATE_SOFT:
    case WL_STATE_AT_ATE:
    case WL_STATE_AT_QICSGP:
    case WL_STATE_AT_QIACT:
    case WL_STATE_AT_CSQ:
    case WL_STATE_AT_QIOPEN:
        return "AT";
    case WL_STATE_WAKEUP:
        return "联络";
    case WL_STATE_REALDATA:
        return "数据";
    case WL_STATE_PWR_FRE:
        return "工频";
    case WL_STATE_WAVE:
        return "高频";
    case WL_STATE_UPDATE:
        return "升级";
    case WL_STATE_UPDATE_RT:
        return "升级回复";
    case WL_STATE_END:
        return "完成";
    default:
        return "未知";
    }
}

void Widget::uiDevInfoRefresh()
{
    ui->devTypeNameLabel->setText("LowPowerCable");
    ui->devNameEdit->setText(QString(reinterpret_cast<char*>(clientDevInfo.name)));
    if (clientDevInfo.typeS != 4)
    {
        ui->devTypeBox->setCurrentIndex(clientDevInfo.typeS - 1);
        ui->communicationTypeBox->setCurrentIndex(0);
    }
    else
    {
        ui->devTypeBox->setCurrentIndex(0);
        ui->communicationTypeBox->setCurrentIndex(1);
    }

    ui->idEdit->setText(QString().sprintf("%08x", clientDevInfo.id));
    ui->csgIdEdit->setText(reinterpret_cast<char*>(clientDevInfo.csgId));
    ui->csgVersionEdit->setText(QString().sprintf("%04x", clientDevInfo.csgVersion));
    ui->factoryDateEdit->setText(reinterpret_cast<char*>(clientDevInfo.factoryTime));
    ui->hwVersionEdit->setText(QString(reinterpret_cast<char*>(clientDevInfo.hardwareVersion)));
    ui->fpgaVersionLabel->setText(QString(reinterpret_cast<char*>(clientDevInfo.fpgaVersion)));
    QString temp;
    QStringList list;
    temp = QString(reinterpret_cast<char*>(clientDevInfo.bootVersion));
    list = temp.split(".");
    if (4 == list.length())
    {
        ui->IAPVersionLabel->setText("V" + list[2] + "." + list[3]);
    }
    ui->IAPDateLabel->setText(QString(reinterpret_cast<char*>(clientDevInfo.bootCompile_time)));
    temp = QString(reinterpret_cast<char*>(clientDevInfo.imgVersion));
    list = temp.split(".");
    if (4 == list.length())
    {
        ui->APPVersionLabel->setText("V" + list[2] + "." + list[3]);
    }
    ui->APPDateLabel->setText(QString(reinterpret_cast<char*>(clientDevInfo.imgCompile_time)));
    ui->macEdit->setText(QString().sprintf("%02x:%02x:%02x:%02x:%02x:%02x", clientDevInfo.mac[0], clientDevInfo.mac[1], clientDevInfo.mac[2],
            clientDevInfo.mac[3], clientDevInfo.mac[4], clientDevInfo.mac[5]));
    ui->ipEdit->setText(QString().sprintf("%d.%d.%d.%d", clientDevInfo.ip[0], clientDevInfo.ip[1], clientDevInfo.ip[2], clientDevInfo.ip[3]));
    ui->maskEdit->setText(QString().sprintf("%d.%d.%d.%d", clientDevInfo.ipMask[0], clientDevInfo.ipMask[1], clientDevInfo.ipMask[2], clientDevInfo.ipMask[3]));
    ui->gwEdit->setText(QString().sprintf("%d.%d.%d.%d", clientDevInfo.ipGw[0], clientDevInfo.ipGw[1], clientDevInfo.ipGw[2], clientDevInfo.ipGw[3]));
    ui->serverEdit->setText(QString().sprintf("%d.%d.%d.%d", clientDevInfo.serverIp[0], clientDevInfo.serverIp[1], clientDevInfo.serverIp[2],
            clientDevInfo.serverIp[3]));
    ui->serverWIEdit->setText(QString().sprintf("%d.%d.%d.%d", clientDevInfo.wirelessServerIp[0], clientDevInfo.wirelessServerIp[1],
            clientDevInfo.wirelessServerIp[2], clientDevInfo.wirelessServerIp[3]));
    ui->serverPortEdit->setText(QString().sprintf("%d", clientDevInfo.serverPort));
    ui->serverWIPortEdit->setText(QString().sprintf("%d", clientDevInfo.wirelessServerPort));
    ui->cardEdit->setText(QString().sprintf("%01x%02x%02x%02x%02x%02x", clientDevInfo.csgCard[0] & 0x0f, clientDevInfo.csgCard[1],
            clientDevInfo.csgCard[2], clientDevInfo.csgCard[3], clientDevInfo.csgCard[4], clientDevInfo.csgCard[5]));
}

void Widget::uiDevConfigRefresh()
{
    if (IS_MONITOR_BIT_SET(clientDevConfig.flag, DEV_FLAG_CLI))
    {
        ui->debugModeBox->setCurrentIndex(0);
    }
    else
    {
        ui->debugModeBox->setCurrentIndex(1);
    }

    if (IS_MONITOR_BIT_SET(clientDevConfig.flag, DEV_FLAG_ADJ))
    {
        ui->workModeBox->setCurrentIndex(1);
    }
    else if(IS_MONITOR_BIT_SET(clientDevConfig.flag, DEV_FLAG_FACTORY))
    {
        ui->workModeBox->setCurrentIndex(2);
    }
    else
    {
        ui->workModeBox->setCurrentIndex(0);
    }

    if (clientDevConfig.energyMode < 3)
    {
        ui->energyModeBox->setCurrentIndex(clientDevConfig.energyMode);
    }

    if (clientDevConfig.normalSleep)
    {
        ui->normalSleepBox->setCurrentIndex(1);
    }
    else
    {
        ui->normalSleepBox->setCurrentIndex(0);
    }

    ui->APNEdit->setText(QString(reinterpret_cast<char*>(clientDevConfig.APN_long)));

    ui->colIntervalEdit->setText(QString::number(clientDevConfig.collectInterval));
    ui->waveIntervalEdit->setText(QString::number(clientDevConfig.waveInterval));
    ui->colThresholdEdit->setText(QString::number(clientDevConfig.collectThreshold));
    ui->waveThresholdEdit->setText(QString::number(clientDevConfig.waveThreshold));
    ui->waveThresholdEdit->setText(QString::number(clientDevConfig.waveThreshold));
    ui->mainCableIdEdit->setText(QString::number(clientDevConfig.mainCable));
    ui->voltageColBox->setChecked(clientDevConfig.isVoltageCol);
    ui->tempColBox->setChecked(clientDevConfig.isTempCol);
    ui->waveColBox->setChecked(clientDevConfig.isWaveCol);

    ui->sensor1IdEdit->setText(QString::number(clientDevConfig.sensor_id[0]));
    ui->sensor2IdEdit->setText(QString::number(clientDevConfig.sensor_id[1]));
    ui->sensor3IdEdit->setText(QString::number(clientDevConfig.sensor_id[2]));
    ui->sensor4IdEdit->setText(QString::number(clientDevConfig.sensor_id[3]));
    ui->sensor5IdEdit->setText(QString::number(clientDevConfig.sensor_id[4]));
    ui->sensor6IdEdit->setText(QString::number(clientDevConfig.sensor_id[5]));
    ui->sensor7IdEdit->setText(QString::number(clientDevConfig.sensor_id[6]));
}

void Widget::uiDevCsgConfigRefresh()
{
	ui->passwdEdit->setText(QString(reinterpret_cast<char*>(csgConfig.passwd)));
	ui->beatIntervalEdit->setText(QString::number(csgConfig.beatInterval));
	ui->csgColIntervalEdit->setText(QString::number(csgConfig.collectInterval));
	ui->sleepTimeEdit->setText(QString::number(csgConfig.sleepTime));
	ui->onlineTimeEdit->setText(QString::number(csgConfig.onlineTime));
	ui->resetTimeEdit->setText(QString().sprintf("%d:%d:%d", csgConfig.resetTime[0], csgConfig.resetTime[1], csgConfig.resetTime[2]));
	ui->ciphertextEdit->setText(QString(reinterpret_cast<char*>(csgConfig.ciphertext)));
}

void Widget::uiDevRealDataRefresh()
{
    QString temp;

    temp.sprintf("%.2f", clientRealData.temperature / 10.0);
    ui->tempLabel->setText(temp);
    temp.sprintf("%.2f", clientRealData.vin / 1000.0);
    ui->vinLabel->setText(temp);
    temp.sprintf("%.2f", clientRealData.vsc / 1000.0);
    ui->vscLabel->setText(temp);
    temp.sprintf("%.2f", clientRealData.vbat / 1000.0);
    ui->vbatLabel->setText(temp);
    ui->signalLabel->setText(QString::number(clientRealData.CSQ));

    temp.sprintf("%.2f", clientRealData.sen_temp[0] / 10.0);
    ui->senTemp1Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.sen_temp[1] / 10.0);
    ui->senTemp2Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.sen_temp[2] / 10.0);
    ui->senTemp3Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.sen_temp[3] / 10.0);
    ui->senTemp4Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.sen_temp[4] / 10.0);
    ui->senTemp5Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.sen_temp[5] / 10.0);
    ui->senTemp6Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.sen_temp[6] / 10.0);
    ui->senTemp7Label->setText(temp);

    ui->senShortLabel->setText(clientRealData.senShort ? "是" : "否");

    ui->senX1Label->setText(QString::number(clientRealData.senX[0] - 16000));
    ui->senX3Label->setText(QString::number(clientRealData.senX[2] - 16000));
    ui->senX5Label->setText(QString::number(clientRealData.senX[4] - 16000));

    ui->senY1Label->setText(QString::number(clientRealData.senY[0] - 16000));
    ui->senY3Label->setText(QString::number(clientRealData.senY[2] - 16000));
    ui->senY5Label->setText(QString::number(clientRealData.senY[4] - 16000));

    ui->senZ1Label->setText(QString::number(clientRealData.senZ[0] - 16000));
    ui->senZ3Label->setText(QString::number(clientRealData.senZ[2] - 16000));
    ui->senZ5Label->setText(QString::number(clientRealData.senZ[4] - 16000));

    temp.sprintf("%.2f", clientRealData.elec[0] / 1000.0);
    ui->elec1Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.elec[1] / 1000.0);
    ui->elec2Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.elec[2] / 1000.0);
    ui->elec3Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.elec[3] / 1000.0);
    ui->elec4Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.elec[4] / 1000.0);
    ui->elec5Label->setText(temp);
    temp.sprintf("%.2f", clientRealData.elec[5] / 1000.0);
    ui->elec6Label->setText(temp);
}

void Widget::uiDevStateRefresh()
{
    QString temp;

    if (clientDevState.energyMode < 4)
    {
        ui->stateEnergyLabel->setText(energyMode[clientDevState.energyMode]);
    }
    else
    {
        ui->stateEnergyLabel->setText(energyMode[0]);
    }
    ui->stateBatChargeLabel->setText(clientDevState.isBatCharge ? "未充电" : "充电");
    ui->stateForceSleepUpLabel->setText(clientDevState.forceSleepUp ? "是" : "否");
    ui->stateAdcColLabel->setText(clientDevState.isAdcCollect ? "完成" : "未完成");
    ui->stateAdcUpLabel->setText(clientDevState.isAdcUp ? "完成" : "未完成");
    ui->stateAdcThrLabel->setText(clientDevState.isAdcthr ? "是" : "否");
    ui->stateAdciCntLabel->setText(QString::number(clientDevState.AdciCnt));
    ui->stateAdciStLabel->setText(QString::number(clientDevState.AdciState));
    ui->stateAdcCntLabel->setText(QString::number(clientDevState.AdcCnt));
    ui->stateAdcStLabel->setText(QString::number(clientDevState.AdcState));

    /*得到系统时间*/
    time_t cur = static_cast<time_t>(clientDevState.waveTime);
    tm *day;
    day = localtime(&cur);
    temp.sprintf("%d/%d/%d %d:%d:%d", day->tm_year + 1900, day->tm_mon+1, day->tm_mday,
        day->tm_hour, day->tm_min, day->tm_sec);
    ui->stateWaveTmLabel->setText(temp);
    ui->stateWaveFinLabel->setText(clientDevState.waveStart ? "未完成" : "完成");
    ui->stateWaveUpLabel->setText(clientDevState.waveUpStart ? "未完成" : "完成");
    ui->stateWaveIdxLabel->setText(QString::number(clientDevState.waveIdx));
    ui->stateWaveStLabel->setText(devStateWaveStateGet(clientDevState.waveState));
    ui->stateWaveRtLabel->setText(QString::number(clientDevState.waveRt));
    ui->stateWaveForceLabel->setText(clientDevState.waveForce ? "是" : "否");

    ui->stateWlStLabel->setText(devStateWlStateGet(clientDevState.wlState));
    ui->stateWlCntLabel->setText(QString::number(clientDevState.wlCnt));
    ui->stateWlUpLabel->setText(clientDevState.isWlUpdate ? "升级" : "未升级");
    ui->stateWlIdxLabel->setText(QString::number(clientDevState.wlWaveIdx));

    ui->waveParamEdit->setText(QString::number(clientDevState.waveAdj));
    ui->waveFinLabel->setText(clientDevState.waveStart ? "未完成" : "完成");
    ui->waveMinEdit->setText(QString::number(clientDevState.waveMin));
    ui->waveMaxEdit->setText(QString::number(clientDevState.waveMax));

    temp.sprintf("%dh:%dm:%ds", clientDevState.sysTime / 3600, (clientDevState.sysTime / 60) % 60, clientDevState.sysTime % 60);
    ui->stateRunTimeLabel->setText(temp);
    double tempSc;
    tempSc = clientDevState.scMax / 1000.00;
    ui->stateScMaxLabel->setText(QString::number(tempSc, 'g', 3));
    tempSc = clientDevState.scMin / 1000.00;
    ui->stateScMinLabel->setText(QString::number(tempSc, 'g', 3));
    ui->stateUpTimeLabel->setText(QString::number(clientDevState.scUpTime));
    ui->stateDownTimeLabel->setText(QString::number(clientDevState.scDownTime));
}


void Widget::protoContact(char *data)
{
	char *pbody = data + sizeof(proto_head_t);
    memcpy(&clientDevInfo, pbody, sizeof(devInfo));
    uiDevInfoRefresh();
    buttonEnable(true);
}

void Widget::protoConfig(char *data)
{
	char *pbody = data + sizeof(proto_head_t);
    memcpy(&clientDevConfig, pbody, sizeof(devConfig));
    uiDevConfigRefresh();
}

void Widget::protoCsgConfig(char *data)
{
	char *pbody = data + sizeof(proto_head_t);
    memcpy(&csgConfig, pbody, sizeof(csgConfig_t));
    uiDevCsgConfigRefresh();
}

void Widget::protoRealdata(char *data)
{
	char *pbody = data + sizeof(proto_head_t);
	memcpy(&clientRealData, pbody, sizeof(realData_t));
	uiDevRealDataRefresh();
	
	if (isDataRefresh)
	{
		sendMsgDeviceRealDataGet();
	}
}

int Widget::protoUpdateReply(char *data, int fileType)
{
    mul_head_t *header = reinterpret_cast<mul_head_t*>(data + sizeof(proto_head_t));

    /* 数据头验证. */
    qDebug() << "recv:index:" << header->index << "upPackIndex:" << upPackIndex << "len:" << header->len << endl;
    if (header->index != upPackIndex
        || header->len > UPDATE_DATA_SIZE)
    {
        return -1;
    }

    /* 发送报文. */
    /* 小于 CM_U_RX_M_PKT_MAX, 表示发送完成进入下个状态, 否则继续发送. */
    if (header->len < UPDATE_DATA_SIZE)
    {
        upPackIndex = 0;
        ui->upFileSizeLabel->setText("升级完成");
        QMessageBox::information(this, "SUCCEED", "文件" + filePath + "升级完成.", QMessageBox::Ok);
    }
    else
    {
    	upPackIndex++;
        sendMsgDeviceUpdate(fileType);
        QString temp;
        upFileRecvSize += header->len;
        temp.sprintf("%d / %lld", upFileRecvSize, upFileSize);
        ui->upFileSizeLabel->setText(temp);
    }
    return 0;
}

int Widget::protoWaveDataUploadReply(char *data)
{
    mul_head_t *header = reinterpret_cast<mul_head_t*>(data + sizeof(proto_head_t));

    /* 数据头校验. */
	qDebug() << "recv:index:" << header->index << "waveIndex:" << waveIndex << "len:" << header->len << endl;
	if (header->index != waveIndex
		|| header->len > UPDATE_DATA_SIZE)
	{
		return -1;
	}

    /* 获取文件. */
    QFile file(waveFilePath);
    if (0 == header->index)
    {
        file.remove();
    }

    if (file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        file.write(data + sizeof(proto_head_t) + sizeof(mul_head_t), header->len);
        file.close();
        qDebug() << "file " << header->index << header->len;
    }
    else
    {
        qDebug() << "file ERROR";
        return -1;
    }

    /* 通知发包线程进入下个状态. */
    if (header->len < UPDATE_DATA_SIZE)
    {
        waveIndex = 0;
        buttonEnable(true);
        is_wave_up = false;
        ui->upWaveIndexLabel->setText("下载完成");
        QMessageBox::information(this, "SUCCEED", "高频录波文件下载完成.", QMessageBox::Ok);
    }
    else
    {
        waveIndex = header->index + 1;
        sendMsgDeviceWaveDataGet();
        ui->upWaveIndexLabel->setText(QString("%1 / 8000").arg(waveIndex));
    }

    return 0;
}

int Widget::protoState(char *data)
{
	char *pbody = data + sizeof(proto_head_t);
    memcpy(&clientDevState, pbody, sizeof(devState));
    uiDevStateRefresh();
	return 0;
}

int Widget::paraseProtocols(char *data)
{
    proto_head_t *header = reinterpret_cast<proto_head_t*>(data);
    
    //qDebug() << "cmd_type:" << header->cmd_type << "cmd:" << header->cmd << endl;
    //qDebug() << "len:" << header->len << endl;
    if (DEBUG_CT_REPLY == header->cmd_type)
    {
        /* 共有命令处理. */
        switch (header->cmd)
        {
        case DEBUG_C_CONTACT:	// 获取配置成功后更新页面
	        protoContact(data);
	        break;
	        
        case DEBUG_C_DEV_INFO_SET:
	        break;
        case DEBUG_C_RESET:
            //_debug_pkt_reset();
            break;
        case DEBUG_C_DEFAULT:
            //_debug_pkt_default();
            break;
        case DEBUG_C_UPDATE_APP:
        case DEBUG_C_UPDATE_IAP:
        	protoUpdateReply(data, header->cmd);
        	break;
        case DEBUG_C_DEV_CONFIG:	// 获取配置成功后更新页面
	        protoConfig(data);
	        break;
        case DEBUG_C_DEV_CONFIG_SET:
            //buttonEnable(false);
            //snedMsgDeviceInfoGet();
            break;
        default:
            break;
        }
    }
    else if (DEBUG_CT_PRV_REPLY == header->cmd_type)
    {
        /* 私有命令处理. */
        switch (header->cmd)
        {
        case DEBUG_PRV_REALDATA:
        	protoRealdata(data);
        	break;
        case DEBUG_PRV_POWER:
            //_debug_pkt_power_fre_get();
            break;
        case DEBUG_PRV_DEFECT:
        	protoWaveDataUploadReply(data);
            break;
        case DEBUG_PRV_ADJ_INFO:
            //_debug_pkt_adj_get();
            break;
        case DEBUG_PRV_ADJ_INFO_SET:
            //_debug_pkt_adj_set();
            break;
        case DEBUG_PRV_ADJ_AUTO:
            //_debug_pkt_adj_auto();
            break;
        case DEBUG_PRV_DEV_STATE:
            protoState(data);
            break;
        case DEBUG_PRV_WAVE_COL:
            //_debug_pkt_wave_col();
            break;
        case DEBUG_PRV_WAVE_CAL:
            //_debug_pkt_wave_cal();
            break;
        case DEBUG_PRV_LOG:
            //_debug_pkt_log_get();
            break;
        case DEBUG_PRV_HISTORY_DATA:
            //_debug_pkt_history_data_get();
            break;
        case DEBUG_PRV_ADJ_MANUAL:
            //_debug_pkt_adj_manual();
            break;
        case DEBUG_PRV_CSG_CONFIG:		// 获取配置成功后更新页面
        	protoCsgConfig(data);
        	break;
        case DEBUG_PRV_CSG_CONFIG_SET:
            //_debug_pkt_csg_config_set();
            break;
        default:
            break;
        }
    }
}

int Widget::snedMsgDeviceInfoGet()
{
	char buf[2048] = {0};
    uint32_t *crc = nullptr;

    proto_head_t *header = reinterpret_cast<proto_head_t *>(buf);
    protoHeaderInit(header, sizeof(proto_head_t), 0xFFFFFFFF, DEBUG_CT_REQUEST, DEBUG_C_CONTACT);
    header->dev_type_m = 1;
    header->dev_type_s = 255;

    /* 计算校验和. */
    crc = reinterpret_cast<uint32_t *>(buf + header->len);
    *crc = crc32(buf, header->len);

    //printHexArray(__FUNCTION__, buf, header->len + 4);
    //HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceInfoSet()
{
	char buf[2048] = {0};
    uint32_t *crc = nullptr;
    
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);
    devInfo *data = reinterpret_cast<devInfo*>(buf + sizeof(proto_head_t));

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t) + sizeof(devInfo), clientDevInfo.id, DEBUG_CT_REQUEST, DEBUG_C_DEV_INFO_SET);

    memcpy(data, &clientDevInfo, sizeof(devInfo));

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    printHexArray(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceReset()
{
	char buf[2048] = {0};
    uint32_t *crc = nullptr;
    
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_REQUEST, DEBUG_C_RESET);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

	printHexArray(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceCfgDefault()
{
	char buf[2048] = {0};
    uint32_t *crc = nullptr;
    
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_REQUEST, DEBUG_C_DEFAULT);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    printHexArray(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceUpdate(int fileType)
{
	char buf[2048] = {0};
    uint32_t *crc = nullptr;
    
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);
    mul_head_t *m_head = (mul_head_t*)(buf + sizeof(proto_head_t));
    uint8_t *data = (uint8_t*)(buf + sizeof(proto_head_t) + sizeof(mul_head_t));

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_REQUEST, fileType);
    m_head->index = upPackIndex;

    /* 读取文件 */
    QFile file_read(filePath);
    int len;
    if (!file_read.open(QIODevice::ReadOnly))
    {
        return -1;
    }

    QDataStream in(&file_read);
    in.skipRawData(static_cast<int>(upPackIndex * UPDATE_DATA_SIZE));
    len = in.readRawData((char *)data, UPDATE_DATA_SIZE);
    file_read.close();
    m_head->len = static_cast<uint32_t>(len);
    header->len = static_cast<uint16_t>(sizeof(proto_head_t) + sizeof(mul_head_t) + m_head->len);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

	qDebug() << "send:upPackIndex=" << upPackIndex << "packLen=" << header->len + 4 << endl;
    //printHexArray(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceConfigSet()
{
	char buf[2048] = {0};
    uint32_t *crc = nullptr;

    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);
    devConfig *data = reinterpret_cast<devConfig*>(buf + sizeof(proto_head_t));

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t) + sizeof(devConfig), clientDevInfo.id, DEBUG_CT_REQUEST, DEBUG_C_DEV_CONFIG_SET);

    memcpy(data, &clientDevConfig, sizeof(devConfig));

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    //printHexArray(__FUNCTION__, buf, header->len + 4);
    //HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceConfigGet()
{
	char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_REQUEST, DEBUG_C_DEV_CONFIG);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

 	HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceCsgConfigGet()
{
    char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_PRV_REQUEST, DEBUG_PRV_CSG_CONFIG);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceCsgConfigSet()
{
    char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t) + sizeof(csgConfig_t), clientDevInfo.id, DEBUG_CT_PRV_REQUEST, DEBUG_PRV_CSG_CONFIG_SET);

    memcpy(buf, &csgConfig, sizeof(csgConfig_t));

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceRealDataGet()
{
    char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);
    
    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_PRV_REQUEST, DEBUG_PRV_REALDATA);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceWaveDataGet()
{
    char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);
    mul_head_t *m_head = (mul_head_t*)(buf + sizeof(proto_head_t));
    
    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t) + sizeof(mul_head_t), clientDevInfo.id, DEBUG_CT_PRV_REQUEST, DEBUG_PRV_DEFECT);
    m_head->index = waveIndex;
    m_head->len = 0;

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::sendMsgDeviceStateGet()
{
    char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_PRV_REQUEST, DEBUG_PRV_DEV_STATE);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}


int Widget::sendMsgWaveCol()
{
    char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t), clientDevInfo.id, DEBUG_CT_PRV_REQUEST, DEBUG_PRV_WAVE_COL);

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    //HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}

int Widget::senMsgWaveCal()
{
    char buf[2048] = {0};
    uint32_t *crc = nullptr;
    proto_head_t *header = reinterpret_cast<proto_head_t*>(buf);
    waveParam_t *data = reinterpret_cast<waveParam_t*>(buf + sizeof(proto_head_t));

    /* 初始化报文头. */
    protoHeaderInit(header, sizeof(proto_head_t) + 4, clientDevInfo.id, DEBUG_CT_PRV_REQUEST, DEBUG_PRV_WAVE_CAL);

    data->param = waveParam;

    /* 计算校验位. */
    crc = reinterpret_cast<uint32_t*>(buf + header->len);
    *crc = crc32(buf, header->len);

    //HexPrint(__FUNCTION__, buf, header->len + 4);
    writeData(buf, header->len + 4);
    return 0;
}





void Widget::on_btnConn_clicked()
{
	if (!isConnected)
	{
		initSerial();
		/* 变更按钮文字. */
        ui->btnConn->setText("断开");
		snedMsgDeviceInfoGet();
		isConnected = 1;
	}
	else
	{
		serialDisconnect();
	}
}

void Widget::on_btnReset_clicked()
{
	sendMsgDeviceReset();
	serialDisconnect();
}


// 获取所有串口信息
void Widget::on_btnRefresh_clicked()
{
    ui->comboPort->clear();
    const auto infos = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &info : infos)
    {
        ui->comboPort->addItem(info.portName());
    }
}

void Widget::on_configButton_clicked()
{
    /* 配置设备信息按钮 */
    QStringList list;

    /* 获取信息. */
    stringToChar(ui->devNameEdit->text(), reinterpret_cast<char*>(clientDevInfo.name), DEV_NAME_LEN);
    clientDevInfo.typeM = 1;
    if (ui->communicationTypeBox->currentIndex() == 0)
    {
        clientDevInfo.typeS = static_cast<uint8_t>(ui->devTypeBox->currentIndex() + 1);
    }
    else
    {
        clientDevInfo.typeS = 4;
    }

    clientDevInfo.id = ui->idEdit->text().toUInt(nullptr, 16);
    stringToChar(ui->csgIdEdit->text(), reinterpret_cast<char*>(clientDevInfo.csgId), 8);
    clientDevInfo.csgVersion = ui->csgVersionEdit->text().toUShort(nullptr, 16);
    stringToChar(ui->factoryDateEdit->text(), reinterpret_cast<char*>(clientDevInfo.factoryTime), DEV_COMPILE_TIME_LEN);
    stringToChar(ui->hwVersionEdit->text(), reinterpret_cast<char*>(clientDevInfo.hardwareVersion), DEV_VERSION_STR_LEN);

    list = ui->macEdit->text().split(":");
    for(int i = 0; i < list.size(); i++)
    {
        clientDevInfo.mac[i] = static_cast<uint8_t>(list[i].toInt(nullptr, 16));
    }

    list = ui->ipEdit->text().split(".");
    for(int i = 0; i < list.size(); i++)
    {
        clientDevInfo.ip[i] = static_cast<uint8_t>(list[i].toInt());
    }

    list = ui->maskEdit->text().split(".");
    for(int i = 0; i < list.size(); i++)
    {
        clientDevInfo.ipMask[i] = static_cast<uint8_t>(list[i].toInt());
    }

    list = ui->gwEdit->text().split(".");
    for(int i = 0; i < list.size(); i++)
    {
        clientDevInfo.ipGw[i] = static_cast<uint8_t>(list[i].toInt());
    }

    list = ui->serverEdit->text().split(".");
    for(int i = 0; i < list.size(); i++)
    {
        clientDevInfo.serverIp[i] = static_cast<uint8_t>(list[i].toInt());
    }

    list = ui->serverWIEdit->text().split(".");
    for(int i = 0; i < list.size(); i++)
    {
        clientDevInfo.wirelessServerIp[i] = static_cast<uint8_t>(list[i].toInt());
    }

    clientDevInfo.serverPort = ui->serverPortEdit->text().toUShort();
    clientDevInfo.wirelessServerPort = ui->serverWIPortEdit->text().toUShort();

    qulonglong temp = ui->cardEdit->text().toULongLong(nullptr, 16);
    qulonglong divisor = 1;
    for(int i = 5; i >= 0; i--)
    {
        clientDevInfo.csgCard[i] = (temp / divisor) & 0xff;
        divisor = divisor * 0x100;

        if (0 == i)
        {
            clientDevInfo.csgCard[i] |= 0xf0;
        }
    }

    /* 下发配置. */
    sendMsgDeviceInfoSet();
}

void Widget::on_defaultButton_clicked()
{
	sendMsgDeviceCfgDefault();
}

void Widget::on_fileButton_clicked()
{
    /* 选择文件按钮. */
    QString Path;
    QString curPath;

    /* 获取目录. */
    if (filePath.isEmpty())
    {
        curPath = QCoreApplication::applicationDirPath();
    }
    else
    {
        QFileInfo fileinfo = QFileInfo(filePath);
        curPath = fileinfo.path();
    }

    /* 记录文件路径. */
    Path = QFileDialog::getOpenFileName(this, "Select Bin File", curPath, "*.bin");
    if (Path.isEmpty())
    {
        return;
    }

    /* 保存文件路径. */
    filePath = Path;
    QFileInfo fileinfo = QFileInfo(filePath);
    ui->fileNameEdit->setText(fileinfo.fileName());
    settings->setValue("updateFile", filePath);
}

void Widget::on_updateButton_clicked()
{
	int fileType = DEBUG_C_UPDATE_APP;
    /* 关闭按钮. */
    buttonEnable(false);

    /* 开始升级. */
    //work->fileNameSet(filePath);
    qDebug() << "filePath:" << filePath << endl;
    QFileInfo fileInfo(filePath);
    QString temp;
    upFileSize = fileInfo.size();
    upFileRecvSize = 0;
    temp.sprintf("%d / %lld", upFileRecvSize, upFileSize);
    ui->upFileSizeLabel->setText(temp);    

    /* 保存文件类型索引. */
    settings->setValue("updateFileType", ui->fileTypeBox->currentIndex());
    
	upPackIndex = 0;
    if (ui->fileTypeBox->currentText() == "APP")
    {
        fileType = DEBUG_C_UPDATE_APP;
    }
    else
    {
    	fileType = DEBUG_C_UPDATE_IAP;
    }

    sendMsgDeviceUpdate(fileType);
}


void Widget::on_configSetButton_clicked()
{

    if (0 == ui->debugModeBox->currentIndex())
    {
        MONITOR_BITMAP_SET(clientDevConfig.flag, DEV_FLAG_CLI);
    }
    else
    {
        MONITOR_BITMAP_RESET(clientDevConfig.flag, DEV_FLAG_CLI);
    }

    if (1 == ui->workModeBox->currentIndex())
    {
        MONITOR_BITMAP_SET(clientDevConfig.flag, DEV_FLAG_ADJ);
        MONITOR_BITMAP_RESET(clientDevConfig.flag, DEV_FLAG_FACTORY);
    }
    else if (2 == ui->workModeBox->currentIndex())
    {
        MONITOR_BITMAP_RESET(clientDevConfig.flag, DEV_FLAG_ADJ);
        MONITOR_BITMAP_SET(clientDevConfig.flag, DEV_FLAG_FACTORY);
    }
    else
    {
        MONITOR_BITMAP_RESET(clientDevConfig.flag, DEV_FLAG_ADJ);
        MONITOR_BITMAP_RESET(clientDevConfig.flag, DEV_FLAG_FACTORY);
    }

    clientDevConfig.energyMode = static_cast<uint8_t>(ui->energyModeBox->currentIndex());
    clientDevConfig.normalSleep = static_cast<uint8_t>(ui->normalSleepBox->currentIndex());
    memset(clientDevConfig.APN, 0, DEV_APN_LEN);
    stringToChar(ui->APNEdit->text(), reinterpret_cast<char*>(clientDevConfig.APN_long), DEV_APN_LEN_LONG);

    clientDevConfig.collectInterval = ui->colIntervalEdit->text().toUShort();
    clientDevConfig.waveInterval = ui->waveIntervalEdit->text().toUShort();
    clientDevConfig.collectThreshold = ui->colThresholdEdit ->text().toUShort();
    clientDevConfig.waveThreshold = ui->waveThresholdEdit->text().toUShort();
    clientDevConfig.mainCable = static_cast<uint8_t>(ui->mainCableIdEdit->text().toUShort());

    clientDevConfig.isVoltageCol = ui->voltageColBox->isChecked();
    clientDevConfig.isTempCol = ui->tempColBox->isChecked();
    clientDevConfig.isWaveCol = ui->waveColBox->isChecked();

    clientDevConfig.sensor_id[0] = static_cast<uint8_t>(ui->sensor1IdEdit->text().toUInt());
    clientDevConfig.sensor_id[1] = static_cast<uint8_t>(ui->sensor2IdEdit->text().toUInt());
    clientDevConfig.sensor_id[2] = static_cast<uint8_t>(ui->sensor3IdEdit->text().toUInt());
    clientDevConfig.sensor_id[3] = static_cast<uint8_t>(ui->sensor4IdEdit->text().toUInt());
    clientDevConfig.sensor_id[4] = static_cast<uint8_t>(ui->sensor5IdEdit->text().toUInt());
    clientDevConfig.sensor_id[5] = static_cast<uint8_t>(ui->sensor6IdEdit->text().toUInt());
    clientDevConfig.sensor_id[6] = static_cast<uint8_t>(ui->sensor7IdEdit->text().toUInt());
    clientDevConfig.sensor_id[7] = 0;

	/* 下发配置. */
    sendMsgDeviceConfigSet();
}


void Widget::on_configGetButton_clicked()
{
	sendMsgDeviceConfigGet();
}

void Widget::on_csgConfigGetButton_clicked()
{
	sendMsgDeviceCsgConfigGet();
}

void Widget::on_csgConfigSetButton_clicked()
{
    stringToChar(ui->passwdEdit->text(), reinterpret_cast<char*>(csgConfig.passwd), CSG_PASSWD_LEN);
    csgConfig.beatInterval = static_cast<uint8_t>(ui->beatIntervalEdit->text().toUInt());
    csgConfig.collectInterval = static_cast<uint16_t>(ui->csgColIntervalEdit->text().toUInt());
    csgConfig.sleepTime = static_cast<uint16_t>(ui->sleepTimeEdit->text().toUInt());
    csgConfig.onlineTime = static_cast<uint16_t>(ui->onlineTimeEdit->text().toUInt());
    QStringList list = ui->resetTimeEdit->text().split(":");
    for(int i = 0; i < list.size(); i++)
    {
        csgConfig.resetTime[i] = static_cast<uint8_t>(list[i].toUInt());
    }
    stringToChar(ui->ciphertextEdit->text(), reinterpret_cast<char*>(csgConfig.ciphertext), CSG_CIPHERTEXT_LEN);
    qDebug() << "passwd:" << csgConfig.passwd << endl;
    qDebug() << "beatInterval:" << csgConfig.beatInterval << endl;
    qDebug() << "collectInterval:" << csgConfig.collectInterval << endl;
    qDebug() << "sleepTime:" << csgConfig.sleepTime << endl;
    qDebug() << "onlineTime:" << csgConfig.onlineTime << endl;
    qDebug() << "resetTime:" << csgConfig.resetTime << endl;
    qDebug() << "ciphertext:" << csgConfig.ciphertext << endl;

    /* 下发配置. */
    sendMsgDeviceCsgConfigSet();
}


void Widget::on_dataRefreshButton_clicked()
{
	sendMsgDeviceRealDataGet();
}

void Widget::on_dataRefreshAutoButton_clicked()
{
	if (isDataRefresh)
    {
        isDataRefresh = false;
        ui->dataRefreshAutoButton->setText("自动刷新");
        buttonEnable(true);

    }
    else
    {
        buttonEnable(false);
        ui->dataRefreshAutoButton->setEnabled(true);
        ui->dataRefreshAutoButton->setText("停止刷新");
        isDataRefresh = true;
        sendMsgDeviceRealDataGet();
    }
}

void Widget::on_stateRefreshButton_clicked()
{
	sendMsgDeviceStateGet();
}

void Widget::on_freRefreshButton_clicked()
{
    /* 刷新工频数据. */
    freIndex = 0;
    QString temp;
    temp.sprintf("%d / 10", freIndex);
    ui->upFreIndexLabel->setText(temp);
    //work->multipleIndexSet(freInde);
    //work->stateSet(CM_usart::WS_POWER_FRE_GET);

    /* 关闭按钮. */
    buttonEnable(false);

    settings->setValue("freChIndex", ui->freChBox->currentIndex());
}


void Widget::on_waveColButton_clicked()
{
	sendMsgWaveCol();
}

void Widget::on_waveRefreshButton_clicked()
{

}

void Widget::on_waveCalButton_clicked()
{
    uint16_t param = static_cast<uint16_t>((ui->waveMaxEdit->text().toInt() - ui->waveMinEdit->text().toInt()) / 5) - 50;
    ui->waveParamEdit->setText(QString::number(param));

    /* 刷新实时数据按钮. */
    
}


void Widget::on_stateLogButton_clicked()
{
    if (is_log_up)
    {
        is_log_up = false;
        ui->stateLogButton->setText("下载 Log");
        //work->stateSet(CM_usart::WS_IDLE);
        buttonEnable(true);
    }
    else
    {
        logIndex = 0;
        QString temp;
        temp.sprintf("0 / %d", ui->stateLogEdit->text().toInt());
        //work->logSumSet(ui->stateLogEdit->text().toInt());
        ui->logTextEdit->clear();
        ui->logIndexLabel->setText(temp);
        //work->multipleIndexSet(0);
        //work->stateSet(CM_usart::WS_LOG_GET);

        /* 关闭按钮. */
        buttonEnable(false);
        ui->stateLogButton->setEnabled(true);

        is_log_up = true;
        ui->stateLogButton->setText("暂停 Log");
    }
}


void Widget::on_historyDataButton_clicked()
{
    if (is_data_up)
    {
        is_data_up = false;
        ui->historyDataButton->setText("下载数据");
        //work->stateSet(CM_usart::WS_IDLE);
        buttonEnable(true);
    }
    else
    {
        dataIndex = 0;
        QString temp;
        temp.sprintf("0 / %d", ui->historyDataEdit->text().toInt());
        //work->logSumSet(ui->historyDataEdit->text().toInt());
        ui->dataIndexLabel->setText(temp);
        //work->multipleIndexSet(0);
        //work->stateSet(CM_usart::WS_HISTORY_DATA_GET);

        int row = ui->historyDataTable->rowCount();
        if (row > 0)
        {
            for(int i = 0; i < row; i++)
            {
                for(int j = 0; j < ui->historyDataTable->columnCount(); j++)
                {
                    delete ui->historyDataTable->item(row - i - 1, j);
                }
                qDebug() << row - i - 1;
                ui->historyDataTable->removeRow(row - i - 1);
            }
        }

        /* 关闭按钮. */
        buttonEnable(false);
        ui->historyDataButton->setEnabled(true);

        is_data_up = true;
        ui->historyDataButton->setText("暂停数据");
    }
}


void Widget::on_waveButton_clicked()
{
    if (is_wave_up)
    {
        is_wave_up = false;
        ui->waveButton->setText("下载高频数据");
        buttonEnable(true);
    }
    else
    {
        QString curPath;
        if (waveFilePath.isEmpty())
        {
            curPath = QCoreApplication::applicationDirPath();
        }
        else
        {
            QFileInfo info = QFileInfo(waveFilePath);
            curPath = info.path();
        }

        curPath.append("/wavefile.wave");
        QString path = QFileDialog::getSaveFileName(this, tr("下载高频数据文件"), curPath, tr("data(*.*)"));
        if (path.isNull() || path.isEmpty())
        {
            QMessageBox::information(this, tr("提示"), tr("下载高频数据文件失败"));
            return;
        }
        else
        {
            waveFilePath = path;
            settings->setValue("waveFile", waveFilePath);
        }

        QString temp;
        temp.sprintf("%d / 8000", waveIndex);
        ui->upWaveIndexLabel->setText(temp);
        waveIndex = 0;

        /* 关闭按钮. */
        buttonEnable(false);
        ui->waveButton->setEnabled(true);

        is_wave_up = true;
        ui->waveButton->setText("暂停高频数据");
    }
}

