Exemple #1
0
static void *do_timer_func(void *arg)
{
	unsigned char nums = 0,weekday = 0;
	timertask_item_t items[100];
	int i = 0;
	memset(items,0,sizeof(items));
	// 1.Get Current Time
	GetCurrentTime(app_status.CurrentTime,&weekday);
	// 2. Read database
	GetValidThingsToDo(app_status.CurrentTime,weekday,&nums,items);
	// 3. if timer is right, execute its task;
	if(nums>0)
	{
		for(i = 0;i< nums; i++)
		{
			ForwardControlToUart(items[i].dev_mac,items[i].dev_name,DEV_SWITCH,items[i].action,items[i].devnumber);
			if(items[i].howlong > 0)
			{
				TimeAdd(app_status.CurrentTime,items[i].howlong/100, items[i].howlong%100, items[i].happen_time);
				if(items[i].action == CMD_SW_OPEN){
					items[i].action = CMD_SW_CLOSE;
				}else{
					items[i].action = CMD_SW_OPEN;
				}
				items[i].howlong = 0;//avoid repeat
				AddOneTimerTask(items[i]);
			}
		}
	}
	return NULL;
}
//计算两个字符串格式的时间之和函数
//return = st1 + st2
//"12:33:43" = "9:10:23" + "3:23:20"
char* StrTimeAdd(char* st1, char* st2)
{
	if(NULL == st1 || NULL == st2)	return NULL;
	//printf("st1 = %s,strlen st1 = %d,sizeof st1 = %d, st2 = %s , strlen st2 = %d,sizeof st2 = %d\n",st1,strlen(st1),sizeof(st1),st2,strlen(st2),sizeof(st2));
	TimeS t1 = StrToTimeS(st1);
	//printf("t1.h = %d, t1.m = %d, t1.s = %d\n",t1.h,t1.m,t1.s);
	TimeS t2 = StrToTimeS(st2);
	//printf("t2.h = %d, t2.m = %d, t2.s = %d\n",t2.h,t2.m,t2.s);
	TimeS *t3 = TimeAdd(&t1,&t2);
	//printf("t3.h = %d, t3.m = %d, t3.s = %d\n",t3->h,t3->m,t3->s);
	char* t = TimeSToStr(*t3);
	//printf("string t  = %s\n",t);
	
	free(t3);
	return t;
}
Exemple #3
0
/*
 * BarrierClient allows for multiple stream clients to be syncronized
 */
void BarrierClient( ReportHeader *agent ) {
    Condition_Lock(agent->multireport->barrier);
    agent->multireport->threads--;
    if ( agent->multireport->threads == 0 ) {
        // last one set time and wake up everyone
        gettimeofday( &(agent->multireport->startTime), NULL );
        Condition_Broadcast( &agent->multireport->barrier );
    } else {
        Condition_Wait( &agent->multireport->barrier );
    }
    agent->multireport->threads++;
    Condition_Unlock( agent->multireport->barrier );
    agent->report.startTime = agent->multireport->startTime;
    agent->report.nextTime = agent->report.startTime;
    TimeAdd( agent->report.nextTime, agent->report.intervalTime );
}
Exemple #4
0
/*
 * Prints reports conditionally
 */
int reporter_condprintstats( ReporterData *stats, MultiHeader *multireport, int force ) {
    if ( force != 0 ) {
        stats->info.cntOutofOrder = stats->cntOutofOrder;
        // assume most of the time out-of-order packets are not
        // duplicate packets, so conditionally subtract them from the lost packets.
        stats->info.cntError = stats->cntError;
        if ( stats->info.cntError > stats->info.cntOutofOrder ) {
            stats->info.cntError -= stats->info.cntOutofOrder;
        }
        stats->info.cntDatagrams = (isUDP(stats) ? stats->PacketID : stats->cntDatagrams);
        stats->info.TotalLen = stats->TotalLen;
        stats->info.startTime = 0;
        stats->info.endTime = TimeDifference( stats->packetTime, stats->startTime );
        stats->info.free = 1;
        reporter_print( stats, TRANSFER_REPORT, force );
        if ( isMultipleReport(stats) ) {
            reporter_handle_multiple_reports( multireport, &stats->info, force );
        }
    } else while ((stats->intervalTime.tv_sec != 0 ||
                   stats->intervalTime.tv_usec != 0) &&
                  TimeDifference( stats->nextTime,
                                  stats->packetTime ) < 0 ) {
        stats->info.cntOutofOrder = stats->cntOutofOrder - stats->lastOutofOrder;
        stats->lastOutofOrder = stats->cntOutofOrder;
        // assume most of the time out-of-order packets are not
        // duplicate packets, so conditionally subtract them from the lost packets.
        stats->info.cntError = stats->cntError - stats->lastError;
        if ( stats->info.cntError > stats->info.cntOutofOrder ) {
            stats->info.cntError -= stats->info.cntOutofOrder;
        }
        stats->lastError = stats->cntError;
        stats->info.cntDatagrams = (isUDP( stats ) ? stats->PacketID - stats->lastDatagrams :
                                                     stats->cntDatagrams - stats->lastDatagrams);
        stats->lastDatagrams = (isUDP( stats ) ? stats->PacketID : stats->cntDatagrams);
        stats->info.TotalLen = stats->TotalLen - stats->lastTotal;
        stats->lastTotal = stats->TotalLen;
        stats->info.startTime = stats->info.endTime;
        stats->info.endTime = TimeDifference( stats->nextTime, stats->startTime );
        TimeAdd( stats->nextTime, stats->intervalTime );
        stats->info.free = 0;
        reporter_print( stats, TRANSFER_REPORT, force );
        if ( isMultipleReport(stats) ) {
            reporter_handle_multiple_reports( multireport, &stats->info, force );
        }
    }
    return force;
}
Exemple #5
0
/*
 * Prints reports conditionally
 */
