Exemple #1
0
void test_css_util_time(void)
{
	struct timeval tv0, tv1;

	struct timeval tv;
	sv_time_t sv;
	time_t tt;
	char str[24];

	gettimeofday(&tv0, NULL);
	Sleep(100);
	gettimeofday(&tv1, NULL);

	printf("diff0: %ld\n", difftimeval(&tv1, &tv0));
	tv0.tv_usec -= 999000;
	printf("diff1: %ld\n", difftimeval(&tv1, &tv0));
	tv1.tv_sec--;
	printf("diff2: %ld\n", difftimeval(&tv1, &tv0));
	tv1.tv_sec += 10;
	printf("diff3: %ld\n", difftimeval(&tv1, &tv0));

	gettimeofday(&tv, NULL);
	time(&tt);
	timeval_to_svtime(&sv, &tv);
	timeval_to_svtime_string(&tv, str, 24);
	printf("%hd-%02hd-%02hd %d\n", sv.year, (short)sv.month, (short)sv.day, sv.milliSeconds);
	printf("%s\n", str);

}
Exemple #2
0
static void start_threads(void)
{
	pthread_t thread_array[threads];
	double elapsed;
	unsigned int i;
	struct rusage start_ru, end_ru;
	struct timeval usr_time, sys_time;
	int err;

	if (verbose)
		printf("Threads starting\n");

	for (i = 0; i < threads; i++) {
		err = pthread_create(&thread_array[i], NULL, thread_run, NULL);
		if (err) {
			fprintf(stderr, "Error creating thread %d\n", i);
			exit(1);
		}
	}

	/*
	 * Begin accounting - this is when we actually do the things
	 * we want to measure. */

	getrusage(RUSAGE_SELF, &start_ru);
	start_time = time(NULL);
	threads_go = 1;
	sleep(seconds);
	threads_go = 0;
	elapsed = difftime(time(NULL), start_time);
	getrusage(RUSAGE_SELF, &end_ru);

	/*
	 * The rest is just clean up.
	 */

	for (i = 0; i < threads; i++) {
		err = pthread_join(thread_array[i], NULL);
		if (err) {
			fprintf(stderr, "Error joining thread %d\n", i);
			exit(1);
		}
	}

	if (verbose)
		printf("Threads finished\n");

	printf("%u records/s\n",
	       (unsigned int)(((double)records_read) / elapsed));

	usr_time = difftimeval(&end_ru.ru_utime, &start_ru.ru_utime);
	sys_time = difftimeval(&end_ru.ru_stime, &start_ru.ru_stime);

	printf("real %5.2f s\n", elapsed);
	printf("user %5.2f s\n", usr_time.tv_sec + usr_time.tv_usec / 1e6);
	printf("sys  %5.2f s\n", sys_time.tv_sec + sys_time.tv_usec / 1e6);
}
Exemple #3
0
void speed_calc(double pkt_sent,double speed_limit, int *sleeper)
{
    static struct timeval tv = {0};
    struct timeval tv_old;
    double ellapsed;
    double speed;
    if((tv.tv_sec == tv.tv_usec) && (tv.tv_sec == 0)) {
	gettimeofday(&tv,NULL);
	return;
    }
    tv_old.tv_sec = tv.tv_sec;
    tv_old.tv_usec = tv.tv_usec;

    gettimeofday(&tv,NULL);

    ellapsed = difftimeval(tv_old,tv);

    speed = (pkt_sent)/ellapsed;

    if(speed>speed_limit) {
        (*sleeper)--;
        if((*sleeper)<1) (*sleeper) = 1;
    }
    else if(speed<speed_limit) {
        (*sleeper)++;
    }
}
Exemple #4
0
void print_result (settings *conf_settings, received_probe *probe , resume *result) {
	double bandwidth = 0.0, diff = 0.0;
	char buffer[256];
	char *log_file = probe->log_file;

	if (!probe)
		return;

	diff = difftimeval2db(&(probe->start), &(probe->end));
	if ((probe->received_total > 0) &&
		(probe->received_packets > 0) && (diff > 0.0)) {
		
		bandwidth = (double)(probe->received_total*8)/diff;

		result->packet_size = probe->received_total/probe->received_packets;
		result->packet_num = probe->received_packets;
		result->bytes = probe->received_total;
		/* double to timeval....*/
		double2timeval(bandwidth, &(result->bw_med));
		/* timeval - timeval */
		difftimeval ( &(probe->start), &(probe->end), &(result->time_med));
		result->jitter_med = result->jitter_med/(probe->received_packets - 1);

		memset (buffer, 0, 256);
		if (!get_currentDateTime (buffer, 256)) {
			LOG_FILE (((log_file != NULL) ? log_file : DEFAULT_RECVCONT_BURST_LOGFILE), "[%s]\t%4d\t%4d\t%5d\t%10d\t%12.4f\t%09.6f\n",
					buffer, conf_settings->recvsock_buffer, probe->received_total/probe->received_packets, probe->received_packets, probe->received_total, bandwidth/1000000, diff);
		}
		else {
			LOG_FILE (((log_file != NULL) ? log_file : DEFAULT_RECVCONT_BURST_LOGFILE), "%4d\t%4d\t%5d\t%10d\t%12.4f\t%09.6f\n",
					conf_settings->recvsock_buffer, probe->received_total/probe->received_packets, probe->received_packets, probe->received_total, bandwidth/1000000, diff);
		}
	}
	return;
}
Exemple #5
0
 bool elapsed_if_wait(const struct timeval& now, uint64_t elapsed)
 {
     if (difftimeval(now, this->now) > elapsed)
     {
         this->now = now;
         return true;
     }
     return false;
 }
Exemple #6
0
 void snapshot( const timeval & now, int x, int y, bool ignore_frame_in_timeval) {
     if (difftimeval(now, this->start_native_capture)
             >= this->inter_frame_interval_native_capture) {
         this->recorder.timestamp(now);
         this->time_to_wait = this->inter_frame_interval_native_capture;
         if (!this->pointer_displayed) {
             this->recorder.mouse(static_cast<uint16_t>(x), static_cast<uint16_t>(y));
         }
         this->start_native_capture = now;
         if (difftimeval(now, this->start_break_capture)
                 >= this->inter_frame_interval_start_break_capture) {
             this->breakpoint();
             this->start_break_capture = now;
         }
     }
     else {
         this->time_to_wait = this->inter_frame_interval_native_capture - difftimeval(now, this->start_native_capture);
     }
 }
Exemple #7
0
/**
 * 播放音频文件.
 * @param file 音频文件
 * @note 如果时间间隔过短,系统将会忽略后一个请求.
 */
