/*!
 * \brief  功能概述 下发命令帧
 * \param  参数描述 无
 * \return 返回值描述 无
 * \author zzy
 * \date   2015/5/25
 */
void CProtocolDLT_645_07::Polling()
{
    if ((GetSysAbsTime() - m_nLastTime) < 1)///如果最后发送时间小于1秒则不发送
    {
        return;
    }
    if (DLT_645_07QueryList.count() == 0)
    {
        return;
    }else if (m_nSendFrameListNumber >= DLT_645_07QueryList.count())
    {
        m_nSendFrameListNumber = 0;
//        qDebug()<<"从零开始发送";
    }
//    qDebug()<<"发送第:"<<SendFrameListNumber<<"个";
    if (NULL == m_pLink)
        return;
    if (!m_pLink->GetLinkState())
        return;
    m_mutexProcessData.lock();
//    m_pModbusRtuQuery = DLT_645_07QueryList.at(m_nSendFrameListNumber);
    CDLT_645_07Query *pQuery = DLT_645_07QueryList.at(m_nSendFrameListNumber);
    if (NULL != pQuery)
    {
        if (m_pLink->write(pQuery->m_ByteArrayFrame.data(),pQuery->m_ByteArrayFrame.count()))
        {
            m_arrayCurrentAddress = pQuery->m_arrayAddress;
            m_arrayRespondBuffer.clear();
            m_mutexProcessData.unlock();
            ShowMessage(0,DLT_645_07QueryList.at(m_nSendFrameListNumber)->m_ByteArrayFrame.toHex());
            m_nSendFrameListNumber++;
        }
    }
    m_nLastTime = GetSysAbsTime();
}
void CMAC::Slot_timeout()
{
    qDebug()<<"AAAA="<<GetSysAbsTime()<<m_nStartTime<<m_nChongQiShiJian;
    if (ABS(GetSysAbsTime()-m_nStartTime) > m_nChongQiShiJian)
    {
        qDebug()<<"BBBB="<<GetSysAbsTime()<<m_nStartTime<<m_nChongQiShiJian;
        m_nStartTime = GetSysAbsTime();
//        qDebug()<<"CCCC="<<system("reboot");
		exit(0);
       // QCoreApplication::exit();
    }
}
void CTcpServer::Slot_TcpServer_TcpSocket_readyRead()
{
//    qDebug()<<__func__;
    QByteArray Response = m_pTcpServer_TcpSocket->readAll();
    m_nTcpClientLastReceiveTime = GetSysAbsTime();
    emit Signal_TcpServer_TcpSocket_Response(Response);
}
bool CTcpClient::SetTcpServerIP_Port(const QHostAddress &TcpServer_HostAddress_, const quint16 nTcpServer_Port_)
{
    m_TcpServer_HostAddress = TcpServer_HostAddress_;
    m_nTcpServer_Port = nTcpServer_Port_;
    if (m_bTcpSocket_IsConnect)
    {

    }else
    {
        m_pTcpSocket = new QTcpSocket(this);
        m_pTcpSocket->connectToHost(m_TcpServer_HostAddress,m_nTcpServer_Port);
        m_bTcpSocket_IsConnect = m_pTcpSocket->waitForConnected(5*1000);
        if (m_bTcpSocket_IsConnect)
        {
            m_nTcpClientLastReceiveTime = GetSysAbsTime();
            connect(m_pTcpSocket,SIGNAL(connected()),this,SLOT(Slot_TcpSocket_connected()));
            connect(m_pTcpSocket,SIGNAL(disconnected()),m_pTcpSocket,SLOT(deleteLater()));
            connect(m_pTcpSocket,SIGNAL(disconnected()),this,SLOT(Slot_TcpSocket_disconnected()));
            connect(m_pTcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(Slot_TcpSocket_error(QAbstractSocket::SocketError)));
            connect(m_pTcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(Slot_TcpSocket_stateChanged(QAbstractSocket::SocketState)));
            connect(m_pTcpSocket,SIGNAL(readyRead()),this,SLOT(Slot_TcpSocket_readyRead()));
            emit Signal_ConnectState(m_bTcpSocket_IsConnect);
        }else
        {
            m_pTcpSocket->deleteLater();
            QTimer::singleShot(10000,this,SLOT(Slot_connectToHost()));
        }
        qDebug()<<__func__<<"  m_bTcpSocket_IsConnect ="<<m_bTcpSocket_IsConnect;
    }
    return m_bTcpSocket_IsConnect;
}
void CProtocolDemo::Polling()
{
//    qDebug()<<__func__<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QMap<unsigned int ,CDemoPointNode *>::iterator iterator;
    for (iterator = m_PointNode.m_PointNodeMap.begin(); iterator != m_PointNode.m_PointNodeMap.end(); ++iterator)
    {
        if (ABS(GetSysAbsTime()-iterator.value()->m_nStorageMoment) >= iterator.value()->m_nPeriodicStorage)
        {
//            qDebug()<<__func__<<"AAAAAAAA"<<iterator.value()->m_nStorageMoment<<iterator.value()->m_nPeriodicStorage;
            iterator.value()->m_nStorageMoment = GetSysAbsTime();
            for (int i = 0; i < iterator.value()->m_PointList.count(); ++i)
            {
//                qDebug()<<__func__<<"bbbbbbbbbb"<<iterator.value()->m_PointList.at(i)->m_strRTDBName;
                ChangeValue(iterator.value()->m_PointList.at(i));
            }
        }
    }
}
CMAC::CMAC(QObject *parent) :
    QObject(parent)
{
    m_nChongQiShiJian = 1*60*60;///< 6个小时重新启动一下机器
    m_nStartTime = GetSysAbsTime();
#if 0
    char p[32] = {'B','E','I','J','I','N','G','W','E','I','K','O','N','G','G','O','N','G','Y','E','W','A','N','G','G','U','A','N','J','I','S','H'};
#else
    char p[32] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
                  0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f};