int reporter_condprintstats( ReporterData *stats, MultiHeader *multireport, int force ) {

    if ( force ) {
#ifdef HAVE_STRUCT_TCP_INFO_TCPI_TOTAL_RETRANS
	gettcpistats(stats);
#endif
        stats->info.cntOutofOrder = stats->cntOutofOrder;
        // assume most of the time out-of-order packets are not
        // duplicate packets, so conditionally subtract them from the lost packets.
        stats->info.cntError = stats->cntError;
        if ( stats->info.cntError > stats->info.cntOutofOrder ) {
            stats->info.cntError -= stats->info.cntOutofOrder;
        }
        stats->info.cntDatagrams = ((stats->info.mUDP == kMode_Server) ? stats->PacketID : stats->cntDatagrams);
        stats->info.TotalLen = stats->TotalLen;
        stats->info.startTime = 0;
        stats->info.endTime = TimeDifference( stats->packetTime, stats->startTime );
	stats->info.transit.minTransit = stats->info.transit.totminTransit;
	stats->info.transit.maxTransit = stats->info.transit.totmaxTransit;
	stats->info.transit.cntTransit = stats->info.transit.totcntTransit;
	stats->info.transit.sumTransit = stats->info.transit.totsumTransit;
	stats->info.transit.meanTransit = stats->info.transit.totmeanTransit;
	stats->info.transit.m2Transit = stats->info.transit.totm2Transit;
	stats->info.transit.vdTransit = stats->info.transit.totvdTransit;
	if (stats->info.mTCP == kMode_Client) {
	    stats->info.tcp.write.WriteErr = stats->info.tcp.write.totWriteErr;
	    stats->info.tcp.write.WriteCnt = stats->info.tcp.write.totWriteCnt;
	    stats->info.tcp.write.TCPretry = stats->info.tcp.write.totTCPretry;
	}
	if (stats->info.mTCP == kMode_Server) {
	    int ix;
	    stats->info.tcp.read.cntRead = stats->info.tcp.read.totcntRead;
	    for (ix = 0; ix < 8; ix++) {
		stats->info.tcp.read.bins[ix] = stats->info.tcp.read.totbins[ix];
	    }
	}
	if (stats->info.endTime > 0) {
	    stats->info.IPGcnt = (int) (stats->cntDatagrams / stats->info.endTime);
	} else {
	    stats->info.IPGcnt = 0;
	}
	stats->info.IPGsum = 1;
        stats->info.free = 1;

        reporter_print( stats, TRANSFER_REPORT, force );
        if ( isMultipleReport(stats) ) {
            reporter_handle_multiple_reports( multireport, &stats->info, force );
        }
    } else while ((stats->intervalTime.tv_sec != 0 ||
                   stats->intervalTime.tv_usec != 0) &&
                  TimeDifference( stats->nextTime, 
                                  stats->packetTime ) < 0 ) {
#ifdef HAVE_STRUCT_TCP_INFO_TCPI_TOTAL_RETRANS
	    gettcpistats(stats);
#endif
	    stats->info.cntOutofOrder = stats->cntOutofOrder - stats->lastOutofOrder;
	    stats->lastOutofOrder = stats->cntOutofOrder;
	    // assume most of the  time out-of-order packets are not
	    // duplicate packets, so conditionally subtract them from the lost packets.
	    stats->info.cntError = stats->cntError - stats->lastError;
	    if ( stats->info.cntError > stats->info.cntOutofOrder ) {
		stats->info.cntError -= stats->info.cntOutofOrder;
	    }
	    stats->lastError = stats->cntError;
	    stats->info.cntDatagrams = ((stats->info.mUDP == kMode_Server) ? stats->PacketID - stats->lastDatagrams :
					stats->cntDatagrams - stats->lastDatagrams);
	    stats->lastDatagrams = ((stats->info.mUDP == kMode_Server) ? stats->PacketID : stats->cntDatagrams);
	    stats->info.TotalLen = stats->TotalLen - stats->lastTotal;
	    stats->lastTotal = stats->TotalLen;
	    stats->info.startTime = stats->info.endTime;
	    stats->info.endTime = TimeDifference( stats->nextTime, stats->startTime );
	    TimeAdd( stats->nextTime, stats->intervalTime );
	    stats->info.free = 0;
	    reporter_print( stats, TRANSFER_REPORT, force );
	    if ( isMultipleReport(stats) ) {
		reporter_handle_multiple_reports( multireport, &stats->info, force );
	    }
	    // Reset stats used by SUM now that the SUM has been reported
	    if (stats->info.mEnhanced) {
		if (stats->info.mUDP) {
		    stats->info.IPGcnt = 0;
		    stats->info.IPGsum = 0;
		} else if (stats->info.mTCP == (char)kMode_Client) {
		    stats->info.tcp.write.WriteCnt = 0;
		    stats->info.tcp.write.WriteErr = 0;
		} else if (stats->info.mTCP == (char)kMode_Server) {
		    int ix;
		    stats->info.tcp.read.cntRead = 0;
		    for (ix = 0; ix < 8; ix++) { 
			stats->info.tcp.read.bins[ix] = 0;
		    }
		}
	    }
	}
    return force;
}
Exemple #6
0
/*
 * InitReport is called by a transfer agent (client or
 * server) to setup the needed structures to communicate
 * traffic.
 */
