#include "network.h"
#include <QMessageBox>
#include <QTime>
#include "string"
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>
#include "LoUIClass/x_uimsgboxokcancel.h"
NetComm::NetComm(QObject *p) :
    QObject(p)
{
    //创建UDP查询定时器，首次打开界面获取，知道控制卡接入，查找到控制卡
    m_pUdpTimer = new QTimer(this);
    connect(m_pUdpTimer,SIGNAL(timeout()),this,SLOT(onUdpTimeout()));

    m_pGetSpecifyIpTimer=new QTimer(this);
    connect(m_pGetSpecifyIpTimer,SIGNAL(timeout()),this,SLOT(onSpecifyIpTimeout()));

    //创建HTTP对象
    pHpptClient = new HpptClient(this);
    connect(pHpptClient,SIGNAL(httpGetRspReady(QString , QByteArray )),this,SLOT(OnProHttpGetResponse(QString , QByteArray)));
    //创建httpGet定时器
    //创建UDP套接字
 //   qDebug() << "udpSocket connect udpRecveive";
    udpSocket = new QUdpSocket(this);
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(UdpRecveive()));

    //界面启动第一次查询，后面使用DUP定时器查询
}


NetComm::~NetComm()
{
    if(m_pUdpTimer->isActive())
    {
        m_pUdpTimer->stop();
    }
    m_pUdpTimer->deleteLater();
    if(m_pGetSpecifyIpTimer->isActive())
    {
        m_pGetSpecifyIpTimer->stop();
    }
    m_pGetSpecifyIpTimer->deleteLater();
    delete udpSocket;
    if(pHpptClient != nullptr)
    {
        qDebug() <<"delete pHpptClient in ~NetComm";
        delete pHpptClient;
        pHpptClient=nullptr;
    }
}

void NetComm::StartUpdCheck()
{
        CheckControllersInLanByUdp255Cmd();
        CheckControllersInLanByUdpSelfBroadcastCmd();
        //CheckControllersInLanByUdpCmd();
        m_pUdpTimer->start(m_UdpTimerInterval);
}
void NetComm::StopUpdCheck()
{
    if(m_pUdpTimer!=nullptr)
        if(m_pUdpTimer->isActive())
           m_pUdpTimer->stop();
}
void NetComm::StopAllCheck()
{
    m_iEnableQuitFlag=1;
    if(m_pUdpTimer!=nullptr)
        if(m_pUdpTimer->isActive())
           m_pUdpTimer->stop();
    if(m_pHttpGetTimer!=nullptr)
      if(m_pHttpGetTimer->isActive())
           m_pHttpGetTimer->stop();
    if(m_pGetSpecifyIpTimer!=nullptr)
         if(m_pGetSpecifyIpTimer->isActive())
             m_pGetSpecifyIpTimer->stop();

}