void SoundSystem::Playing(const char *file)
{
        GstElement *pipeline, *filesrc;
        struct timeval time;

        gettimeofday(&time, NULL);
        if (!FLAG_ISSET(progdt.sndfgs, 0) || (difftimeval(time, timestamp) < 0.1))
                return;

        if (persist)
                EosMessageOccur(this);
        persist = true;
        filesrc = GST_ELEMENT(g_datalist_get_data(&eltset, "filesrc-element"));
        g_object_set(filesrc, "location", file, NULL);
        pipeline = GST_ELEMENT(g_datalist_get_data(&eltset, "pipeline-element"));
        gst_element_set_state(pipeline, GST_STATE_PLAYING);
        timestamp = time;
}
void signal_kill_handler(int signum){
/*	for(int i=0; i<connectionCnt; i++){
			CDBConnection* ptr = (CDBConnection*)pDBClist[i];
			profile_node *cur = ptr->head;
			double total_exec = 0;
			while(cur!=NULL){
					double exec_time = difftimeval(cur->end, cur->start);
					ptr->outfile<<"start=( "<<cur->start.tv_sec<<" "<<cur->start.tv_usec<<" ), end=( "<<cur->end.tv_sec<<" "<<cur->end.tv_usec<<" ), "<<exec_time<<endl;
					cur = cur->next;
					total_exec += exec_time;
			}
			ptr->outfile<<endl<<endl;
			ptr->outfile<<"total exec: "<<total_exec<<endl;
			ptr->outfile.flush();
	}*/
	timeval t2;
	gettimeofday(&t2, NULL);
	cout<<dec;
	for(int i=0; i<connectionCnt; i++){
			CDBConnection* ptr = (CDBConnection*)pDBClist[i];
			double timerange = difftimeval(t2, t_start_values[i]);
			cout<<"txn cnt for connection "<<i<<": commit "<<ptr->txn_cnt<<", abort "<<ptr->abort_cnt<<", timerange = "<<timerange<<", txn_time = "<<ptr->txn_time<<endl;
//				cout<<"txn cnt for connection "<<i<<": "<<ptr->txn_cnt<<endl;
	}
#ifdef TIMEPROFILE
	for(int i=0; i<connectionCnt; i++){
		CDBConnection *ptr = (CDBConnection*)pDBClist[i];
		int j = 0;
		while(j<46 /*&& ptr->_time[j] !=0*/){
			if(ptr->_time[j]!=0)cout<<"connection "<<i<<": "<<"query "<<j<<" execute_cnt = "<<ptr->_cnt[j]<<", average time "<<(ptr->_time[j]/(double)ptr->_cnt[j])<<", var = "<<(ptr->_var[j]/(double)ptr->_cnt[j])<<endl;
			if(j==21)
			cout<<"- - - - - - - - - - - - "<<endl;
			j++;
		}
		cout<<"================================"<<endl;
	}
#endif

	exit(signum);
}
void *workerThread(void *data)
{
	signal(SIGTERM, signal_kill_handler);
	try {
		PThreadParameter pThrParam = reinterpret_cast<PThreadParameter>(data);

		CSocket sockDrv;
		sockDrv.setSocketFd(pThrParam->iSockfd); // client socket
#ifndef NO_DEBUG_INFO
		ostringstream msg2;
		msg2<<"workerThread "<<pThrParam->t_id<<", start, iSockfd = "<<pThrParam->iSockfd<<endl;
		pThrParam->pBrokerageHouse->logErrorMessage(msg2.str());
#endif
		PMsgDriverBrokerage pMessage = new TMsgDriverBrokerage;
		memset(pMessage, 0, sizeof(TMsgDriverBrokerage)); // zero the structure

		TMsgBrokerageDriver Reply; // return message
		INT32 iRet = 0; // transaction return code
		CDBConnection *pDBConnection = NULL;

#ifdef DB_PGSQL
		// new database connection
		pDBConnection = new CDBConnection(
				pThrParam->pBrokerageHouse->m_szHost,
				pThrParam->pBrokerageHouse->m_szDBName,
				pThrParam->pBrokerageHouse->m_szDBPort);
#else
	pDBConnection = new CDBConnection(
			pThrParam->pBrokerageHouse,
			pThrParam->pBrokerageHouse->mysql_dbname,
			pThrParam->pBrokerageHouse->mysql_host,
			pThrParam->pBrokerageHouse->mysql_user,
			pThrParam->pBrokerageHouse->mysql_pass,
			pThrParam->pBrokerageHouse->mysql_port_t,
			pThrParam->pBrokerageHouse->mysql_socket_t);
			pDBClist[pThrParam->t_id] = pDBConnection;
#ifdef CAL_RESP_TIME
			pDBConnection->init_profile_node(pThrParam->t_id, pThrParam->outputDir);
#endif
#endif


		pDBConnection->setBrokerageHouse(pThrParam->pBrokerageHouse);
		CSendToMarket sendToMarket = CSendToMarket(
				&(pThrParam->pBrokerageHouse->m_fLog));
#ifdef NO_MEE_FOR_TRADERESULT
		sendToMarket.m_pCMEE = pThrParam->pBrokerageHouse->m_pCMEE[pThrParam->t_id%pThrParam->pBrokerageHouse->iUsers];
#endif
		CMarketFeedDB marketFeedDB(pDBConnection);
		CMarketFeed marketFeed = CMarketFeed(&marketFeedDB, &sendToMarket);
		CTradeOrderDB tradeOrderDB(pDBConnection);
		CTradeOrder tradeOrder = CTradeOrder(&tradeOrderDB, &sendToMarket);

		// Initialize all classes that will be used to execute transactions.
		CBrokerVolumeDB brokerVolumeDB(pDBConnection);
		CBrokerVolume brokerVolume = CBrokerVolume(&brokerVolumeDB);
		CCustomerPositionDB customerPositionDB(pDBConnection);
		CCustomerPosition customerPosition = CCustomerPosition(&customerPositionDB);
		CMarketWatchDB marketWatchDB(pDBConnection);
		CMarketWatch marketWatch = CMarketWatch(&marketWatchDB);
		CSecurityDetailDB securityDetailDB = CSecurityDetailDB(pDBConnection);
		CSecurityDetail securityDetail = CSecurityDetail(&securityDetailDB);
		CTradeLookupDB tradeLookupDB(pDBConnection);
		CTradeLookup tradeLookup = CTradeLookup(&tradeLookupDB);
		CTradeStatusDB tradeStatusDB(pDBConnection);
		CTradeStatus tradeStatus = CTradeStatus(&tradeStatusDB);
		CTradeUpdateDB tradeUpdateDB(pDBConnection);
		CTradeUpdate tradeUpdate = CTradeUpdate(&tradeUpdateDB);
		CDataMaintenanceDB dataMaintenanceDB(pDBConnection);
		CDataMaintenance dataMaintenance = CDataMaintenance(&dataMaintenanceDB);
		CTradeCleanupDB tradeCleanupDB(pDBConnection);
		CTradeCleanup tradeCleanup = CTradeCleanup(&tradeCleanupDB);
		CTradeResultDB tradeResultDB(pDBConnection);
		CTradeResult tradeResult = CTradeResult(&tradeResultDB);

		int txn_cnt = 0;
		int abort_cnt = 0;
		double txn_time = 0;
		bool commit = true;
		double receiving_time = 0;
//		gettimeofday(&(pDBConnection->t1), NULL);
		do {
			try {
				//gettimeofday(&tt1, NULL);
				sockDrv.dbt5Receive(reinterpret_cast<void *>(pMessage),
						sizeof(TMsgDriverBrokerage));
				//gettimeofday(&tt2, NULL);
				//if(txn_cnt > 0 && difftimeval(tt2, tt1)>1)pDBConnection->outfile<<"END"<<endl;
				//pDBConnection->outfile.flush();
			} catch(CSocketErr *pErr) {
				sockDrv.dbt5Disconnect();

				ostringstream osErr;
				osErr << "Error on Receive: " << pErr->ErrorText() <<
						" at BrokerageHouse::workerThread" << endl;
				pThrParam->pBrokerageHouse->logErrorMessage(osErr.str());
				delete pErr;

				// The socket has been closed, break and let this thread die.
				break;
			}
loop:
			timeval t1, t2;
			double exec_time;
		 	gettimeofday(&t1, NULL);

			commit = true;
			iRet = CBaseTxnErr::SUCCESS;
			try {
				//  Parse Txn type
				switch (pMessage->TxnType) {

				/*case BROKER_VOLUME:
					iRet = pThrParam->pBrokerageHouse->RunBrokerVolume(
							&(pMessage->TxnInput.BrokerVolumeTxnInput),
							brokerVolume);
					break;
				case CUSTOMER_POSITION:
					iRet = pThrParam->pBrokerageHouse->RunCustomerPosition(
							&(pMessage->TxnInput.CustomerPositionTxnInput),
							customerPosition);
					break;
				case MARKET_FEED:
					iRet = pThrParam->pBrokerageHouse->RunMarketFeed(
							&(pMessage->TxnInput.MarketFeedTxnInput), marketFeed);
					break;
				case MARKET_WATCH:
					iRet = pThrParam->pBrokerageHouse->RunMarketWatch(
							&(pMessage->TxnInput.MarketWatchTxnInput), marketWatch);
					break;
				case SECURITY_DETAIL:
					iRet = pThrParam->pBrokerageHouse->RunSecurityDetail(
							&(pMessage->TxnInput.SecurityDetailTxnInput),
							securityDetail);
					break;
				case TRADE_LOOKUP:
					iRet = pThrParam->pBrokerageHouse->RunTradeLookup(
							&(pMessage->TxnInput.TradeLookupTxnInput), tradeLookup);
					break;*/
#ifdef TRADEORDER
				case TRADE_ORDER:
					iRet = pThrParam->pBrokerageHouse->RunTradeOrder(
							&(pMessage->TxnInput.TradeOrderTxnInput), tradeOrder);
					break;
#endif
#ifdef TRADEMIX
				case TRADE_ORDER:
					iRet = pThrParam->pBrokerageHouse->RunTradeOrder(
							&(pMessage->TxnInput.TradeOrderTxnInput), tradeOrder);
					break;

				case TRADE_RESULT:
					iRet = pThrParam->pBrokerageHouse->RunTradeResult(
							&(pMessage->TxnInput.TradeResultTxnInput), tradeResult);
					break;
#endif
#ifdef TRADESTATUS
				case TRADE_STATUS:
					iRet = pThrParam->pBrokerageHouse->RunTradeStatus(
							&(pMessage->TxnInput.TradeStatusTxnInput),
							tradeStatus);
					break;
#endif
#ifdef TRADEUPDATE
				case TRADE_UPDATE:
					iRet = pThrParam->pBrokerageHouse->RunTradeUpdate(
							&(pMessage->TxnInput.TradeUpdateTxnInput), tradeUpdate);
					break;
#endif
				/*case DATA_MAINTENANCE:
					iRet = pThrParam->pBrokerageHouse->RunDataMaintenance(
							&(pMessage->TxnInput.DataMaintenanceTxnInput),
							dataMaintenance);
					break;
				case TRADE_CLEANUP:
					iRet = pThrParam->pBrokerageHouse->RunTradeCleanup(
							&(pMessage->TxnInput.TradeCleanupTxnInput),
							tradeCleanup);
					break;*/
				default:
					//cout << "wrong txn type" << endl;
					iRet = ERR_TYPE_WRONGTXN;
				}
					txn_cnt++;
					pDBConnection->txn_cnt = txn_cnt;
					if(txn_cnt==1)gettimeofday(&(t_start_values[pThrParam->t_id]), NULL);
			} catch (const char *str) {

			pDBConnection->rollback();
#ifdef CAL_RESP_TIME
//			gettimeofday(&t2, NULL);
//			exec_time = difftimeval(t2, t1);
//			txn_time += exec_time;
			//pDBConnection->append_profile_node(t1, t2, pMessage->TxnType, false);
//			pDBConnection->outfile<<"error: "<<str<<endl;
//#ifdef PROFILE_EACH_QUERY
//			pDBConnection->print_profile_query();
//#endif
//			pDBConnection->outfile.flush();
#endif
				//ostringstream msg;
				//msg << time(NULL) << " " << (long long) pthread_self() << " " <<
				//		szTransactionName[pMessage->TxnType] << "; "<<str<<endl;
				//pThrParam->pBrokerageHouse->logErrorMessage(msg.str());
				iRet = CBaseTxnErr::EXPECTED_ROLLBACK;
				//cout<<"query fail:"<<str<<endl;

				commit = false;
				abort_cnt++;
				pDBConnection->abort_cnt = abort_cnt;
				//XXX:debug for trade result
			}
			gettimeofday(&t2, NULL);
			exec_time = difftimeval(t2, t1);

			txn_time += exec_time;
			pDBConnection->txn_time = txn_time;
#ifdef CAL_RESP_TIME

//			pDBConnection->append_profile_node(t1, t2, pMessage->TxnType, true);
//			pDBConnection->outfile<<commit<<" start=( "<<t1.tv_sec<<" "<<t1.tv_usec<<" ), end=( "<<t2.tv_sec<<" "<<t2.tv_usec<<" ), "<<exec_time<<", txn_cnt = "<<txn_cnt<<"total: "<<txn_time<<endl;
#ifdef PROFILE_EACH_QUERY
//			pDBConnection->print_profile_query();
#endif
//			pDBConnection->outfile.flush();

#endif
			// send status to driver
			Reply.iStatus = iRet;
			try {
				sockDrv.dbt5Send(reinterpret_cast<void *>(&Reply), sizeof(Reply));
			} catch(CSocketErr *pErr) {
				sockDrv.dbt5Disconnect();

				ostringstream osErr;
				osErr << "Error on Send: " << pErr->ErrorText() <<
						" at BrokerageHouse::workerThread" << endl;
				pThrParam->pBrokerageHouse->logErrorMessage(osErr.str());
				delete pErr;

				// The socket has been closed, break and let this thread die.
				break;
			}
		} while (true);

//		delete pDBConnection; // close connection with the database
		close(pThrParam->iSockfd); // close socket connection with the driver
		delete pThrParam;
		delete pMessage;
	} catch (CSocketErr *err) {
	}
	return NULL;
}
Exemple #10
0
void *db_worker(void *data)
{
	int id = *((int *) data); /* Whoa... */

	struct transaction_queue_node_t *node;
	struct db_context_t *dbc;
	char code;
	double response_time;
	struct timeval rt0, rt1;
	int local_seed;
	pid_t pid;
	pthread_t tid;
	extern unsigned int seed;
	int status;

	/* Each thread needs to seed in Linux. */
    tid = pthread_self();
    pid = getpid();
	if (seed == -1) {
		struct timeval tv;
		unsigned long junk; /* Purposely used uninitialized */

		local_seed = pid;
		gettimeofday(&tv, NULL);
		local_seed ^=  tid ^ tv.tv_sec ^ tv.tv_usec ^ junk;
	} else {
		local_seed = seed;
	}
	set_random_seed(local_seed);

	/* Open a connection to the database. */
	dbc = db_init();

	if (!exiting && connect_to_db(dbc) != OK) {
		LOG_ERROR_MESSAGE("connect_to_db() error, terminating program");
		printf("cannot connect to database(see details in error.log file, exiting...\n");
		exit(1);
	}

	while (!exiting) {
		/*
		 * I know this loop will prevent the program from exiting
		 * because of the dequeue...
		 */
		node = dequeue_transaction();
		if (node == NULL) {
			LOG_ERROR_MESSAGE("dequeue was null");
			continue;
		}

		/* Execute transaction and record the response time. */
		if (gettimeofday(&rt0, NULL) == -1) {
			perror("gettimeofday");
		}

		status =
			process_transaction(node->client_data.transaction,
								dbc, &node->client_data.transaction_data);
		if (status == ERROR) {
			LOG_ERROR_MESSAGE("process_transaction() error on %s",
							  transaction_name[
								  node->client_data.transaction]);
			/*
			 * Assume this isn't a fatal error, send the results
			 * back, and try processing the next transaction.
			 */
			while (need_reconnect_to_db(dbc))
			{
				LOG_ERROR_MESSAGE("try to reconnect to database");
				disconnect_from_db(dbc);

				if (connect_to_db(dbc) != OK)
				{
					LOG_ERROR_MESSAGE("reconnect to database error, try again after sleep 5 seconds");
					sleep(5);
				}
			}
		}

		if (status == OK) {
			code = 'C';
		} else if (status == STATUS_ROLLBACK) {
			code = 'R';
		} else if (status == ERROR) {
			code = 'E';
		}

		if (gettimeofday(&rt1, NULL) == -1) {
			perror("gettimeofday");
		}

		response_time = difftimeval(rt1, rt0);
		log_transaction_mix(node->client_data.transaction, code, response_time,
							mode_altered > 0 ? node->termworker_id : node->term_id);
		enqueue_terminal(node->termworker_id, node->term_id);

		/* Keep track of how many transactions this thread has done. */
		++worker_count[id];

		/* Keep track of then the last transaction was execute. */
		time(&last_txn[id]);
	}

	/* Disconnect from the database. */
	disconnect_from_db(dbc);

	free(dbc);

	sem_wait(&db_worker_count);

	return NULL;        /* keep compiler quiet */
}
Exemple #11
0
 uint64_t elapsed(const struct timeval& now)
 {
     uint64_t diff = difftimeval(now, this->now);
     this->now = now;
     return diff;
 }
