#include "coreobject.h"

#define iServerIP "172.19.198.166"
#define oServerIP "47.103.74.123"

#define UN_REFERENCED_PARAMETER(x) {(x) = (x);}

extern BOOL CALLBACK RegisterCallBack(LONG lUserID, DWORD dwDataType, void *pOutBuffer, DWORD dwOutLen, void *pInBuffer, DWORD dwInLen, void *pUser);
extern BOOL CALLBACK fnPREVIEW_NEWLINK_CB(LONG lPreviewHandle, NET_EHOME_NEWLINK_CB_MSG *pNewLinkCBMsg, void *pUserData);
extern void CALLBACK fnPREVIEW_DATA_CB(LONG lPreviewHandle, NET_EHOME_PREVIEW_CB_MSG *pPreviewCBMsg, void *pUserData);
extern BOOL InputStreamData(QString deviceid, BYTE byDataType, char* pBuffer, int iDataLen);
extern BOOL CALLBACK AlarmMSGCallBack (LONG lHaldle, NET_EHOME_ALARM_MSG *pAlarmMsg, void *pUserData);
extern QDateTime getFullTime(FullTime fTime);
extern void setFullTime(FullTime *fTime, QDateTime qTime);
extern QString getNewId();

uint start_time;
bool had_reg;

MyEHomeShm *ytShm;

CoreObject::CoreObject(QObject *parent) :
    QObject(parent)
{
    processList.clear();
    sqlList.clear();
    reportList.clear();
    companyphoneList.clear();
    isWorking = false;
    start_time = QDateTime::currentDateTime().toTime_t();
    had_reg = false;
    timer = new QTimer();
    db = QSqlDatabase::addDatabase("QMYSQL","conf_db");
    db.setDatabaseName("jdxf");
    db.setHostName("47.98.201.187");
    db.setUserName("root");
    db.setPassword("Yt2018IoT");
    NET_ESTREAM_Init();
    NET_EALARM_Init();
    NET_ECMS_Init();
    if(shm_load()){
        QDateTime zeroTime = QDateTime::fromTime_t(0);
        for(int i=0;i<DEVICES_COUNT;i++){
            ytShm->eHomeDevice[i].LoginId = -1;
            ytShm->eHomeDevice[i].SessionId = -1;
            ytShm->eHomeDevice[i].listen_preview_handle = -1;
            ytShm->eHomeDevice[i].listen_alarm_handle = -1;
            ytShm->eHomeDevice[i].lLinkHandle = -1;
            ytShm->eHomeDevice[i].previewId = -1;
            ytShm->eHomeDevice[i].Connected = 0x00;
            ytShm->eHomeDevice[i].Inited = 0x00;
            ytShm->eHomeDevice[i].onLined = 0x00;
            ytShm->eHomeDevice[i].savetmp = 0x00;
            ytShm->eHomeDevice[i].transed = 0x00;
            for(int j=0;j<8;j++)
                ytShm->eHomeDevice[i].io[j] = 0x00;
            ytShm->eHomeDevice[i].time[0]=0;
            ytShm->eHomeDevice[i].time[1]=0;
            ytShm->eHomeDevice[i].tmpfile = NULL;
            setFullTime(&(ytShm->eHomeDevice[i].onLinetime),zeroTime);
            setFullTime(&(ytShm->eHomeDevice[i].transtime),zeroTime);
            QProcess *process = new QProcess(this);
            connect(process,SIGNAL(finished(int)),this,SLOT(process_stop()));
            connect(process,SIGNAL(destroyed()),this,SLOT(process_stop()));
            connect(process,SIGNAL(aboutToClose()),this,SLOT(process_stop()));
            processList.append(process);
        }
        for(quint16 i=0;i<8;i++){
            wxThreads[i] = new WechartThreads(this,i,"47.98.201.73","/jdxf/wxapp2.php/Home/GeneralPush/voice");
//            connect(wxThreads[i],&WechartThreads::wxchart,this,&CoreObject::chartlog);
            wssThread[i] = new ttsThreads(this,i,"47.98.201.73","/report",55125);
//            spThread[i] = new ttsThreads(this,i,"47.98.201.187","/report",55335);
//            connect(wssThread[i],&ttsThreads::ttslog,this,&CoreObject::chartlog);
            wxThreads[i]->start();
            wssThread[i]->start();
//            spThread[i]->start();
        }
        repcur = 0;
        wxcur = 0;
    }
    chkPhoneList();
    connect(timer,SIGNAL(timeout()),this,SLOT(time_out()));
}

CoreObject::~CoreObject()
{
    for(int i=0;i<processList.length();i++){
        if(processList.at(i)->pid()>0)
            processList.at(i)->close();
    }
    NET_ECMS_Fini();
    NET_ESTREAM_Fini();
    NET_EALARM_Fini();
}

void CoreObject::chkPhoneList()
{
    if(db.open()){
        QList<Company_Phone> tmpList;
        QSqlQuery qry = db.exec("select owner_code, phone from sp_owner_phone where phone<>''");
        while (qry.next()) {
            tmpList.append(Company_Phone(qry.value(0).toString(),qry.value(1).toString()));
        }
        db.close();
        companyphoneList.clear();
        if(tmpList.length()>0)
            companyphoneList.append(tmpList);
        synchour = QTime::currentTime().hour();
    }
}

void CoreObject::chartlog(quint16 idx, QDateTime t, QString data, bool dirflag){
    if(dirflag)
        printf("[ %04d-%02d-%02d %02d:%02d:%02d >>> ] %s\n",
               t.date().year(),t.date().month(),t.date().day(),
               t.time().hour(),t.time().minute(),t.time().second(),
               data.toUtf8().data());
    else
        printf("[ %04d-%02d-%02d %02d:%02d:%02d <<< ] %s\n",
               t.date().year(),t.date().month(),t.date().day(),
               t.time().hour(),t.time().minute(),t.time().second(),
               data.toUtf8().data());
}

bool CoreObject::shm_load()
{
    int shmid;
    key_t key;
    if((key = ftok(SHM_PATH,(int)SHM_PORT))==-1)
        return false;
    if((shmid = shmget(key,sizeof(MyEHomeShm),IPC_CREAT|0666))==-1)
        return false;
    ytShm = (MyEHomeShm *)shmat(shmid,NULL,0);
    return true;
}

QString getNewId()
{
    return QUuid::createUuid().toString().replace("{","").replace("}","");
}