#endif
    memcpy(myKey,p,32);
}
void CTcpServer::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_nTimerID)
    {
        qDebug()<<__func__<<m_bTcpServer_TcpSocket_IsConnect;
        if (m_bTcpServer_TcpSocket_IsConnect)
        {
            if (Absolute(GetSysAbsTime() - m_nTcpClientLastReceiveTime) > 30)
            {///< 30秒没有收到数据则断开连接
                SetTcpServer_CloseTcpSocket();
            }
        }else
        {

        }

    }
}
void CTcpServer::Slot_TcpServer_newConnection()
{
    qDebug()<<__func__;

    if (m_bTcpServer_TcpSocket_IsConnect)
    {
        m_pTcpServer->nextPendingConnection()->deleteLater();
    }else
    {
        m_pTcpServer_TcpSocket = m_pTcpServer->nextPendingConnection();
        qDebug()<<"m_pTcpServer->socketDescriptor()="<<m_pTcpServer->socketDescriptor();
        m_bTcpServer_TcpSocket_IsConnect = true;
        qDebug()<<"m_pTcpSocket="<<m_pTcpServer_TcpSocket;
        m_pTcpServer->socketDescriptor();
    //    connect(((QTcpSocket *)m_pLinkIODevice),SIGNAL(disconnected()), this,SLOT(SocketDeleteLater()));
        connect(m_pTcpServer_TcpSocket,SIGNAL(readyRead()),this,SLOT(Slot_TcpServer_TcpSocket_readyRead()));
        connect(m_pTcpServer_TcpSocket,SIGNAL(disconnected()),this,SLOT(Slot_TcpServer_TcpSocket_disconnected()));
        connect(m_pTcpServer_TcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(Slot_TcpServer_TcpSocket_error(QAbstractSocket::SocketError)));
        connect(m_pTcpServer_TcpSocket,SIGNAL(disconnected()),m_pTcpServer_TcpSocket,SLOT(deleteLater()));
        m_nTcpClientLastReceiveTime = GetSysAbsTime();
        emit Signal_ConnectState(m_bTcpServer_TcpSocket_IsConnect);
    }
}
void CProtocolDemo::GetTimeInfo(CPointDemoBase *pPoint_)
{
//    CPU_OCCUPY cpu_stat1;
//    CPU_OCCUPY cpu_stat2;
//    MEM_OCCUPY mem_stat;
//    int cpu;
    //获取内存
//    CLinuxInfo::get_memoccupy ((MEM_OCCUPY *)&mem_stat);

    //第一次获取cpu使用情况
//    CLinuxInfo::get_cpuoccupy((CPU_OCCUPY *)&cpu_stat1);
//    sleep(10);

    //第二次获取cpu使用情况
//    CLinuxInfo::get_cpuoccupy((CPU_OCCUPY *)&cpu_stat2);

    //计算cpu使用率
//    cpu = CLinuxInfo::cal_cpuoccupy ((CPU_OCCUPY *)&cpu_stat1, (CPU_OCCUPY *)&cpu_stat2);
    CTagI *pTempTagI = pPoint_->m_pTag;
    if (pTempTagI)
    {
        double fValue=0.0;
        switch(pPoint_->m_nFunction)
        {
        case 50://windows系统已经运行时间
    //        fValue= GetTickCount()/1000.0f;
        {
            struct sysinfo info;
            time_t cur_time = 0;
//            time_t boot_time = 0;
//            struct tm *ptm = NULL;
            if (sysinfo(&info))
            {
        //        PrintRunInfo("get systime from boottime to now");
                return ;
            }
            qDebug()<<info.uptime;
            time(&cur_time);
//            if (cur_time > info.uptime) {
//                boot_time = cur_time - info.uptime;
//            }
//            else {
//                boot_time = info.uptime - cur_time;
//            }
            fValue = info.uptime;
        }
            break;
        case 52://程序启动时间 秒
//            FileTimeToSystemTime(&timeCreate,&systemTime);
//            fValue= CTime(systemTime).GetTime();
        {
            fValue = pPoint_->m_nStartRunTime;
        }
            break;
        case 54://程序运行时间 秒
//            fValue= clock()/(float)CLOCKS_PER_SEC;
            fValue = GetSysAbsTime() - pPoint_->m_nStartRunTime;
            break;
        case 56://内核运行时间
//            FileTimeToSystemTime(&timeKernel,&systemTime);
//            fValue= systemTime.wHour*3600+systemTime.wMinute*60+systemTime.wSecond+systemTime.wMilliseconds/1000.0;
        {

        }
            break;
        case 58://用户运行时间
//            FileTimeToSystemTime(&timeUser,&systemTime);
//            fValue= systemTime.wHour*3600+systemTime.wMinute*60+systemTime.wSecond+systemTime.wMilliseconds/1000.0;
            fValue = clock();
            break;
        default:
            Q_ASSERT(false);//"IO变量定义无效:未定义的时间变量取值方式 funcno=4 param1=%d\n",nType);
            break;
        }
        QVariant value(fValue);
        pTempTagI->SetValue(pPoint_,value,value);
    }

    //    return fValue;
}
void CTcpClient::Slot_TcpSocket_readyRead()
{
    m_nTcpClientLastReceiveTime = GetSysAbsTime();
    QByteArray Response = m_pTcpSocket->readAll();
    emit Signal_TcpSocket_Response(Response);
}