void NetComm::onUdpTimeout()
{
    CheckControllersInLanByUdp255Cmd();
    CheckControllersInLanByUdpSelfBroadcastCmd();
    //CheckControllersInLanByUdpCmd();
}
void NetComm::UdpRecveive()
{
//    qDebug() << "NetComm func:" << "UdpRecveive";
    QByteArray ba;
    while(udpSocket->hasPendingDatagrams())
    {
        if(m_iEnableQuitFlag==1)
            return;
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress qhostaddress;
        quint16 recPort = 0;
        udpSocket->readDatagram(datagram.data(),datagram.size(),&qhostaddress,&recPort);
        if(m_iEnableQuitFlag==1)
            return;
//        qDebug() << "NetComm func:" << "readDatagram";
        QString msg=datagram.data();
        STREAM_PACKET *pStreamPacket=(STREAM_PACKET *)datagram.data();
        if(pStreamPacket->ucCommType==NET_COMMU_TYPE_SYSTEM_BROADCAST_ANSWER)
        {
            QString strtempCardId=pStreamPacket->ucSerialCode;
            QHostAddress temp;
            temp.setAddress(qhostaddress.toIPv4Address());
            QString strtempCardIp=temp.toString();
            JieXiQJsonObjectOfLedCardInfoOld(strtempCardId,strtempCardIp);
//            HttpGetFuncByPort("deviceList?fromDetector=true",strtempCardIp);

       }
       else//杨作栋增加的udp查询命令应答，应答中包含jsonObject
       {
            QJsonParseError parseJsonErr;
            QJsonDocument document = QJsonDocument::fromJson(datagram,&parseJsonErr);
            if(!(parseJsonErr.error == QJsonParseError::NoError))
            {
                if(datagram.size()==0)
                    qDebug()<<"json is empty";
                else
                    qDebug()<<tr("wDevicesItem OnProHttpResponse 解析json文件错误！");
                return;
            }
            QJsonObject jsonObject = document.object();
            QHostAddress temp;
            temp.setAddress(qhostaddress.toIPv4Address());
            QString strtempCardIp=temp.toString();
            JieXiQJsonObjectOfLedCardInfo(jsonObject,strtempCardIp);

        }
    }
    //   qDebug() << "NetComm func:" << "UdpRecveive end";
}
//在该ip的3000端口get方法deviceList，可以一次性获取到局域网中设备列表的详细信息
//int  ddddd=0;
void NetComm::HttpGetFuncByPort(QString strFunc,QString strIp)
{
 //   if(ddddd==0)
 //   {
        m_strUrl="http://"+strIp+":3000/"+strFunc;
        pHpptClient->httpGet(m_strUrl);
        qDebug() << "HttpGetFuncByPort" << m_strUrl;
 //       ddddd=1;
 //   }


}
void NetComm::CheckSpecifyIpRange(QString strFromIp,QString strToIp)
{
    Q_UNUSED(strFromIp)
    Q_UNUSED(strToIp)
    qDebug() <<"HttpGetFuncFromIpRange:" << "this func not finished";
}
void NetComm::CheckSpecifyIp(QString strIp)
{
    m_strCurSpecifyIp=strIp;
    qDebug() <<"CheckSpecifyIp:";
    HttpGetFuncByPort("deviceList?fromDetector=true",strIp);
    m_pGetSpecifyIpTimer->start(1000);
    //发送3次，都收不到应答怎标识超时
    //启动定时器，如果3秒内找不到超时提示没有搜索到
}
void NetComm::onSpecifyIpTimeout()
{
    if(m_intSpecifyIpGetNumber < 3)
    {
        m_intSpecifyIpGetNumber++;
        HttpGetFuncByPort("deviceList?fromDetector=true",m_strCurSpecifyIp);
    }else {
        qDebug() <<"onSpecifyIpTimeout:";
        emit sigGetSpecifyIpTimerOut();
        m_pGetSpecifyIpTimer->stop();
        m_intSpecifyIpGetNumber=0;
        m_strCurSpecifyIp="";

    }
}
/*************************************
* 获取本机 IPV4 地址，如果有多个，返回所有
* 有效的IPV4地址
**************************************/
QHostAddress NetComm::getHostIPV4Address()
{
    foreach(const QHostAddress& hostAddress,QNetworkInterface::allAddresses())
        if ( hostAddress != QHostAddress::LocalHost && hostAddress.toIPv4Address() )
            return hostAddress;

    return QHostAddress::LocalHost;

}