BOOL RegisterCallBack(LONG lUserID, DWORD dwDataType, void *pOutBuffer, DWORD dwOutLen, void *pInBuffer, DWORD dwInLen, void *pUser)
{
    int i,idx=0;
    bool found = false;

    had_reg = true;
    QDateTime zeroTime = QDateTime::fromTime_t(0);
    if (ENUM_DEV_ON == dwDataType)
    {
        NET_EHOME_DEV_REG_INFO *pDevInfo = (NET_EHOME_DEV_REG_INFO *)pOutBuffer;
//        qDebug()<<"RegisterCallBack: "<<(char*)(pDevInfo->byDeviceID);
        if(pDevInfo!=NULL)
        {
            for(i=0;i<DEVICES_COUNT;i++){
                if(strcmp(ytShm->eHomeDevice[i].deviceID,QString((char*)(pDevInfo->byDeviceID)).replace(" ","_").toUtf8().data())==0){
                    found = true;
                    memcpy(ytShm->eHomeDevice[i].devIp,(char *)(pDevInfo->struDevAdd.szIP),sizeof(ytShm->eHomeDevice[i].devIp));
                    ytShm->eHomeDevice[i].LoginId = lUserID;
                    ytShm->eHomeDevice[i].Connected = 0x00;
                    ytShm->eHomeDevice[i].Inited = 0x01;
                    ytShm->eHomeDevice[i].onLined = 0x00;
                    ytShm->eHomeDevice[i].savetmp = 0x00;
                    if(ytShm->eHomeDevice[i].transed==0x01)
                        fclose(ytShm->eHomeDevice[i].tmpfile);
                    ytShm->eHomeDevice[i].tmpfile = NULL;
                    ytShm->eHomeDevice[i].transed = 0x00;
                    ytShm->eHomeDevice[i].io[15]=0x00;
                    ytShm->eHomeDevice[i].io[14]=0x03;
                    setFullTime(&(ytShm->eHomeDevice[i].onLinetime),zeroTime);
                    setFullTime(&(ytShm->eHomeDevice[i].transtime),zeroTime);
                    idx=i;
                    break;
                }
            }
            if(!found){
//                return FALSE;
                for(int i=0;i<DEVICES_COUNT;i++){
                    if(QString(ytShm->eHomeDevice[i].deviceID).trimmed().length()==0){
                        ytShm->eHomeDevice[i].io[8]=0x00;
                        ytShm->eHomeDevice[i].LoginId = lUserID;
                        sprintf(ytShm->eHomeDevice[i].deviceID,"%s",QString((char *)(pDevInfo->byDeviceID)).replace(" ","_").toUtf8().data());
                        ytShm->eHomeDevice[i].Connected = 0x00;
                        ytShm->eHomeDevice[i].onLined = 0x00;
                        setFullTime(&(ytShm->eHomeDevice[i].onLinetime),zeroTime);
                        setFullTime(&(ytShm->eHomeDevice[i].transtime),zeroTime);
                        ytShm->eHomeDevice[i].Inited = 0x01;
                        ytShm->eHomeDevice[i].savetmp = 0x00;
                        if(ytShm->eHomeDevice[i].transed==0x01)
                            fclose(ytShm->eHomeDevice[i].tmpfile);
                        ytShm->eHomeDevice[i].tmpfile = NULL;
                        ytShm->eHomeDevice[i].transed = 0x00;
                        ytShm->eHomeDevice[i].io[15]=0x00;
                        ytShm->eHomeDevice[i].io[14]=0x03;
                        idx = i;
                        break;
                    }
                }
            }

            //输入参数
            NET_EHOME_SERVER_INFO *pServerInfo = (NET_EHOME_SERVER_INFO *)pInBuffer;
            pServerInfo->dwTimeOutCount = 6; //心跳超时次数
            pServerInfo->dwKeepAliveSec = 15; //心跳间隔
            memcpy(pServerInfo->struUDPAlarmSever.szIP, oServerIP, sizeof(oServerIP));
            memcpy(pServerInfo->struTCPAlarmSever.szIP, oServerIP, sizeof(oServerIP)); //报警服务器IP地址（TCP协议）
            pServerInfo->struUDPAlarmSever.wPort = 7669; //报警服务器端口（UDP协议），需要和报警服务器启动监听的端口一致
            pServerInfo->struTCPAlarmSever.wPort = 7668;
            pServerInfo->dwAlarmServerType = 1;  //报警服务器类型：0- 只支持UDP协议上报，1- 支持UDP、TCP两种协议上报
        }
    }else if (ENUM_DEV_OFF == dwDataType){
        for(int i=0;i<DEVICES_COUNT;i++){
            if(ytShm->eHomeDevice[i].LoginId==lUserID){
                ytShm->eHomeDevice[i].io[15]=0x00;
                ytShm->eHomeDevice[i].io[14]=0x02;
                ytShm->eHomeDevice[i].LoginId = -1;
//                printf("%s link off\n",ytShm->eHomeDevice[i].deviceID);
                if(ytShm->eHomeDevice[i].SessionId>=0){
                    if(NET_ECMS_StopGetRealStream(lUserID,ytShm->eHomeDevice[i].SessionId)){
                        ytShm->eHomeDevice[i].SessionId = -1;
                        if(ytShm->eHomeDevice[i].previewId>=0){
                            if(NET_ESTREAM_StopPreview(ytShm->eHomeDevice[i].previewId)){
                                ytShm->eHomeDevice[i].previewId = -1;
                                QString tmpfile = QString(ytShm->eHomeDevice[i].filename);
                                QFile(tmpfile).remove();
                                ytShm->eHomeDevice[i].Connected = 0x00;
//                                        bzero(ytShm->eHomeDevice[i].deviceID,sizeof(ytShm->eHomeDevice[i].deviceID));
                                ytShm->eHomeDevice[i].Inited = 0x00;
                                ytShm->eHomeDevice[i].onLined = 0x00;
                                setFullTime(&(ytShm->eHomeDevice[i].onLinetime),zeroTime);
                                setFullTime(&(ytShm->eHomeDevice[i].transtime),zeroTime);

                                ytShm->eHomeDevice[i].savetmp = 0x00;
                                if(ytShm->eHomeDevice[i].transed==0x01)
                                    fclose(ytShm->eHomeDevice[i].tmpfile);
                                ytShm->eHomeDevice[i].tmpfile = NULL;
                                ytShm->eHomeDevice[i].transed = 0x00;
                                if(ytShm->eHomeDevice[i].lLinkHandle>0){
                                    if(NET_ESTREAM_StopListenPreview(ytShm->eHomeDevice[i].lLinkHandle)){
                                        ytShm->eHomeDevice[i].lLinkHandle = -1;
                                    }
                                }
                            }
                        }
                    }
                }else{
                    QString tmpfile = QString(ytShm->eHomeDevice[i].filename);
                    QFile(tmpfile).remove();
                    ytShm->eHomeDevice[i].io[15]=0x00;
                    ytShm->eHomeDevice[i].Connected = 0x00;
//                    bzero(ytShm->eHomeDevice[i].deviceID,sizeof(ytShm->eHomeDevice[i].deviceID));
                    ytShm->eHomeDevice[i].Inited = 0x00;
                    ytShm->eHomeDevice[i].onLined = 0x00;
                    ytShm->eHomeDevice[i].LoginId = -1;
                    setFullTime(&(ytShm->eHomeDevice[i].onLinetime),zeroTime);
                    setFullTime(&(ytShm->eHomeDevice[i].transtime),zeroTime);
                    ytShm->eHomeDevice[i].lLinkHandle = -1;
                    ytShm->eHomeDevice[i].savetmp = 0x00;
                    if(ytShm->eHomeDevice[i].transed==0x01)
                        fclose(ytShm->eHomeDevice[i].tmpfile);
                    ytShm->eHomeDevice[i].tmpfile = NULL;
                    ytShm->eHomeDevice[i].transed = 0x00;
                }
                break;
            }
        }
        NET_ECMS_ForceLogout(lUserID);
    }
    return TRUE;
}