Exemple #12
0
void *terminal_worker(void *data)
{
#ifndef STANDALONE
	int length;
	int sockfd;
#endif /* NOT STANDALONE */

	struct terminal_context_t *tc;
	struct client_transaction_t client_data;
	double threshold;
	int keying_time;
	struct timespec thinking_time, rem;
	int mean_think_time; /* In milliseconds. */
	struct timeval rt0, rt1;
	double response_time;
	extern int errno;
	int rc;
	int local_seed;

#ifdef STANDALONE
	struct db_context_t dbc;
	struct transaction_queue_node_t *node =
			(struct transaction_queue_node_t *)
			malloc(sizeof(struct transaction_queue_node_t));
	extern char sname[32];
	extern int exiting;
#ifdef LIBPQ
	extern char postmaster_port[32];
#endif /* LIBPQ */

#ifdef LIBMYSQL
	extern char dbt2_mysql_port[32];
#endif /* LIBMYSQL */

#endif /* STANDALONE */

	tc = (struct terminal_context_t *) data;
	/* Each thread needs to seed in Linux. */
	if (seed == -1) {
		struct timeval tv;
		unsigned long junk; /* Purposely used uninitialized */

		gettimeofday(&tv, NULL);
		local_seed = getpid() ^ (int) pthread_self() ^ tv.tv_sec ^
				tv.tv_usec ^ junk;
	} else {
		local_seed = seed;
	}
	printf("seed: %u\n", local_seed);
	fflush(stdout);
	srand(local_seed);

#ifdef STANDALONE
#ifdef ODBC
	db_init(sname, DB_USER, DB_PASS);
#endif /* ODBC */
#ifdef LIBPQ
	db_init(DB_NAME, sname, postmaster_port);
#endif /* LIBPQ */
#ifdef LIBMYSQL
	printf("CONNECTED TO DB |%s| |%s| |%s|\n", DB_NAME, sname, dbt2_mysql_port);
	db_init(sname, "", dbt2_mysql_port);
#endif /* LIBMYSQL */

	if (!exiting && connect_to_db(&dbc) != OK) {
		LOG_ERROR_MESSAGE("db_connect() error, terminating program");
		printf("cannot connect to database, exiting...\n");
		exit(1);
	}
#else
	/* Connect to the client program. */
	sockfd = connect_to_client(hostname, client_port);
	if (sockfd < 1) {
		LOG_ERROR_MESSAGE( "connect_to_client() failed, thread exiting...");
		printf("connect_to_client() failed, thread exiting...");
		pthread_exit(NULL);
	}
#endif /* STANDALONE */

	do {
		if (mode_altered == 1) {
			/*
			 * Determine w_id and d_id for the client per
			 * transaction.
			 */
			tc->w_id = w_id_min + get_random(w_id_max - w_id_min + 1);
			tc->d_id = get_random(table_cardinality.districts) + 1;
		}

		/*
		 * Determine which transaction to execute, minimum keying time,
		 * and mean think time.
		 */
		threshold = get_percentage();
		if (threshold < transaction_mix.new_order_threshold) {
			client_data.transaction = NEW_ORDER;
			keying_time = key_time.new_order;
			mean_think_time = think_time.new_order;
		} else if (transaction_mix.payment_actual != 0 &&
			threshold < transaction_mix.payment_threshold) {
			client_data.transaction = PAYMENT;
			keying_time = key_time.payment;
			mean_think_time = think_time.payment;
		} else if (transaction_mix.order_status_actual != 0 &&
			threshold < transaction_mix.order_status_threshold) {
			client_data.transaction = ORDER_STATUS;
			keying_time = key_time.order_status;
			mean_think_time = think_time.order_status;
		} else if (transaction_mix.delivery_actual != 0 &&
			threshold < transaction_mix.delivery_threshold) {
			client_data.transaction = DELIVERY;
			keying_time = key_time.delivery;
			mean_think_time = think_time.delivery;
		} else {
			client_data.transaction = STOCK_LEVEL;
			keying_time = key_time.stock_level;
			mean_think_time = think_time.stock_level;
		}

#ifdef DEBUG
		printf("executing transaction %c\n", 
			transaction_short_name[client_data.transaction]);
		fflush(stdout);
		LOG_ERROR_MESSAGE("executing transaction %c", 
			transaction_short_name[client_data.transaction]);
#endif /* DEBUG */

		/* Generate the input data for the transaction. */
		if (client_data.transaction != STOCK_LEVEL) {
			generate_input_data(client_data.transaction,
					&client_data.transaction_data, tc->w_id);
		} else {
			generate_input_data2(client_data.transaction,
					&client_data.transaction_data, tc->w_id, tc->d_id);
		}

		/* Keying time... */
		pthread_mutex_lock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		++terminal_state[KEYING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		if (time(NULL) < stop_time) {
			sleep(keying_time);
		} else {
			break;
		}
		pthread_mutex_lock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		--terminal_state[KEYING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[KEYING][client_data.transaction]);

		/* Note this thread is executing a transation. */
		pthread_mutex_lock(
				&mutex_terminal_state[EXECUTING][client_data.transaction]);
		++terminal_state[EXECUTING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[EXECUTING][client_data.transaction]);
		/* Execute transaction and record the response time. */
		if (gettimeofday(&rt0, NULL) == -1) {
			perror("gettimeofday");
		}
#ifdef STANDALONE
		memcpy(&node->client_data, &client_data, sizeof(client_data));
/*
		enqueue_transaction(node);
		node = get_node();
		if (node == NULL) {
			LOG_ERROR_MESSAGE("Cannot get a transaction node.\n");
		}
*/
		rc = process_transaction(node->client_data.transaction, &dbc,
				&node->client_data.transaction_data);
		if (rc == ERROR) {
			LOG_ERROR_MESSAGE("process_transaction() error on %s",
					transaction_name[node->client_data.transaction]);
		}
#else /* STANDALONE */
		length = send_transaction_data(sockfd, &client_data);
		length = receive_transaction_data(sockfd, &client_data);
		rc = client_data.status;
#endif /* STANDALONE */
		if (gettimeofday(&rt1, NULL) == -1) {
			perror("gettimeofday");
		}
		response_time = difftimeval(rt1, rt0);
		pthread_mutex_lock(&mutex_mix_log);
		if (rc == OK) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					transaction_short_name[client_data.transaction],
					response_time, (int) pthread_self());
		} else if (rc == STATUS_ROLLBACK) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					toupper(transaction_short_name[client_data.transaction]),
					response_time, (int) pthread_self());
		} else if (rc == ERROR) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					'E', response_time, (int) pthread_self());
		}
		fflush(log_mix);
		pthread_mutex_unlock(&mutex_mix_log);
		pthread_mutex_lock(&mutex_terminal_state[EXECUTING][client_data.transaction]);
		--terminal_state[EXECUTING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[EXECUTING][client_data.transaction]);

		/* Thinking time... */
		pthread_mutex_lock(&mutex_terminal_state[THINKING][client_data.transaction]);
		++terminal_state[THINKING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[THINKING][client_data.transaction]);
		if (time(NULL) < stop_time) {
			thinking_time.tv_nsec = (long) get_think_time(mean_think_time);
			thinking_time.tv_sec = (time_t) (thinking_time.tv_nsec / 1000);
			thinking_time.tv_nsec = (thinking_time.tv_nsec % 1000) * 1000000;
			while (nanosleep(&thinking_time, &rem) == -1) {
				if (errno == EINTR) {
					memcpy(&thinking_time, &rem, sizeof(struct timespec));
				} else {
					LOG_ERROR_MESSAGE(
							"sleep time invalid %d s %ls ns",
							thinking_time.tv_sec,
							thinking_time.tv_nsec);
					break;
				}
			}
		}
		pthread_mutex_lock(&mutex_terminal_state[THINKING][client_data.transaction]);
		--terminal_state[THINKING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[THINKING][client_data.transaction]);
	} while (time(NULL) < stop_time);