STREAM_PACKET NetComm::LedOkMakeStreamPacket(int iComType,int iLen,unsigned char *ucBuf,QString str)
{
    STREAM_PACKET Temp;
    memset(&Temp,0x00,sizeof(STREAM_PACKET));
    if(iLen>2048)
        return Temp;
    memset(Temp.SyncHead,STREAM_SYNC_HEAD,STREAM_SYNC_HEAD_NUM);
    memset(Temp.ucSerialCode,0x00,20);
    char*  ch;
    QByteArray ba = str.toLatin1(); // must
    ch=ba.data();
    memcpy(Temp.ucSerialCode,ch,ba.size());
    Temp.iLength=iLen;
    Temp.ucCommType=iComType;
    memcpy(Temp.pDataBuffer,ucBuf,iLen);
    Temp.pDataBuffer[Temp.iLength]=
            GetCheckCodeIn8(&Temp.ucCommType,Temp.iLength+sizeof(Temp.ucCommType)+sizeof(char)*20+sizeof(Temp.iLength));
    return Temp;
}
//设备界面刷新按钮点击响应槽函数
void NetComm::CheckControllersInLanByUdpCmd()
{
    // return;       //  qDebug() << "CheckControllersInLanByUdpCmd" ;
    if(m_iEnableQuitFlag==1)
        return;
          QString strIpAddress;
          SYSTIMER tempTimer;
          memset(&tempTimer,0x00,sizeof(SYSTIMER));
          QDateTime t=QDateTime::currentDateTime(); //获取系统日期
          tempTimer.y=t.date().year(); //获取年份
          tempTimer.m=t.date().month(); //获取当前月份
          tempTimer.d=t.date().day(); //获得几号
          tempTimer.h=t.time().hour(); //获取当前为几时
          tempTimer.mm=t.time().minute(); //获取分钟
          tempTimer.s=t.time().second(); //获取秒
          tempTimer.w=1; //获取星期几，注意1为星期天，7为星期六
          STREAM_PACKET tempStreadPacket=LedOkMakeStreamPacket(NET_COMMU_TYPE_SYSTEM_BROADCAST,sizeof(SYSTIMER),(unsigned char *)&tempTimer,"Broadcast!");

          int iLenPacket=tempStreadPacket.iLength+sizeof(int)+STREAM_SYNC_HEAD_NUM*sizeof(unsigned char)+sizeof(char)+20*sizeof(char)+sizeof(char);/////除正文外的协议结构大小；
          //UDP多网卡广播
          QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
          foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表
          {
              if(m_iEnableQuitFlag==1)
                  return;
              if(m_strDirectlyConnectNetworkName.isEmpty())
              {
                  foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
                  {
                      if(m_iEnableQuitFlag==1)
                          return;
                      QHostAddress broadcastAddress("255.255.255.255");
//                      QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
//                      broadcastAddress.toIPv4Address();
//                      if (broadcastAddress != QHostAddress::Null
//                              && entry.ip() != QHostAddress::LocalHost
//                              && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                              )
                      {
                          strIpAddress =entry.ip().toString();// broadcastAddress.toString();
                          if(udpSocket->writeDatagram((char *)&tempStreadPacket,iLenPacket,broadcastAddress,m_port) != iLenPacket)
                          {
                              qDebug()  << strIpAddress<< "error" << "CheckControllersInLanByUdpCmd writedata fram error!";
                             // return;
                          }
                          else {
                              qDebug() << strIpAddress << "send udp cmd1" ;
                          }
                      }

                  }
              }
              else {
                  //if(interfaces.humanReadableName()==m_strDirectlyConnectNetworkName)
                  {
                      foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
                      {
                          if(m_iEnableQuitFlag==1)
                              return;
                          QHostAddress broadcastAddress("255.255.255.255");
//                          QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
//                          broadcastAddress.toIPv4Address();
//                          if (broadcastAddress != QHostAddress::Null
//                                  && entry.ip() != QHostAddress::LocalHost
//                                  && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                                  )
                          {
                              strIpAddress =entry.ip().toString();// broadcastAddress.toString();
                              if(udpSocket->writeDatagram((char *)&tempStreadPacket,iLenPacket,broadcastAddress,m_port) != iLenPacket)
                              {
                                  qDebug()  << strIpAddress<< "error" << "m_strDirectlyConnectNetworkName CheckControllersInLanByUdpCmd writedata fram error!";
                                 // return;
                              }
                              else {
                                  qDebug() << strIpAddress << "send udp cmd by cable network1" ;
                              }
                          }

                      }
                  }

              }

          }
}
void NetComm::CheckControllersInLanByUdp255Cmd()
{
    if(m_iEnableQuitFlag==1)
        return;
          QString strIpAddress;
          //UDP多网卡广播
          QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
          foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表
          {
              if(m_iEnableQuitFlag==1)
                  return;
              if(m_strDirectlyConnectNetworkName.isEmpty())//如果网线直连
              {
                  foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
                  {
                      if(m_iEnableQuitFlag==1)
                          return;
                      //QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
                      QHostAddress broadcastAddress("255.255.255.255");
//                      broadcastAddress.toIPv4Address();
//                      if (broadcastAddress != QHostAddress::Null
//                              && entry.ip() != QHostAddress::LocalHost
//                              && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                              )
                      {
                          strIpAddress =entry.ip().toString();// broadcastAddress.toString();
                          QJsonObject login_json;
#ifdef MACRO_YUANHENG_VERSION
                          login_json.insert("action", "getCardInfo");//元亨
#else
                          login_json.insert("action", "getInfo");
#endif
                          QJsonDocument doc;
                          doc.setObject(login_json);
                          QByteArray post_loginArray = doc.toJson(QJsonDocument::Compact);
                          int iLenPacket=post_loginArray.length();
                          if(udpSocket->writeDatagram((char *)post_loginArray.data(),iLenPacket,broadcastAddress,22222) != iLenPacket)
                          {
                             // qDebug()  << strIpAddress<< "error" << "CheckControllersInLanByUdpCmd writedata fram error!";
                             // return;
                          }
                          else {
                     //         qDebug() << strIpAddress << "send udp cmd2" ;
                          }
                      }

                  }
              }
              else {
                  //if(interfaces.humanReadableName()==m_strDirectlyConnectNetworkName)
                  {
                      foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
                      {
                          if(m_iEnableQuitFlag==1)
                              return;
                         // QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
                          QHostAddress broadcastAddress("255.255.255.255");
                          broadcastAddress.toIPv4Address();
//                          if (broadcastAddress != QHostAddress::Null
//                                  && entry.ip() != QHostAddress::LocalHost
//                                  && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                                  )
                          {
                              strIpAddress =entry.ip().toString();// broadcastAddress.toString();
                              QJsonObject login_json;
#ifdef MACRO_YUANHENG_VERSION
                          login_json.insert("action", "getCardInfo");
#else
                          login_json.insert("action", "getInfo");
#endif
                              QJsonDocument doc;
                              doc.setObject(login_json);
                              QByteArray post_loginArray = doc.toJson(QJsonDocument::Compact);
                               int iLenPacket=post_loginArray.length();
                               if(!udpSocket->bind(entry.ip()))
                                   break;
                              if(udpSocket->writeDatagram((char *)post_loginArray.data(),iLenPacket,broadcastAddress,22222) != iLenPacket)
                              {
                                  qDebug()  << strIpAddress<< "error" << "m_strDirectlyConnectNetworkName CheckControllersInLanByUdpCmd writedata fram error!";
                                 // return;
                              }
                              else {
                                  qDebug() << strIpAddress << "send udp cmd by cable network2" ;
                              }
                          }

                      }
                  }

              }

          }
}
void NetComm::CheckControllersInLanByUdpSelfBroadcastCmd()
{

     if(m_iEnableQuitFlag==1)
        return;
          QString strIpAddress;
          //UDP多网卡广播
          QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
          foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表
          {
              if(m_iEnableQuitFlag==1)
                  return;
              if(m_strDirectlyConnectNetworkName.isEmpty())//如果网线直连
              {
                  foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
                  {
                      if(m_iEnableQuitFlag==1)
                          return;
                      QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
//                      broadcastAddress.toIPv4Address();
//                      if (broadcastAddress != QHostAddress::Null
//                              && entry.ip() != QHostAddress::LocalHost
//                              && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                              )
                      {
                          strIpAddress =entry.ip().toString();// broadcastAddress.toString();
                          QJsonObject login_json;
#ifdef MACRO_YUANHENG_VERSION
                          login_json.insert("action", "getCardInfo");
#else
                          login_json.insert("action", "getInfo");
#endif
                          QJsonDocument doc;
                          doc.setObject(login_json);
                          QByteArray post_loginArray = doc.toJson(QJsonDocument::Compact);
                          int iLenPacket=post_loginArray.length();
                          if(udpSocket->writeDatagram((char *)post_loginArray.data(),iLenPacket,broadcastAddress,22222) != iLenPacket)
                          {
                             // qDebug()  << strIpAddress<< "error" << "CheckControllersInLanByUdpCmd writedata fram error!";
                             // return;
                          }
                          else {
                            //  qDebug() << strIpAddress << "send udp cmd2" ;
                          }
                      }

                  }
              }
              else {
                  //if(interfaces.humanReadableName()==m_strDirectlyConnectNetworkName)
                  {
                      foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
                      {
                          if(m_iEnableQuitFlag==1)
                              return;
                          QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
                           broadcastAddress.toIPv4Address();
//                          if (broadcastAddress != QHostAddress::Null
//                                  && entry.ip() != QHostAddress::LocalHost
//                                  && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                                  )
                          {
                              strIpAddress =entry.ip().toString();// broadcastAddress.toString();
                              QJsonObject login_json;
#ifdef MACRO_YUANHENG_VERSION
                          login_json.insert("action", "getCardInfo");
#else
                          login_json.insert("action", "getInfo");
#endif
                              QJsonDocument doc;
                              doc.setObject(login_json);
                              QByteArray post_loginArray = doc.toJson(QJsonDocument::Compact);
                               int iLenPacket=post_loginArray.length();
                               if(!udpSocket->bind(entry.ip()))
                                   break;
                              if(udpSocket->writeDatagram((char *)post_loginArray.data(),iLenPacket,broadcastAddress,22222) != iLenPacket)
                              {
                                  qDebug()  << strIpAddress<< "error" << "m_strDirectlyConnectNetworkName CheckControllersInLanByUdpCmd writedata fram error!";
                                 // return;
                              }
                              else {
                                  qDebug() << strIpAddress << "send udp cmd by cable network2" ;
                              }
                          }

                      }
                  }

              }

          }
}
//设备界面刷新按钮点击响应槽函数
void NetComm::RestoreLedCardIpByUdpCmdBefore(QString strNetworkName)
{
    m_strDirectlyConnectNetworkName=strNetworkName;
}
void NetComm::RestoreLedCardIpToDhcpByUdpCmd()
{
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetEthernet");
    json.insert("dhcp", true);
    json.insert("ip", "0.255.255.255");
    json.insert("gateWay", "0.255.255.255");
    json.insert("netMask", "0.255.255.255");
    json.insert("dns", "0.255.255.255");

    QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表
    {
        if(m_iEnableQuitFlag==1)
            return;
        //if(interfaces.humanReadableName()==m_strDirectlyConnectNetworkName)
        {

            foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
            {

                if(m_iEnableQuitFlag==1)
                    return;
                entry.setBroadcast(QHostAddress::Broadcast);
                QHostAddress broadcastAddress("255.255.255.255");
                {
                    qDebug() << "RestoreLedCardIpByUdpCmd" ;
                    entry.setBroadcast(QHostAddress::Broadcast);

                    RESTORE_IP stTempIp;
                    memset(&stTempIp,0x00,sizeof(RESTORE_IP));

                    QString strNew=entry.ip().toString();
                    int itempOffset = strNew.lastIndexOf(".");
                    for(int m=1;m<255;m++)
                    {
                        QString sstrNew=strNew.left(itempOffset)+QString::number(m);
                        QString m_strUrl="http://"+sstrNew+":2016/settings";
                        HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
                    }
                    }
                }
            }
        }

}
#include "LoUIClass/x_uimsgboxok.h"
void NetComm::RestoreLedCardIpByUdpCmd()
{
    qDebug()<<"RestoreLedCardIpByUdpCmd";
    if(m_iEnableQuitFlag==1)
        return;


/*20201017 masked by alahover -s
   qDebug() << "RestoreLedCardIpByUdpCmd" ;
    QString strIpAddress;
    RESTORE_IP stTempIp;
    memset(&stTempIp,0x00,sizeof(RESTORE_IP));

    QString strNew="192.168.0.200";
    memcpy(stTempIp.cNewIp,strNew.toLatin1().data(),strNew.length());

    QString strMask="255.255.255.0";
    memcpy(stTempIp.cMask,strMask.toLatin1().data(),strMask.length());

    QString strGateway="192.168.0.1";
    memcpy(stTempIp.cGateway,strGateway.toLatin1().data(),strGateway.length());
    memcpy(stTempIp.cDns,strGateway.toLatin1().data(),strGateway.length());

//    QString strB="192.168.0.1";
//    memcpy(stTempIp.cGateway,strGateway.toLatin1().data(),20);

//    QString strLocalIp="192.168.0.88";
//    memcpy(stTempIp.cLocalIp,strLocalIp.toLatin1().data(),20);

    //STREAM_PACKET tempStreadPacket=LedOkMakeStreamPacket(COMMAND_ONLY_RESET_CARD_IP,sizeof(RESTORE_IP),(unsigned char *)&stTempIp,"Broadcast!");
    STREAM_PACKET tempStreadPacket=LedOkMakeStreamPacket(COMMAND_ONLY_RESET_CARD_IP,80,(unsigned char *)&stTempIp,"Broadcast!");

    int iLenPacket=tempStreadPacket.iLength+sizeof(int)+STREAM_SYNC_HEAD_NUM*sizeof(unsigned char)+sizeof(char)+20*sizeof(char)+sizeof(char);/////除正文外的协议结构大小；

    QUdpSocket *tempUdpSocket= new QUdpSocket(this);
    if(!tempUdpSocket->bind(QHostAddress("192.168.0.88")))
        return;
    QHostAddress broadcastAddress("255.255.255.255");
    int iSendLength=tempUdpSocket->writeDatagram((char *)&tempStreadPacket,iLenPacket,broadcastAddress,m_port);
    if( iSendLength != iLenPacket)
    {
        qDebug() << "error" << "RestoreLedCardIpByUdpCmd error!send restore led card ip by udp cmd";
        return;
    }
    else {
        strIpAddress ="192.168.0.88";// broadcastAddress.toString();
        qDebug() << strIpAddress << "send restore led card ip by udp cmd" ;
    }
    tempUdpSocket->deleteLater();
*/
    //UDP多网卡广播
    QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表
    {
        if(m_iEnableQuitFlag==1)
            return;
        //if(interfaces.humanReadableName()==m_strDirectlyConnectNetworkName)
        {

            foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
            {

                if(m_iEnableQuitFlag==1)
                    return;
                entry.setBroadcast(QHostAddress::Broadcast);
                QHostAddress broadcastAddress("255.255.255.255");
//                QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
//                broadcastAddress.toIPv4Address();



//                if (broadcastAddress != QHostAddress::Null
//                        && entry.ip() != QHostAddress::LocalHost
//                        && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                        )
                {
                    //qDebug() << "RestoreLedCardIpByUdpCmd" ;
                    entry.setBroadcast(QHostAddress::Broadcast);

                    RESTORE_IP stTempIp;
                    memset(&stTempIp,0x00,sizeof(RESTORE_IP));

                    QString strNew=entry.ip().toString();
                    int itempOffset = strNew.lastIndexOf(".");
                    QString sstrNew=strNew.left(itempOffset)+".254";
                    if(sstrNew.length()<=20)
                        memcpy(stTempIp.cNewIp,sstrNew.toLatin1().data(),sstrNew.length());
                    QString strMask=entry.netmask().toString();
                    if(strMask.length()<=20)
                    memcpy(stTempIp.cMask,strMask.toLatin1().data(),strMask.length());
                    QString strGateway=entry.ip().toString();
                    if(strGateway.length()<=20)
                    memcpy(stTempIp.cGateway,strGateway.toLatin1().data(),strGateway.length());
                    if(strGateway.length()<=20)
                    memcpy(stTempIp.cDns,strGateway.toLatin1().data(),strGateway.length());
                    STREAM_PACKET tempStreadPacket=LedOkMakeStreamPacket(COMMAND_ONLY_RESET_CARD_IP,80,(unsigned char *)&stTempIp,"Broadcast!");
                    int iLenPacket=tempStreadPacket.iLength+sizeof(int)+STREAM_SYNC_HEAD_NUM*sizeof(unsigned char)+sizeof(char)+20*sizeof(char)+sizeof(char);/////除正文外的协议结构大小；

                    QUdpSocket *tempUdpSocket= new QUdpSocket(this);
                    if(!tempUdpSocket->bind(entry.ip()))
                        break;
                    int iSendLength=tempUdpSocket->writeDatagram((char *)&tempStreadPacket,iLenPacket,broadcastAddress,m_port);
                    if( iSendLength != iLenPacket)
                    {
//                        qDebug() << "error" << "RestoreLedCardIpByUdpCmd error!send restore led card ip by udp cmd";
//                       // return;
                    }
                    else {
//                        strIpAddress =entry.ip().toString();// broadcastAddress.toString();
//                        qDebug() << strIpAddress << "send restore led card ip by udp cmd" ;
                    }
                    //tempUdpSocket->deleteLater();
                }

            }
        }

    }
}
void NetComm::RestoreLedCardIpToDhcpByUdpCmd(QString strNetworkName)
{
    if(m_iEnableQuitFlag==1)
        return;
    QString strIpAddress;
    char cTemp[20];
    memset(cTemp,0x00,20);
//    QString strLocalIp="192.168.0.88";
//    memcpy(cTemp,strLocalIp.toLatin1().data(),20);

    STREAM_PACKET tempStreadPacket=LedOkMakeStreamPacket(COMMAND_ONLY_RESET_CARD_IP,20,(unsigned char *)cTemp,"Broadcast!");

    int iLenPacket=tempStreadPacket.iLength+sizeof(int)+STREAM_SYNC_HEAD_NUM*sizeof(unsigned char)+sizeof(char)+20*sizeof(char)+sizeof(char);/////除正文外的协议结构大小；
    QUdpSocket *tempUdpSocket= new QUdpSocket(this);
    if(!tempUdpSocket->bind(QHostAddress("192.168.0.88")))
        return;
    QHostAddress broadcastAddress("255.255.255.255");
    if(tempUdpSocket->writeDatagram((char *)&tempStreadPacket,iLenPacket,broadcastAddress,m_port) != iLenPacket)
    {
        qDebug() << "error" << "\033[32mwritedatafram error!";
        return;
    }
    else {
        qDebug() << strIpAddress << "send udp cmd3" ;
    }
    tempUdpSocket->deleteLater();

//    //UDP多网卡广播
//    QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
//    foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表
//    {
//        if(m_iEnableQuitFlag==1)
//            return;
//        if(interfaces.humanReadableName()==strNetworkName)
//        {

//            foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址，子网掩码和广播地址
//            {
//                if(m_iEnableQuitFlag==1)
//                    return;
//                QHostAddress broadcastAddress = entry.broadcast();//返回IPV4地址和子网掩码相关联的广播地址
//                broadcastAddress.toIPv4Address();
//                if (broadcastAddress != QHostAddress::Null
//                        && entry.ip() != QHostAddress::LocalHost
//                        && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
//                        )
//                {
//                    strIpAddress =entry.ip().toString();// broadcastAddress.toString();
//                    QUdpSocket *tempUdpSocket= new QUdpSocket(this);
//                    if(!tempUdpSocket->bind(entry.ip()))
//                        break;
//                    if(tempUdpSocket->writeDatagram((char *)&tempStreadPacket,iLenPacket,broadcastAddress,m_port) != iLenPacket)
//                    {
//                        qDebug() << "error" << "\033[32mwritedatafram error!";
//                        return;
//                    }
//                    else {
//                        qDebug() << strIpAddress << "send udp cmd3" ;
//                    }
//                    tempUdpSocket->deleteLater();
//                }

//            }
//        }

//    }
}
void NetComm::OnProHttpGetResponse(QString url, QByteArray data)
{
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(m_iEnableQuitFlag==1)
        return;
    if(url!="")
    {
        //qDebug()<<"POST";
        //qDebug()<<data;
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            qDebug()<<tr("解析json文件错误！");
            return;
        }
        //QJsonObject jsonObject = document.object();
        QJsonObject rootObj = document.object();
        QStringList keys = rootObj.keys();
        for(int i = 0; i < keys.size(); i++)
        {
            QString strKey=keys.at(i);
            //qDebug() << "key" << i << " is:" << strKey;
            if(rootObj.contains(strKey))
            {
                QJsonObject subObj = rootObj.value(strKey).toObject();
                JieXiQJsonObjectOfLedCardInfo(subObj,"");

            }
        }
    }
}
void NetComm::ClearAllLedcardList()
{
    LedCardList.clear();
}

