Exemplo n.º 1
0
int readMeasures()
{
	int temperature   = getTemperature();
	double humidity   = getHumidity();
	double luminosity = getLuminosity() ;

	char str[250];
	sprintf(str," temperature=%d, humidity=%lf, luminosity=%lf",  temperature, humidity, luminosity);
	printf("[Entry_point] Reading measures : %s\n", str);

	/*payload =
		"["
	    "{"
	    "\"machine.temperature\": [{"
	    "  \"timestamp\" : %d, "
	    "  \"value\" : \"%lf\""
	    "}]"
	    "}"
	    "]";*/
	int timestamp = getTimeStamp();
	temp_ts[temp_size] = timestamp;
	temp_values[temp_size] = malloc(10);
	sprintf(temp_values[temp_size], "%d", temperature);
	temp_size++;

	hum_ts[hum_size] = timestamp;
	hum_values[hum_size] = malloc(10);
	sprintf(hum_values[hum_size], "%lf", humidity);
	hum_size++;

	return 0;
}
int main()
{
	wiringPiSetup();
	int fd = wiringPiI2CSetup(HTU21D_I2C_ADDR);
	if ( 0 > fd )
	{
		fprintf(stderr, "ERROR: Unable to access RabbitMax humidity sensor: %s\n", strerror (errno));
		exit (-1);
	}

	// Retrieve temperature and humidity
	double temperature = 0;
	double humidity = 0;
	if ( (0 > getHumidity(fd, &humidity)) || (0 > getTemperature(fd, &temperature)) )
	{
		fprintf(stderr, "ERROR: RabbitMax humidity sensor not found\n");
		exit(-1);
	}
	
	// Print temperature and humidity on the screen
	printf("RabbitMax Humidity and Temperature Sensor\n");
	printf("%5.2fC\n", temperature);
	printf("%5.2f%%rh\n", humidity);
	
	return 0;
}
Exemplo n.º 3
0
void decode(char *data, int length, int noisy){
    //int i;
    //for(i=0; i<length; i++){
    //    fprintf(stderr,"%0.2X ",data[i]);
    //}
    //fprintf(stderr,"\n"); */
    time_t seconds = time (NULL);
    //There are two varieties of data, both of them have wind speed
    // first variety of the data
    if ((data[2] & 0x0f) == 1){ // this has wind speed, direction and rainfall
        if(noisy)
            fprintf(stderr,"Wind Speed: %.1f ",getWindSpeed(data));
        weatherData.windSpeed = getWindSpeed(data);
        weatherData.wsTime = seconds;
        if(noisy)
            fprintf(stderr,"Wind Direction: %s ",Direction[getWindDirection(data)]);
        weatherData.wdTime = seconds;
        weatherData.windDirection = getWindDirection(data);
        if(noisy){
            fprintf(stderr,"Rain Counter: %d ",getRainCount(data));
            fprintf(stderr,"\n");
        }
        weatherData.rainCounter = getRainCount(data);
        weatherData.rcTime = seconds;
        reportsSeen |= 0x01; //I've seen report 1 type 2 now
    }
    // this is the other variety
    if ((data[2] & 0x0f) == 8){ // this has wind speed, temp and relative humidity
        if(noisy)
            fprintf(stderr,"Wind Speed: %.1f ",getWindSpeed(data));
        weatherData.windSpeed = getWindSpeed(data);
        weatherData.wsTime = seconds;
        if(noisy)
            fprintf(stderr,"Temperature: %.1f ",getTemp(data));
        weatherData.temperature = getTemp(data);
        weatherData.tTime = seconds;
        if(noisy){
            fprintf(stderr,"Humidity: %d ", getHumidity(data));
            fprintf(stderr,"\n");
        }
        weatherData.humidity = getHumidity(data);
        weatherData.hTime = seconds;
        reportsSeen |= 0x02;  // I've seen report 1 type 2 now

    }
}
Exemplo n.º 4
0
QString WeatherPlugin::replace(const QString &text)
{
    QString res = text;
    QString sun_set, sun_raise, updated;
#if COMPAT_QT_VERSION >= 0x030000
    QTime tmp_time;
    QDateTime dt;
    int h,m;

    parseTime(getSun_set(),h,m);
    tmp_time.setHMS(h,m,0,0);
    sun_set = tmp_time.toString(Qt::LocalDate);
    sun_set = sun_set.left(sun_set.length() - 3);

    parseTime(getSun_raise(),h,m);
    tmp_time.setHMS(h,m,0,0);
    sun_raise = tmp_time.toString(Qt::LocalDate);
    sun_raise = sun_raise.left(sun_raise.length() - 3);

    parseDateTime(getUpdated(),dt);
    updated = dt.toString(Qt::LocalDate);
    updated = updated.left(updated.length() - 3);
#else
    sun_set = getSun_set();
    sun_raise = getSun_raise();
    updated = getUpdated();
#endif
    /* double Expressions *before* single or better RegExp ! */
    res = res.replace(QRegExp("\\%mp"), i18n("moonphase", getMoonPhase()));
    res = res.replace(QRegExp("\\%mi"), number(getMoonIcon()));
    res = res.replace(QRegExp("\\%pp"), number(getPrecipitation()));
	res = res.replace(QRegExp("\\%ut"), i18n("weather", getUV_Description()));
	res = res.replace(QRegExp("\\%ui"), number(getUV_Intensity()));
    res = res.replace(QRegExp("\\%t"), QString::number((int)getTemperature()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%f"), QString::number((int)getFeelsLike()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%d"), QString::number((int)getDewPoint()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%h"), number(getHumidity()) + "%");
    res = res.replace(QRegExp("\\%w"), number(getWind_speed()) + " " + i18n(getUS()));
    res = res.replace(QRegExp("\\%x"), QString::number(getWind_speed() * 10 / 36) + " " + i18n("m/s"));
    res = res.replace(QRegExp("\\%g"), getWindGust() ? QString("(") + i18n("gust ") + number(getWindGust()) + i18n(getUS()) + QString(")") : QString(""));
    res = res.replace(QRegExp("\\%y"), getWindGust() ? QString("(") + i18n("gust ") + number(getWindGust() * 10 / 36) + QString(" ") + i18n("m/s") + QString(")") : QString(""));
    res = res.replace(QRegExp("\\%p"), number(getPressure()) + " " + i18n(getUP()));
    res = res.replace(QRegExp("\\%a"), number(getPressure() * 75 / 100));
    res = res.replace(QRegExp("\\%q"), i18n("weather", getPressureD()));
    res = res.replace(QRegExp("\\%l"), getLocation());
    res = res.replace(QRegExp("\\%b"), i18n("weather", getWind()));
    res = res.replace(QRegExp("\\%u"), updated);
    res = res.replace(QRegExp("\\%r"), sun_raise);
    res = res.replace(QRegExp("\\%s"), sun_set);
    res = res.replace(QRegExp("\\%c"), i18n_conditions(getConditions()));
    res = res.replace(QRegExp("\\%v"), i18n("weather", getVisibility()) + (atol(getVisibility()) ? QString(" ") + i18n(getUD()) : QString("")));
    res = res.replace(QRegExp("\\%i"), number(getIcon()));
    return res;
}
Exemplo n.º 5
0
void loop() {
    client = server.available();
    if (client) {
        while (client.connected()) {
            if (client.available()) {
                if (client.find("GET /")) {

                    //INICIAR CRONOMETRAGEM
                    if (client.find("setCron=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            iniciarCronometragem();
                        }
                    }

                    //RETORNA O TEMPO DESDE O INICIO
                    if (client.find("getCron=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            getCronometragem();
                        }
                    }

                    //RETORNA TEMPERATURA
                    if (client.find("getTemp=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            getTemperature();
                        }
                    }

                    //RETORNA HUMIDADE
                    if (client.find("getHum=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            getHumidity();
                        }
                    }

                }
            }
            Serial.println();
            break;
        }
        client.println(" HTTP/1.1 200 OK ");
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
}
Exemplo n.º 6
0
QString WeatherPlugin::replace(const QString &text)
{
    QString res = text;
    res = res.replace(QRegExp("\\%t"), number(getTemperature()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%h"), number(getHumidity()) + "%");
    res = res.replace(QRegExp("\\%w"), number(getWind_speed()) + " " + getUS());
    res = res.replace(QRegExp("\\%i"), number(getPressure()) + " " + getUP());
    res = res.replace(QRegExp("\\%l"), getLocation());
    res = res.replace(QRegExp("\\%r"), getWind());
    res = res.replace(QRegExp("\\%u"), getUpdated());
    res = res.replace(QRegExp("\\%p"), getSun_raise());
    res = res.replace(QRegExp("\\%q"), getSun_set());
    res = res.replace(QRegExp("\\%c"), i18n("weather", getConditions()));
    return res;
}
Exemplo n.º 7
0
QString WeatherPlugin::replace(const QString &text)
{
    QString res = text;
    res = res.replace(QRegExp("\\%f"), number(getTemperature_f()));
    res = res.replace(QRegExp("\\%s"), number(getTemperature_c()));
    res = res.replace(QRegExp("\\%h"), number(getHumidity()));
    res = res.replace(QRegExp("\\%w"), number(getWind_speed_mph()));
    res = res.replace(QRegExp("\\%x"), number(getWind_speed_km()));
    res = res.replace(QRegExp("\\%i"), number(getPressure_in()));
    res = res.replace(QRegExp("\\%a"), number(getPressure_hpa()));
    res = res.replace(QRegExp("\\%l"), getLocation());
    res = res.replace(QRegExp("\\%r"), getWind());
    res = res.replace(QRegExp("\\%u"), getUpdated());
    res = res.replace(QRegExp("\\%p"), getSun_raise());
    res = res.replace(QRegExp("\\%q"), getSun_set());
    res = res.replace(QRegExp("\\%c"), i18n("weather", getConditions()));
    return res;
}
Exemplo n.º 8
0
QString WeatherPlugin::replace(const QString &text)
{
    QString res = text;
    res = res.replace(QRegExp("\\%t"), number(getTemperature()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%f"), number(getFeelsLike()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%d"), number(getDewPoint()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%h"), number(getHumidity()) + "%");
    res = res.replace(QRegExp("\\%w"), number(getWind_speed()) + " " + getUS());
    res = res.replace(QRegExp("\\%g"), getWindGust() ? QString("<") + i18n("gust ") + number(getWindGust()) + ")" : "");
    res = res.replace(QRegExp("\\%p"), number(getPressure()) + " " + getUP() + " (" + i18n("weather", getPressureD()) + ")");
    res = res.replace(QRegExp("\\%a"), number(getPressure() * 75 / 100));
    res = res.replace(QRegExp("\\%l"), getLocation());
    res = res.replace(QRegExp("\\%b"), getWind());
    res = res.replace(QRegExp("\\%u"), getUpdated());
    res = res.replace(QRegExp("\\%r"), getSun_raise());
    res = res.replace(QRegExp("\\%s"), getSun_set());
    res = res.replace(QRegExp("\\%c"), i18n_conditions(getConditions()));
    res = res.replace(QRegExp("\\%v"), i18n("weather", getVisibility()));
    return res;
}
Exemplo n.º 9
0
void MapgenV6::placeTreesAndJungleGrass()
{
	//TimeTaker t("placeTrees");

	PseudoRandom grassrandom(blockseed + 53);

	content_t c_sand            = ndef->getId("mapgen_sand");

	content_t c_junglegrass = ndef->getId("mapgen_junglegrass");
	// if we don't have junglegrass, don't place cignore... that's bad
	if (c_junglegrass == CONTENT_IGNORE)
		c_junglegrass = CONTENT_AIR;
	MapNode n_junglegrass(c_junglegrass);
	v3s16 em = vm->m_area.getExtent();

	// Divide area into parts
	s16 div = 8;
	s16 sidelen = central_area_size.X / div;
	double area = sidelen * sidelen;

	// N.B.  We must add jungle grass first, since tree leaves will
	// obstruct the ground, giving us a false ground level
	for (s16 z0 = 0; z0 < div; z0++)
	for (s16 x0 = 0; x0 < div; x0++) {
		// Center position of part of division
		v2s16 p2d_center(
			node_min.X + sidelen / 2 + sidelen * x0,
			node_min.Z + sidelen / 2 + sidelen * z0
		);
		// Minimum edge of part of division
		v2s16 p2d_min(
			node_min.X + sidelen * x0,
			node_min.Z + sidelen * z0
		);
		// Maximum edge of part of division
		v2s16 p2d_max(
			node_min.X + sidelen + sidelen * x0 - 1,
			node_min.Z + sidelen + sidelen * z0 - 1
		);

		// Get biome at center position of part of division
		BiomeV6Type bt = getBiome(v3POS(p2d_center.X, node_min.Y, p2d_center.Y));

		// Amount of trees
		float humidity = getHumidity(v3POS(p2d_center.X, node_max.Y, p2d_center.Y));
		s32 tree_count;
		if (bt == BT_JUNGLE || bt == BT_TAIGA || bt == BT_NORMAL) {
			tree_count = area * getTreeAmount(p2d_center) * ((humidity + 1)/2.0);
			if (bt == BT_JUNGLE)
				tree_count *= 4;
		} else {
			tree_count = 0;
		}

		if (node_max.Y < water_level)
			tree_count /= 2;

		// Add jungle grass
		if (bt == BT_JUNGLE) {
			u32 grass_count = 5 * humidity * tree_count;
			for (u32 i = 0; i < grass_count; i++) {
				s16 x = grassrandom.range(p2d_min.X, p2d_max.X);
				s16 z = grassrandom.range(p2d_min.Y, p2d_max.Y);
/* wtf
				int mapindex = central_area_size.X * (z - node_min.Z)
								+ (x - node_min.X);
				s16 y = heightmap[mapindex];
*/
				s16 y = findGroundLevelFull(v2s16(x, z));
				if (y < water_level)
					continue;

				u32 vi = vm->m_area.index(x, y, z);
				// place on dirt_with_grass, since we know it is exposed to sunlight
				if (vm->m_data[vi].getContent() == c_dirt_with_grass) {
					vm->m_area.add_y(em, vi, 1);
					vm->m_data[vi] = n_junglegrass;
				}
			}
		}

		// Put trees in random places on part of division
		for (s32 i = 0; i < tree_count; i++) {
			s16 x = myrand_range(p2d_min.X, p2d_max.X);
			s16 z = myrand_range(p2d_min.Y, p2d_max.Y);
/* wtf
			int mapindex = central_area_size.X * (z - node_min.Z)
							+ (x - node_min.X);
			s16 y = heightmap[mapindex];
*/
			s16 y = findGroundLevelFull(v2s16(x, z));

			// Don't make a tree under water level
			// Don't make a tree so high that it doesn't fit
			if (y > node_max.Y - 6)
				continue;

			v3s16 p(x, y, z);
			// Trees grow only on mud and grass and snowblock
			{
				u32 i = vm->m_area.index(p);
				content_t c = vm->m_data[i].getContent();
				if (c != c_dirt &&
						c != c_dirt_with_grass &&
						c != c_dirt_with_snow &&
						c != c_snowblock &&
						(y >= water_level || c != c_sand))
					continue;
			}
			p.Y++;

			// Make a tree
			if (y < water_level) {
				if (y < water_level - 20) // do not spawn trees in lakes
					treegen::make_cavetree(*vm, p, bt == BT_JUNGLE, ndef, myrand());
			} else if (bt == BT_JUNGLE) {
				treegen::make_jungletree(*vm, p, ndef, myrand());
			} else if (bt == BT_TAIGA) {
				treegen::make_pine_tree(*vm, p - v3s16(0, 1, 0), ndef, myrand());
			} else if (bt == BT_NORMAL) {
				bool is_apple_tree = (myrand_range(0, 3) == 0) &&
							getHaveAppleTree(v2s16(x, z));
				treegen::make_tree(*vm, p, is_apple_tree, ndef, myrand());
			}
		}
	}
	//printf("placeTreesAndJungleGrass: %dms\n", t.stop());
}
Exemplo n.º 10
0
int main(int argc, char* argv[])
{
   uint8_t data_pin  = 0;
   uint8_t power_pin  = 0;
   DHT_MODEL_t model = AUTO_DETECT;
   int retry = MAX_RETRIES;
 
   
   /* Parse command line */
   switch (argc)
   {   
      case 2:  /* 1 paramters provided */
      case 3:  /* 2 paramters provided */
      case 4:  /* 3 paramters provided */
         /* Get first parameter: sensor type */ 
         if (strcmp(argv[1], "DHT11")==0) model = DHT11;
         else if (strcmp(argv[1], "DHT22")==0) model = DHT22;
         else
         {
            printf("Unknown sensor model %s\n", argv[1]);
            return -1;
         }

         /* Get second parameter: data pin */ 
         if (argc==3)
         {
            /* Get Kernel Id of data pin */
            data_pin = atoi(argv[2]);
         }
         
         /* Get third parameter: power pin */ 
         if (argc==4)
         {
            /* Get Kernel Id of power pin */
            power_pin = atoi(argv[3]);
         }
      break;
      
      default: /* print help message */
         printf("dhtsensor - read temperature and humidity data from DHT11 and DHT22 sensors\n\n");
         printf("Usage: dhtsensor <sensor type> [<data pin>] [<power pin>]\n");
         printf("       sensor type: DHT11|DHT22 \n");
         printf("       data pin:    Kernel Id of GPIO data pin (not needed for SPI communication mode)\n");
         printf("       power pin:   Kernel Id of GPIO power pin (optional)\n");
         return -1;
   }

   /* Power on the sensor */
   if (power_pin) dhtPoweron(power_pin);
   
   /* Init sensor communication */
   dhtSetup(data_pin, model);
   if (getStatus() != ERROR_NONE)
   {
      printf("Error during setup: %s\n", getStatusString());
      return -1;
   }

   /* Read sensor with retry */
   do    
   {
      readSensor();
   
      if (getStatus() == ERROR_NONE)
      {
         printf("Rel. Humidity: %3.1f %%\n", getHumidity());
         printf("Temperature:   %3.1f °C\n", getTemperature());
      }
      else
      {
         sleep(2);
      }
   }
   while ((getStatus() != ERROR_NONE) && retry--);
   
   if (getStatus() != ERROR_NONE)
   {
      printf("Error reading sensor: %s\n", getStatusString());
   }
   
   /* Cleanup */
   dhtCleanup();

   /* Power off the sensor */
   if (power_pin) dhtPoweroff(power_pin);
   
   return 0;
}
Exemplo n.º 11
0
void MapgenV6::placeTreesAndJungleGrass() {
	//TimeTaker t("placeTrees");
	
	PseudoRandom grassrandom(blockseed + 53);

	content_t c_sand            = ndef->getId("mapgen_sand");

	content_t c_junglegrass = ndef->getId("mapgen_junglegrass");
	// if we don't have junglegrass, don't place cignore... that's bad
	if (c_junglegrass == CONTENT_IGNORE)
		c_junglegrass = CONTENT_AIR;
	MapNode n_junglegrass(c_junglegrass);
	v3s16 em = vm->m_area.getExtent();
	
	// Divide area into parts
	s16 div = 8;
	s16 sidelen = central_area_size.X / div;
	double area = sidelen * sidelen;
	
	// N.B.  We must add jungle grass first, since tree leaves will
	// obstruct the ground, giving us a false ground level
	for (s16 z0 = 0; z0 < div; z0++)
	for (s16 x0 = 0; x0 < div; x0++) {
		// Center position of part of division
		v2s16 p2d_center(
			node_min.X + sidelen / 2 + sidelen * x0,
			node_min.Z + sidelen / 2 + sidelen * z0
		);
		// Minimum edge of part of division
		v2s16 p2d_min(
			node_min.X + sidelen * x0,
			node_min.Z + sidelen * z0
		);
		// Maximum edge of part of division
		v2s16 p2d_max(
			node_min.X + sidelen + sidelen * x0 - 1,
			node_min.Z + sidelen + sidelen * z0 - 1
		);
		
		// Amount of trees, jungle area
		u32 tree_count = area * getTreeAmount(p2d_center);
		
		float humidity = 0;
		bool is_jungle = false;
		if (flags & MGV6_JUNGLES) {
			humidity = getHumidity(p2d_center);
			if (humidity > 0.75) {
				is_jungle = true;
				tree_count *= 4;
			}
		}

		if (node_max.Y < water_level)
			tree_count /= 2;

		// Add jungle grass
		if (is_jungle) {			
			u32 grass_count = 5 * humidity * tree_count;
			for (u32 i = 0; i < grass_count; i++) {
				s16 x = grassrandom.range(p2d_min.X, p2d_max.X);
				s16 z = grassrandom.range(p2d_min.Y, p2d_max.Y);
				
				s16 y = findGroundLevelFull(v2s16(x, z)); ////////////////optimize this!
				if (y < water_level || y < node_min.Y || y > node_max.Y)
					continue;
				
				u32 vi = vm->m_area.index(x, y, z);
				// place on dirt_with_grass, since we know it is exposed to sunlight
				if (vm->m_data[vi].getContent() == c_dirt_with_grass) {
					vm->m_area.add_y(em, vi, 1);
					vm->m_data[vi] = n_junglegrass;
				}
			}
		}
		
		// Put trees in random places on part of division
		for (u32 i = 0; i < tree_count; i++) {
			s16 x = myrand_range(p2d_min.X, p2d_max.X);
			s16 z = myrand_range(p2d_min.Y, p2d_max.Y);
			s16 y = findGroundLevelFull(v2s16(x, z)); ////////////////////optimize this!
			// Don't make a tree under water level
			// Don't make a tree so high that it doesn't fit
			if(y > node_max.Y - 6)
				continue;
			
			v3s16 p(x,y,z);
			// Trees grow only on mud and grass
			{
				u32 i = vm->m_area.index(p);
				MapNode *n = &vm->m_data[i];
				if (n->getContent() != c_dirt &&
					n->getContent() != c_dirt_with_grass &&
					(y >= water_level || n->getContent() != c_sand))
					continue;
			}
			p.Y++;
			
			// Make a tree
			if (y < water_level) {
				if (y < water_level - 20) // do not spawn trees in lakes
					treegen::make_cavetree(*vm, p, is_jungle, ndef, myrand());
			}
			else if (is_jungle) {
				treegen::make_jungletree(*vm, p, ndef, myrand());
			} else {
				bool is_apple_tree = (myrand_range(0, 3) == 0) &&
										getHaveAppleTree(v2s16(x, z));
				treegen::make_tree(*vm, p, is_apple_tree, ndef, myrand());
			}
		}
	}
	//printf("placeTreesAndJungleGrass: %dms\n", t.stop());
}
Exemplo n.º 12
0
float PietteTech_DHT::readHumidity() {
    acquireAndWait();
    return getHumidity();
}
Exemplo n.º 13
0
int main(int argc, char **argv) {
	InitDHT(1);
	char* json;

	int lckStatus;
	int res;
	int sleepTimeout;
	struct config configstr;

	char *passwd;
	char *username;
	char msproxyUrl[MAXBUF];

	//setup the syslog logging
	setlogmask(LOG_UPTO(LOGLEVEL));
	openlog("iot", LOG_PID | LOG_CONS, LOG_USER);
	syslog(LOG_INFO, "**** IoT Raspberry Pi Sample has started ****");

	// register the signal handler for USR1-user defined signal 1
	if (signal(SIGUSR1, sig_handler) == SIG_ERR)
		syslog(LOG_CRIT, "Not able to register the signal handler\n");
	if (signal(SIGINT, sig_handler) == SIG_ERR)
		syslog(LOG_CRIT, "Not able to register the signal handler\n");

	//read the config file, to decide whether to goto quickstart or registered mode of operation
	isRegistered = get_config(configFile, &configstr);

	if (isRegistered) {
		syslog(LOG_INFO, "Running in Registered mode\n");
		sprintf(msproxyUrl, "ssl://%s.messaging.internetofthings.ibmcloud.com:8883", configstr.org);
		if(strcmp(configstr.authmethod ,"token") != 0) {
			syslog(LOG_ERR, "Detected that auth-method is not token. Currently other authentication mechanisms are not supported, IoT process will exit.");
			syslog(LOG_INFO, "**** IoT Raspberry Pi Sample has ended ****");
				closelog();
				exit(1);
		} else {
			username = "******";
			passwd = configstr.authtoken;
		}
	} else {
		syslog(LOG_INFO, "Running in Quickstart mode\n");
		strcpy(msproxyUrl,"tcp://quickstart.messaging.internetofthings.ibmcloud.com:1883");
	}

	// read the events
	char* mac_address = getmac("eth0");
	getClientId(&configstr, mac_address);
	//the timeout between the connection retry
	int connDelayTimeout = 1;	// default sleep for 1 sec
	int retryAttempt = 0;

	// initialize the MQTT connection
	init_mqtt_connection(&client, msproxyUrl, isRegistered, clientId, username, passwd);
	// Wait till we get a successful connection to IoT MQTT server
	while (!MQTTAsync_isConnected(client)) {
		connDelayTimeout = 1; // add extra delay(3,60,600) only when reconnecting
		if (connected == -1) {
			connDelayTimeout = reconnect_delay(++retryAttempt);	//Try to reconnect after the retry delay
			syslog(LOG_ERR,
					"Failed connection attempt #%d. Will try to reconnect "
							"in %d seconds\n", retryAttempt, connDelayTimeout);
			connected = 0;
			init_mqtt_connection(&client, msproxyUrl, isRegistered, clientId, username,
					passwd);
		}
		fflush(stdout);
		sleep(connDelayTimeout);
	}
	// resetting the counters
	connDelayTimeout = 1;
	retryAttempt = 0;

	// count for the sine wave
	int count = 1;
	sleepTimeout = EVENTS_INTERVAL;

	//subscribe for commands - only on registered mode
	if (isRegistered) {
		subscribe(&client, subscribeTopic);
	}
	while (1) {
		JsonMessage json_message = { DEVICE_NAME, getCPUTemp(), sineVal(
				MIN_VALUE, MAX_VALUE, 16, count), GetCPULoad() , getHumidity(), getTemp()};
		json = generateJSON(json_message);
		res = publishMQTTMessage(&client, publishTopic, json);
		syslog(LOG_DEBUG, "Posted the message with result code = %d\n", res);
		if (res == -3) {
			//update the connected to connection failed
			connected = -1;
			while (!MQTTAsync_isConnected(client)) {
				if (connected == -1) {
					connDelayTimeout = reconnect_delay(++retryAttempt); //Try to reconnect after the retry delay
					syslog(LOG_ERR, "Failed connection attempt #%d. "
							"Will try to reconnect in %d "
							"seconds\n", retryAttempt, connDelayTimeout);
					sleep(connDelayTimeout);
					connected = 0;
					reconnect(&client, isRegistered, username,passwd);
				}
				fflush(stdout);
				sleep(1);
			}
			// resetting the counters
			connDelayTimeout = 1;
			retryAttempt = 0;
		}
		fflush(stdout);
		free(json);
		count++;
		sleep(sleepTimeout);
	}

	return 0;
}
Exemplo n.º 14
0
 int getHumidityRelative()
 {
     return int(getHumidity());
 };
Exemplo n.º 15
0
/*
 * The Connection Handler for each client
 *********************************************************************************
 */
void *connectionHandler(void *socket_desc) {
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
	int buffersize = 255;
    
    char * client_message[2000];
	
	clientIsConnected = true;
	setUpdateDisplay(true);
	
    //Send some messages to the client
    //strcmp(message,"Welcome to Raspberry Pi gbmon2\n");
    //write(sock , message , strlen(message));
    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 ){
        //end of string marker
		
		char * buffer = (char*)malloc(buffersize);
		
        sprintf(buffer,"Received Command: *%s*", client_message);
        debugPrint(true, true, buffer, true, "SERVER");
		
		// usage
        if((strcmp(client_message, "usage") == 0) || (strcmp(client_message, "help") == 0)){
            debugPrint(true, false, "usage", false,"");
            write(sock,"Available Commands:\n   getVersion \t\t- returns version\n   getServerTime \t- returns current server time\0\n   getWifiStrength \t- returns current wifi signal strength\n   getTemperature \t- returns current temperature\n   getHumidity \t- returns current humidity\n   getFan \t- returns current fan status \n\n setFan \t- toggle fan On or Off\0",400);
        }
		
		// getServerTime
        if(strcmp(client_message, "getServerTime") == 0) {
            sprintf(buffer,"Sending Response: *%s*", getTime());
            debugPrint(true, true, buffer, true, "SERVER");
            write(sock,getTime(),30);
			
        }
		
		// getVersion
        if(strcmp(client_message, "getVersion") == 0) {
            sprintf(buffer,"Sending Response: *%s*", getVersion());
            debugPrint(true, true, buffer, true, "SERVER");
            write(sock,getVersion(),3);
        }
		
		// getWifiStrength
		if(strcmp(client_message, "getWifiStrength") == 0) {
            sprintf(buffer,"Sending Response: *%d*", getWifiStrength());
            debugPrint(true, true, buffer, true, "SERVER");
            write(sock,getWifiStrength(),3);
        }
		
		// getTemperature
		if(strcmp(client_message, "getTemperature") == 0) {
            sprintf(buffer,"Sending Response: *%s*", getTemperature());
            debugPrint(true, true, buffer, true, "SERVER");
            write(sock,getTemperature(),4);
        }
		
		// getHumidity
		if(strcmp(client_message, "getHumidity") == 0) {
            sprintf(buffer,"Sending Response: *%s*", getHumidity());
            debugPrint(true, true, buffer, true, "SERVER");
            write(sock,getHumidity(),4);
        }
		
		// getFan
		if(strcmp(client_message, "getFan") == 0) {
			sprintf(buffer,"Sending Response: *%s*", getFanAsString());
            debugPrint(true, true, buffer, true, "SERVER");
			write(sock,getFanAsString(),2);
        }
		
		// setFan
		if(strcmp(client_message, "setFan") == 0) {
            sprintf(buffer,"Sending Response: *%d*", setFan());
            debugPrint(true, true, buffer, true, "SERVER");
            write(sock,getFanAsString(),2);
        }
		
        /*
         if(strcmp(client_message, "getHumidity") == 0) {
         printf(">>> getHumidity \n");
         char tmp[4];
         sprintf(tmp,"%.1f\0",measure.humidity);
         //send(sock, &measure.humidity, sizeof(float),0);
         //write(sock,&measure.humidity, sizeof(float));
         write(sock,tmp,4);
         }
         if(strcmp(client_message, "getTemperature") == 0) {
         printf(">>> getTemperature \n");
         char tmp[4];
         sprintf(tmp,"%.1f\0",measure.temperature[0]);
         write(sock,tmp,4);
         }
         if(strcmp(client_message, "getAll") == 0) {
         if (debug==2) {
         printf(">>> getAll\n");
         }
         char tmp[255];
         sprintf(tmp,"%s\0",getAllJSON());
         write(sock,tmp,strlen(tmp));
         //n = write(sock,measure.humidity,6);
         }
         if(strcmp(client_message, "makePic") == 0) {
         printf(">>> makePic \n");
         char shellCommand [100];
         struct tm *t ;
         time_t tim ;
         char buf2[32];
         tim = time (NULL) ;
         t = localtime (&tim) ;
         sprintf (buf2,"%02d-%02d-%04d.jpg", t->tm_mday, t->tm_mon + 1, t->tm_year+1900);
         sprintf(shellCommand,"raspistill -o /home/pi/.gbmon/pics/%s",buf2);
         //printf("CAM command: %s",shellCommand);
         FILE * pp ;
         //char shellCommand[] = buf;
         pp = popen(shellCommand, "r");
         if (pp != NULL) {
         while (1) {
         char *line;
         char buf[1000];
         line = fgets(buf, sizeof buf, pp);
         if (line == NULL) break;
         if (line[0] == 'd') printf("%s", line); // line includes '\n'
         }
         pclose(pp);
         }
         sprintf(shellCommand,"sshpass -p 'alpine' scp /home/pi/.gbmon/pics/%s [email protected]:./Sites/MacServer/gbmon/pics/",buf2);
         pp = popen(shellCommand, "r");
         pclose(pp);
         write(sock,"Picture updated\0",20);
         }
         */
        //client_message[read_size] = '\0';
        //Send the message back to client
        //write(sock , client_message , strlen(client_message));
        //clear the message buffer
		
		free(buffer);
        read_size=1;
        memset(client_message, 0, 2000);
    }
    if(read_size == 0) {
        debugPrint(true, true, "Client disconnected", true, "SERVER");
        fflush(stdout);
		// DIsplay UPdate
		clientIsConnected = false;
		setUpdateDisplay(true);
		
    } else if(read_size == -1) {
        perror("recv failed");
    }
    return 0;
}
Exemplo n.º 16
0
 void SCKAmbient::updateSensors(byte mode) 
  {   
     boolean ok_read = false; 
     byte    retry   = 0;
     
     #if F_CPU == 8000000 
       getSHT21();
       ok_read = true;
     #else
       base_.timer1Stop();
       while ((!ok_read)&&(retry<5))
       {
         ok_read = getDHT22();
         retry++; 
         if (!ok_read)delay(3000);
       }
       base_.timer1Initialize(); 
     #endif
       if (((millis()-timeMICS)<=6*minute)||(mode!=ECONOMIC))  //6 minutes
       {  
         #if F_CPU == 8000000 
           getVcc();
         #endif
         getMICS();
         value[5] = getCO(); //ppm
         value[6] = getNO2(); //ppm
       }
       else if((millis()-timeMICS)>=60*minute) 
             {
               GasSensor(true);
               timeMICS = millis();
             }
       else
       {
         GasSensor(false);
       }
       
       if (ok_read )  
       {
         #if ((decouplerComp)&&(F_CPU > 8000000 ))
           uint16_t battery = base_.getBattery(Vcc);
           decoupler.update(battery);
           value[0] = getTemperature() - (int) decoupler.getCompensation();
         #else
           value[0] = getTemperature();
         #endif
          value[1] = getHumidity();
       }
       else 
       {
         value[0] = 0; // ºC
         value[1] = 0; // %
       }  
       value[2] = getLight(); //mV
       value[3] = base_.getBattery(Vcc); //%
       value[4] = base_.getPanel(Vcc);  // %
       value[7] = getNoise(); //mV     
       if (mode == NOWIFI)
            {
              value[8] = 0;  //Wifi Nets
              base_.RTCtime(time);
            } 
       else if (mode == OFFLINE)
         {
           value[8] = base_.scan();  //Wifi Nets
           base_.RTCtime(time);
         }
  }