BOOL CALLBACK fnPREVIEW_NEWLINK_CB(LONG lPreviewHandle, NET_EHOME_NEWLINK_CB_MSG *pNewLinkCBMsg, void *pUserData)
{
    for(int i=0;i<DEVICES_COUNT;i++){
        if((ytShm->eHomeDevice[i].LoginId>-1)&&(ytShm->eHomeDevice[i].listen_preview_handle>-1)){
            if(ytShm->eHomeDevice[i].SessionId == pNewLinkCBMsg->iSessionID){
//                printf("fnPREVIEW_NEWLINK_CB:%s\n",ytShm->eHomeDevice[i].deviceID);
                ytShm->eHomeDevice[i].lLinkHandle = lPreviewHandle;
                NET_EHOME_PREVIEW_DATA_CB_PARAM struDataCB = {0};
                struDataCB.pUserData = &(ytShm->eHomeDevice[i]);
                struDataCB.fnPreviewDataCB = fnPREVIEW_DATA_CB;
                struDataCB.byStreamFormat = 0;//封装格式：0- PS
                if (!NET_ESTREAM_SetPreviewDataCB(lPreviewHandle, &struDataCB))
                {
                    ytShm->eHomeDevice[i].SessionId = -1;
                    ytShm->eHomeDevice[i].Connected = 0x00;;
//                    printf("NET_ESTREAM_SetPreviewDataCB set failed(%s)\n",ytShm->eHomeDevice[i].deviceID);
                    return false;
                }
//                printf("NET_ESTREAM_SetPreviewDataCB set pass(%s)\n",ytShm->eHomeDevice[i].deviceID);
                return true;
            }
        }
    }
    return false;
}

void CALLBACK fnPREVIEW_DATA_CB(LONG lPreviewHandle, NET_EHOME_PREVIEW_CB_MSG *pPreviewCBMsg, void *pUserData)
{
    if (NULL == pPreviewCBMsg)
    {
        return ;
    }
    EHomeDevice *dev= (EHomeDevice *)pUserData;
    dev->Connected = 0x01;
    dev->previewId = lPreviewHandle;
    InputStreamData(QString(dev->deviceID).replace(" ","_"), pPreviewCBMsg->byDataType, (char*)pPreviewCBMsg->pRecvdata, pPreviewCBMsg->dwDataLen);
}