void NetComm::JieXiQJsonObjectOfLedCardInfoOld(const QString &strId,const QString &strIp)
{
    LedCard *pLedCard=new LedCard(this);//alahover 没有释放
    pLedCard->m_strCardId=strId;
    pLedCard->m_strCardIp=strIp;
    int iExistFlag=0;
    for(int i=0;i<LedCardList.count();i++)
    {
        QString ddd=LedCardList.at(i)->m_strCardId;
        if(LedCardList.at(i)->m_strCardId==pLedCard->m_strCardId )//如果已经存在在列表中
        {
            iExistFlag=1;
            LedCard *pOldLedCard=LedCardList.at(i);//获取到旧的对象指针
            pOldLedCard->m_bOnLine=true;
            if(pOldLedCard->CompareHTTPGetParam(pLedCard)==false)//如果ip地址变化了
            {
                pOldLedCard->copyLedCardHTTPGetParam(pLedCard);
                qDebug() << pLedCard->m_strCardId << "modifed param";
                //emit LedCardChanged(pOldLedCard);//发送信号到界面
                emit addLedCard(pOldLedCard);//发送信号到界面
            }
            else {
                //post失败的概率比较小，所以这里是否需要平凡的更新，不需要刻意屏蔽该操作改为在其他点击操作中进行
               // emit sigwDeviceItemHttpPost(pOldLedCard);//每检索到该控制卡都会触发post获取控制卡的信息
                //qDebug() << pLedCard->m_strCardId <<"    already exist";
                emit ClearHeartbeatFlagByUdp(pOldLedCard);
            }
            break;
        }
    }
    if(iExistFlag == 0)
    {
        //每新增一个控制卡，申请的内存传给其他窗口，不在这里释放
        qDebug() << pLedCard->m_strCardId <<"    add to list";
        pLedCard->m_bOnLine=true;

        LedCardList.append(pLedCard);
        emit addLedCard(pLedCard);//发送信号到界面
        m_UdpTimerInterval=10000;
        m_pUdpTimer->setInterval(m_UdpTimerInterval);
    }
    else
    {
        delete pLedCard;
    }

}