#ifdef STANDALONE
	/*recycle_node(node);*/
#endif /* STANDALONE */
	/* Note when each thread has exited. */
	pthread_mutex_lock(&mutex_mix_log);
	fprintf(log_mix, "%d,TERMINATED,%d\n", (int) time(NULL),
			(int) pthread_self());
	fflush(log_mix);
	pthread_mutex_unlock(&mutex_mix_log);
	return NULL; /* keep the compiler quiet */
}
Exemple #13
0
static PyObject *UtilsC_expectation_H(PyObject *self, PyObject *args){
    PyObject *XGamma,*Y,*y_tilde,*m_A,*m_H,*X,*R,*Gamma,*Sigma_A,*sigma_epsilone,*Sigma_H,*QQ_barnCond;
    PyArrayObject *XGammaarray,*QQ_barnCondarray,*Yarray,*y_tildearray,*Rarray,*m_Aarray,*m_Harray,*sigma_epsilonearray,*Sigma_Harray,*Xarray,*Gammaarray,*Sigma_Aarray;
    int j,J,m,m2,d,D,nCond,Nrep,nr;
    npy_float64 scale,sigmaH;
    PyArg_ParseTuple(args, "OOOOOOOOOOOOiiiidd",&XGamma,&QQ_barnCond,&sigma_epsilone,&Gamma,&R,&Sigma_H,&Y,&y_tilde,&m_A,&m_H,&Sigma_A,&X,&J,&D,&nCond,&Nrep,&scale,&sigmaH);
    Xarray   = (PyArrayObject *) PyArray_ContiguousFromObject(X,PyArray_INT,3,3);
    m_Aarray = (PyArrayObject *) PyArray_ContiguousFromObject(m_A,PyArray_FLOAT64,2,2);
    Rarray = (PyArrayObject *) PyArray_ContiguousFromObject(R,PyArray_FLOAT64,2,2);
    m_Harray = (PyArrayObject *) PyArray_ContiguousFromObject(m_H,PyArray_FLOAT64,1,1);
    y_tildearray = (PyArrayObject *) PyArray_ContiguousFromObject(y_tilde,PyArray_FLOAT64,2,2);
    sigma_epsilonearray = (PyArrayObject *) PyArray_ContiguousFromObject(sigma_epsilone,PyArray_FLOAT64,1,1);
    Yarray   = (PyArrayObject *) PyArray_ContiguousFromObject(Y,PyArray_FLOAT64,2,2);
    Sigma_Harray   = (PyArrayObject *) PyArray_ContiguousFromObject(Sigma_H,PyArray_FLOAT64,2,2);
    Gammaarray   = (PyArrayObject *) PyArray_ContiguousFromObject(Gamma,PyArray_FLOAT64,2,2);
    Sigma_Aarray = (PyArrayObject *) PyArray_ContiguousFromObject(Sigma_A,PyArray_FLOAT64,3,3);
    QQ_barnCondarray = (PyArrayObject *) PyArray_ContiguousFromObject(QQ_barnCond,PyArray_FLOAT64,4,4);
    XGammaarray = (PyArrayObject *) PyArray_ContiguousFromObject(XGamma,PyArray_FLOAT64,3,3);
    npy_float64 *S,*H,*tmp,*tmpT,*GGamma,*tmp2;
    npy_float64 *yy_tilde,*Y_bar_tilde,*Q_bar,*Q_barnCond;
    struct timeval tstart, tend;

    S = malloc(sizeof(npy_float64)*Nrep);
    H = malloc(sizeof(npy_float64)*D);
    tmp = malloc(sizeof(npy_float64)*Nrep*D);
    tmpT = malloc(sizeof(npy_float64)*Nrep*D);
    GGamma = malloc(sizeof(npy_float64)*Nrep*Nrep);
    tmp2 = malloc(sizeof(npy_float64)*Nrep*D);
    yy_tilde = malloc(sizeof(npy_float64)*Nrep);
    Y_bar_tilde = malloc(sizeof(npy_float64)*D);
    Q_bar = malloc(sizeof(npy_float64)*D*D);
    Q_barnCond = malloc(sizeof(npy_float64)*nCond*nCond*D*D);

    for (d=0;d<Nrep;d++){
        for (nr=0;nr<Nrep;nr++){
            GGamma[d*Nrep + nr] = GetValue(Gammaarray,nr,d);
        }
    }
    for (d=0;d<D;d++){
        for (nr=0;nr<D;nr++){
            Q_bar[d*D+nr] = GetValue(Rarray,d,nr) * scale/sigmaH;
        }
        Y_bar_tilde[d] = 0;
    }
    gettimeofday(&tstart, NULL);
    for (j=0;j<J;j++){
        if (GetValue1D(sigma_epsilonearray,j) < eps) GetValue1D(sigma_epsilonearray,j) = eps;
        for (nr=0;nr<Nrep;nr++){
            yy_tilde[nr] = GetValue(y_tildearray,nr,j);
            for (d=0;d<D;d++){   
                tmp[nr*D + d] = 0;
                tmp2[nr*D + d] = 0;
                tmpT[nr*D + d] = 0;
            }
        }
        for (m=0;m<nCond;m++){
            for (nr=0;nr<Nrep;nr++){  
                for (d=0;d<D;d++){
                    tmp2[d*Nrep + nr] += GetValue3D(XGammaarray,m,d,nr) * GetValue(m_Aarray,j,m) / GetValue1D(sigma_epsilonearray,j);
                    tmpT[d*Nrep+nr] += GetValue(m_Aarray,j,m) * GetValue3DInt(Xarray,m,nr,d);
                }
            }
        }
        prodaddMat(tmp2,yy_tilde,Y_bar_tilde,D,1,Nrep);
        for (m=0;m<nCond;m++){
            for (m2=0;m2<nCond;m2++){
                for (d=0;d<D;d++){
                    for (nr=0;nr<D;nr++){
                        Q_bar[d*D+nr] += GetValue4D(QQ_barnCondarray,m,m2,d,nr) * ( GetValue3D(Sigma_Aarray,m,m2,j) + GetValue(m_Aarray,j,m2) * GetValue(m_Aarray,j,m)) / GetValue1D(sigma_epsilonearray,j) ;
                    }
                }
            }
        }
    }
    gettimeofday(&tend, NULL);
    if (profiling)
        printf ("Ytilde and Q_bar step took %ld msec\n", difftimeval(&tend,&tstart));

    gettimeofday(&tstart, NULL);
    invMat(Q_bar,D);
    gettimeofday(&tend, NULL);
    if (profiling)
        printf ("Inv Q_bar step took %ld msec\n", difftimeval(&tend,&tstart));

    gettimeofday(&tstart, NULL);
    prodMat2(Q_bar,Y_bar_tilde,H,D,1,D);
    gettimeofday(&tend, NULL);
    if (profiling)
        printf ("Prod Q_bar Y_bar step took %ld msec\n", difftimeval(&tend,&tstart));

    for (d=0;d<D;d++){
        GetValue1D(m_Harray,d) = H[d];
        for (m=0;m<D;m++){
            GetValue(Sigma_Harray,d,m) = Q_bar[d*D+m];
        }
    }
    
    free(S);
    free(H);
    free(tmp);
    free(tmpT);
    free(GGamma);
    free(tmp2);
    free(yy_tilde);
    free(Y_bar_tilde);
    free(Q_bar);
    free(Q_barnCond);
    Py_DECREF(QQ_barnCondarray);
    Py_DECREF(XGammaarray);
    Py_DECREF(Sigma_Harray);
    Py_DECREF(Sigma_Aarray);
    Py_DECREF(m_Aarray);
    Py_DECREF(m_Harray);
    Py_DECREF(Xarray);
    Py_DECREF(Yarray);
    Py_DECREF(Rarray);
    Py_DECREF(y_tildearray);
    Py_DECREF(Gammaarray);
    Py_DECREF(sigma_epsilonearray);
    Py_INCREF(Py_None);
    return Py_None;
}   
Exemple #14
0
void *db_worker(void *data)
{
        int id = *((int *) data); /* Whoa... */
#ifndef STANDALONE
        int length;
#endif /* NOT STANDALONE */
        struct transaction_queue_node_t *node;
        struct db_context_t dbc;
#ifdef STANDALONE
        struct timeval rt0, rt1;
        double response_time;
#endif /* STANDALONE */

        /* Open a connection to the database. */
#ifdef ODBC
        printf("connect to ODBC server with parameters: DSN: |%s| user: |%s| pass: |%s|\n", sname, dbt2_user, dbt2_pass);
        db_init(sname, dbt2_user, dbt2_pass);
#endif /* ODBC */
#ifdef LIBPQ
        db_init(DB_NAME, sname, postmaster_port);
#endif /* LIBPQ */

#ifdef LIBMYSQL
       printf("connect to mysql server with parameters: db_name: |%s| host: |%s| user: |%s| pass: |%s| port: |%s| socket: |%s|\n", sname, dbt2_mysql_host, dbt2_user, dbt2_pass, dbt2_mysql_port, dbt2_mysql_socket);
       db_init(sname, dbt2_mysql_host , dbt2_user, dbt2_pass, dbt2_mysql_port, dbt2_mysql_socket);
#endif /* LIBMYSQL */


        if (!exiting && connect_to_db(&dbc) != OK) {
                LOG_ERROR_MESSAGE("connect_to_db() error, terminating program");
                printf("cannot connect to database(see details in error.log file, exiting...\n");
                exit(1);
        }

        while (!exiting) {
                /*
                 * I know this loop will prevent the program from exiting
                 * because of the dequeue...
                 */
                node = dequeue_transaction();
                if (node == NULL) {
                        LOG_ERROR_MESSAGE("dequeue was null");
                        continue;
                }
#ifdef STANDALONE
                if (gettimeofday(&rt0, NULL) == -1) {
                        perror("gettimeofday");
                }
#endif /* STANDALONE */
                node->client_data.status =
                        process_transaction(node->client_data.transaction,
                        &dbc, &node->client_data.transaction_data);
                if (node->client_data.status == ERROR) {
                        LOG_ERROR_MESSAGE("process_transaction() error on %s",
                                transaction_name[
                                node->client_data.transaction]);
                        /*
                         * Assume this isn't a fatal error, send the results
                         * back, and try processing the next transaction.
                         */
                }
                else
                {
                  if (node->client_data.status == ERROR_FATAL) 
                  {
                        LOG_ERROR_MESSAGE("process_transaction() fatal error on %s",
                                transaction_name[
                                node->client_data.transaction]);
                        LOG_ERROR_MESSAGE("stopping db_thread");
                        exiting=1;
                  }
                }

#ifdef STANDALONE
                if (gettimeofday(&rt1, NULL) == -1) {
                        perror("gettimeofday");
                }
                response_time = difftimeval(rt1, rt0);
                pthread_mutex_lock(&mutex_mix_log);
                fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
                transaction_short_name[node->client_data.transaction],
                        response_time, (int) pthread_self());
                        fflush(log_mix);
                pthread_mutex_unlock(&mutex_mix_log);
#endif /* STANDALONE */

#ifndef STANDALONE
                length = send_transaction_data(node->s, &node->client_data);
                if (length == ERROR) {
                        LOG_ERROR_MESSAGE("send_transaction_data() error");
                        /*
                         * Assume this isn't a fatal error and try processing
                         * the next transaction.
                         */
                }
#endif /* NOT STANDALONE */
                pthread_mutex_lock(&mutex_transaction_counter[REQ_EXECUTING][
                        node->client_data.transaction]);
                --transaction_counter[REQ_EXECUTING][
                        node->client_data.transaction];
                pthread_mutex_unlock(&mutex_transaction_counter[REQ_EXECUTING][
                        node->client_data.transaction]);
                recycle_node(node);

                /* Keep track of how many transactions this thread has done. */
                ++worker_count[id];

                /* Keep track of then the last transaction was execute. */
                time(&last_txn[id]);
        }

        /* Disconnect from the database. */
        disconnect_from_db(&dbc);

        sem_wait(&db_worker_count);

        return NULL;        /* keep compiler quiet */
}
Exemple #15
0
// wildi ToDo this thread must go into a separate file
void *
oak_digin_thread(void * args)
{
  int ret ;
  // wildi ToDo int *values = xmalloc(devInfo.numberOfChannels * sizeof(int));
  int *values = malloc(200 * sizeof(int));
  int rd_stat;
  int bits = 0xff;
  int print_bits = 0xff;
  int bit;
  int i ;
  int lastDoorStateTest= DS_UNDEF ;
  int lastDoorState= DS_UNDEF ;
  int stop_motor= STOP_MOTOR_UNDEFINED ;
  char bits_str[32] ;
  struct timespec sl ;
  struct timespec rsl ;
  static struct timeval time_last_stat;
  static struct timeval time_enq;
  gettimeofday(&time_last_stat, NULL);
  // debug
  int print =0 ;
  oak_thread_state= THREAD_STATE_UNDEFINED ; // make it "reentrant"

  sl.tv_sec= 0. ;
  sl.tv_nsec= (long ) 200 * 1000 * 1000 ;

  if( test_oak== TEST_OAK) {
    fprintf( stderr,  "oak_digin_thread: test_oak== TEST_OK, sleep %d milliseconds\n", SLEEP_TEST_OAK_MILLISECONDS);
  } 
  fprintf( stderr,  "oak_digin_thread: thread started\n");

  while (1) {

    oak_digin_thread_heart_beat++ ;

    if( oak_digin_thread_heart_beat > HEART_BEAT_UPPER_LIMIT) {
      oak_digin_thread_heart_beat= 0 ;
    }
    rd_stat = readInterruptReport(oakDiginHandle, values);
    if ((rd_stat < 0) && (errno == EINTR)) {
      oak_thread_state= THREAD_STATE_UNDEFINED ;
      // wildi ToDo something sensible here values[1]=
      fprintf( stderr, "oak_digin_thread:  problems reading from oak device\n") ;
    }
    bits      = values[1] & 0xff ;
    print_bits= values[1] & 0xff ;
   
    print= 0 ;
    for (i = 0; i < 8; i++) {
      bit = (print_bits & 0x1) ;
      if( bit) {
	bits_str[7-i]= '1' ;
	print++ ;
      } else {
	bits_str[7-i]= '0' ;
      }
      print_bits = print_bits >> 1;
    }
    bits_str[8]= '\0' ;
    //fprintf( stderr, "oak_digin_thread: doorState=%d, bits %s\n",  doorState, bits_str) ;
    // turn off the motor first

    if((( bits & OAK_MASK_CLOSED) > 0) && (( doorState== DS_STOPPED_CLOSED) || ( doorState== DS_RUNNING_OPEN)))  {
      // let the motor open the door
      stop_motor= STOP_MOTOR_UNDEFINED ;

    } else if((( bits & OAK_MASK_OPENED) > 0) && (( doorState== DS_STOPPED_OPENED) || ( doorState== DS_RUNNING_CLOSE) || ( doorState== DS_RUNNING_CLOSE_UNDEFINED)))  {
      // let the motor close the door
      stop_motor= STOP_MOTOR_UNDEFINED ;

    } else if((( bits & OAK_MASK_CLOSED) > 0) && ( motorState== SSD650V_MS_RUNNING)) { // 2nd expr. necessary not to overload SSD650v on RS 232
      stop_motor= STOP_MOTOR ;
      fprintf( stderr, "oak_digin_thread: found ( bits & OAK_MASK_CLOSED) > 0), bits %s\n",  bits_str) ;

    } else if((( bits & OAK_MASK_OPENED) > 0) && ( motorState== SSD650V_MS_RUNNING)){
      stop_motor= STOP_MOTOR ;
      fprintf( stderr, "oak_digin_thread: found (bits & OAK_MASK_OPENED) > 0), bits %s\n",  bits_str) ;

    } else if ( (bits & OAK_MASK_END_SWITCHES) > 0) {  
      // the motor is turned off and eventually OAK devices too (no cummunication possible)
      stop_motor= STOP_MOTOR ;
    } else if ( (bits & OAK_MASK_END_SWITCHES) == 0) { // both end switches are zero 
      // the door is inbetween, (or beyond the software end switches :-(( = very close to the end switches)
      //fprintf( stderr, "oak_digin_thread:  might be a bad reading from oak device\n") ; // see above ToDo
      // wildi ToDo: not yet defined what to do
    } 

    // test
    if( test_oak== TEST_OAK) {
      if( lastDoorStateTest != doorState) {
	lastDoorStateTest= doorState ;
	gettimeofday(&time_last_stat, NULL);
	fprintf( stderr, "oak_digin_thread:  status change resetting timer\n") ;
      }
      if( motorState== SSD650V_MS_RUNNING) {
	gettimeofday(&time_enq, NULL);
	if (difftimeval(&time_enq, &time_last_stat) > (SLEEP_TEST_OAK_MILLISECONDS * 1000)) { // milliseconds
	  stop_motor= STOP_MOTOR ;
	  fprintf( stderr, "oak_digin_thread: motorState== (DS_RUNNING_OPEN|DS_RUNNING_CLOSE), stopping now, diff %d[msec]\n", (int)difftimeval(&time_enq, &time_last_stat)) ;
	  gettimeofday(&time_last_stat, NULL);
	  fprintf( stderr, "oak_digin_thread: stopping motor  after time ellapsed\n") ;
	}
      }
      if(( print > 0) &&  ( stop_motor != STOP_MOTOR)) {
	stop_motor= STOP_MOTOR ;
	fprintf( stderr, "oak_digin_thread: print stop_motor= STOP_MOTOR \n") ;
      }
    }
    // end test
    // manual mode, in case an endswitch erroneously indicates contact
    if(ignoreEndswitch==NOT_IGNORE_END_SWITCH){
    if( stop_motor== STOP_MOTOR) {
      
      fprintf( stderr, "oak_digin_thread: stopping motor now\n") ;
      while(( ret= motor_off()) != SSD650V_MS_STOPPED) { // 
	fprintf( stderr, "oak_digin_thread: can not turn motor off\n") ;
	ret= nanosleep( &sl, &rsl) ;
	if((errno== EFAULT) || ( errno== EINTR)||( errno== EINVAL ))  {
	  fprintf( stderr, "Error in nanosleep\n") ;
	  errno= 0 ;
	}
      }
      set_setpoint(0.);
      fprintf( stderr, "oak_digin_thread: motor stopped\n") ;
      stop_motor= STOP_MOTOR_UNDEFINED ;
      struct ln_date utm;
      ln_get_date_from_sys( &utm) ;
      sprintf( date_time, "%4d-%02d-%02dT%02d:%02d:%02d", utm.years, utm.months, utm.days, utm.hours, utm.minutes, (int) utm.seconds) ;

    }
    }
    // door status
    if( motorState== SSD650V_MS_STOPPED) {
      // change status here
      if( bits & OAK_MASK_CLOSED) { // true if OAK sees the door
	doorState= DS_STOPPED_CLOSED ;
	if( lastDoorState != doorState) {
	  lastDoorState= doorState ;
	  fprintf( stderr, "oak_digin_thread: state is DS_STOPPED_CLOSED\n") ;
	} 
      } else if( bits & OAK_MASK_OPENED) { // true if OAK sees the door
	doorState= DS_STOPPED_OPENED ;
	if( lastDoorState != doorState) {
	  lastDoorState= doorState ;
	  fprintf( stderr, "oak_digin_thread: state is DS_STOPPED_OPENED\n") ;
	}
      } else {
	doorState= DS_STOPPED_UNDEF ;
	lastDoorState= doorState ;
	//fprintf( stderr, "oak_digin_thread: state is DS_STOPPED_UNDEFINED\n") ;
      }
    } else if( motorState== SSD650V_MS_RUNNING) {
      // keep status here 
      if( doorState == DS_RUNNING_OPEN) {
      } else if( doorState == DS_RUNNING_CLOSE) {
      } else if( doorState == DS_RUNNING_CLOSE_UNDEFINED) {
      } else {
	// should occasianally occur if the door is stopped manually 
	doorState= DS_RUNNING_UNDEF ;
	lastDoorState= doorState ;
	//fprintf( stderr, "oak_digin_thread: motorState== SSD650V_MS_RUNNING, state is DS_RUNNING_UNDEF\n") ;
      }
    } else if( motorState== SSD650V_MS_UNDEFINED) {
      doorState= DS_UNDEF ;
      lastDoorState= doorState ;

      if( bits & OAK_MASK_OPENED) { // true if OAK sees the door
	fprintf( stderr, "oak_digin_thread: state is DS_UNDEF, door is opened, motor is undefined\n") ;
      } else if( bits & OAK_MASK_CLOSED) { // true if OAK sees the door
	fprintf( stderr, "oak_digin_thread: state is DS_UNDEF, door is closed, motor is undefined\n") ;
      } else {
	fprintf( stderr, "oak_digin_thread: state is DS_UNDEF, door is undefined, motor is undefined\n") ;
      }
    } else {
      // should never occur
      doorState= DS_UNDEF ;
      lastDoorState= doorState ;
      fprintf( stderr, "oak_digin_thread: state is DS_UNDEF, should never never occur\n") ;
    }

    CHECK_OAK_CALL(rd_stat); // wildi ToDo: what's that?
  } /* while (1) */
  
  return NULL;
}
    bool interpret_chunk(bool real_time = true) {
        try {
            uint8_t array[AUTOSIZE];

            static_assert(AUTOSIZE >= TRANSPARENT_CHUNK_HEADER_SIZE, "");
            InStream header(array, TRANSPARENT_CHUNK_HEADER_SIZE);

            uint8_t * end = array;
            this->t->recv(&end, header.get_capacity());

            uint8_t  chunk_type = header.in_uint8();
            uint16_t data_size  = header.in_uint16_le();

            timeval last_record_now = this->record_now;
            header.in_timeval_from_uint64le_usec(this->record_now);

            //LOG(LOG_INFO, "chunk_type=%u data_size=%u", chunk_type, data_size);

            end = array;
            this->t->recv(&end, data_size);
            InStream payload(array, end - array);

            switch (chunk_type) {
                case CHUNK_TYPE_META:
                    {
                        uint8_t trm_format_version = payload.in_uint8();
(void)trm_format_version;

                        this->replay_now = tvtime();
                        this->meta_ok    = true;
                    }
                    break;
                case CHUNK_TYPE_FASTPATH:
                    {
                        this->consumer->send_fastpath_data(payload);
                    }
                    break;
                case CHUNK_TYPE_FRONTCHANNEL:
                    {
                        uint8_t  mod_channel_name_length = payload.in_uint8();
                        uint16_t length                  = payload.in_uint16_le();
                        uint16_t chunk_size              = payload.in_uint16_le();
                        uint32_t flags                   = payload.in_uint32_le();

                        char mod_channel_name[256];
                        payload.in_copy_bytes(mod_channel_name, mod_channel_name_length);
                        mod_channel_name[mod_channel_name_length] = 0;

                        const CHANNELS::ChannelDef * front_channel =
                            this->consumer->get_channel_list().get_by_name(mod_channel_name);
                        if (front_channel) {
                            this->consumer->send_to_channel(*front_channel,
                                const_cast<uint8_t *>(payload.in_uint8p(length)), length, chunk_size, flags);
                        }
                    }
                    break;
                case CHUNK_TYPE_SLOWPATH:
                    {
                        uint16_t channelId = payload.in_uint16_le();

                        HStream data(1024, 65535);
                        size_t  length(data_size - sizeof(uint16_t));
                        data.out_copy_bytes(payload.in_uint8p(length), length);
                        data.mark_end();

                        this->consumer->send_data_indication_ex(channelId, data);
                    }
                    break;
                case CHUNK_TYPE_RESIZE:
                    {
                        uint16_t width  = payload.in_uint16_le();
                        uint16_t height = payload.in_uint16_le();
                        uint8_t  bpp    = payload.in_uint8();

                        this->consumer->server_resize(width, height, bpp);
                    }
                    break;
                default:
                    LOG(LOG_ERR, "Unknown chunt type(%d)", chunk_type);
                    throw Error(ERR_TRM_UNKNOWN_CHUNK_TYPE);
            }

            if (real_time && (chunk_type != CHUNK_TYPE_META)) {
                timeval  now     = tvtime();
                uint64_t elapsed = difftimeval(now, this->replay_now);

                this->replay_now = now;

                uint64_t record_elapsed = difftimeval(this->record_now, last_record_now);

                if (elapsed <= record_elapsed) {
                    struct timespec wtime     = {
                          static_cast<time_t>((record_elapsed - elapsed) / 1000000LL)
                        , static_cast<time_t>(((record_elapsed - elapsed) % 1000000LL) * 1000)
                        };
                    struct timespec wtime_rem = { 0, 0 };

                    while ((nanosleep(&wtime, nullptr) == -1) && (errno == EINTR)) {
                        wtime = wtime_rem;
                    }
                }
            }
        }
        catch (Error & e){
            LOG(LOG_INFO,"receive error %u : end of transport", e.id);
            // receive error, end of transport
            return false;
        }

        return true;
    }