ReportHeader* InitReport( thread_Settings *agent ) {
    ReportHeader *reporthdr = NULL;
    ReporterData *data = NULL;
    if ( isDataReport( agent ) ) {
        /*
         * Create in one big chunk
         */
        reporthdr = malloc( sizeof(ReportHeader) +
                            NUM_REPORT_STRUCTS * sizeof(ReportStruct) );
        if ( reporthdr != NULL ) {
            // Only need to make sure the headers are clean
            memset( reporthdr, 0, sizeof(ReportHeader));
            reporthdr->data = (ReportStruct*)(reporthdr+1);
            reporthdr->multireport = agent->multihdr;
            data = &reporthdr->report;
            reporthdr->reporterindex = NUM_REPORT_STRUCTS - 1;
            data->info.transferID = agent->mSock;
            data->info.groupID = (agent->multihdr != NULL ? agent->multihdr->groupID : 128);
            data->type = TRANSFER_REPORT;
            if ( agent->mInterval != 0.0 ) {
                struct timeval *interval = &data->intervalTime;
                interval->tv_sec = (long) agent->mInterval;
                interval->tv_usec = (long) ((agent->mInterval - interval->tv_sec) * rMillion);
            }
            data->mHost = agent->mHost;
            data->mLocalhost = agent->mLocalhost;
            data->mBufLen = agent->mBufLen;
            data->mMSS = agent->mMSS;
            data->mTCPWin = agent->mTCPWin;
            data->flags = agent->flags;
            data->mThreadMode = agent->mThreadMode;
            data->mode = agent->mReportMode;
            data->info.mFormat = agent->mFormat;
            data->info.mTTL = agent->mTTL;
	    if (data->mThreadMode == kMode_Server) 
		data->info.tcp.read.binsize = data->mBufLen / 8;
            if ( isUDP( agent ) ) {
		gettimeofday(&data->IPGstart, NULL);
                reporthdr->report.info.mUDP = (char)agent->mThreadMode;
            } else {
                reporthdr->report.info.mTCP = (char)agent->mThreadMode;
	    }
	    if ( isEnhanced( agent ) ) {
		data->info.mEnhanced = 1;
	    } else {
		data->info.mEnhanced = 0;
	    }
        } else {
            FAIL(1, "Out of Memory!!\n", agent);
        }
    }
    if ( isConnectionReport( agent ) ) {
        if ( reporthdr == NULL ) {
            /*
             * Create in one big chunk
             */
            reporthdr = malloc( sizeof(ReportHeader) );
            if ( reporthdr != NULL ) {
                // Only need to make sure the headers are clean
                memset( reporthdr, 0, sizeof(ReportHeader));
                data = &reporthdr->report;
                data->info.transferID = agent->mSock;
                data->info.groupID = 128;
            } else {
                FAIL(1, "Out of Memory!!\n", agent);
            }
        }
        if ( reporthdr != NULL ) {
            data->type |= CONNECTION_REPORT;
            data->connection.peer = agent->peer;
            data->connection.size_peer = agent->size_peer;
            data->connection.local = agent->local;
            data->connection.size_local = agent->size_local;
        } else {
            FAIL(1, "Out of Memory!!\n", agent);
        }
    }
    if ( isConnectionReport( agent ) || isDataReport( agent ) ) {

#ifdef HAVE_THREAD
        /*
         * Update the ReportRoot to include this report.
         */
        if ( reporthdr->report.mThreadMode == kMode_Client &&
             reporthdr->multireport != NULL ) {
            // syncronize watches on my mark......
            BarrierClient( reporthdr );
        } else {
            if ( reporthdr->multireport != NULL && isMultipleReport( agent )) {
                reporthdr->multireport->threads++;
                if ( reporthdr->multireport->report->startTime.tv_sec == 0 ) {
                    gettimeofday( &(reporthdr->multireport->report->startTime), NULL );
                }
                reporthdr->report.startTime = reporthdr->multireport->report->startTime;
            } else {
                // set start time
                gettimeofday( &(reporthdr->report.startTime), NULL );
            }
            reporthdr->report.nextTime = reporthdr->report.startTime;
            TimeAdd( reporthdr->report.nextTime, reporthdr->report.intervalTime );
        }
        Condition_Lock( ReportCond );
        reporthdr->next = ReportRoot;
        ReportRoot = reporthdr;
        Condition_Signal( &ReportCond );
        Condition_Unlock( ReportCond );
#else
        // set start time
        gettimeofday( &(reporthdr->report.startTime), NULL );
        /*
         * Process the report in this thread
         */
        reporthdr->next = NULL;
        process_report ( reporthdr );
#endif 
    }
    if ( !isDataReport( agent ) ) {
        reporthdr = NULL;
    }
    return reporthdr;
}
Exemple #7
0
/*----------------------------------------------------------------------------*
 *  NAME
 *      SchedTimerSet
 *
 *  DESCRIPTION
 *      Causes the void function "fn" to be called with the arguments
 *      "fniarg" and "fnvarg" after "delay" has elapsed.
 *
 *      "delay" must be less than half the range of a Time.
 *
 *      SchedTimerSet() does nothing with "fniarg" and "fnvarg" except
 *      deliver them via a call to "fn()".   (Unless SchedTimerCancel()
 *      is used to prevent delivery.)
 *
 *  NOTE
 *      The function will be called at or after "delay"; the actual delay will
 *      depend on the timing behaviour of the scheduler's tasks.
 *
 *  RETURNS
 *      SchedTid - A timer identifier, can be used in SchedTimerCancel().
 *
 *----------------------------------------------------------------------------*/