void NetComm::JieXiQJsonObjectOfLedCardInfo(const QJsonObject &subObj,const QString &strIp)
{
    LedCard *pLedCard=new LedCard(this);//alahover 没有释放
    pLedCard->m_strCardId=subObj["cardId"].toString();
    if(strIp.isEmpty())
    {
        QString strtempIp=subObj["ip"].toString();
        if(!strtempIp.isEmpty())
          pLedCard->m_strCardIp=strtempIp;
        qDebug()<<"ip="<<strtempIp;
        QString strtempNewIp=subObj["newIp"].toString();
        if(!strtempNewIp.isEmpty())
            pLedCard->m_strCardIp=strtempNewIp;
        qDebug()<<"new ip="<<strtempNewIp;

    }
    else
    {
        pLedCard->m_strCardIp=strIp;
    }
 //   qDebug()<<"JieXiQJsonObjectOfLedCardInfo="<<strIp;
    pLedCard->m_iWidth=subObj["width"].toInt();
    pLedCard->m_iHeight=subObj["height"].toInt();
 //   pLedCard->m_strCardRemarkName=subObj["name"].toString();

    pLedCard->starterversionName=subObj["versionName"].toString();
    pLedCard->starterPort=subObj["starterPort"].toInt();
    pLedCard->androidVersion=subObj["androidVersion"].toString();
    pLedCard->iHttpGetId=subObj["id"].toInt();
    pLedCard->androidHeight=subObj["androidHeight"].toInt();
    pLedCard->androidWidth=subObj["androidWidth"].toInt();
    pLedCard->lastActive=subObj["lastActive"].toInt();

    if(m_strCurSpecifyIp!="")//指定IP的查找,找到的设备，直接返回，不需要释放pLedCard
    {
        emit sigGetSpecifyIpResponse(pLedCard);
        m_pGetSpecifyIpTimer->stop();
        m_intSpecifyIpGetNumber=0;
        m_strCurSpecifyIp="";
    }

    int iExistFlag=0;
    for(int i=0;i<LedCardList.count();i++)
    {
        QString ddd=LedCardList.at(i)->m_strCardId;
        if(LedCardList.at(i)->m_strCardId==pLedCard->m_strCardId )//如果已经存在在列表中
        {
            iExistFlag=1;
            LedCard *pOldLedCard=LedCardList.at(i);//获取到旧的对象指针
            pOldLedCard->m_bOnLine=true;
            if(pOldLedCard->CompareHTTPGetParam(pLedCard)==false)//如果ip地址变化了
            {
                pOldLedCard->copyLedCardHTTPGetParam(pLedCard);
                qDebug() << pLedCard->m_strCardId << "modifed param";
                //emit LedCardChanged(pOldLedCard);//发送信号到界面
                emit addLedCard(pOldLedCard);//发送信号到界面
            }
            else {
                //post失败的概率比较小，所以这里是否需要平凡的更新，不需要刻意屏蔽该操作改为在其他点击操作中进行
               // emit sigwDeviceItemHttpPost(pOldLedCard);//每检索到该控制卡都会触发post获取控制卡的信息
                //qDebug() << pLedCard->m_strCardId <<"    already exist";
                emit ClearHeartbeatFlagByUdp(pOldLedCard);
            }
            break;
        }
    }
    if(iExistFlag == 0)
    {
        //每新增一个控制卡，申请的内存传给其他窗口，不在这里释放
        qDebug() << pLedCard->m_strCardId <<"    add to list";
        pLedCard->m_bOnLine=true;

        LedCardList.append(pLedCard);
        emit addLedCard(pLedCard);//发送信号到界面
        m_UdpTimerInterval=10000;
        m_pUdpTimer->setInterval(m_UdpTimerInterval);
    }
    else
    {
        delete pLedCard;
    }

}
void NetComm::OnStartUdpTimer(bool b)
{
    if(b)
    {
//        m_UdpTimerInterval=1000;
        m_pUdpTimer->start(m_UdpTimerInterval);
    }
    else
        m_pUdpTimer->stop();
}
