def init(): global int_lastSound global float_tempOutMax global float_tempInMin global float_tempOutMax global float_tempOutMin global int_currentHour try: [temp, humidity] = grovepi.dht(temperatureSensorIn, 0) float_tempOutMax = temp float_tempInMin = temp [temp, humidity] = grovepi.dht(temperatureSensorOut, 1) float_tempOutMax = temp float_tempOutMin = temp int_lastSound = grovepi.analogRead(soundSensor) int_currentHour = datetime.datetime.now().hour except: error(" init") init()
async def get_telemetry() -> str: # The dht call returns the temperature and the humidity, # we only want the temperature, so ignore the humidity [temperature, humidity] = grovepi.dht(temperature_sensor_port, 0) # The temperature can come as 0, meaning you are reading # too fast, if so sleep for a second to ensure the next reading # is ready while (temperature == 0 or humidity == 0): [temperature, humidity] = grovepi.dht(temperature_sensor_port, 0) await asyncio.sleep(1) # Read the background noise level from an analog port sound = grovepi.analogRead(sound_sensor_port) # Build a dictionary of data # The items in the dictionary need names that match the # telemetry values expected by IoT Central dict = { "Temperature": temperature, # The temperature value "Humidity": humidity, # The humidity value "Sound": sound # The background noise value } # Convert the dictionary to JSON return json.dumps(dict)
def init(): global int_lastSound global float_tempOutMax global float_tempInMin global float_tempOutMax global float_tempOutMin global int_currentHour try: [temp,humidity] = grovepi.dht(temperatureSensorIn,0) float_tempOutMax = temp float_tempInMin = temp [temp,humidity] = grovepi.dht(temperatureSensorOut,1) float_tempOutMax = temp float_tempOutMin = temp int_lastSound = grovepi.analogRead(soundSensor) int_currentHour = datetime.datetime.now().hour except: error(" init") init()
def main(): global isConnected # Create an MQTT client for connecting to AWS IoT via MQTT. client = mqtt.Client(deviceName + "_sr") # Client ID must be unique because AWS will disconnect any duplicates. client.on_connect = on_connect # When connected, call on_connect. client.on_message = on_message # When message received, call on_message. client.on_log = on_log # When logging debug messages, call on_log. # Set the certificates and private key for connecting to AWS IoT. TLS 1.2 is mandatory for AWS IoT and is supported # only in Python 3.4 and later, compiled with OpenSSL 1.0.1 and later. client.tls_set(awsCert, deviceCertificate, devicePrivateKey, ssl.CERT_REQUIRED, ssl.PROTOCOL_TLSv1_2) # Connect to AWS IoT server. Use AWS command line "aws iot describe-endpoint" to get the address. print("Connecting to AWS IoT...") client.connect("A1P01IYM2DOZA0.iot.us-west-2.amazonaws.com", 8883, 60) # Start a background thread to process the MQTT network commands concurrently, including auto-reconnection. client.loop_start() # Configure the Grove LED port for output. grovepi.pinMode(led, "OUTPUT") time.sleep(1) # Loop forever. while True: try: # If we are not connected yet to AWS IoT, wait 1 second and try again. if not isConnected: time.sleep(1) continue # Read Grove sensor values. Prepare our sensor data in JSON format. payload = { "state": { "reported": { # Uncomment the next line if you're using the Grove Analog Temperature Sensor. # "temperature": round(grovepi.temp(temp_sensor, '1.1'), 1), # Comment out the next 2 lines if you're using the Grove Analog Temperature Sensor. "temperature": grovepi.dht(dht_sensor, 0)[0], # The first 0 means that the DHT module is DHT11. "humidity": grovepi.dht(dht_sensor, 0)[1], "light_level": grovepi.analogRead(light_sensor), "sound_level": grovepi.analogRead(sound_sensor), "timestamp": datetime.datetime.now().isoformat() } } } print("Sending sensor data to AWS IoT...\n" + json.dumps(payload, indent=4, separators=(',', ': '))) # Publish our sensor data to AWS IoT via the MQTT topic, also known as updating our "Thing Shadow". client.publish("$aws/things/" + deviceName + "/shadow/update", json.dumps(payload)) print("Sent to AWS IoT") # Wait 30 seconds before sending the next set of sensor data. time.sleep(30) except KeyboardInterrupt: break except IOError: print("Error")
def check_dht(): global io #print 'check_dht' # There are two types of DHT sensor, a blue one (generic, not ver good) # and a more accurate white sensor # I haven't worked out a method of capturing the color in the configuration # just yet, so I'm hardcoding it here. TODO # Blue sensor (2nd param is 0) #[ temp,hume ] = grovepi.dht(int(io['input']['dht']),0) # White sensor (2nd param is 1) #print 'dht sensor is on port: %s'% int(io['input']['dht']) [temp, hume] = grovepi.dht(int(io['input']['dht']), 1) time.sleep(.5) [temp, hume] = grovepi.dht(int(io['input']['dht']), 1) time.sleep(.5) t = str(temp) #print 't: %s'% t h = str(hume) #print 'h: %s'% h t.rstrip("0") h.rstrip("0") #s = "T:"+t+"C H:"+h+"%" #print "\t\tReporting: %s"% s return (t, h)
def get_temperature(port, settings): try: if settings['temp_mode'] == 'raw_temp': if settings['units'] == 'celsius': return grovepi.dht(port, 1) elif settings['units'] == 'fahrenheit': return (grovepi.dht(port, 1)*1.8) + 32 except ValueError: return "Not found"
def get_temperature(port, settings): try: if settings['temp_mode'] == 'raw_temp': if settings['units'] == 'celsius': return grovepi.dht(port, 1) elif settings['units'] == 'fahrenheit': return (grovepi.dht(port, 1) * 1.8) + 32 except ValueError: return "Not found"
def update_values(self): if self.name == "temperature": try: temp_var = grovepi.dht(self.pin, 1) if type(temp_var) is int: value = "IOError" else: value = temp_var[0] except IOError: value = "IOError" elif self.name == "humidity": try: temp_var = grovepi.dht(self.pin, 1) if type(temp_var) is int: value = "IOError" else: value = temp_var[1] except IOError: value = "IOError" elif self.name == "light": grovepi.pinMode(self.pin, "INPUT") try: value = grovepi.analogRead(self.pin) except IOError: value = "IOError" elif self.name == "air": grovepi.pinMode(self.pin, "INPUT") try: value = grovepi.analogRead(self.pin) except IOError: value = "IOError" else: return "invalid sensor: " + self.name if (value != "IOError"): x = float(value) if math.isnan(x): return "invalid value for " + self.name if self.name == "temperature" or self.name == "humidity": self.instantaneous = value self.samples.appendleft(value) l = list(collections.deque(self.samples)) self.current = sum(l) / float(len(l)) self.last_sample_time = time.time() if self.current > self.maximum: self.maximum = self.current elif self.current < self.minimum: self.minimum = self.current self.total_samples += 1 elif self.name == "light" or "air": self.calibrate_analog(value) s = "Successful update for %s. Current value is %d" % ( self.name, self.current) return s else: return "IOError: Could not update %s" % self.name
def temperature(): starttemp =datetime.datetime.today() trytemp = 0 tmp1 = grovepi.dht(th_sensor,0) [0] while trytemp < retry_limit: if float(tmp1) != float(tmp1) or tmp1 < 0: tmp1 = grovepi.dht(th_sensor,0) [0] trytemp += 1 sleep(tryspan) else: return tmp1 return "nodata"
def readData(): try: json_obj = json.dumps({ 'temp' : grovepi.dht(DHT_pin,1)[0], 'hum' : grovepi.dht(DHT_pin,1)[1], 'lum' : grovepi.analogRead(0), 'dist' : grovepi.ultrasonicRead(US_pin), 'pot' : grovepi.analogRead(1), 'pir' : grovepi.digitalRead(PIR_pin) }) return json_obj except IOError: print "Erreur d'entrée/sortie"
def readGroveValues(self): if time.time() - self.lastTime > 0.5: lastTime = time.time() [self.temperature, self.humidity] = grovepi.dht(self.dhtSensor, self.dhtSensorType) #self.airQuality = 'NaN' self.airQuality = grovepi.analogRead(self.airQualitySensor)
def get_temperature(a=1): sensor = PORT [temp,humidity] = grovepi.dht(sensor, 0) if math.isnan(temp): temp = ltemp else: ltemp = temp
def sensor_read_humidity(): temp = 0.01 hum = 0.01 [ temp,hum ] = grovepi.dht(dht11_sensor_port,0) time.sleep(.5) #print hum return hum
def sensor_read_temp(): temp = 0.01 hum = 0.01 [ temp,hum ] = grovepi.dht(dht11_sensor_port,0) time.sleep(.5) #print temp return temp
def tempAndHumData(portNumber, duration): sensor = portNumber if (duration <= 0): duration = 1 if (duration > 2): duration = duration - 1 t_end = time.time() + duration while time.time() < t_end: try: # This example uses the blue colored sensor. # The first parameter is the port, the second parameter is the type of sensor. [celcius, humidity] = grovepi.dht(sensor, blue) if math.isnan(celcius) == False and math.isnan(humidity) == False: fahrenheit = (1.8 * celcius) + 32 print("%.02f %.02f %.02f," % (fahrenheit, celcius, humidity)) time.sleep(.5) except IOError: print("Error")
def run(self): """ lolololollolololol """ i = 0 while self.__on: try: if len(self.__dataTemp) == 59: self.setaveragetemp(sum(self.__dataTemp) / 60) del self.__dataTemp[:] if len(self.__dataHum) == 59: self.setaveragehum(sum(self.__dataHum) / 60) del self.__dataHum[:] [temp, humidity] = grovepi.dht(self.__sensor, 1) self.setdatatemp(float(temp)), self.setdatahum(float(humidity)) if self.__mu == 'F': temp = (temp * 1.8) + 32 print("entry #:", i, "temp =", temp, self.getmu(), " humidity =", humidity) i += 1 else: print("entry #:", i, "temp =", temp, self.getmu(), " humidity =", humidity) i += 1 except IOError: print(0)
def sensors_test(): """Test the GrovePi DHT sensor, LEDs and RGB LCD screen.""" try: for y in range(3): # Get sensor data and actuate LEDs and RGB LCD screen [temp, humid] = grovepi.dht(DHT_SENSOR_PORT, BLUE_DHT) if not math.isnan(temp) and not math.isnan(humid): if temp >= 20.0: # Temperature is good: Everything is green. grove_rgb_lcd.setRGB(0, 255, 0) grovepi.digitalWrite(GREEN_LED, ON) time.sleep(2) grovepi.digitalWrite(GREEN_LED, OFF) else: # Temperature is too low: Turn to red. grove_rgb_lcd.setRGB(255, 0, 0) grovepi.digitalWrite(RED_LED, ON) time.sleep(2) grovepi.digitalWrite(RED_LED, OFF) t_str = str(temp) h_str = str(humid) print("Temperature: {}C | Humidity: {}%".format(t_str, h_str)) grove_rgb_lcd.setText_norefresh("Tmp: {} C\nHmd: {} %".format( t_str, h_str)) # For DHT22, wait three seconds before next reading time.sleep(3) grove_rgb_lcd.setRGB(0, 0, 0) except (IOError, TypeError) as ex: print("Error: {}".format(str(ex))) shutdown_board() except KeyboardInterrupt: shutdown_board() shutdown_board()
def index(): # On recupere la température et l'humidité actuelle, à l'heure où on se connecte au site [ctemp, chumidity ] = dht(4, 1) # 4 pour le port du GrovePi / 1 pour le capteur de type DHT22 # On transmet les mesures à la page web return render_template('index.html', temperature=ctemp, humidity=chumidity)
def tempF(): time.sleep(0.5) try: #temperatuur en humindity [temp,hum] = grovepi.dht(temphum,0) if math.isnan(temp)==False and math.isnan(hum)==False: if canEdit==True: lcd.setText("Temp:" + str(temp) + "C\n" + "Hum:" + str(hum) + " %") global isNight isNight=in_between(datetime.datetime.now().time(), datetime.time(23, 0, 0), datetime.time(4, 0, 0)) if isNight==True: lcd.setRGB(0,0,0) else: lcd.setRGB(100,100,100) display_status="" client.publish("temp", temp) client.publish("hum", hum) print('temperatuur: ' + temp) except (IOError,TypeError) as ex: error="Error: " + str(ex)
def collect_sensor_data(): """Collects temperature and humidity data :return: The temperature and humidity data collected, formated with atmospheric pressure, air speed, metabolic rate, and clothing level. :rtype: list of tuples """ sensor_data = [] try: for y in range(3): [temp, humid] = grovepi.dht(DHT_SENSOR_PORT, BLUE_DHT) if not math.isnan(temp) and not math.isnan(humid): t_str = str(temp) h_str = str(humid) grove_rgb_lcd.setRGB(127, 127, 127) grove_rgb_lcd.setText_norefresh("Tmp: {} C\nHmd: {} %".format( t_str, h_str)) sensor_data.append(([[1013.25, 0.1, humid, 1.0, 0.61, temp]])) # For DHT11, wait three seconds before next reading time.sleep(3) grove_rgb_lcd.setRGB(0, 0, 0) except (IOError, TypeError) as ex: print("Error: {}".format(str(ex))) shutdown_board() except KeyboardInterrupt: shutdown_board() for index, data in enumerate(sensor_data): print("Sample #{0} collected: {1}".format(index + 1, data)) shutdown_board() return sensor_data
def processDHT(period): global mutex [t, h] = -1, -1 with mutex: printLog("processDHT started with period %f sec" % (period)) while stop == 0: startT = datetime.datetime.now() try: mutex.acquire() # Get value from temperature sensor [t, h] = grovepi.dht(dht_sensor_port, dht_blue) except Exception as e: printLog("processDHT[error]: %s\r\n" % (str(e))) finally: mutex.release() # Send t = threading.Thread(target=sendToCloud, args=("processDHT", startT.isoformat(), { 'nodeid': nodeName, 'tempvals': [{ 'timestamp': startT.isoformat(), 'val': t }], 'humidvals': [{ 'timestamp': startT.isoformat(), 'val': h }] })) t.start() time.sleep( max(period - (datetime.datetime.now() - startT).total_seconds(), 0))
def handledhtdata(): global temp, hum [temp, hum] = grovepi.dht(dht_sensor_port, dht_sensor_type) if temp != -1 and hum != -1: display("temp = {}C humidity={}%".format(temp, hum), (0, 255, 0)) else: display("Error reading DTH sensor")
def main(): global THINGSPEAKKEY global THINGSPEAKURL # initialize hum2 = 0 temp2 = -100 while True: [temp, hum] = grovepi.dht(4, 1) #D4 input, the white version # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). hum2_old = hum2 temp2_old = temp2 hum2, temp2 = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN) # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if hum2 is None or temp2 is None: hum2 = hum2_old temp2 = temp2_old if all(x is not None for x in [temp, hum, temp2, hum2]) & ( -40 < temp) & (temp < 50) & (0 < hum) & (hum < 100): print("temp = %.02f C humidity =%.02f%%" % (temp, hum)) print("temp = %.02f C humidity =%.02f%%" % (temp2, hum2)) sendData(THINGSPEAKURL, THINGSPEAKKEY, temp, hum, temp2, hum2) sys.stdout.flush() time.sleep(60)
def run(self): values = [] # while we haven't called stop function while not self.event_stopper.is_set(): counter = 0 # while we haven't done a cycle (period) while counter < self.refresh_period and not self.event_stopper.is_set(): temp = None humidity = None # read data try: [temp, humidity] = dht(self.pin, self.sensor_type) # check for NaN errors if math.isnan(temp) is False and math.isnan(humidity) is False: new_entry = {"temp" : temp, "hum" : humidity} values.append(new_entry) else: raise RuntimeWarning("[dht sensor][we've caught a NaN]") counter += 1 # in case we have an I2C error except IOError: if self.debugging is True: print("[dht sensor][we've got an IO error]") # intented to catch NaN errors except RuntimeWarning as error: if self.debugging is True: print(str(error)) finally: # the DHT can be read once a second time.sleep(1) if len(values) > 0: # remove outliers temp = numpy.mean(statisticalNoiseReduction([x["temp"] for x in values], self.filtering_aggresiveness)) humidity = numpy.mean(statisticalNoiseReduction([x["hum"] for x in values], self.filtering_aggresiveness)) # insert into the filtered buffer self.lock.acquire() self.filtered_temperature.append(temp) self.filtered_humidity.append(humidity) self.lock.release() # if we have set a callback then call that function w/ its parameters if not self.callbackfunc is None: self.callbackfunc(*self.args) # reset the values for the next iteration/period values = [] if self.debugging is True: print("[dht sensor][called for joining thread]")
def dht22_values(): try: # Get DHT22 Temperature & Humidity # The first parameter is the port, the second parameter is the type of sensor. [config.tempF, config.humidity] = grovepi.dht(config.TEMP_SENSOR, config.WHITE) # Convert to Fahrenheit = 9.0/5.0 * Celsius + 32 config.tempF = (9 / 5 * config.tempF) + 32 # calibrate the temp # config.tempF = config.tempF * 1.6279 - 15.833 # config.tempF = ((config.tempF**2 * 0.0336) - (1.7846 * config.tempF) + 69.078) config.tempF = round( ((config.tempF**2 * 0.034) - (1.78 * config.tempF) + 69.08) - 6.0, 1) # calibrate the humidity # config.humidity = (0.4477 * (config.humidity**1.0516)) config.humidity = ((0.6007 * config.humidity) - 2.9439) config.humidity = round(config.humidity, 1) except IOError: print("DHT22 Temp/Humid Sensor Error") if (config.DEBUG): print("Temp/Humidity is: ", config.tempF, config.humidity) print("get.dht22_values module done") time.sleep(1)
def get_temperature_grove(): sensor = PORT [temp, humidity] = grovepi.dht(sensor, 0) if math.isnan(temp): temp = 0.0 else: LTEMP = temp return jsonify({'temperature': temp, 'text': str(temp), 'unit': 'Celsius'})
def getTH(self): [temp,humidity] = grovepi.dht(self.pin,self.model) if math.isnan(temp) == False and math.isnan(humidity) == False: temp1 = math.isnan(temp) humidity1 = math.isnan(humidity) return '{"temp":%.02f, "humidity":%.02f}'%(temp, humidity) else: return '{"temp":%.02f, "humidity":%.02f}'%(self.temp1, self.humidity1)
def index(): try: [temp, humid] = g.dht(sensor_pin, 0) return template("<h1>Le capteur à Gégé</h1><br/><b>Le capteur dit :\ <br/>Température : {{temp}}°C\ <br/>Humidité : {{humid}}%", temp=temp, humid=humid) except Exception, e: return template("<h1>Oups, rechargez la page</h1>")
def getGrovePlusData(): try: [temperature,humidity] = grovepi.dht(DHT_SENSOR_DOGITAL_PIN,0) air_quality = grovepi.analogRead(MQ135_SENSOR_ANALOG_PIN) sound = int( (grovepi.analogRead(SOUND_SENSON_ANALOG_PIN) / 1024.0) * 54 * 1.664) lpg_value = grovepi.analogRead(MQ2_SENSOR_ANALOG_PIN) except IOError: print ("IO Error") return([temperature,humidity,air_quality,sound,lpg_value])
def temp(sensor = 4): try: temp, humidity = dht(sensor, 0) return f"temp == {temp}, humidity == {humidity}" except Exception as err: return err finally: print("Finished Read")
def read_temp_humidity_sensor_digitalport(port): tempsensor = port grovepi.pinMode(tempsensor,"INPUT") temp_humidity_list = None try: temp_humidity_list = grovepi.dht(port,0) #0 - type blue sensor except IOError: #this doesnt appear to work log.error("Error in reading the temp and humidity sensor") return temp_humidity_list
def read(self): while True: temperature, humidity = grovepi.dht(self.port, self.dht_type) # Sit here until we don't get NaN's. if math.isnan(temperature) is False and math.isnan( humidity) is False: break self.value = {"temperature": temperature, "humidity": humidity} return self.value
def getData(): global luminosity, humidity, temperature #temperature & humidity v1.2 blue grovepi sensor [temp, hum] = grovepi.dht(temHum_sensor, 0) if math.isnan(temp) == False and math.isnan(hum) == False: temperature = temp humidity = hum #Digital light grovepi sensor luminosity = light.readVisibleLux()
def __init__(self): try: SensorData = grovepi.dht(temperature_humidity_sensor, sensorTypeCode) self.temperature = SensorData[0] self.humidity = SensorData[1] except IOError: print("Error -- Temp/Humidity Sensor")
def getDhtReadings(): logging.debug( "Obtaining Temperature and Humidity readings..." ) [ fTemp, fHumidity ] = grovepi.dht( iDHtSensorPort, 0 ) logging.info( "Temp reading: " + str( fTemp ) + "C\tHumidity reading: " + str( fHumidity ) + "%" ) client.fSample_Temp = fTemp + client.iOverride #always safe to add it whether it's zero or non-zero client.fSample_Humidity = fHumidity if client.iOverride > 0: logging.info( "Override invoked. Current Override value: " + str( client.iOverride ) + "\tNew temp value: " + str( client.fSample_Temp) ) logging.debug( "'client' Object settings for Temp: " + str( client.fSample_Temp ) + " and Humidity: " + str( client.fSample_Humidity ) )
def read_temp_humidity_sensor_digitalport(port): if not ENABLED: return -1 temp_humidity_list = None try: temp_humidity_list = grovepi.dht(port,0) except IOError: #this doesnt appear to work print("Error in reading the temp and humidity sensor") return temp_humidity_list
def get_data(): """ Read sensor data right from grovepi. Don't call in more than one thread. """ loopstate = get_loopstate() loudness = grovepi.analogRead(LOUDNESS_SENSOR) [temp, hum] = grovepi.dht(TEMP_HUM_SENSOR, module_type=0) return [loopstate, loudness, temp, hum]
def run(self): while not self.stop: try: [temp, humidity] = grovepi.dht(self.pin, self.blue) if math.isnan(temp) == False and math.isnan(humidity) == False: #print("temp = %.02f C humidity =%.02f%%" % (temp, humidity)) self.temp = temp self.humidity = humidity except IOError as e: print("Sound sensor exception: %s" % (e))
def readTH(): temp = float("nan") humid = float("nan") while (math.isnan(temp) or math.isnan(humid)): try: [temp,humid]=g.dht(7,0) except: print(time.ctime(t)) print(traceback.format_exc()) return [temp, humid]
def append_csv(): [temp, humidity] = grovepi.dht(sensor, blue) temp_measure = "%.02f" % (temp) humidity_measure = "%.02f" % (humidity) new_mesurement = [ '{}-{}-{}'.format(now.day, now.month, now.year), '{}'.format(now.strftime("%X")), '{}'.format(temp_measure), '{}'.format(humidity_measure) ] append_list_as_row('write_obj', new_mesurement)
def sensorCheck(dht_pin, light_sensor_pin, DHTtype): try: light_value = grovepi.analogRead(light_sensor_pin) except IOError: return "error" try: [temp,humidity] = grovepi.dht(dht_pin,DHTtype) except IOError: return "error" result = "%s temp = %.1f , humidity = %.1f , light = %d" % (datetime.now().strftime("%H:%M:%S "), temp, humidity, light_value) return result
def get_clima(): while True: try: # This example uses the blue colored sensor. # The first parameter is the port, the second parameter is the type of sensor. [temp,humidity] = grovepi.dht(sensor,blue) if math.isnan(temp) == False and math.isnan(humidity) == False: return { "temp" : temp, "humidity" : humidity} except IOError: print ("Error")
def getTemperatureAndHumidity(): try: [temp, humidity] = grovepi.dht(digitalPins.get('tempAndHumidity'), 0) if math.isnan(temp) == False and math.isnan(humidity) == False: return temp, humidity else: return None, None except IOError: print('IO Error') return None, None
def read_sensor(): try: light = grovepi.analogRead(light_sensor) distance = grovepi.ultrasonicRead(ultrasonic_ranger) [temp, humidity] = grovepi.dht(temp_humidity_sensor, blue) #Return -1 in case of bad temp/humidity sensor reading if math.isnan(temp) or math.isnan(humidity): return [-1, -1, -1, -1] return [light, distance, temp, humidity] except IOError as TypeError: return [-1, -1, -1, -1]
def read_sensor(): try: moisture=grovepi.analogRead(mositure_sensor) light=grovepi.analogRead(light_sensor) [temp,humidity] = grovepi.dht(temp_himidity_sensor,white) #Return -1 in case of bad temp/humidity sensor reading if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan return [-1,-1,-1,-1] return [moisture,light,temp,humidity] #Return -1 in case of sensor error except IOError as TypeError: return [-1,-1,-1,-1]
def handlerequests(req): if req.operation==0: pin = req.pin.split("Pin")[1] grovepi.pinMode(int(pin), "INPUT") try: sensorval = grovepi.digitalRead(int(pin)) except: sensorval =0 msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation == 1: pin = req.pin.split("Pin")[1] grovepi.pinMode(int(pin), "OUTPUT") try: grovepi.digitalWrite(int(pin), int(req.payload)) except: grovepi.digitalWrite(int(pin), int(req.payload)) elif req.operation == 2: pin = req.pin.split("Pin")[1] grovepi.pinMode(int(pin), "INPUT") try: sensorval = grovepi.analogRead(int(pin)) except: sensorval = 0 msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation ==4: pin = req.pin.split("Pin")[1] try: [temp,humidity] = grovepi.dht(int(pin),1) except: temp=0 humidity =0 a= json.dumps({'temp':temp,'humidity':humidity}) msgtx = Python2Sharp(msg.isRequest,msg.watcherid,msg.syncid,a,msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation == 5: pin = req.pin.split("Pin")[1] try: sensorval=grovepi.ultrasonicRead(int(pin)) except: sensorval=0 msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation == 6: try: setRGB(0,128,64) setText(req.payload) except: pass
def read_sensor(): try: # pressure=pressure = bmp.readPressure()/100.0 light=grovepi.analogRead(light_sensor) [temp,humidity] = grovepi.dht(temp_humidity_sensor,therm_version) # Here we're using the thermometer version. #Return -1 in case of bad temp/humidity sensor reading if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan # return [-1,-1,-1,-1] return [-1,-1,-1] # return [pressure,light,temp,humidity] return [light,temp,humidity] #Return -1 in case of sensor error except (IOError,TypeError) as e: return [-1,-1,-1]
def read(self): [temperature,humidity] = grovepi.dht(self.pin, self.mod_type) result = OrderedDict() if not math.isnan(temperature): result['temp'] = { 'value': temperature, 'level': self.get_level(temperature, self.temp_levels) } if not math.isnan(humidity): result['humi'] = { 'value': humidity, 'level': self.get_level(humidity, self.humi_levels) } return result
def update(self): try: brightness = grovepi.analogRead(pins_brightness) self.dataDict["p_brightness"] = brightness except: print "[logger] update: analogRead error" try: [temperature, humidity] = grovepi.dht(pins_dht, 1) self.dataDict["p_temperature"] = temperature self.dataDict["p_humidity"] = humidity except: print "[logger] update: dht error" try: pressure = self.bmp.readPressure() self.dataDict["p_pressure"] = pressure / 100.0 except: print "[logger] update: readPressure error" self.serial.flush() while True: gps = self.serial.readline() if gps[:6] == "$GPGGA": break; time.sleep(0.1) try: index = gps.index("$GPGGA", 5, len(gps)) gps = gps[index:] except: pass gga = gps.split(",") if len(gga) > 9: lat = gga[2] lat_ns = gga[3] lon = gga[4] lon_ew = gga[5] alt = gga[9] if lat.replace(".", "", 1).isdigit(): lat = self.decimal_degrees(float(lat)) if lat_ns == "S": lat = -lat self.dataDict["p_lat"] = lat if lon.replace(".", "", 1).isdigit(): lon = self.decimal_degrees(float(lon)) if lon_ew == "W": lon = -lon self.dataDict["p_lon"] = lon if alt.replace(".", "", 1).isdigit(): self.dataDict["p_alt"] = float(alt)
def sensor_read_humidity(): temp = 0.01 hum = 0.01 retry = 3 while retry > 0: try: [ temp,hum ] = grovepi.dht(dht11_sensor_port,0) time.sleep(.01) if math.isnan(hum): print 'fail to read humidity sensor, retry again' retry = retry - 1 else: break except: print 'can not read humidity sensor, retry again' retry = retry - 1 time.sleep(.1) if retry == 0: return -1 else: return hum
def main(): # ply = Plotly_writer() # ply.open_stream() mac_address = get_mac('wlan0') co2_value = grove_co2_lib.CO2() # インスタンス作成時に protocol v3.1.1 を指定します client = mqtt.Client(client_id="hoge", protocol=mqtt.MQTTv311) client.connect(mqtt_host, port=mqtt_port, keepalive=60) client.loop_start() print("starting post to the api...") while True: print("fetching data from sensor...") # 各種センサー情報の取得 loudness = grovepi.analogRead(LOUDNESS_PORT) light = grovepi.analogRead(LIGHT_PORT) air_cleanness = grovepi.analogRead(AIR_PORT) (temp, humid) = grovepi.dht(TEMP_HUMID_PORT, 0) (ppm, temp_from_co2) = co2_value.read() now_time = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') client.publish(mqtt_topic, mqtt_message) sleep(10) person_data = read_data() print(person_data) # ply.write_stream(x=now_time, loudness=loudness, light=light) req = RequestToApi('https://anaba-works.herokuapp.com/api/environments/', time=now_time, place=mac_address, loudness=loudness, light=light, air_cleanness=air_cleanness, temp=temp, humid=humid, co2_ppm=ppm, no_of_person=person_data) req.execute_request() sleep(300)
sens=digitalOp[s_no] l=len(sens) port=int(msg[l:l+1]) state=msg[l+1:] grovepi.pinMode(port,"OUTPUT") if state=='on': grovepi.digitalWrite(port,1) else: grovepi.digitalWrite(port,0) if en_debug: print msg elif msg[:4].lower()=="temp".lower(): if en_grovepi: port=int(msg[4:]) [temp,humidity] = grovepi.dht(port,0) s.sensorupdate({'temp':temp}) if en_debug: print msg print "temp: ",temp elif msg[:8].lower()=="humidity".lower(): if en_grovepi: port=int(msg[8:]) [temp,humidity] = grovepi.dht(port,0) s.sensorupdate({'humidity':humidity}) if en_debug: print msg print "humidity:",humidity elif msg[:8].lower()=="distance".lower():
api = tweepy.API(auth) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') api.update_status("Session start at: " + st) print "Twitter Connected" grovepi.pinMode(led,"OUTPUT") last_sound = 0 while True: # Error handling in case of problems communicating with the GrovePi try: # Get value from temperature sensor [temp,humidity] = grovepi.dht(temperature_sensor,0) t=temp h=humidity # Get value from light sensor light_intensity = grovepi.analogRead(light_sensor) # Give PWM output to LED grovepi.analogWrite(led,light_intensity/4) # Get sound level sound_level = grovepi.analogRead(sound_sensor) if sound_level > 0: last_sound = sound_level
def reflesh(self): [temp,humidity] = grovepi.dht(pins_dht,1) pressure = self.bmp.readPressure() self.dataDict["brightness"] = 0 self.dataDict["temp"] = 0 self.dataDict["humid"] = 0 self.dataDict["pressure"] = 0 try: self.dataDict["brightness"] = grovepi.analogRead(pins_bright) except IOError: print ("analog Error") self.dataDict["temp"] = temp self.dataDict["humid"] = humidity self.dataDict["pressure"] = pressure / 100.0 #GPS cnt = 0 gpsSuccess = False print "start GPS..." while (cnt < 30): self.inp = self.ser.readline() if self.inp[:6] == '$GPGGA': gpsSuccess = True break time.sleep(0.1) cnt = cnt + 1 try: ind=self.inp.index('$GPGGA', 5, len(self.inp)) self.inp = self.inp[ind:] except ValueError: print "Value error" self.dataDict["Altitude"] = 0 self.dataDict["Latitude"] = 0 self.dataDict["Longtitude"] = 0 if gpsSuccess: self.GGA = self.inp.split(",") if len(self.GGA) > 9: t = self.GGA[1] lat = self.GGA[2] lat_ns = self.GGA[3] long = self.GGA[4] long_ew = self.GGA[5] fix = self.GGA[6] sats = self.GGA[7] alt = self.GGA[9] if lat.replace(".","",1).isdigit(): lat = self.decimal_degrees(float(lat)) #lat = lat / 100.0 if lat_ns == "S": lat = -lat if long.replace(".","",1).isdigit(): long = self.decimal_degrees(float(long)) #long = long / 100.0 if long_ew == "W": long = -long self.dataDict["Altitude"] = alt self.dataDict["Latitude"] = lat self.dataDict["Longtitude"] = long
import time import grovepi from grove_oled import * # Connect the OLED module to port I2C-1 oled_init() oled_clearDisplay() oled_setNormalDisplay() oled_setVerticalMode() time.sleep(.1) # Connect the Grove Temperature & Humidity Sensor Pro to digital port D4 # SIG,NC,VCC,GND sensor = 4 while True: try: [temp,humidity] = grovepi.dht(sensor,1) print "temp =", temp, " humidity =", humidity oled_setTextXY(0,0) oled_putString("Temp= "+ str(temp)+"C") oled_setTextXY(1,0) oled_putString("Hum= "+ str(humidity)) time.sleep(30) except IOError: print "Error" except TypeError: print "Error"
dht11_port = 8 # DHT11 temp & humidity sensor is connected to port D8 # Other global variables baseurl = "http://piland.socialdevices.io" dht22_temp_baseurl = baseurl + "/" + str(room) + "/write/" + str(dht22_slot_temp) + "?name=" + dht22_name_temp + "&value=" dht22_humi_baseurl = baseurl + "/" + str(room) + "/write/" + str(dht22_slot_humi) + "?name=" + dht22_name_humi + "&value=" dht11_temp_baseurl = baseurl + "/" + str(room) + "/write/" + str(dht11_slot_temp) + "?name=" + dht11_name_temp + "&value=" dht11_humi_baseurl = baseurl + "/" + str(room) + "/write/" + str(dht11_slot_humi) + "?name=" + dht11_name_humi + "&value=" while True: try: # Read the temperature and humidity from both sensors [dht22_temp, dht22_humi] = grovepi.dht(dht22_port, 1) # second parameter: 1 = DHT22 sensor [dht11_temp, dht11_humi] = grovepi.dht(dht11_port, 0) # second parameter: 0 = DHT11 sensor dht22_temp_url = dht22_temp_baseurl + "%0.1f" % dht22_temp + "+C" dht22_humi_url = dht22_humi_baseurl + "%0.1f" % dht22_humi + "+%25" # %25 will display as % sign dht11_temp_url = dht11_temp_baseurl + "%0.1f" % dht11_temp + "+C" dht11_humi_url = dht11_humi_baseurl + "%0.1f" % dht11_humi + "+%25" # %25 will display as % sign print dht22_temp_url print dht22_humi_url print dht11_temp_url print dht11_humi_url requests.get(dht22_temp_url) # write data requests.get(dht22_humi_url) # write data requests.get(dht11_temp_url) # write data
# grovepi_lcd_dht.py # from grovepi import * import grovepi from grove_rgb_lcd import * sensor = 6 # Connect the DHt Pro sensor to port 6 while True: try: [ temp,hum ] = grovepi.dht(sensor,1) #Get the temperature and Humidity from the DHT sensor print "temp =", temp, "C\thumadity =", hum,"%" t = str(temp) h = str(hum) setRGB(0,128,64) setRGB(0,255,0) setText("Temp:" + t + "C " + "Humidity :" + h + "%") except (IOError,TypeError) as e: print "Error"
# getCurrent time laFecha = time.strftime("%Y-%m-%d %H:%M:%S") # Declare sensorth = 4 gas_sensor = 1 grovepi.pinMode(gas_sensor, "INPUT") air_sensor = 0 grovepi.pinMode(air_sensor, "INPUT") pir_sensor = 3 grovepi.pinMode(pir_sensor, "INPUT") # Get Temperature and humidity from the declared sensorth [temp, humi] = grovepi.dht(sensorth, 0) print "" logTemp(temp, humi, laFecha) print "" # Get the gas sensor value gas_value = grovepi.analogRead(gas_sensor) logGas(gas_value, laFecha) sensor_valueAir = grovepi.analogRead(air_sensor) air = "" # Pollution is an enumerator with the next values (1-'low', 2-'medium', 3='high') if sensor_valueAir > 700: air = "high" elif sensor_valueAir > 300: air = "medium" else: