Beispiel #1
0
void LoggedMeasurement::makeMeasurement()
{
//	measurementTimer.reset();

	MixedData newResult;
	MixedData delta;
	MixedData sigmaSqrd;
	
	getDeviceData(newResult);
	if(measurement == 0)
		delta.setValue(newResult);
	else
		delta.setValue(newResult - measurement);

	thresholdExceeded = false;

	//Does the -1 have to be on the rhs?
	if(sigma != 0 && ((delta < sigma*threshold*(-1)) || (delta > sigma*threshold) ) )
	{
		//spurious data point detected
		thresholdExceeded = true;
		std::cerr << "Threshold Exceeded" << std::endl;
		measurement.setValue(newResult);
		numberAveragedMeasurements = 0;
	}
	else
	{
		//the measurement average resets after each save interval
		measurement.setValue((measurement * numberAveragedMeasurements + newResult) / (numberAveragedMeasurements + 1));
	}

	numberAveragedMeasurements++;

	//standard deviation sigma always includes a contribution from the previous sigma (before numberAveragedMeasurements is reset).
	sigmaSqrd.setValue(
		(sigma*sigma * numberAveragedMeasurements + delta*delta) / (numberAveragedMeasurements + 1) 
		);
	sigma.setValue(sigmaSqrd.sqroot());

	if (numberAveragedMeasurements >= maxNumberToAverage || thresholdExceeded)
	{
		resultIsReady = true;
	}
}
Beispiel #2
0
void HandleDevices(){
	//char uriStr[] = "coap://[aaab::ff:fe00:3]:5863/humidity_sht";

	datapaketcontainer *dpc;
	time_t rawtime;
	struct tm *now;
	struct tm lastPaketTime;
	static struct tm *nextScan;
	double diff;
	static Ldevice *lastDevice;
	Ldevice *d;
	int nextScanInt;
  char log[LOG_BUF_LEN];


	memset(&lastPaketTime, 0, sizeof(struct tm));

	//get systemtime
	time(&rawtime);
	now = gmtime(&rawtime);
  
  if(now->tm_sec  > 3 || now->tm_sec < 2){
      return;
  }
  
	if(nextScan == NULL){	//first call of this function
		nextScan = malloc(sizeof(struct tm));
		if(nextScan == NULL)
			return;
		memcpy(nextScan, now, sizeof(struct tm));
	}else{	// time to get data
		diff = difftime(mktime(now), mktime(nextScan));
		if(diff < 1.0 && diff > (-MAX_GET_DEVICE_DATA_INTERVAL)){
			return;
		}
	}
	if(nextScan == NULL)
		return;

	d = LDCgetFirstDevice();
	if(lastDevice != NULL){
		while(d != lastDevice){
			d = LDCgetNextDevice();
			if(d == NULL){
				break;
			}
		}
		d = LDCgetNextDevice();
		if(d == NULL){
			d = LDCgetFirstDevice();
		}
		lastDevice = d;
	}else{
		lastDevice = d;
	}

	if(LDCgetNextDevice() == NULL){
		nextScanInt =GET_FIRST_DEVICE_DATA_INTERVAL;
	}else{
		nextScanInt =GET_NEXT_DEVICE_DATA_INTERVAL;
	}

	time(&rawtime);
	now = gmtime(&rawtime);
	free(nextScan);
	nextScan = malloc(sizeof(struct tm));
	if(nextScan == NULL)
		return;
	memcpy(nextScan, now, sizeof(struct tm));
	nextScan->tm_sec += nextScanInt;
	mktime(nextScan);
	nextScan->tm_sec = 0;

	if(d == NULL){
		return;
	}

  lielas_log((unsigned char*)"**********", LOG_LEVEL_DEBUG);
  snprintf(log, LOG_BUF_LEN, "Start device scanning: %s", d->address);
  lielas_log((unsigned char*)log, LOG_LEVEL_DEBUG);
  
	//turn cycle mode off and sync if out of sync
  if(setCycleMode(d, LWP_CYCLE_MODE_OFF)){
    lielas_log((unsigned char*)"failed to switch off cycle mode", LOG_LEVEL_DEBUG);
    return;
  }
	sleep(5);


	dpc = CreateDatapaketcontainer();
	if(dpc == NULL)
		return;

	if(!getDeviceData(d, dpc)){
		SaveDataPaketContainerToDatabase(dpc);
	}
	DeleteDatapaketcontainer(dpc);

  //set device date and time
	DeviceSetDatetime(d);
  
  //set interval if changed
  setLoggerMint(d, d->modul[1]);

  //turn cycle mode on again
  setCycleMode(d, LWP_CYCLE_MODE_ON);
  
  lielas_log((unsigned char*)"End device scanning", LOG_LEVEL_DEBUG);
  lielas_log((unsigned char*)"**********", LOG_LEVEL_DEBUG);

}
/**
 * Entry point of the Timer application.
 * It takes the name of the configuration file (use
 * example_timer_config.xml).
 *
 * @see example_timer_config.xml
 */
int main(int argc, char** argv)
{
    if (argc != 5)
    {
        printf("Usage: %s <config_file> <device_uri> <const_mem> <var_mem>\n"
               " where <config_file> - Address of the configuration file;\n"
               "       <device_uri>  - URI at which the device will be "
               "registered;\n"
               "       <const_mem>   - Additional memory, which will be "
               "allocated all\n"
               "                       the time;\n"
               "       <var_mem>     - Amount of memory which adapter will try "
               "to allocate\n"
               "                       and release periodically.\n", argv[0]);
        return -1;
    }

    // load connection settings from file
    int error = obix_loadConfigFile(argv[1]);
    if (error != OBIX_SUCCESS)
    {
    	log_error("Unable to load configuration file.\n");
        return error;
    }

    // open connection to the server
    error = obix_openConnection(CONNECTION_ID);
    if (error != OBIX_SUCCESS)
    {
    	log_error("Unable to establish connection with oBIX server.\n");
        return error;
    }

    // register timer device at the server
    char* deviceData = getDeviceData(argv[2]);
    int deviceId = obix_registerDevice(CONNECTION_ID, deviceData);
    free(deviceData);
    if (deviceId < 0)
    {
    	log_error("Unable to register device at oBIX server.\n");
        return deviceId;
    }

    // register listener of the "reset" field
    // it will be invoked every time when someone changes
    // "reset" field at the server
    int listenerId = obix_registerListener(CONNECTION_ID,
                                           deviceId,
                                           "reset",
                                           &resetListener);
    if (listenerId < 0)
    {
    	log_error("Unable to register update listener.\n");
        return listenerId;
    }

    // Initialize separate thread for timer
    _taskThread = ptask_init();
    if (_taskThread == NULL)
    {
    	log_error("Unable to start separate thread for timer.\n");
        return -1;
    }
    // start updating time once in a second
    _timerTaskId = ptask_schedule(_taskThread, &timerTask, &deviceId,
                                  1000, EXECUTE_INDEFINITE);

    printf("Test device is successfully registered at the server at the "
           "following address: %s\n", argv[2]);

    // allocate additional memory
    int size = atoi(argv[3]);
    char* additionalMemory = (char*) malloc(size);
    if (additionalMemory == NULL)
    {
        printf("Unable to allocate %d bytes of memory!\n", size);
        log_error("Unable to allocate %d bytes of memory!\n", size);
        return -1;
    }
    // fill allocated memory with very 'sensitive' data :)
    int i;
    for (i = 0; i < size; i++)
    {
        additionalMemory[i] = (char)i;
    }

    printf("%d additional bytes are successfully allocated!\n", size);

    // register more fake listeners
    char* hrefs[] = {"dummy/str1",
                     "dummy/str2",
                     "dummy/str3",
                     "dummy/str4",
                     "dummy/str5/",
                     "dummy/str5/int1",
                     "dummy/str5/int2",
                     "dummy/str5/int3",
                     "dummy/str5/int4",
                     "dummy/str5/int5",
                     "dummy/str5/int6",
                     "dummy/str5/int7",
                     "dummy/str5/int8",
                     "dummy/str5/int9",
                     "dummy/str5/int0"};
    for (i = 0; i < 15; i++)
    {
        error = obix_registerListener(CONNECTION_ID,
                                      deviceId,
                                      hrefs[i],
                                      &dummyListener);
        if (error < 0)
        {
        	log_error("Unable to register the dummy listener number %d!\n", i + 1);
            return -1;
        }
    }

    // register signal handler
    signal(SIGINT, &signalHandler);
    printf("Press Ctrl+C to shutdown.\n");

    // fall into the endless loop
    size = atoi(argv[4]);
    while (_shutDown == FALSE)
    {
        // try to allocate some more memory
        char* buffer = (char*) malloc(size);
        if (buffer == NULL)
        {
            printf("Unable to allocate variable piece of memory - %d bytes!\n",
                   size);
            log_error("Unable to allocate variable piece of memory - "
                      "%d bytes!\n", size);
            return -1;
        }
        buffer[0] = '\0';
        strlen(buffer);
        free(buffer);

        sleep(2);
    }

    // shutdown gracefully
    ptask_dispose(_taskThread, TRUE);

    // release all resources allocated by oBIX client library.
    // No need to close connection or unregister listener explicitly - it is
    // done automatically.
    return obix_dispose();
}