void ProcessHttpAlarmInfo(void *pXml, unsigned long dwLen, void *pUrl, unsigned long dwUrllen,CoreObject *obj){
    if((pXml==NULL)&&(pUrl==NULL))
        return;
    UN_REFERENCED_PARAMETER(dwLen);
    UN_REFERENCED_PARAMETER(pUrl);
    UN_REFERENCED_PARAMETER(dwUrllen);
    char deviceID[32] = {0};
    char eventTime[20] = {0};
    char eventType[128] = {0};
    char eventState[20] = {0};
    char pic[2][256]={0};
    LPNET_EHOME_ALARM_ISAPI_INFO pISAPIAlarm = (NET_EHOME_ALARM_ISAPI_INFO *)(pXml);
    NET_EHOME_ALARM_ISAPI_INFO struISAPIAlarm = {0};
    memcpy(&struISAPIAlarm,pISAPIAlarm, sizeof(NET_EHOME_ALARM_ISAPI_INFO));
    if(struISAPIAlarm.pAlarmData)
    {
         if(struISAPIAlarm.byDataType==2){
        }else if(struISAPIAlarm.byDataType==1){
            QByteArray data = QByteArray((const   char *)(struISAPIAlarm.pAlarmData));
            int cur = data.indexOf("--boundary");
            if(cur>0){
                QXmlStreamReader reader;
                reader.addData(data.mid(0,cur));
                while(!reader.atEnd()){
                    if(reader.isStartElement()){
                        if(reader.name()=="eventType"){
                            sprintf(eventType,"%s",reader.readElementText().toUtf8().data());
                        }else if(reader.name()=="deviceID"){
                            sprintf(deviceID,"%s",reader.readElementText().toUtf8().data());
                        }else if(reader.name()=="dateTime"){
                            sprintf(eventTime,"%s",reader.readElementText().replace("T"," ").mid(0,19).toUtf8().data());
                        }else if(reader.name()=="eventState"){
                            sprintf(eventState,"%s",reader.readElementText().toUtf8().data());
                        }
                    }
                    reader.readNext();
                }
            }
        }
        if(struISAPIAlarm.byPicturesNumber>0){
            time_t t = QDateTime::currentDateTime().toTime_t();
            for(int i=0;i<struISAPIAlarm.byPicturesNumber;i++){
                char fname[128];
                sprintf(fname,"/usr/local/nginx/html/VideoAlarmPics/pic_%d_%s_%d.jpg",t,deviceID,i);
                if(i<2)
                    sprintf(pic[i],"http://47.103.74.123/VideoAlarmPics/pic_%d_%s_%d.jpg",t,deviceID,i);
                FILE *f = fopen(fname,"w");
                fwrite(((NET_EHOME_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].pPicData,1,((NET_EHOME_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].dwPicLen,f);
                fclose(f);
            }
        }
        obj->reportList.append(Alarm_Report(deviceID,eventTime,QString::fromUtf8("200001"),
                                            QString::fromUtf8("insert into sp_video2017 (id,port,device_code,time,status,address,ncmd,data1,data2,data3,data4,data5,clsj,clr,clnr,clwb,cllxr,cldh,clzt,cllx,video) values (NULL,'%1','%2','%3','%4','','%5','%6','%7','%8','火点/高温检测告警','','1970-01-01 08:00:00','','','','','',0,'','')")
                            .arg(2).arg(deviceID).arg(eventTime).arg(1)
                            .arg(2).arg(eventState).arg(pic[0]).arg(pic[1])));
    }
}

BOOL CALLBACK AlarmMSGCallBack(LONG lHandle, NET_EHOME_ALARM_MSG *pAlarmMsg, void *pUserData)
{
//    LONG lListenHandle = -1;
//    lListenHandle = lHandle;
    int i;
    CoreObject *obj = (CoreObject *)pUserData;
    DWORD dwType = pAlarmMsg->dwAlarmType;  //不同的报警类型(dwAlarmType)，pAlarmInfo对应不同的报警信息类型

    if(pAlarmMsg->pHttpUrl!=NULL)
        dwType = EHOME_ISAPI_ALARM;
//    printf("Callback of alarm listening, dwAlarmType[%d]\n", dwType);

    switch(dwType)
    {
    case EHOME_ALARM_UNKNOWN://未知报警信息
//        printf("Unknown Alarm Type!\n");
        break;
    case EHOME_ALARM://基本报警信息：移动侦测、视频遮盖、视频丢失、PIR报警、人脸侦测、区域入侵等
    {
        NET_EHOME_ALARM_INFO struAlarmInfo;
        memcpy(&struAlarmInfo, pAlarmMsg->pAlarmInfo, sizeof(NET_EHOME_ALARM_INFO));
        printf("Basic Alarm: Device ID[%s], szAlarmTime[%s], Alarm Type[%d], Action[%d], VideoChannel[%d]!\n", struAlarmInfo.szDeviceID, \
            struAlarmInfo.szAlarmTime, struAlarmInfo.dwAlarmType, struAlarmInfo.dwAlarmAction, struAlarmInfo.dwVideoChannel);
        if((struAlarmInfo.dwAlarmType==ALARM_TYPE_INTRUSION)||(struAlarmInfo.dwAlarmType==ALARM_TYPE_LEFT)||(struAlarmInfo.dwAlarmType==ALARM_TYPE_TAKE))
        {
            QString devId = QString(struAlarmInfo.szDeviceID);
            for(i=0;i>obj->alarmList.length();i++){
                if(obj->alarmList.at(i).Device_Code.compare(devId)==0){
                    if((struAlarmInfo.dwAlarmType==ALARM_TYPE_INTRUSION)&&(struAlarmInfo.dwAlarmAction!=0))
                        obj->alarmList.removeAt(i);
                    else if(struAlarmInfo.dwAlarmType==ALARM_TYPE_TAKE)
                        obj->alarmList.removeAt(i);
                    return TRUE;
                }
            }
            QString time1 = QString(struAlarmInfo.szAlarmTime);
            QString time2 = time1.mid(0,10)+" "+time1.mid(11,8);
//            QString sql = QString::fromUtf8("insert into sp_video2017 (id,port,device_code,time,status,address,ncmd,data1,data2,data3,data4,data5,clsj,clr,clnr,clwb,cllxr,cldh,clzt,cllx,video) values (NULL,'%1','%2','%3','%4','','%5','%6','','','占道检测告警','','1970-01-01 08:00:00','','','','','',0,'','')")
//                .arg(1).arg(struAlarmInfo.szDeviceID).arg(time2).arg(struAlarmInfo.dwAlarmAction==0?1:0)
//                .arg(struAlarmInfo.dwAlarmType).arg(struAlarmInfo.dwAlarmAction);
//            obj->sqlList.append(sql);
            if(struAlarmInfo.dwAlarmType==ALARM_TYPE_INTRUSION)
                obj->alarmList.append(AlarmEvent(devId,time2,(struAlarmInfo.dwAlarmAction==0?1:0)));
            else
                obj->alarmList.append(AlarmEvent(devId,time2,1));
            for(i=0;i<DEVICES_COUNT;i++){
                if(strcmp(ytShm->eHomeDevice[i].deviceID,(char*)(struAlarmInfo.szDeviceID))==0){
                    ytShm->eHomeDevice[i].io[6]=0x01;
                }
            }
        }
    }
        break;
//    case EHOME_ALARM_HEATMAP_REPORT://热度图报告上传
//        NET_EHOME_HEATMAP_REPORT struHeatmapInfo;
//        memcpy(&struHeatmapInfo, pAlarmMsg->pAlarmInfo, sizeof(NET_EHOME_HEATMAP_REPORT));
//        printf("Heatmap report: Device ID[%s], StartTime[%s], StopTime[%s], dwVideoChannel[%d]!\n", struHeatmapInfo.byDeviceID, \
//            struHeatmapInfo.byStartTime, struHeatmapInfo.byStopTime, struHeatmapInfo.dwVideoChannel);
//        break;
//    case EHOME_ALARM_FACESNAP_REPORT://人脸抓拍报告上传
//        NET_EHOME_FACESNAP_REPORT struFaceSnap;
//        memcpy(&struFaceSnap, pAlarmMsg->pAlarmInfo, sizeof(NET_EHOME_FACESNAP_REPORT));
//        printf("Face snap: Device ID[%s], AlarmTime[%s], dwFaceScore[%d], dwVideoChannel[%d]!\n", struFaceSnap.byDeviceID, \
//            struFaceSnap.byAlarmTime, struFaceSnap.dwFaceScore, struFaceSnap.dwVideoChannel);
//        break;
//    case EHOME_ALARM_GPS://GPS信息上传
//        NET_EHOME_GPS_INFO struGpsInfo;
//        memcpy(&struGpsInfo, pAlarmMsg->pAlarmInfo, sizeof(NET_EHOME_GPS_INFO));
//        printf("GPS info: Device ID[%s], SampleTime[%s], Longitude[%d], Latitude[%d]!\n", struGpsInfo.byDeviceID, \
//            struGpsInfo.bySampleTime, struGpsInfo.dwLongitude, struGpsInfo.dwLatitude );
//        break;
//    case EHOME_ALARM_CID_REPORT://报警主机CID报警信息
//        NET_EHOME_CID_INFO struCIDInfo;
//        memcpy(&struCIDInfo, pAlarmMsg->pAlarmInfo, sizeof(NET_EHOME_CID_INFO));
//        printf("CID info: Device ID[%s], AlarmTime[%s], CID Code[%d], CID Type[%d], CID Describe[%s]!\n", struCIDInfo.byDeviceID, \
//        struCIDInfo.byTriggerTime, struCIDInfo.dwCIDCode, struCIDInfo.dwCIDType, struCIDInfo.byCIDDescribe );
//        break;
    case EHOME_ISAPI_ALARM:
        ProcessHttpAlarmInfo(pAlarmMsg->pAlarmInfo,pAlarmMsg->dwAlarmInfoLen,pAlarmMsg->pHttpUrl,pAlarmMsg->dwHttpUrlLen,obj);
        break;
    default:
        break;
    }

    return TRUE;
}

BOOL InputStreamData(QString deviceid, BYTE byDataType, char* pBuffer, int iDataLen)
{
    int i;
    uint t = QDateTime::currentDateTime().toTime_t();
    for(i=0;i<DEVICES_COUNT;i++){
        if(QString(ytShm->eHomeDevice[i].deviceID).compare(deviceid)==0){
            if(ytShm->eHomeDevice[i].io[0]==0x01){
                ytShm->eHomeDevice[i].time[0] = t;
                if(ytShm->eHomeDevice[i].savetmp==0x00){
                    QString tmpfile = QString("/tmp/%1.mp4").arg(ytShm->eHomeDevice[i].deviceID).replace(" ","_");
                    sprintf(ytShm->eHomeDevice[i].filename,"%s",tmpfile.toUtf8().data());
                    setFullTime(&(ytShm->eHomeDevice[i].onLinetime),QDateTime::currentDateTime());
                    ytShm->eHomeDevice[i].savetmp = 0x01;
                    ytShm->eHomeDevice[i].tmpfile  = fopen(tmpfile.toUtf8().data(),"wb");
                    fwrite(pBuffer,iDataLen,1,ytShm->eHomeDevice[i].tmpfile);
                }else{
                    if(ytShm->eHomeDevice[i].tmpfile!=NULL){
                        fwrite(pBuffer,iDataLen,1,ytShm->eHomeDevice[i].tmpfile);
                    }
                }
            }else{
                NET_ECMS_StopGetRealStream(ytShm->eHomeDevice[i].LoginId,ytShm->eHomeDevice[i].SessionId);
            }
            return true;
        }
    }
    return false;
}

void setFullTime(FullTime *fTime, QDateTime qTime){
    fTime->YEAR = qTime.date().year()&0xffff;
    fTime->MONTH = qTime.date().month()&0xff;
    fTime->DAY = qTime.date().day()&0xff;
    fTime->HOUR = qTime.time().hour()&0xff;
    fTime->MINUTE = qTime.time().minute()&0xff;
    fTime->SECOND = qTime.time().second()&0xff;
    fTime->TIMESTAMP = qTime.toTime_t();
}

QDateTime getFullTime(FullTime fTime){
    if((fTime.YEAR==0)||(fTime.MONTH==0)||(fTime.DAY==0))
        return QDateTime::fromTime_t(fTime.TIMESTAMP);
    else
        return QDateTime(QDate((int)fTime.YEAR,(int)fTime.MONTH,(int)fTime.DAY),QTime((int)fTime.HOUR,(int)fTime.MINUTE,(int)fTime.SECOND));
}

void CoreObject::start()
{
    //预览监听参数
    NET_EHOME_LOCAL_GENERAL_CFG struGeneralCfg = {0};
    struGeneralCfg.byAlarmPictureSeparate = 1;
    if(!NET_EALARM_SetSDKLocalCfg(LOCAL_CFG_TYPE_GENERAL,&struGeneralCfg)){
//        printf("NET_EALARM_SetSDKLocalCfg falied\n");
        NET_ECMS_Fini();
        return;
    }
//    printf("NET_EALARM_SetSDKLocalCfg pass!\n");
    //报警监听参数
    NET_EHOME_ALARM_LISTEN_PARAM struTcpAlarmListenParam = {0};
    memcpy(struTcpAlarmListenParam.struAddress.szIP, iServerIP, sizeof(iServerIP));
    struTcpAlarmListenParam.byProtocolType = 0;
    struTcpAlarmListenParam.struAddress.wPort = 7668;
    struTcpAlarmListenParam.fnMsgCb = AlarmMSGCallBack;
    struTcpAlarmListenParam.pUserData = this;
    struTcpAlarmListenParam.byUseCmsPort = 0;
    struTcpAlarmListenParam.byUseThreadPool = 0;
    if(NET_EALARM_StartListen(&struTcpAlarmListenParam)<-1){
//        printf("NET_EALARM_StartListen TCP failed, error code: %d\n", NET_EALARM_GetLastError());
        NET_ECMS_Fini();
        NET_ESTREAM_Fini();
        NET_EALARM_Fini();
        exit(1);
    }
//    printf("NET_EALARM_StartListen TCP!\n");

    //报警监听参数
    NET_EHOME_ALARM_LISTEN_PARAM struListen = {0};
    memcpy(struListen.struAddress.szIP, iServerIP, sizeof(iServerIP));
    struListen.struAddress.wPort = 7669; //报警服务器监听端口
    struListen.fnMsgCb = AlarmMSGCallBack; //报警回调函数
    struListen.pUserData = this;
    struListen.byUseCmsPort = 0;
    struListen.byUseThreadPool = 0;
    struListen.byProtocolType = 1; //0- TCP方式(保留，暂不支持)，1- UDP方式

    //启动报警监听
    LONG lHandle = NET_EALARM_StartListen(&struListen);
    if(lHandle< -1)
    {
//        printf("NET_EALARM_StartListen failed, error code: %d\n", NET_EALARM_GetLastError());
        NET_ECMS_Fini();
        NET_ESTREAM_Fini();
        NET_EALARM_Fini();
        exit(1);
    }
//    printf("NET_EALARM_StartListen!\n");
    for(int i=0;i<DEVICES_COUNT;i++){
        ytShm->eHomeDevice[i].previewport = 58000+i;
        ytShm->eHomeDevice[i].listen_alarm_handle = lHandle;
        NET_EHOME_LISTEN_PREVIEW_CFG struListen = {0};
        memcpy(struListen.struIPAdress.szIP,iServerIP, sizeof(iServerIP));
        struListen.struIPAdress.wPort = ytShm->eHomeDevice[i].previewport; //流媒体服务器监听端口
        struListen.fnNewLinkCB = fnPREVIEW_NEWLINK_CB; //预览连接请求回调函数
        struListen.pUser =&(ytShm->eHomeDevice[i]);
        struListen.byLinkMode = 0; //0- TCP方式，1- UDP方式
        lHandle = NET_ESTREAM_StartListenPreview(&struListen);
        if(lHandle<-1){
        }else{
            ytShm->eHomeDevice[i].listen_preview_handle = lHandle;
        }
    }
    NET_EHOME_CMS_LISTEN_PARAM struCMSListenPara = {0};
    memcpy(struCMSListenPara.struAddress.szIP, "0.0.0.0", sizeof("0.0.0.0"));
    struCMSListenPara.struAddress.wPort = 7660;
    struCMSListenPara.fnCB = RegisterCallBack;
    LONG lListen = NET_ECMS_StartListen(&struCMSListenPara);
    if(lListen < -1)
    {
        NET_ECMS_Fini();
        NET_ESTREAM_Fini();
        NET_EALARM_Fini();
        exit(1);
    }
    timer->start(3000);
//    qDebug()<<"start core";
}

void CoreObject::process_stop()
{
    QProcess *p = (QProcess *)sender();
    for(int i=0;i<DEVICES_COUNT;i++){
        if(p==processList.at(i)){
            if(ytShm->eHomeDevice[i].Connected==0x01){
                ytShm->eHomeDevice[i].io[0]=0x00;
            }
            break;
        }
    }
}

void CoreObject::AlarmReport(QString addr, QString type, QString time, QString companyCode, quint64 insertid)
{
//    if(type.toInt()==200104)
//        type="占道侦测报警";
//    else if(type.toInt()==200001)
//        type="火点侦测报警";
//    QString rep2 = QString("{\"SubType\":16,\"DeviceId\":\"%1\",\"InsertId\":%2,\"Confirmed\":0,\"CompanyCode\":\"%3\",\"evt_name\":\"%4\",\"evt\":0,\"alarm_time\":\"%5\"}")
//            .arg(addr).arg(insertid).arg(companyCode).arg(type).arg(time);
//    printf("%s\n",rep2.toUtf8().data());
//    repcur++;
//    repcur &= 0x07;
//    wssThread[repcur]->appendData(rep2);
}

QString CoreObject::getCompanyCode(QString addr){
    for(int i=0;i<DEVICES_COUNT;i++){
        QString devid = QString(ytShm->eHomeDevice[i].deviceID);
        if(QString::compare(addr,devid)==0){
            return QString(ytShm->eHomeDevice[i].rtsppath);
        }
    }
    return "";
}

void CoreObject::time_out()
{
    QDateTime t = QDateTime::currentDateTime();
    ytShm->workingTime[0] = t.toTime_t();
    if(!had_reg){
        if((ytShm->workingTime[0]-start_time)>30)
            exit(1);
    }
    if(isWorking)
        return;
    isWorking = true;
    if(synchour!=t.time().hour())
        chkPhoneList();
    for(int i=0;i<DEVICES_COUNT;i++){
        if(ytShm->eHomeDevice[i].Inited==0x01){
            if(ytShm->eHomeDevice[i].Connected==0x00){
                if(ytShm->eHomeDevice[i].io[8]==0x01)
                    ytShm->eHomeDevice[i].io[0] = 0x01;
                else if(ytShm->eHomeDevice[i].io[7]==0x01){
                    if((ytShm->eHomeDevice[i].time[1]>0)&&((t.toTime_t()-ytShm->eHomeDevice[i].time[1])>300)){
//                        printf("%s time over close\n",ytShm->eHomeDevice[i].deviceID);
                        ytShm->eHomeDevice[i].io[0] = 0x00;
                        ytShm->eHomeDevice[i].io[7] = 0x00;
                        ytShm->eHomeDevice[i].time[1]=0;
                    }else if(ytShm->eHomeDevice[i].io[0]==0x00){
//                        printf("%s io7 on\n",ytShm->eHomeDevice[i].deviceID);
//                        ytShm->eHomeDevice[i].io[7] = 0x00;
                        ytShm->eHomeDevice[i].io[0] = 0x01;
                    }else if(ytShm->eHomeDevice[i].io[0]==0x01){
                        if(ytShm->eHomeDevice[i].io[15]>2){
//                            printf("%s NET_ECMS_StopGetRealStream\n",ytShm->eHomeDevice[i].deviceID);
                            if(NET_ECMS_StopGetRealStream(ytShm->eHomeDevice[i].LoginId,ytShm->eHomeDevice[i].SessionId)){
//                                ytShm->eHomeDevice[i].io[0] = 0x00;
//                                ytShm->eHomeDevice[i].io[7] = 0x00;
                            }
                            ytShm->eHomeDevice[i].time[1]=0;
                            ytShm->eHomeDevice[i].SessionId=-1;
                        }
                    }
                }else if(ytShm->eHomeDevice[i].io[6]==0x01){
//                    printf("%s io6 on\n",ytShm->eHomeDevice[i].deviceID);
                    ytShm->eHomeDevice[i].io[0] = 0x01;
                }
                if(ytShm->eHomeDevice[i].io[0]==0x01){
                    if(ytShm->eHomeDevice[i].SessionId>-1){
                        NET_EHOME_PUSHSTREAM_IN struPushStreamIn = {0};
                        struPushStreamIn.dwSize = sizeof(struPushStreamIn);
                        struPushStreamIn.lSessionID = ytShm->eHomeDevice[i].SessionId; //SessionID，预览请求会话ID
                        //预览请求推流输出参数
                        NET_EHOME_PUSHSTREAM_OUT struPushStreamOut = {0};
                        if(!NET_ECMS_StartPushRealStream(ytShm->eHomeDevice[i].LoginId, &struPushStreamIn, &struPushStreamOut)){
//                            printf("%s NET_ECMS_StartGetRealStreamV11 failed.\n",ytShm->eHomeDevice[i].deviceID);
                            ytShm->eHomeDevice[i].io[15]++;
                        }else{
//                            printf("%s start push real stream\n",ytShm->eHomeDevice[i].deviceID);
                            ytShm->eHomeDevice[i].io[15]=0x00;
                        }
                    }
                    else
                    {
                        ytShm->eHomeDevice[i].previewport = 58000+i;
//                        printf("actice %s at %d(loginId:%d)\n",ytShm->eHomeDevice[i].deviceID,ytShm->eHomeDevice[i].previewport,ytShm->eHomeDevice[i].LoginId);
                        NET_EHOME_PREVIEWINFO_IN_V11 struPreviewIn = {0};
                        struPreviewIn.iChannel = 1; //通道号
                        struPreviewIn.dwLinkMode = 0; //0- TCP方式，1- UDP方式
                        struPreviewIn.dwStreamType = 1; //码流类型：0- 主码流，1- 子码流, 2- 第三码流
                        memcpy(struPreviewIn.struStreamSever.szIP, oServerIP, sizeof(oServerIP));//流媒体服务器IP地址
                        struPreviewIn.struStreamSever.wPort = ytShm->eHomeDevice[i].previewport;
                        //预览请求输出参数
                        NET_EHOME_PREVIEWINFO_OUT struPreviewOut = {0};
                        if(!NET_ECMS_StartGetRealStreamV11(ytShm->eHomeDevice[i].LoginId, &struPreviewIn, &struPreviewOut)){
//                            printf("%s NET_ECMS_StartGetRealStreamV11 failed.\n",ytShm->eHomeDevice[i].deviceID);
                        }else{
//                            printf("active %s lSessionID:%d\n",ytShm->eHomeDevice[i].deviceID,struPreviewOut.lSessionID);
                            ytShm->eHomeDevice[i].SessionId = struPreviewOut.lSessionID;
                            NET_EHOME_PUSHSTREAM_IN struPushStreamIn = {0};
                            struPushStreamIn.dwSize = sizeof(struPushStreamIn);
                            struPushStreamIn.lSessionID = struPreviewOut.lSessionID; //SessionID，预览请求会话ID
                            //预览请求推流输出参数
                            NET_EHOME_PUSHSTREAM_OUT struPushStreamOut = {0};
                            if(!NET_ECMS_StartPushRealStream(ytShm->eHomeDevice[i].LoginId, &struPushStreamIn, &struPushStreamOut)){
//                                printf("%s NET_ECMS_StartGetRealStreamV11 failed.\n",ytShm->eHomeDevice[i].deviceID);
                                ytShm->eHomeDevice[i].io[15]++;
                            }else{
//                                printf("%s start push real stream\n",ytShm->eHomeDevice[i].deviceID);
                                ytShm->eHomeDevice[i].io[15]=0x00;
                            }
                        }
                    }
                }
            }else if((ytShm->eHomeDevice[i].time[1]>0)&&((t.toTime_t()-ytShm->eHomeDevice[i].time[1])>300)){
                if((ytShm->eHomeDevice[i].io[7]==0x01)||(ytShm->eHomeDevice[i].io[8]==0x01)){
                    if(NET_ECMS_StopGetRealStream(ytShm->eHomeDevice[i].LoginId,ytShm->eHomeDevice[i].SessionId)){
                        ytShm->eHomeDevice[i].io[0] = 0x00;
                        ytShm->eHomeDevice[i].io[7] = 0x00;
                        ytShm->eHomeDevice[i].time[1]=0;
                        ytShm->eHomeDevice[i].SessionId =-1;
                    }
                }
            }else if((ytShm->eHomeDevice[i].Connected==0x01)&&(ytShm->eHomeDevice[i].io[0]==0x00)){
                if(NET_ECMS_StopGetRealStream(ytShm->eHomeDevice[i].LoginId,ytShm->eHomeDevice[i].SessionId)){
                    ytShm->eHomeDevice[i].Connected=0x00;
                    ytShm->eHomeDevice[i].SessionId=-1;
                    ytShm->eHomeDevice[i].time[0]=0;
                    ytShm->eHomeDevice[i].time[1]=0;
                    if(processList.at(i)->pid()>0){
                        processList.at(i)->close();
                    }
//                    qDebug()<<QString("%1 will  close.(%2)").arg(ytShm->eHomeDevice[i].deviceID).arg(i).toUtf8().data();
                    QString tmpfile = QString(ytShm->eHomeDevice[i].filename).replace(" ","_");
                    if(ytShm->eHomeDevice[i].tmpfile!=NULL)
                        fclose(ytShm->eHomeDevice[i].tmpfile);
                    ytShm->eHomeDevice[i].savetmp = 0x00;
                    ytShm->eHomeDevice[i].tmpfile = NULL;
                    QFile(tmpfile).remove();
                    if(ytShm->eHomeDevice[i].io[8]==0x01){
                        tmpfile = QString("/tmp/%1.mp4").arg(ytShm->eHomeDevice[i].deviceID);
                        sprintf(ytShm->eHomeDevice[i].filename,"%s",tmpfile.toUtf8().data());
                        ytShm->eHomeDevice[i].tmpfile  = fopen(tmpfile.toUtf8().data(),"wb");
                        setFullTime(&(ytShm->eHomeDevice[i].onLinetime),t);
                        sprintf(ytShm->eHomeDevice[i].filename,"");
                    }
                    ytShm->eHomeDevice[i].transed = 0x00;
                }
            }else if((ytShm->eHomeDevice[i].savetmp==0x01)&&(ytShm->eHomeDevice[i].transed==0x00)&&(ytShm->eHomeDevice[i].onLinetime.TIMESTAMP>0)&&((t.toTime_t()-ytShm->eHomeDevice[i].onLinetime.TIMESTAMP)>3)){
                if(ytShm->eHomeDevice[i].io[6]==0x01){
                    ytShm->eHomeDevice[i].io[6]=0x00;
                    ytShm->eHomeDevice[i].io[0]=0x00;
                    for(int j=0;j<alarmList.length();j++){
                        if(alarmList.at(j).Device_Code.compare(QString(ytShm->eHomeDevice[i].deviceID))==0){
                            QString tmpfile = QString(ytShm->eHomeDevice[i].filename).replace(" ","_");
                            QString pic1name = QString("http://47.103.74.123/VideoAlarmPics/pic_%1_%2_0.jpg").arg(QDateTime::fromString(alarmList.at(j).Event_Time,"yyyy-MM-dd HH:mm:ss").toTime_t()).arg(QString(alarmList.at(j).Device_Code).replace(" ","_"));
                            QString picname = QString("/usr/local/nginx/html/VideoAlarmPics/pic_%1_%2_0.jpg").arg(QDateTime::fromString(alarmList.at(j).Event_Time,"yyyy-MM-dd HH:mm:ss").toTime_t()).arg(QString(alarmList.at(j).Device_Code).replace(" ","_"));
                            QString cmd1 = QString("ffmpeg -ss 00:00:00 -i \"%1\" -f image2 -y \"%2\"").arg(tmpfile).arg(picname);
                            if(ytShm->eHomeDevice[i].io[8]==0x02){
                                reportList.append(Alarm_Report(alarmList.at(j).Device_Code,alarmList.at(j).Event_Time,QString::fromUtf8("200104"),
                                                                    QString::fromUtf8("insert into sp_video2017 (id,port,device_code,time,status,address,ncmd,data1,data2,data3,data4,data5,clsj,clr,clnr,clwb,cllxr,cldh,clzt,cllx,video) values (NULL,'%1','%2','%3','%4','','%5','%6','%7','%8','消防占道告警','','1970-01-01 08:00:00','','','','','',0,'','')")
                                                    .arg(2).arg(alarmList.at(j).Device_Code).arg(alarmList.at(j).Event_Time).arg(1)
                                                    .arg(104).arg(alarmList.at(j).Event_Status).arg(pic1name).arg("")));
                            }else if(ytShm->eHomeDevice[i].io[8]==0x04){
                                reportList.append(Alarm_Report(alarmList.at(j).Device_Code,alarmList.at(j).Event_Time,QString::fromUtf8("200105"),
                                                                    QString::fromUtf8("insert into sp_video2017 (id,port,device_code,time,status,address,ncmd,data1,data2,data3,data4,data5,clsj,clr,clnr,clwb,cllxr,cldh,clzt,cllx,video) values (NULL,'%1','%2','%3','%4','','%5','%6','%7','%8','电动车禁入/区域入侵告警','','1970-01-01 08:00:00','','','','','',0,'','')")
                                                    .arg(2).arg(alarmList.at(j).Device_Code).arg(alarmList.at(j).Event_Time).arg(1)
                                                    .arg(104).arg(alarmList.at(j).Event_Status).arg(pic1name).arg("")));
                            }

                            if(processList.at(i)->pid()>0)
                                processList.at(i)->close();
                            processList.at(i)->start(cmd1);
                            alarmList.removeAt(j);
                            break;
                        }
                    }
                }else{
                    setFullTime(&(ytShm->eHomeDevice[i].transtime),t);
                    QString tmpfile = QString(ytShm->eHomeDevice[i].filename).replace(" ","_");
                    ytShm->eHomeDevice[i].transed = 0x01;
                    sprintf(ytShm->eHomeDevice[i].filename,"%s",tmpfile.toUtf8().data());
                    system(QString("rm -f /usr/local/nginx/html/hls/%1*").arg(ytShm->eHomeDevice[i].deviceID).toUtf8().data());
                    QString  cmd1 = QString("ffmpeg -re -i \"%1\" -c:v libx264 -an -strict -2 -s 352x278 -g 15 -f flv -v quiet \"rtmp://%2/hls/%3\"   -c:v libx264 -an -strict -2 -s  352x278 -g 15 -f flv -v quiet \"rtmp://%4/live/%5\" ").arg(tmpfile).arg(iServerIP).arg(ytShm->eHomeDevice[i].deviceID).arg(iServerIP).arg(ytShm->eHomeDevice[i].deviceID);
                    if(processList.at(i)->pid()>0)
                        processList.at(i)->close();
                    processList.at(i)->start(cmd1);
                    ytShm->eHomeDevice[i].time[1] = t.toTime_t();
//                    qDebug()<<QString("%1 will on line.(%2)").arg(ytShm->eHomeDevice[i].deviceID).arg(i).toUtf8().data();
                }
            }else if((ytShm->eHomeDevice[i].transed==0x01)&&(ytShm->eHomeDevice[i].time[1]>0)&&((t.toTime_t()-ytShm->eHomeDevice[i].time[1])>600)){
                if(NET_ECMS_StopGetRealStream(ytShm->eHomeDevice[i].LoginId,ytShm->eHomeDevice[i].SessionId)){
                    ytShm->eHomeDevice[i].Connected=0x00;
                    ytShm->eHomeDevice[i].SessionId=-1;
                    ytShm->eHomeDevice[i].time[0]=0;
                    ytShm->eHomeDevice[i].time[1]=0;
//                    qDebug()<<QString("%1 will  close.(%2)").arg(ytShm->eHomeDevice[i].deviceID).arg(i).toUtf8().data();
                    processList.at(i)->close();
                    QString tmpfile = QString(ytShm->eHomeDevice[i].filename);
                    if(ytShm->eHomeDevice[i].tmpfile!=NULL)
                        fclose(ytShm->eHomeDevice[i].tmpfile);
                    ytShm->eHomeDevice[i].savetmp = 0x00;
                    ytShm->eHomeDevice[i].tmpfile = NULL;
                    QFile(tmpfile).remove();
                    ytShm->eHomeDevice[i].transed = 0x00;
                }
            }
        }
    }
    if(reportList.length()>0){
        if(db.open()){
            while (reportList.length()>0) {
                QString phonelist = "";
                Alarm_Report rep = reportList.first();
                QSqlQuery qry = db.exec(rep.Sql);
                quint64 insertId = qry.lastInsertId().toULongLong();
                QString type="";
                QString companyCode = getCompanyCode(rep.Device_Code);
                if(rep.Event_Name.toInt()==200104)
                    type=QString::fromUtf8("占道侦测报警");
                else if(rep.Event_Name.toInt()==200001)
                    type=QString::fromUtf8("火点侦测报警");
                else if(rep.Event_Name.toInt()==200105)
                    type=QString::fromUtf8("电动车禁入/区域入侵告警");
                printf("device code:%s\nget company code:%s\n",rep.Device_Code.toUtf8().data(),companyCode.toUtf8().data());
                if(companyCode.length()>0){
//                    QString rep1 = QString("{\"SubType\":16,\"DeviceId\":\"%1\",\"InsertId\":%2,\"Confirmed\":false}").arg(rep.Device_Code).arg(insertId);
//                    spThread[repcur]->appendData(rep1);
                    QString rep2 = QString("{\"SubType\":16,\"DeviceId\":\"%1\",\"InsertId\":%2,\"Confirmed\":0,\"CompanyCode\":\"%3\",\"evt_name\":\"%4\",\"evt\":0,\"alarm_time\":\"%5\"}")
                                    .arg(rep.Device_Code).arg(insertId).arg(companyCode).arg(type).arg(rep.Event_Time);
                    printf("%s\n",rep2.toUtf8().data());
                    wssThread[repcur]->appendData(rep2);
                    for(int i=0;i<companyphoneList.length();i++){
                        if(QString::compare(companyphoneList.at(i).CompanyCode,companyCode)==0){
                            if(phonelist.length()==0)
                                phonelist = companyphoneList.at(i).Phone;
                            else
                                phonelist.append(","+companyphoneList.at(i).Phone);
                        }
                    }
                    repcur++;
                    repcur &= 0x07;
                    if(phonelist.length()>0){
                        QString data = QString("evt_name=%1&device_code=%2&phone=%3&insert_id=%4&time=%5&bz=%1").arg(type).arg(rep.Device_Code).arg(phonelist).arg(insertId).arg(rep.Event_Time)
                                .replace(",","%2C").replace(":","%3A").replace(" ","+");
                        printf("%s\n",data.toUtf8().data());
                        wxThreads[wxcur]->appendData(data);
                        wxcur++;
                        wxcur &= 0x07;
                    }

                }
                reportList.removeFirst();
            }
            db.close();
        }
    }
    if(sqlList.length()>0){
        if(db.open()){
            while(sqlList.length()>0){
                db.exec(sqlList.first());
//                system(QString("echo \"%1\" > /tmp/pic_sql.log").arg(sqlList.first()).toUtf8().data());
//                printf("%s\n",sqlList.first().toUtf8().data());
                sqlList.removeFirst();
            }
            db.close();
        }
    }
    isWorking = false;
}