SchedTid SchedTimerSet(Time delay,
    void (*fn)(SchedTid timerid, uint16 mi, void *mv),
    uint16 fniarg,
    void *fnvarg)
{
    SchedTid tid;
    uint8 index;

    index = GetThreadIndex();
    if (index < _SCHED_MAX_SEGMENTS) {
        ThreadInstanceType *thread;
        TimerType *newTimer;
        Time when;
        Time now;
        uint32 whenWrapCount;

        thread = &instance->thread[index];

        newTimer = timerAlloc(thread);

        /* Get absolute time of event */
        now = TimeGet(NULL);
        when = TimeAdd(now, delay);

        if (when < now) {
            whenWrapCount = 1;
        }
        else {
            whenWrapCount = 0;
        }

        /* Build the structure. */
        newTimer->when = when;
        newTimer->wrapCount = whenWrapCount;
        newTimer->eventFunction = fn;
        newTimer->fniarg = fniarg;
        newTimer->fnvarg = fnvarg;

        newTimer->queue = thread->currentTask;
        newTimer->active = TRUE;

        /* Handle timer wrap */
        adjust_wrap_count(thread, now);

        newTimer->wrapCount += thread->currentWrapCount;

        /* Store struct in time position in the timer list. */
        if (thread->timerList == NULL) {
            newTimer->prev = NULL;
            newTimer->next = NULL;

            thread->timerList = newTimer;
        }
        else {
            TimerType *ptr, *prev;

            ptr = thread->timerList;
            prev = NULL;

            /* Determine where to insert element */
            while (ptr) {
                if (((ptr->when > newTimer->when) &&
                     (ptr->wrapCount == newTimer->wrapCount)) ||
                    (ptr->wrapCount > newTimer->wrapCount)) {
                    break;
                }
                else {
                    prev = ptr;
                    ptr = ptr->next;
                }
            }

            newTimer->prev = prev;
            newTimer->next = ptr;

            if (prev != NULL) {
                prev->next = newTimer;
            }
            else {
                thread->timerList = newTimer;
            }

            if (ptr != NULL) {
                ptr->prev = newTimer;
            }
        }

        tid = newTimer->id;
    }
    else {
        tid = _SCHED_TID_INVALID;
    //    Panic(_TECH_FW, _PANIC_FW_UNEXPECTED_VALUE,
    //        "SchedTimerSet not called from scheduler thread");
    }

    return tid;
}
Exemple #8
0
void *client_thread(void *arg)
{
	cJSON *root = NULL;
	char buffer[512] = {0};
	dev_tt dev;
	DEV_ADD_RETURN ret_add_dev = DEV_ADD_OK;
	BOOL ret = FALSE;
	char cityid[20] = {0};
	fd_set pending_data;
	struct timeval block_time;
	if (arg == NULL) {
		return NULL;
	}
	int *fd = arg;

	FD_ZERO(&pending_data);
	FD_SET(*fd,&pending_data);
	block_time.tv_sec = 5;
	block_time.tv_usec = 0;

	/*if client connect and not send message in 5 seconds,we will close the connection*/
	if (select((*fd) + 1, &pending_data, NULL, NULL, &block_time) > 0) {
		if (FD_ISSET(*fd, &pending_data)) {
			if (read(*fd, buffer, sizeof(buffer)) < 0) {
				close(*fd);
				return NULL;
			}
		}
	} 
	
	led_flash(LED_FOR_NETWORK, 1, 3);
	DEBUG_MSG("Network receive:%s\n", buffer);
	root = cJSON_Parse(buffer);//parse json
	if (root == NULL) {
		return NULL;
	}
	memset(&dev, 0, sizeof(dev_tt));
	char *who			= cJSON_GetObjectItem(root, "param0")->valuestring;
	dev.user_action 		= cJSON_GetObjectItem(root, "param1")->valuestring;
	dev.basic_info.mac		= cJSON_GetObjectItem(root, "param2")->valuestring;
	dev.basic_info.name 		= cJSON_GetObjectItem(root, "param3")->valuestring;
	dev.type 				= cJSON_GetObjectItem(root, "param4")->valuestring;
	dev.dev_cmd 			= cJSON_GetObjectItem(root, "param5")->valuestring;
	dev.basic_info.groupname	= cJSON_GetObjectItem(root, "param6")->valuestring;
	char *param1			= cJSON_GetObjectItem(root, "param7")->valuestring;
	char *param2			= cJSON_GetObjectItem(root, "param8")->valuestring;
	
	if (who == NULL || dev.user_action == NULL || dev.basic_info.mac==NULL ||dev.basic_info.name== NULL||dev.dev_cmd==NULL||dev.basic_info.groupname==NULL) {
		close(*fd);
		return NULL;
	}
	USER_ACTION user_action_type = (USER_ACTION)atoi(dev.user_action);
	switch (user_action_type) {
	case ACTION_DEV_ADD:
		dev.basic_info.name 		= strtok(dev.basic_info.name,":");//contains unicode
		dev.basic_info.unicode 	= strtok(NULL,":");
		dev.type = param2;
		if (dev.basic_info.name == NULL ||dev.basic_info.unicode == NULL) {
			break;
		}
		DEBUG_MSG("ADD:name= %s,unicode= %s\n",dev.basic_info.name,dev.basic_info.unicode);
		ret_add_dev = AddDevToStaticTable(dev.basic_info.mac,dev.basic_info.name,dev.basic_info.unicode,dev.basic_info.groupname,atoi(param1),atoi(dev.type));
		if (ret_add_dev==DEV_ADD_OK) {
			write(*fd, SOCKET_RESPONSE_YES, strlen(SOCKET_RESPONSE_YES));
			send_broadcast(who, user_action_type, dev.basic_info.name);
		} else if (ret_add_dev == DEV_MAC_EXIST) {
			write(*fd,SOCKET_RESPONSE_MAC_EXIST, strlen(SOCKET_RESPONSE_MAC_EXIST));
		} else if (ret_add_dev == DEV_NAME_EXIST) {
			write(*fd,SOCKET_RESPONSE_NAME_EXIST, strlen(SOCKET_RESPONSE_NAME_EXIST));
		}
		break;
	case ACTION_DEV_REMOVE:
		ret = RemoveDevFromStaticTable(dev.basic_info.mac,dev.basic_info.name);
		if (ret) {
			send_broadcast(who,user_action_type,dev.basic_info.name);
		}
		goto response_client;
		break;
	case ACTION_DEV_ADD_GROUP:
		ret = AddDevGroupName(dev.basic_info.groupname);
		goto response_client;
		break;
	case ACTION_DEV_EDIT:
		{
			char *oldname = param1;
			dev.basic_info.name = strtok(dev.basic_info.name,":");
			dev.basic_info.unicode = strtok(NULL,":");
			if (dev.basic_info.name == NULL ||dev.basic_info.unicode == NULL||oldname==NULL) {
				break;			
			}
			DEBUG_MSG("UPDATE:oldname = %s newname= %s,unicode= %s\n",oldname,dev.basic_info.name,dev.basic_info.unicode);
			ret = UpdateDevDisplayName(dev.basic_info.mac, oldname,dev.basic_info.name,dev.basic_info.unicode);
			if (ret) {
				send_broadcast(who,user_action_type,dev.basic_info.name);
			}
			goto response_client;
		}
		break;
	case ACTION_GET_ALARM_LIST:
		GetAlarmAllList();
		write(*fd,get_alarm_alllist(),strlen(get_alarm_alllist()));
		break;
	case ACTION_GET_DEV_LIST:
		GetDeviceList();
		write(*fd,get_dev_list(),strlen(get_dev_list()));
		break;
	case ACTION_GET_CITY_ID:
		//char *name = dev.basic_info.name;
		memset(cityid,0,sizeof(cityid));
		if (GetCityIDByName(dev.basic_info.name, cityid)) {
			write(*fd,cityid,strlen(cityid));
		} else {
			write(*fd,SOCKET_RESPONSE_NO,strlen(SOCKET_RESPONSE_NO));
		}
		break;
	case ACTION_DEV_CONTROL:
		if (app_status.is_uart_ok) {
			ret = ForwardControlToUart(dev.basic_info.mac,dev.basic_info.name,(DEV_TYPE_INDEX)(atoi(dev.type)),atoi(dev.dev_cmd),atoi(param1));
		} else {
			ret = FALSE;
		}
		goto response_client;
		break;
	case ACTION_SEND_MSG:
		if (app_status.is_sms_ok) {
			ret = sms.send(dev.basic_info.mac,dev.basic_info.name);
		} else {
			ret = FALSE;
		}
		goto response_client;
		break;
	case ACTION_ALARM_ADD:
		//mac as the value(email or mobile value)
		ret = AddAlarmItem((ALARM_TYPE)(atoi(dev.type)), dev.basic_info.mac);
		goto response_client;
		break;
	case ACTION_ALARM_LOCK:
		ret = ChangeAlarmItemToState(ALARM_LOCK,(ALARM_TYPE)(atoi(dev.type)), dev.basic_info.mac);
		goto response_client;
		break;
	case ACTION_ALARM_UNLOCK:
		ret = ChangeAlarmItemToState(ALARM_UNLOCK,(ALARM_TYPE)(atoi(dev.type)), dev.basic_info.mac);
		goto response_client;
		break;
	case ACTION_ALARM_DELETE:
		ret = DeleteFromAlarmTable((ALARM_TYPE)(atoi(dev.type)), dev.basic_info.mac);
		goto response_client;
		break;
	case ACTION_GET_ALL_GROUP_NAME:
		GetAllGroupName();
		write(*fd , get_group_list(), strlen(get_group_list()));
		break;
	case ACTION_UPDATE_DEV_GROUP:
		ret = UpdateDevGroupName(dev.basic_info.mac,dev.basic_info.name,dev.basic_info.groupname);
		goto response_client;
		break;
	case ACTION_SET_GROUP_ID:
		{
			groupInfo_t group_info;
			memset(&group_info,0,sizeof(&group_info));
			strcpy(group_info.group_id,dev.basic_info.mac);
			strcpy(group_info.group_name,dev.basic_info.name);
			ret = SetFamilyGroupInfo(group_info);
			goto response_client;
		}
		break;
	case ACTION_GET_GROUP_ID:
		{
			groupInfo_t group_info;
			memset(&group_info,0,sizeof(&group_info));
			if (GetFamilyGroupInfo(&group_info)) {
					char buf[1024] = {0};
					sprintf(buf,"%s,%s,",group_info.group_id,group_info.group_name);
					write(*fd,buf,strlen(buf));
			} else {
				write(*fd,"_FAIL_",strlen("_FAIL_"));
			}
		}
		break;
	case ACTION_ADD_TIMERTASK:
		{
			timertask_item_t item;
			DEBUG_MSG("add timertask!\n");
			memset(&item,0,sizeof(&item));
			strcpy(item.dev_mac,dev.basic_info.mac);
			strcpy(item.dev_name,dev.basic_info.name);
			strcpy(item.happen_time ,param1);
			item.period		=	atoi(dev.type);
			item.action		=	atoi(dev.dev_cmd);
			item.tipinfo		=	atoi(dev.basic_info.groupname);
			item.howlong		=	atoi(param2);
			DEBUG_MSG("action = %d, howlong = hour:%2d,minute:%2d\n",item.action,(item.howlong)/100,(item.howlong)%100);
			ret = AddOneTimerTask(item);
			if (ret && item.howlong > 0) {
				TimeAdd(item.happen_time,item.howlong/100, item.howlong%100, item.happen_time);
				if (item.action == CMD_SW_OPEN) {
					item.action = CMD_SW_CLOSE;
				} else {
					item.action = CMD_SW_OPEN;
				}
				item.howlong = 0;//avoid repeat
				ret = AddOneTimerTask(item);
			}
			goto response_client;
		}
		break;
	case ACTION_DELETE_TIMERTASK:
		{
			int timertask_id = 0;
			ret = DeleteOneTimerTaskByID(timertask_id);
			goto response_client;
		}
		break;
	case ACTION_GET_TIMERTASK_INFO:
		GetAllTimerTaskInfo();
		write(*fd,g_timertask_info,strlen(g_timertask_info));
		break;
	case ACTION_SW_GET_STATE:
		{
			char buffer[10] = {0};
			enum control_cmd state = SWGetCurrentState(dev.basic_info.mac,dev.basic_info.name,atoi(param1));
			sprintf(buffer,"%d", state);
			write(*fd,buffer,strlen(buffer));
		}
		break;
	case ACTION_QUIT:
		close(*fd);
		return NULL;
	default:
		break;
	}
	close(*fd);
	return NULL;
response_client:
	if (ret) {
		write(*fd, SOCKET_RESPONSE_YES, strlen(SOCKET_RESPONSE_YES));
	} else {
		write(*fd, SOCKET_RESPONSE_NO, strlen(SOCKET_RESPONSE_NO));
	}
	close(*fd);
	return NULL;
}
void CServer::Run(void)
{
  char v18; // [sp+8Fh] [bp-C85h]@56
  //fd_set exceptfds; // [sp+90h] [bp-C84h]@53
  //fd_set writefds; // [sp+490h] [bp-884h]@53
  //fd_set readfds; // [sp+890h] [bp-484h]@53
  //int v22; // [sp+C90h] [bp-84h]@9
  pthread_t newthread; // [sp+CA0h] [bp-74h]@1
  //fd_set *i; // [sp+CA4h] [bp-70h]@1
  //int v25; // [sp+CA8h] [bp-6Ch]@1
  //fd_set *v26; // [sp+CACh] [bp-68h]@1
  int v27; // [sp+CB0h] [bp-64h]@1
  int v28; // [sp+CB4h] [bp-60h]@1
  int v29; // [sp+CB8h] [bp-5Ch]@3
  int v30; // [sp+CBCh] [bp-58h]@5
  //int v31; // [sp+CC0h] [bp-54h]@25
  //int v32; // [sp+CC4h] [bp-50h]@26
  //char v33; // [sp+CC8h] [bp-4Ch]@1
  //struct timeval timeout; // [sp+CDCh] [bp-38h]@7
  //char v35; // [sp+CE4h] [bp-30h]@7
  //char v36; // [sp+CECh] [bp-28h]@3
  //char v37; // [sp+CF4h] [bp-20h]@7
  //int v38; // [sp+CFCh] [bp-18h]@3
  //int v39; // [sp+D00h] [bp-14h]@4
  //int v40; // [sp+D04h] [bp-10h]@1
  //int v41; // [sp+D08h] [bp-Ch]@1
  //struct timeval tv; // [sp+D0Ch] [bp-8h]@1

  fd_set exceptfds, writefds, readfds;
  CDescriptor *v31, *v32;
  CNetMsg v33;
  struct timeval timeout, v35, v36, v37, v38, v40, tv;
  int m_ret = 0;

  v28 = 0;
  v27 = 72000;
  v40.tv_usec = 50000;
  v40.tv_sec = 0;
  memset(this->p_unk_array4, 0, 0x400);
  GetTimeofDay(&tv, 0);

  while(!this->Shutdowned)
  {
    v29 = InitFDSET(this->ServerSocket, this->ClientDescriptors, &this->ReadFDS, &this->WriteFDS, &this->ExceptFDS);
    GetTimeofDay(&v36, 0);
    TimeDiff(&v38, &v36, &tv);

    if(v38.tv_sec || v38.tv_usec > 49999)
    {
      v30 = v38.tv_usec / 50000 + 20 * v38.tv_sec;
      v38.tv_sec = 0;
      v38.tv_usec %= 50000;
    }
    else
    {
      v30 = 0;
    }

    TimeDiff(&v37, &v40, &v38);
    TimeAdd(&tv, &v36, &v37);
    GetTimeofDay(&v35, 0);
    TimeDiff(&timeout, &tv, &v35);

    do
    {
      if(timeout.tv_sec >= 0)
      {
        if(!timeout.tv_sec && timeout.tv_usec < 0)
        {
          g_gamelogbuffer.__ls(init("SYS_ERR"));
          g_gamelogbuffer.__ls("Timeout value is negative");
          g_gamelogbuffer.__ls(end);

          timeout.tv_usec = 0;
        }
      }
      else
      {
        g_gamelogbuffer.__ls(init("SYS_ERR"));
        g_gamelogbuffer.__ls("Timeout value is negative");
        g_gamelogbuffer.__ls(end);

        timeout.tv_sec = 0;
      }

      this->ServerSleep(&timeout);
      GetTimeofDay(&v35, 0);
      TimeDiff(&timeout, &tv, &v35);
    }
    while(timeout.tv_usec || timeout.tv_sec);

    a_NullTime.tv_sec = 0;
    a_NullTime.tv_usec = 0;

    if(select(v29 + 1, &this->ReadFDS, &this->WriteFDS, &this->ExceptFDS, &a_NullTime) < 0)
    {
      g_gamelogbuffer.__ls(init("SYS_ERR"));
      g_gamelogbuffer.__ls("Select poll");
      g_gamelogbuffer.__ls(end);

      return;
    }

    a_NullTime.tv_sec = 0;
    a_NullTime.tv_usec = 0;

    if(FD_ISSET(this->ServerSocket, &this->ReadFDS))
        this->NewDescriptor(this->ServerSocket);


    if(v27 >= 0)
    {
      --v27;
    }
    else
    {
      v27 = 72000;

      g_gamelogbuffer.__ls(init("CONNECTIONS"));
      g_gamelogbuffer.__ls(v28);
      g_gamelogbuffer.__ls(end);
    }

    v28 = 0;
    ++v30;

    if(v30 <= 0)
      v30 = 1;

    v31 = this->ClientDescriptors;
RESTART:
    while(1)
    {
      v32 = v31;

      if(!v31)
        break;

      v31 = v32->Node;

      if(v32->Unk152 != 1 && v32->Unk152 != 17)
      {
        if(v32->Unk148 >= 0)
          v32->Unk148 += v30;

        if(FD_ISSET(v32->Socket, &this->ExceptFDS))
        {
          v32->WasErrors = true;
          this->CloseSocket(v32);

          continue;
        }

        if(FD_ISSET(v32->Socket, &this->ReadFDS) && v32->Unk152 != 17 && v32->ProcessInput() < 0)
        {
          v32->WasErrors = true;
          this->CloseSocket(v32);

          continue;
        }

        ++v28;
        if(v32->InputQueue2.Get(v33))
        {
          while(1)
          {
            if(v32->Unk152)
            {
              if(v32->Unk152 == 23)
              {
                if(!v32->GetLogin(v33))
                {
                  v32->WasErrors = true;
                  this->CloseSocket(v32);

                  goto RESTART;
                }

                g_gamelogbuffer.__ls(init("CONNECTED", v32->Hostname));
                g_gamelogbuffer.__ls(v32->IsTester);
                g_gamelogbuffer.__ls(delim);
                g_gamelogbuffer.__ls((int)v32->SubServerID);
                g_gamelogbuffer.__ls(end);
              }
            }
            else
            {
              this->CommandInterpreter(v32, v33);

              if(this->Shutdowned)
                goto RESTART;
            }

            if(!v32->InputQueue2.Get(v33))
              goto RESTART;
          }
        }

        if(v32->Unk152 == 23)
        {
          ++v32->Unk156;
          if(v32->Unk156 > 3600)
          {
            g_gamelogbuffer.__ls(init("BAD_CONNECTION", v32->Hostname));
            g_gamelogbuffer.__ls(end);
            v32->WasErrors = true;

            this->CloseSocket(v32);
          }
        }
      }
    }
	
    this->CheckPlayers();
	
    if(this->BillingClient.IsRunning())
    {
        FD_ZERO(&readfds);
        FD_ZERO(&writefds);
        FD_ZERO(&exceptfds);

        FD_SET(this->BillingClient.Socket, &readfds);
        FD_SET(this->BillingClient.Socket, &writefds);
        FD_SET(this->BillingClient.Socket, &exceptfds);

        a_NullTime.tv_sec = 0;
        a_NullTime.tv_usec = 0;

        m_ret = select(this->BillingClient.Socket + 1, &readfds, &writefds, &exceptfds, &a_NullTime);

        a_NullTime.tv_sec = 0;
        a_NullTime.tv_usec = 0;

        if(m_ret < 0 || FD_ISSET(this->BillingClient.Socket, &exceptfds))
        {
            this->BillingClient.Close();
        }
        else
        {
            v18 = 1;

            if(FD_ISSET(this->BillingClient.Socket, &readfds) && !this->BillingClient.ProcessInput())
            {
                v18 = 0;
                this->BillingClient.Close();
            }

            if(v18)
            {
                for(int i = 0; i <= 50 && this->BillingClient.ProcessInputQueue(); i++)
                    this->BillingClient.ProcessBilling();

                if(FD_ISSET(this->BillingClient.Socket, &writefds))
                    this->BillingClient.ProcessOutput();
            }
        }
    }
    else
    {
      if(!this->BillingClient.IsTrying())
        pthread_create(&newthread, 0, (void *(*)(void *))CBillingClient::BillingConnect, (char *)&this->BillingClient);
    }

    if(this->Shutdowned)
      break;

    v31 = this->ClientDescriptors;

    while(1)
    {
      v32 = v31;

      if(!v31)
        break;

      v31 = v32->Node;

      if(v32->WasErrors || v32->Unk152 == 1 || v32->Unk152 == 17)
      {
        this->CloseSocket(v32);
      }
      else
      {
        if(v32->OutputBuffer.GetNextPoint() && FD_ISSET(v32->Socket, &this->WriteFDS) && !v32->WasErrors && v32->ProcessOutput() < 0)
        {
          v32->WasErrors = true;
          this->CloseSocket(v32);
        }
      }
    }

    this->Unk1 += v30;

    this->HeartBeat();
    v30 = 0;
  }
}