Exemplo n.º 1
0
def read_temperatures():
    # Schreibt alle Variablen fuer die anderen Funktionen
    global rh1, rh2, rh3, t1, t2, t3, t4
    global absdraussen, absdrinnen, abscal
    global timestamp
    # zeit im ms seid 1/1/1970 + 2h UTC=>berlin+7200
    timestamp = time.time() * 1000 + 7200

    humidity, temperature = Adafruit_DHT.read_retry(rhsensor, rh1pin)
    rh1 = round(humidity, 1)
    t1 = round(temperature, 1)
    if verbose == 1:
        print ("read_temperatures: Sensor1: DHT{} -- Temp={}*C  Humidity={}%".format(rhsensor, t1, rh1))

    humidity, temperature = Adafruit_DHT.read_retry(rhsensor, rh2pin)
    rh2 = round(humidity, 1)
    t2 = round(temperature, 1)
    if verbose == 1:
        print ("read_temperatures: Sensor2: DHT{} -- Temp={}*C  Humidity={}%".format(rhsensor, t2, rh2))

    humidity, temperature = Adafruit_DHT.read_retry(rhsensor, rh3pin)
    rh3 = round(humidity, 1)
    t3 = round(temperature, 1)
    if verbose == 1:
        print ("read_temperatures: Sensor3: DHT{} -- Temp={}*C  Humidity={}%".format(rhsensor, t3, rh3))

    absdraussen = round(absfeucht(t2, rh2), 2)  ######################
    absdrinnen = round(absfeucht(t3, rh3), 2)  ######################
    abscal = absdraussen / absdrinnen
    # Wassertemperatur mittels DS18B20 lesen
    id = "28-021502f5e1ff"
    t4 = read_DS18B20(id)
Exemplo n.º 2
0
    def run(self):
        while True:
            h1, t1 = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 23)
            h2, t2 = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 24)

            if t1 >= conf["temp_notification_threshold"] or t2 >= conf["temp_notification_threshold"]:
                if self.__last_t_max is None or self.__last_t_max < conf["temp_notification_threshold"]:
                    message = 'ODNOTOWANO PODWYŻSZONĄ TEMPERATURĘ O WARTOŚCI: %s STOPNI' % '{0:0.1f}'.format(max(t1, t2))
                    notifier.send_temp_warning(message)
            if h1 >= conf["humidity_notification_threshold"] or h2 >= conf["humidity_notification_threshold"]:
                if self.__last_h_max is None or self.__last_h_max < conf["humidity_notification_threshold"]:
                    message = 'ODNOTOWANO PODWYŻSZONĄ WILGOTNOŚĆ O WARTOŚCI: %s PROCENT' % '{0:0.1f}'.format(max(h1, h2))
                    notifier.send_hum_warning(message)

            result = {}

            if h1 is not None and t1 is not None:
                result['Sensor1'] = {}
                result['Sensor1']['temperature'] = '{0:0.1f}'.format(t1)
                result['Sensor1']['humidity'] = '{0:0.1f}'.format(h1)

            if h2 is not None and t2 is not None:
                result['Sensor2'] = {}
                result['Sensor2']['temperature'] = '{0:0.1f}'.format(t2)
                result['Sensor2']['humidity'] = '{0:0.1f}'.format(h2)

            self.__lastResults = result
            self.__last_t_max = max(t1, t2)
            self.__last_h_max = max(h1, h2)

            time.sleep(10)
Exemplo n.º 3
0
def on_message(client, userdata, msg):
	print(msg.topic+"\nMensaje: "+str(msg.payload))
	if (msg.topic == 'orden'):
		if (msg.payload == 'temperatura'):
			humidity, temperature = Adafruit_DHT.read_retry(sensor, temphum)
			if temperature is not None:
				message = 'temperatura:{0:0.1f}'.format(temperature)
			else:
				message = 'temperatura:0'
			client.publish("temperatura", message)
		if (msg.payload == 'humedad'):
			humidity, temperature = Adafruit_DHT.read_retry(sensor, temphum)
			if humidity is not None:
				message = 'humedad:{0:0.1f}'.format(humidity)
			else:
				message = 'humedad:0'
			client.publish("humedad", message)
		if (msg.payload == 'giroON'):
			GPIO.output(rel2_giro, 0)  #Turn ON
		if (msg.payload == 'luzON'):
			GPIO.output(rel3_luz_sirena, 0)  #Turn ON
		if (msg.payload == 'sirenaON'):
			GPIO.output(rel1_sirena, 0)  #Turn ON
		if (msg.payload == 'giroOFF'):
			GPIO.output(rel2_giro, 1)  #Turn OFF
		if (msg.payload == 'luzOFF'):
			GPIO.output(rel3_luz_sirena, 1)  #Turn OFF
		if (msg.payload == 'sirenaOFF'):
			GPIO.output(rel1_sirena, 1)  #Turn OFF
		if (msg.payload == 'dispara'):
			os.system('mpg321 -g 100 -q mob_ua-gun_shoot_m_16.mp3 &')
Exemplo n.º 4
0
def lab_temp():
    # import sys
    import Adafruit_DHT
    ambient_humidity, ambient_temperature = Adafruit_DHT.read_retry(
        Adafruit_DHT.DHT22, 4)

    if ambient_humidity is None or ambient_temperature is None:
        logging.warning(
            'Sensor {0} reading failed (from /lab_temp).'.format('Ambient'))
        return render_template("no_sensor.html")

    fridge_humidity, fridge_temperature = Adafruit_DHT.read_retry(
        Adafruit_DHT.DHT22, 24)

    if fridge_humidity is None or fridge_temperature is None:
        logging.warning(
            'Sensor {0} reading failed (from /lab_temp).'.format('Fridge'))
        return render_template("no_sensor.html")

    curing_humidity, curing_temperature = Adafruit_DHT.read_retry(
        Adafruit_DHT.DHT22, 25)

    if curing_humidity is None or curing_temperature is None:
        logging.warning(
            'Sensor {0} reading failed (from /lab_temp).'.format('Curing'))
        return render_template("no_sensor.html")

    return render_template("lab_temp.html",
                           ambient_temp=ambient_temperature,
                           ambient_hum=ambient_humidity,
                           fridge_temp=fridge_temperature,
                           fridge_hum=fridge_humidity,
                           curing_temp=curing_temperature,
                           curing_hum=curing_humidity)
def read_temperatures():
    # Schreibt alle Variablen fuer die anderen Funktionen
    global rh1, rh2, rh3, t1, t2, t3
    global absdraussen, absdrinnen
    global timestamp
    # zeit im ms seid 1/1/1970 + 2h UTC=>berlin+7200
    timestamp = time.time() * 1000 + 7200

    humidity, temperature = Adafruit_DHT.read_retry(rhsensor, rh1pin)
    rh1 = round(humidity, 1)
    t1 = round(temperature, 1)
    if verbose == 1:
        print ("main: Sensor1: DHT{} -- Temp={}*C  Humidity={}%".format(rhsensor, t1, rh1))

    humidity, temperature = Adafruit_DHT.read_retry(rhsensor, rh2pin)
    rh2 = round(humidity, 1)
    t2 = round(temperature, 1)
    if verbose == 1:
        print ("main: Sensor2: DHT{} -- Temp={}*C  Humidity={}%".format(rhsensor, t2, rh2))

    humidity, temperature = Adafruit_DHT.read_retry(rhsensor, rh3pin)
    rh3 = round(humidity, 1)
    t3 = round(temperature, 1)
    if verbose == 1:
        print ("main: Sensor3: DHT{} -- Temp={}*C  Humidity={}%".format(rhsensor, t3, rh3))

    absdraussen = round(absfeucht(t1, rh1), 3)
    absdrinnen = round(absfeucht(t2, rh2), 3)
Exemplo n.º 6
0
def readSensors():
    """
    """
    data = [[datetime.now().strftime("%Y-%m-%d %H:%M:%S"),],[datetime.now().strftime("%Y-%m-%d %H:%M:%S"),]]
    lock.acquire()
    #sensor MCP9808
    if SENSOR == 'MCP':
        temp = sensor.readTempC()    
    #sensor DHT22
    elif SENSOR == 'DHT':
        hum, temp = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, PIN1)
        data[0].append("H%0.1f" % hum)
    #endif
    data[0].append("T%0.1f" % temp)
    #sensor MCP9808
    if SENSOR == 'MCP':
        temp = sensor.readTempC()    
    #sensor DHT22
    elif SENSOR == 'DHT':
        hum, temp = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, PIN2)
        data[1].append("H%0.1f" % hum)
    #endif
    data[1].append("T%0.1f" % temp)
    lock.release()
    return data
Exemplo n.º 7
0
def humtemp():
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    while humidity is None or temperature is None:
        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        time.sleep(1)

    if humidity is not None and temperature is not None:
        return round(temperature, 1), round(humidity,1)
Exemplo n.º 8
0
def main():

        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        while humidity is None and temperature is None:
                time.sleep(3)
                humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        temperature = float("{0:.1f}".format(temperature))
        humidity = float("{0:.1f}".format(humidity))
        log_temperature(temperature,humidity)
Exemplo n.º 9
0
def read_values():

	humi, temp = Adafruit_DHT.read_retry(sensor, pin)

	if humi > 100:
		humi, temp = Adafruit_DHT.read_retry(sensor, pin)

	if humi <= 100:
		return humi, temp

	return None, None
Exemplo n.º 10
0
    def get_data(self):
        # 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).
        self.humidity, self.temperature = Adafruit_DHT.read_retry(self.sensor, self.pin)

        while self.humidity > 100.0:
            time.sleep(2)
            self.humidity, self.temperature = Adafruit_DHT.read_retry(self.sensor, self.pin)

        self.humidity = self.humidity + self.humidityOffset
        self.temperature = self.temperature + self.temperatureOffset
def read_sensors(silent):
    global tempc
    global humidity
    global dewpointc
    global heatindexc
    global chktemp
    chktemp = 1
    
    if (DHTSensor == 'DHT11'): sensor = Adafruit_DHT.DHT11
    elif (DHTSensor == 'DHT22'): sensor = Adafruit_DHT.DHT22
    elif (DHTSensor == 'AM2302'): sensor = Adafruit_DHT.AM2302
    else: sensor = 'Other'

    if not silent and not Terminate:
        logging.info("[Read Sensors] Taking first Temperature/humidity reading")
    if not Terminate:
        humidity2, tempc2 = Adafruit_DHT.read_retry(sensor, DHTPin)
        if humidity2 == None or tempc2 == None:
            logging.warning("[Read Sensors] Could not read temperature/humidity!")
        if not silent and humidity2 != None and tempc2 != None:
            logging.info("[Read Sensors] %.1f°C, %.1f%%", tempc2, humidity2)
    if not Terminate:
        time.sleep(2)
        if not silent: 
            logging.info("[Read Sensors] Taking second Temperature/humidity reading")
    while chktemp and not Terminate and humidity2 != None and tempc2 != None:
        if not Terminate:
            humidity, tempc = Adafruit_DHT.read_retry(sensor, DHTPin)
        if humidity != 'None' or tempc != 'None':
            if not silent and not Terminate: 
                logging.info("[Read Sensors] %.1f°C, %.1f%%", tempc, humidity)
                logging.info("[Read Sensors] Differences: %.1f°C, %.1f%%", abs(tempc2-tempc), abs(humidity2-humidity))
            if abs(tempc2-tempc) > 1 or abs(humidity2-humidity) > 1 and not Terminate:
                tempc2 = tempc
                humidity2 = humidity
                chktemp = 1
                if not silent:
                    logging.info("[Read Sensors] Successive readings > 1 difference: Rereading")
                time.sleep(2)
            elif not Terminate:
                chktemp = 0
                if not silent: 
                    logging.info("[Read Sensors] Successive readings < 1 difference: keeping.")
                tempf = float(tempc)*9.0/5.0 + 32.0
                dewpointc = tempc - ((100-humidity) / 5)
                #dewpointf = dewpointc * 9 / 5 + 32
                #heatindexf =  -42.379 + 2.04901523 * tempf + 10.14333127 * humidity - 0.22475541 * tempf * humidity - 6.83783 * 10**-3 * tempf**2 - 5.481717 * 10**-2 * humidity**2 + 1.22874 * 10**-3 * tempf**2 * humidity + 8.5282 * 10**-4 * tempf * humidity**2 - 1.99 * 10**-6 * tempf**2 * humidity**2
                #heatindexc = (heatindexf - 32) * (5 / 9)
                if not silent: 
                    logging.info("[Read Sensors] Temp: %.1f°C, Hum: %.1f%%, DP: %.1f°C", tempc, humidity, dewpointc)
        else: logging.warning("[Read Sensors] Could not read temperature/humidity!")
def read_DHT():

    value = 0
    temp1_List = []
    temp2_List = []
    temp3_List = []
    tempIn_List = []
    humi1_List = []
    humi2_List = []
    humi3_List = []
    humiIn_List = []
    print '\n Reading DHT - Temperature and Humidity: '

    while value < 6: # 6 = 1 minute, 30 = 5 mintutes
                
        # read data from pins: 25,23,24
        humi1, temp1 = Adafruit_DHT.read_retry(11,25) #temp sensor 1 out 
        humi2, temp2 = Adafruit_DHT.read_retry(11,23) #temp sensor 2 in top
        humi3, temp3 = Adafruit_DHT.read_retry(11,24) #temp sensor 3 in bottom     
                
        # Get average inside Temperature and Huminity
        tempIn = (temp2 + temp3)/2
        humiIn = (humi2 + humi3)/2
                
        #print ('The' + str(value) + 'reading is:')
        print ' Temperature Outside: {0:0.1f}C   Temperature Inside: {1:0.1f}C  ({2:0.1f}C - {3:0.1f}C) '.format(temp1,tempIn,temp2,temp3)
        print ' Humidity Outside:    {0:0.1f}%   Humidity Inside:    {1:0.1f}%  ({2:0.1f}% - {3:0.1f}%) \n'.format(humi1,humiIn,humi2,humi3)
                
        time.sleep(10)
        temp1_List.append(temp1)
        temp2_List.append(temp2)
        temp3_List.append(temp3)
        tempIn_List.append(tempIn)
        humi1_List.append(humi1)
        humi2_List.append(humi2)
        humi3_List.append(humi3)
        humiIn_List.append(humiIn)
                
        value = value + 1
    
    temp_1  = float(mode(temp1_List)[0])
    temp_2  = float(mode(temp2_List)[0])
    temp_3  = float(mode(temp3_List)[0])
    temp_In = float(mode(tempIn_List)[0])
    humi_1  = float(mode(humi1_List)[0])
    humi_2  = float(mode(humi2_List)[0])
    humi_3  = float(mode(humi3_List)[0])
    humi_In = float(mode(humiIn_List)[0])
                
    return (temp_1,temp_In,temp_2,temp_3,humi_1,humi_In,humi_2,humi_3)          
    def run(self):

        # 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).
        while True:
            try:
                if running_mode.RUNNING_MODE == 'N':
                    humidity, temperature = Adafruit_DHT.read_retry(iotUtils.TEMP_SENSOR_TYPE, iotUtils.TEMP_PIN)
                else:
                    humidity, temperature = iotUtils.generateRandomTemperatureAndHumidityValues()

                if temperature != iotUtils.LAST_TEMP:
                    time.sleep(PUSH_INTERVAL)
                    iotUtils.LAST_TEMP = temperature
                    connectAndPushData()

                iotUtils.LAST_TEMP = temperature
                print 'RASPBERRY_STATS: Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity)

            except Exception, e:
                print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                print "RASPBERRY_STATS: Exception in TempReaderThread: Could not successfully read Temperature"
                print ("RASPBERRY_STATS: " + str(e))                
                pass
                time.sleep(self.interval)
Exemplo n.º 14
0
def main(argv=None):

	pin = 4
	humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, pin)

	#convert temp to F
	temperature = temperature * 9/5.0 + 32

        db = influxdb.InfluxDBClient("192.168.1.105", 8086, "root", "root", "climate")

        data = [
            {
                "measurement": "temperature",
                "fields": { "value": temperature },
                "tags": { "device": "cerberus-rpi-am2302", "location":"basement", "type":"current" }
            },
            {
                "measurement":"humidity",
                "fields": { "value": humidity },
                "tags": { "device": "cerberus-rpi-am2302", "location":"basement", "type":"current" }
            },
        ]

	if humidity is not None and temperature is not None:
            db.write_points(data)
	else:
	    print('Failed to get reading. Try again!')
	    sys.exit(1)
Exemplo n.º 15
0
def main():
    # Prep json variable
    data = {}

    # Move to config eventually
    sensor = Adafruit_DHT.DHT22
    pin = 4

    # 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).
    humidity, celsius = Adafruit_DHT.read_retry(sensor, pin)

    if humidity is not None and celsius is not None:
        # Some conversion for fehrenheit
        fahrenheit = 9.0/5.0 * celsius + 32

        # Manually assign good CRC
        crc_error = "false"
    else:
        # Failed to get pull, zero-ize data and flag CRC
        fahrenheit = 0
        crc_error = "true"
        humidity = 0
        celsius = 0

    # Return as dictionary, will be formating this in JSON
    return({'dht22': {'celsius': round(celsius,2), 'fahrenheit' : round(fahrenheit,2), 'humidity' : round(humidity,2), 'crc error' : crc_error, 'datetime': time.strftime("%Y-%m-%d %H:%M")} })
Exemplo n.º 16
0
 def run(self):
     logging.info("DHT module initialized")
     webservice_state_instances_add(self.get_class_name(), self.get_json_status)
     timecheck = time.time()
     while not self.stop_event.is_set():
         time.sleep(1)
         humidity_previous = self.humidity
         temperature_previous = self.temperature
         self.humidity, self.temperature = Adafruit_DHT.read_retry(self.sensor, self.pin)
         if humidity_previous > self.humidity:
             c1 = humidity_previous - self.humidity
         else:
             c1 = self.humidity - humidity_previous
         if temperature_previous > self.temperature:
             c2 = temperature_previous - self.temperature
         else:
             c2 = self.temperature - temperature_previous
         if c1 > 5 or c2 > 2:
             # values have changed, add to plot data
             open(SENSORDHT_PLOTDATA_PATH + os.sep + time.strftime("%d.%m.%y.plotdata"), "a").write(
                 datetime.datetime.now().strftime("%d.%m.%y %H:%M:%S")
                 + "\t%.02f\t%.02f\n" % (self.temperature, self.humidity)
             )
             logging.info(
                 "plotting data due to change, prev h:%s cur h: %s prev t:%s cur t: %s - c1:%s c2:%s"
                 % (humidity_previous, self.humidity, temperature_previous, self.temperature, c1, c2)
             )
         # after 15 tries/30 seconds, None, None
         if time.time() - timecheck > 60:
             timecheck = time.time()
             logging.debug(
                 "60 interval - temperature: " + str(self.temperature) + " Humidity: " + str(self.humidity)
             )
         time.sleep(1)
Exemplo n.º 17
0
def climate():
	pin = 3
	hum,temp = dht.read_retry(dht.DHT22, pin)
	humidity = float(round(hum))
	temperature = float(round(temp))
	return {'hum': humidity, 'temp': temperature}
	time.sleep(1)
Exemplo n.º 18
0
def Start():
    sensorType = Constellation.GetSetting("SensorType")
    if sensorType == "DHT11":
        sensor = Adafruit_DHT.DHT11
    elif sensorType == "DHT22":
        sensor = Adafruit_DHT.DHT22
    elif sensorType == "AM2302":
        sensor = Adafruit_DHT.AM2302
    else:
        Constellation.WriteError("Sensor type not supported ! Check your settings")
        return
    sensorPin = int(Constellation.GetSetting("SensorPin"))
    Constellation.WriteInfo("%s on #%d is ready !" % (sensorType, sensorPin))
    lastSend = 0
    while Constellation.IsRunning:
        ts = int(round(time.time()))
        if ts - lastSend >= int(Constellation.GetSetting("Interval")):
            humidity, temperature = Adafruit_DHT.read_retry(sensor, sensorPin)
            if humidity is not None and temperature is not None:
                Constellation.PushStateObject("Temperature", round(temperature, 2), lifetime = int(Constellation.GetSetting("Interval")) * 2)
                Constellation.PushStateObject("Humidity", round(humidity, 2), lifetime = int(Constellation.GetSetting("Interval")) * 2)
                lastSend = ts
            else:
                Constellation.WriteError("Failed to get reading")                
        time.sleep(1)
Exemplo n.º 19
0
def menu():
    parser = argparse.ArgumentParser(description='Read from the DHT sensor')
    parser.add_argument('sensor', choices=['DHT11', 'DHT22', 'AM2302'], help="Sensor Name")
    parser.add_argument('pin', type=int,
                        help="The GPIO (BCM numbering) connected to the sensor data pin")

    args = parser.parse_args()

    if args.sensor == 'DHT11':
        device = Adafruit_DHT.DHT11
    elif args.sensor == 'DHT22':
        device = Adafruit_DHT.DHT22
    elif args.sensor == 'AM2302':
        device = Adafruit_DHT.AM2302
    else:
        # Invalid device name
        sys.exit(1)

    if not 0 < args.pin < 40:
        print('Error: Invalid GPIO pin.\n')
        sys.exit(1)

    for x in range(10):
        humidity, temperature = Adafruit_DHT.read_retry(device, args.pin)
        print("Temperature: %s" % temperature)
        print("Humidity: %s" % humidity)
        time.sleep(2)
Exemplo n.º 20
0
def getDatenFromSensor():
    humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
    #print("Feuchtigkeit", humidity, "Temperatur", temperature)
    if (humidity is not None) and (temperature is not None):
        return {"hum":humidity, "tmp":temperature}
    else:
        return None
def GPIOtemperRead():
  sensor =  Adafruit_DHT.DHT11
  pin = "P9_11"

  humid, temp = Adafruit_DHT.read_retry(sensor, pin)

  return int(temp)
Exemplo n.º 22
0
    def run(self): 
        pin = self.intConfig('sensorPort', 18)
        
        h1 = self.screen.add_number_widget("h1", x=1, value=0)
        h2 = self.screen.add_number_widget("h2", x=4, value=0)
        m1 = self.screen.add_number_widget("m1", x=8, value=0)
        m2 = self.screen.add_number_widget("m2", x=11, value=0)
        temp = self.screen.add_string_widget("temp", '--', x=15, y=1)
        humidity = self.screen.add_string_widget("humidity", '--', x=15, y=2)

        dot1 = self.screen.add_string_widget("d1", ".", x=7, y=1)
        dot2 = self.screen.add_string_widget("d2", ".", x=7, y=2)

        while True:
            try:
                h, t = dht.read_retry(dht.AM2302, pin, retries=5, delay_seconds=2)
            except RuntimeError:
                h, t = (None, None)

            if h or t:
                temp.set_text("{0:02.0f}".format(t))
                humidity.set_text("{0:02.0f}".format(h))
            else:
                temp.set_text("--")
                humidity.set_text("--")

            for _ in range(12):
                t = now()
                h1.set_value(t.hour / 10)
                h2.set_value(t.hour % 10)
                m1.set_value(t.minute / 10)
                m2.set_value(t.minute % 10)
                sleep(5)
Exemplo n.º 23
0
def main(*args, **kwargs):
	# Parse command line parameters.
	sensor_args = { '11': Adafruit_DHT.DHT11,
			'22': Adafruit_DHT.DHT22,
			'2302': Adafruit_DHT.AM2302 }
	if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
		sensor = sensor_args[sys.argv[1]]
		pin = sys.argv[2]
	else:
		print 'usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#'
		print 'example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4'
		sys.exit(1)

	# 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).
	humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

	# Un-comment the line below to convert the temperature to Fahrenheit.
	# temperature = temperature * 9/5.0 + 32

	# 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 humidity is not None and temperature is not None:
		print 'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity)
	else:
		print 'Failed to get reading. Try again!'
		sys.exit(1)
Exemplo n.º 24
0
def getHwInfo():
    try: 
        humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, dht_pin)
        #logging.info('200: getHwInfo - H:{0} T:{1}'.format(round(humidity,2),round((temperature * 9/5 + 32),2)))
        return round(humidity,2), round((temperature * 9/5 + 32),2)
    except: 
        ThermoHardwareLogger.exception('Exception Occurred in ThermoHardware getHwInfo')
Exemplo n.º 25
0
def temp_hit():									#Poll the temp sensor and update vars
	global h,t
	global temp
	global humid
	h,t = dht.read_retry(dht.DHT11, pin)		#Change sensor here DHT11, DHT22 etc
	temp =  'Temp : {0:0.1f}C'.format(t)			#Formatting
	humid = 'Humid: {1:0.1f}%'.format(t,h)	#Formatting don't really understand these args
Exemplo n.º 26
0
def main():
    humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, '17')
    if humidity is not None and temperature is not None:
        requests.post(THERMOSTAT_URI, data=dict(temperature=temperature, humidity=humidity))
        logger.warn('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
    else:
        logger.error('Failed to get reading. Try again!')
Exemplo n.º 27
0
    def sensor_read_callback(self):
        super(Dht, self).sensor_read_callback()
        # 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).
        humidity, temperature = Adafruit_DHT.read_retry(self.SENSOR, self.sensor_pin)
        self.logger.info("Data from sensor: %s *C and %s" % (temperature, humidity))

        if humidity is not None and temperature is not None:

            humidity = round(humidity, 2)
            if self.humidity != humidity:
                self.humidity = humidity

                if self.config.has_option("server", "hostname"):
                    self.post_data("api/measurements/", self.generate_post_dict(humidity, 2))

            temperature = round(temperature, 2)
            if self.temperature != temperature:
                self.temperature = temperature

                if self.config.has_option("server", "hostname"):
                    self.post_data("api/measurements/", self.generate_post_dict(temperature, 1))

            self.failed = 0
        else:
            self.failed += 1
Exemplo n.º 28
0
def sensor():
    sensor = Adafruit_DHT.AM2302

    humidity, temperature = Adafruit_DHT.read_retry(sensor, TEMP_SENSOR_PIN)
    humidity, temperature = str(round(humidity, 1)), str(round(temperature, 1))

    newrow = [time.strftime("%Y-%m-%d %H:%M:%S"), temperature, humidity,
              str(round(vpdcalc(float(temperature), float(humidity)), 1))]

    destfolder = os.path.join(FOLDERS['sensor'], time.strftime("%Y"))
    destfile = os.path.join(destfolder, time.strftime("%Y-%m") + ".csv")

    if not os.path.isdir(destfolder):
        os.makedirs(destfolder)
        os.chmod(destfolder, 0o777)

    if not os.path.isfile(destfile):
        with open(destfile, "w+") as f:
            f.write("timestamp,temp,rh,vpd\n")
            f.write(",".join(newrow) + "\n")
    else:
        with open(destfile, "a+") as f:
            f.write(",".join(newrow) + "\n")

    print(time.strftime("%Y-%m-%d %H:%M:%S"), "Sensor update", temperature, humidity)
Exemplo n.º 29
0
 def post(self):
     try: 
         # Parse the arguments
         #parser = reqparse.RequestParser()
        # parser.add_argument('id', type=str)
         humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
         data='Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity)
def calculate():
    while True:
        temp = trim_pot

        #calculate DHT
        RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)
    
        #Convert from Celius to Farenheit
        TWF = 9/5*TW+32

        print "temperature is"
        print TWF
        print "humidity is"
        print RHW
          
        if (TWF>75):
            subject = 'Room2 alert'
            text = 'Temperature high!!!'
            msg = 'Subject: %s\n\n%s' % (subject, text)
            server = smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login(username,password)
            server.sendmail(fromaddr, toaddrs, msg)
            server.quit()
        if (temp>566):
            print " sending mail"
            subject = 'Room2 alert'
            text = 'Air Quality badd!!!'
            msg = 'Subject: %s\n\n%s' % (subject, text)
            server = smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login(username,password)
            server.sendmail(fromaddr, toaddrs, msg)
            server.quit()
        break
Exemplo n.º 31
0
	not_connected = 1 
	while (not_connected):
		try:
			conn = http.HTTPConnection("api.mediatek.com:80")
			conn.connect() 
			not_connected = 0 
		except (http.HTTPException, socket.error) as ex: 
			print ("Error: %s" % ex)
 			#time.sleep(10)
	conn.request("POST", "/mcs/v2/devices/" + deviceId + "/datapoints", json.dumps(payload), headers) 
	response = conn.getresponse() 
	print( response.status, response.reason, json.dumps(payload), time.strftime("%c")) 
	data = response.read() 
	conn.close()
while True:
	h0, t0= Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, GPIO_PIN)
	SwitchStatus = GPIO.input(24)
	if(SwitchStatus == 1):
		print('Button pressed')
		print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(t0, h0))
	else:
		print('Button released')
		print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(t0, h0))

	payload = {"datapoints":[{"dataChnId":"Humidity","values":{"value":h0}}
		,{"dataChnId":"Temperature","values":{"value":t0}}	
		,{"dataChnId":"SwitchStatus","values":{"value":SwitchStatus}}]}
	
	post_to_mcs(payload)
	time.sleep(1)
Exemplo n.º 32
0
#!/usr/bin/python

import sys
import Adafruit_DHT as dht

if (len(sys.argv) == 2):
    pin = sys.argv[1]
else:
    print "usage:\n", sys.argv[0], "<SENSOR_PIN>"
    sys.exit(1)

humidity, temperature = dht.read_retry(dht.DHT22, pin)

if humidity is not None and temperature is not None:
    print('{0:0.1f} {1:0.1f}'.format(temperature, humidity))
else:
    print("")
Exemplo n.º 33
0
 def read(self):
     h, t = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, self.pin)
     if not self._reasonable_sensor_values(h, t):
         raise SensorReadFailure(h, t)
     return h, t
Exemplo n.º 34
0
def getThermalSensorData():
    H, T = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302,'4')
    return H, T
Exemplo n.º 35
0
import os
import time
import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PINE = 10

try:
    f = open('/var/www/html/enviro.csv', 'a+')
    if os.stat('/var/www/html/enviro.csv').st_size == 0:
        f.write('Date,Time,TempE,HumE\r\n')
except:
    pass

while True:
    humidityE, temperatureE = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PINE)
    if humidityE is not None and temperatureE is not None:

        f.write('{0} {1},{2:0.1f},{3:0.1f}%\r\n'.format(
            time.strftime('%m/%d/%y'), time.strftime('%H:%M:%S'),
            ((temperatureE * 1.8) + 32), humidityE))
        f.flush()

        f2 = open("/var/www/html/latest.php", "w")
        f2.write('Saturn Enclosure: {0:0.1f}/{1:0.1f}%\r\n'.format(
            ((temperatureE * 1.8) + 32), humidityE))
        f2.close()
        f.flush()

    time.sleep(10)
Exemplo n.º 36
0
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS Ambient 
    (id INTEGER PRIMARY KEY AUTOINCREMENT,
    Temperature REAL NOT NULL,
    Humidity REAL NOT NULL,
    Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
conn.commit()
DATA_TIME = 300 # In seconds
MEASUREMENTS_PER_INTERVAL = 50 
MEASUREMENT_TIME = DATA_TIME // MEASUREMENTS_PER_INTERVAL

measurements = []
start = time.time()    
while True:
    start_measure = time.time()
    t = Adafruit_DHT.read_retry(11,4)
    elapsed_measure = time.time() - start_measure
    measurements.append(t)
    print('Temp: {0:0.3f} C  Hum: {1:0.3f} %'.format(t[1], t[0]))
    if len(measurements) == MEASUREMENTS_PER_INTERVAL:
        avg_hum = sum([t[0] for t in measurements])/MEASUREMENTS_PER_INTERVAL
        avg_temp = sum([t[1] for t in measurements])/MEASUREMENTS_PER_INTERVAL
        print('Temp: {0:0.3f} C  Hum: {1:0.3f} %'.format(avg_temp, avg_hum))
        # Insert into DB
        c = conn.cursor()
        c.execute('''INSERT INTO Ambient (Humidity,Temperature) VALUES
        ({0:0.3f},{1:0.3f})'''.format(avg_hum,avg_temp))
        conn.commit()
        # Reset queue
        elapsed = time.time() - start
        print("Total elapsed time: " + str(elapsed))
Exemplo n.º 37
0
#!/usr/bin/python
import Adafruit_DHT
import sys

if len(sys.argv) != 2:
    print 'Missing pin argument'
    sys.exit(2)

gpioPin = int(sys.argv[1])

humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11,
                                                gpioPin,
                                                delay_seconds=1)

if humidity is not None and temperature is not None:
    print 'temp:{0:0.1f}|hum:{1}'.format(temperature, humidity)
else:
    print 'invalid'
	def read_sensor (sensor, pin):
# 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).
		return Adafruit_DHT.read_retry(sensor, pin)
Exemplo n.º 39
0
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP


# DHT22

dht22_pin = 27  # pin for DHT22 Data
dht22_sensor = Adafruit_DHT.DHT22

dht22_humidity, dht22_temperature = Adafruit_DHT.read_retry(
    dht22_sensor, dht22_pin)
if dht22_humidity is not None and dht22_temperature is not None:
    dht22_temperature_raw = round(dht22_temperature, 5)
    dht22_temperature_calib = round(
        dht22_temperature * temperature_cal_a1 + temperature_cal_a0, 3)
    dht22_temperature = dht22_temperature_calib
    saturation_vappress_ucalib = 6.113 * numpy.exp(
        (2501000.0 / 461.5) *
        ((1.0 / 273.15) -
         (1.0 /
          (dht22_temperature_raw + 273.15))))  #Clausius-Clapeyron-Gleichung
    saturation_vappress_calib = 6.113 * numpy.exp(
        (2501000.0 / 461.5) * ((1.0 / 273.15) -
                               (1.0 / (dht22_temperature_calib + 273.15))))
    #saturation_vappress_ucalib= 6.1078 * numpy.exp((17.08085*dht22_temperature_raw)/(234.175+dht22_temperature_raw))      # Ansatz für VPmax in der Psychrometertafel
    #saturation_vappress_calib= 6.1078 * numpy.exp((17.08085*dht22_temperature_calib)/(234.175+dht22_temperature_calib))
Exemplo n.º 40
0
def main():
    GPIO.setmode(GPIO.BOARD)  # Numbers GPIOs by physical location
    GPIO.setwarnings(False)

    GPIO.setup(ReedPin, GPIO.IN, pull_up_down=GPIO.PUD_UP
               )  # Set BtnPin's mode is input, and pull up to high level(3.3V)
    GPIO.add_event_detect(ReedPin, GPIO.BOTH, callback=detect, bouncetime=200)

    GPIO.setup(BuzzerPin, GPIO.OUT, initial=GPIO.LOW)  #Default State Off.

    for pin in pins:
        GPIO.setup(pin, GPIO.OUT)  # Set all pins' mode is output

    strdoorstatus = ' '

    # Initialise display
    init()

    #buzzertest()
    Led(0)

    #Start main Routine
    while True:
        localtime = time.asctime(time.localtime(time.time()))
        strlocaltime = 'Local Time: ', localtime

        # -------------------------------------------------------------------------------
        #check door sensor status
        # -------------------------------------------------------------------------------
        Led(GPIO.input(ReedPin))

        # --------------------------------------------------------------------------------
        # Temperature Sensor
        # --------------------------------------------------------------------------------
        humidity, temperature = DHT.read_retry(Sensor,
                                               humiture)  #built in 2sec delay

        if humidity is not None and temperature is not None:
            #strtemp = str(Temp={0:0.1f}*C).format(temperature)

            temperature = str(temperature)
            humidity = str(humidity)
            strdoorstatus = str(strdoorstatus)

            # ------------------------
            #strtemp = 'Temp: ' + str(temperature) + ' ' + chr(223) + 'C' #add degree symbol
            #strhumidity = 'Humidity: ' + str(humidity) + '%'
            # ------------------------

            # ----------------------------------------------------------------------
            # print 'Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity)
            # strdisplay = str('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
            # print strdisplay #print on console window

            ###########################################################
            #
            #
            displayonlcd(temperature, humidity, strdoorstatus)

            if webpage == 1:
                updatewebpage(temperature, humidity, strdoorstatus)
            #
            ###########################################################

        else:
            print('Failed to get reading')
Exemplo n.º 41
0
import sys
import Adafruit_DHT

while True:
    humidity, temperature = Adafruit_DHT.read_retry(11, 4)
    print 'Temp: {0:0.1f} C --- Humidity: {1:0.1f}%'.format(
        temperature, humidity)
Exemplo n.º 42
0
# The break of 2 seconds will be configured here
sleeptime = 2

# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHTSensor = Adafruit_DHT.DHT11

# The pin which is connected with the sensor will be declared here
GPIO_Pin = 24

print('KY-015 sensortest - temperature and humidity')

try:
    while (1):
        # Measurement will be started and the result will be written into the variables
        humid, temper = Adafruit_DHT.read_retry(DHTSensor, GPIO_Pin)

        print(
            "-----------------------------------------------------------------"
        )
        if humid is not None and temper is not None:

            # The result will be shown at the console
            print(
                'temperature = {0:0.1f}C  | rel. humidity = {1:0.1f}%'.format(
                    temper, humid))

        # Because of the linux OS, the Raspberry Pi has problems with realtime measurements.
        # It is possible that, because of timing problems, the communication fails.
        # In that case, an error message will be displayed - the result should be shown at the next try.
        else:
Exemplo n.º 43
0
    else:
        #on
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(pin_number, GPIO.OUT)  #устанавливаем пин на выходной сигнал
        GPIO.output(pin_number,
                    GPIO.HIGH)  #ставим логическую еденицу на выходе
        print('Relay On')


sensor = 22
pin = 4
pin2 = 18

# Снимаем показания с датчика на пине 4, т.е. в помещении
humidity, temperature = dht.read_retry(sensor, pin)
if (humidity is not None) and (temperature is not None):
    nowtime = datetime.strftime(datetime.now(), "%Y-%d-%m %H:%M:%S")
    temperature = float(temperature)
    humidity = float(humidity)
    temperature = round(temperature, 1)
    humidity = round(humidity, 1)
    #        print(nowtime + "\t" + temperature + "C\t" + humidity +"%")
    print(temperature)
    print(humidity)

# Перед этим надо считать признак упрвления реле - вручную или автомат
# Это будет хранитья в БД climat

# Если автомат, то считать Т включения и Т выключения
# Это будет хранитья в БД climat
Exemplo n.º 44
0
def getSensorData():
    RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 23)
    # return dict
    return (str(RH), str(T))
 def get(self):
     humidity, temperature = Adafruit_DHT.read_retry(
         config.sensor, config.gpio)
     return {"humidity": humidity, "temperature": temperature}
Exemplo n.º 46
0
def watch(signum, frame):

    global LOGDIR
    global INTERVAL
    global DHT_SENSOR
    global DHT_PIN
    global col
    global series
    global currentIndex
    global vcmd
    global previousDateTime
    global activity

    currentDateTime = datetime.now()
    day, tm = currentDateTime.strftime('%Y%m%d-%H%M%S').split('-')

    series[currentIndex][['date', 'time']] = [day, tm]
    series[currentIndex][['humid[%]', 'temp[*C]']] = [
        round(x, 2) if x else 0
        for x in Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    ]
    series[currentIndex][['CPU[*C]', 'CPU[v]', 'CPU[MHz]']] = [
        vcmd.measure_temp(),
        vcmd.measure_volts('core'),
        round(vcmd.measure_clock('arm') / 1000000)
    ]
    series[currentIndex][['CPU[%]', 'memory[%]', 'rootfs[%]', 'usb[%]']] = [
        psutil.cpu_percent(interval=1),
        psutil.virtual_memory().percent,
        psutil.disk_usage('/').percent,
        psutil.disk_usage('/home/pi/usb').percent
    ]
    series[currentIndex]['activity'], oldestJPG, recentFiles = countMotion(
        previousDateTime, currentDateTime)

    if 80 < series[currentIndex]['usb[%]'] and oldestJPG:
        if os.path.exists(oldestJPG):
            os.remove(oldestJPG)
            if oldestJPG in recentFiles:
                del recentFiles[recentFiles.index(oldestJPG)]
        print(oldestJPG, 'deleted due to free space shortage.')
    '''
    if 95 < series[currentIndex]['usb[%]']:
        fname = min(glob(LOGDIR + '20*.csv'))
        os.remove(fname)
        print(fname, 'deleted due to free space shortage.')
    '''

    response = None
    activity += series[currentIndex]['activity']
    if 0 < series[currentIndex]['activity']:

        msg = series[currentIndex]['time'][:2] + ':' + series[currentIndex][
            'time'][2:4] + ' '
        n = series[currentIndex]['activity']
        for li in range(len(lastMoveIndex)):
            lastMoveIndex[li] = (lastMoveIndex[li] + 1) % len(lastMoveIndex)
        lastMoves[lastMoveIndex[-1]] = (msg, str(n))

        if n < 10:
            msg += 'たろいもさんが起きました'
        elif n < 20:
            msg += 'たろいもさんがうろうろしてます'
        elif n < 30:
            msg += 'たろいもさんが走り回ってます'
        else:
            msg += 'たろいもさんが暴れてます'

        msg += ":" + str(n) + ' activity/分, '
        msg += '温度:' + str(series[currentIndex]['temp[*C]']) + '℃, '
        msg += '湿度:' + str(series[currentIndex]['humid[%]']) + '%'

        client = WebClient(token=os.environ["SLACK_API_TOKEN"])
        try:
            response = client.chat_postMessage(channel='C018J2HN0UB', text=msg)

            for fname in getLastNImages(False, True, 5):
                if fname in recentFiles:
                    response = client.files_upload(
                        channels='C018J2HN0UB',
                        file=fname,
                    )

        except urllib.error.URLError as e:
            print(response, '\n', e, '\n', currentDateTime)
            sendMail(msg, str(response) + str(e))
            pass
        except:
            print(response, currentDateTime)
            sendMail(msg, str(response))
            pass

    if currentIndex % 10 == 0:

        drawChart(pd.DataFrame([y for y in \
                                [x for x in series if not pd.isnull(x['date'])]]))

        df = pd.DataFrame([y for y in \
                           [x for x in series if not pd.isnull(x['date'])] \
                           if y['date'] == day]) \
               .sort_values(by = ['date', 'time'], ascending = False).reset_index(drop = True)

        df.to_csv(LOGDIR + day + '.csv', encoding='utf-8', index=False)
        print(day + '.csv dumped with', len(df),
              'records (' + tm[:2] + ':' + tm[2:4] + ':' + tm[4:] + ')')

        msg = currentDateTime.strftime('%H:%M') + ' 最近の10分間:' + str(
            activity) + ' activity, '
        msg += '温度:' + str(series[currentIndex]['temp[*C]']) + '℃, '
        msg += '湿度:' + str(series[currentIndex]['humid[%]']) + '%, '
        msg += 'CPU温度,使用率:' + str(
            series[currentIndex]['CPU[*C]']) + '℃,' + str(
                series[currentIndex]['CPU[%]']) + '%, '
        msg += 'メモリ使用率:' + str(series[currentIndex]['memory[%]']) + '%, '
        msg += 'SD,USB使用率:' + str(
            series[currentIndex]['rootfs[%]']) + '%, ' + str(
                series[currentIndex]['usb[%]']) + '%, '

        msg += '最近の動き:'
        for li in range(len(lastMoveIndex) - 1, -1, -1):
            if not lastMoveIndex[li] in lastMoves:
                break
            lm = lastMoves[lastMoveIndex[li]]
            msg += lm[0] + lm[1] + 'act, '

        activity = 0
        client = WebClient(token=os.environ["SLACK_API_TOKEN"])
        try:
            response = client.chat_postMessage(channel='C018J2HN0UB', text=msg)
            for fname in getLastNImages(True, False, 0):
                response = client.files_upload(
                    channels='C018J2HN0UB',
                    file=fname,
                )

        except urllib.error.URLError as e:
            print(response, '\n', e, currentDateTime)
            sendMail(msg, str(response) + str(e))
            pass
        except:
            print(response, currentDateTime)
            sendMail(msg, str(response))
            pass
    '''
    if currentIndex % 10 == 0 or 0 < series[currentIndex]['activity']:
                
        sbj = ''
        for c in ['activity', 'temp[*C]', 'humid[%]', 'CPU[*C]', 'CPU[%]', 'memory[%]', 'rootfs[%]', 'usb[%]']:
            sbj += c + ':' + str(series[currentIndex][c]) + ', '

        body = ' '.join(df.columns.tolist())
        for i in range(10 if 10 < len(df.index) else len(df.index)):
            body += '\n'
            for c in df.columns[1:]:
                body += c + ':' + str(df.loc[i, c]) + ', '

        try:
            os.system('python3 mail.py \"yahoo\" \"[email protected]\" \"' + sbj + '\" \"' + body + '\"')
        except:
            pass
    '''

    if tm.startswith('235'):
        df = pd.DataFrame([y for y in \
                           [x for x in series if not pd.isnull(x['date'])] \
                           if y['date'] == day]) \
               .sort_values(by = ['date', 'time'], ascending = False).reset_index(drop = True)

        df.to_csv(LOGDIR + day + '.csv', encoding='utf-8', index=False)
        print(day + '.csv dumped with', len(df),
              'records (' + tm[:2] + ':' + tm[2:4] + ':' + tm[4:] + ')')

    currentIndex = (currentIndex + 1) % len(series)
    previousDateTime = currentDateTime
Exemplo n.º 47
0
    sensor = Adafruit_DHT.DHT22
    #传感器设置为DHT22, 驱动选用Adafruit_DHT

    tem_MAX = 31
    hum_MAX = 9  #设定温度湿度最大值
    receivers = ['*****@*****.**', '*****@*****.**', '*****@*****.**']
    #报警接收人

    ntp_server = 'x.x.x.x'
    #设定时钟服务器
    if int(time.time() / 60) % 10 == 0:
        os.system('sudo ntpdate ' + ntp_server)
        print('sudo ntpdate ' + ntp_server)
    #每十分钟同步一次时钟

    humidity, temperature = Adafruit_DHT.read_retry(sensor, 27)
    #湿度和温度来自pin角27
    tmp = "{:.1f}".format(temperature)
    hmt = "{:.1f}".format(humidity)
    #格式化温湿度数值,保留一位小数
    if humidity < 99:
        #如果湿度超过99, 传感器有些问题,经常湿度会到3000+,引起不必要的麻烦,故这里使用软件方式跳过这些非正常值

        date = datetime.datetime.now().strftime("%Y-%m-%d")

        time = now = datetime.datetime.now().strftime("%H:%M")
        print(tmp, hmt, date, time, ip())

        display("Temperature:" + tmp + "C", "Humidity:" + hmt + "%", time,
                ip())
        #led显示器上显示温度,湿度
Exemplo n.º 48
0
def get_dht():
    humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, dht_pin)
    print("Humidity ", humidity, " - Temperature: ", temperature)
    return humidity, temperature
Exemplo n.º 49
0
contenido_parseado = json.loads(contenido)
Write_API_key = contenido_parseado["api_keys"][0]["api_key"]

#-------------------------------------------------------------------
#CONFIGURACION DEL SENSOR DHT11

# Configuracion del tipo de sensor DHT

sensor = Adafruit_DHT.DHT22

# Configuracion del puerto GPIO al cual esta conectado  (GPIO 23)
pin = 4

# Obtiene la humedad y la temperatura desde el sensor
while True:
    humedad, temperatura = Adafruit_DHT.read_retry(sensor, pin)

    # Calcular la temperatura del Punto de Rocio [ºC]
    PuntoRocio = (humedad / 100)**(1 / 8) * (112 + 0.9 * temperatura) + (
        0.1 * temperatura) - 112
    print("Punto de Rocio:" + str(PuntoRocio))

    #print "--> Subiendo datos a ThingSpeak"
    #print "--> Enviando peticion HTTP"
    metodo = "POST"
    uri = "/update.json"
    cabeceras = {
        "Host": "api.thingspeak.com",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    params = {
def SeeAndListen():
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    if humidity is not None and temperature is not None:
        if temperature >= 0 and temperature <= 10:
            greenled.on()
            sleep(0.5)
            greenled.off()
            sleep(0.5)
            greenled.on()
            sleep(0.5)
            greenled.off()
            sleep(0.5)
            greenled.on()
            sleep(0.5)
            greenled.off()
            cmd = "espeak 'The current temperature is " + str(
                temperature) + "Degrees Celcius and the humidity is" + str(
                    humidity) + "Percent'"
            #Uncomment the below line if you would like to hear your Raspberry Pi speak
            #os.system(cmd)
            time.sleep(2)
            return
        elif temperature > 10 and temperature <= 20:
            amberled.on()
            sleep(0.5)
            amberled.off()
            sleep(0.5)
            amberled.on()
            sleep(0.5)
            amberled.off()
            sleep(0.5)
            amberled.on()
            sleep(0.5)
            amberled.off()
            cmd = "espeak 'The current temperature is " + str(
                temperature) + "Degrees Celcius and the humidity is" + str(
                    humidity) + "Percent'"
            #Uncomment the below line if you would like to hear your Raspberry Pi speak
            #os.system(cmd)
            time.sleep(2)
            return
        elif temperature > 20:
            redled.on()
            sleep(0.5)
            redled.off()
            sleep(0.5)
            redled.on()
            sleep(0.5)
            redled.off()
            sleep(0.5)
            redled.on()
            sleep(0.5)
            redled.off()
            cmd = "espeak 'The current temperature is " + str(
                temperature) + "Degrees Celcius and the humidity is" + str(
                    humidity) + "Percent'"
            #Uncomment the below line if you would like to hear your Raspberry Pi speak
            #os.system(cmd)
            time.sleep(2)
            return
    else:
        print(
            'Failed to get a reading. I will not blink this time around. Will try again soon!!!'
        )
        time.sleep(5)
        return
def GetInternalTemp():
    hum, temp = Adafruit_DHT.read_retry(Ada_Type, Ada_Pin)

    return round(hum), round(temp)
Exemplo n.º 52
0
# Author: Tony DiCola
'''

import sys
import Adafruit_DHT

DHT11 = 11        # DHT22 = 11 | DHT22 = 22
DHT11_PIN = 21    # DHT11 BCM 핀 번호 정의 

try:

  while 1 :

    # 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).
    humidity, temperature = Adafruit_DHT.read_retry(DHT11, DHT11_PIN)

    # Un-comment the line below to convert the temperature to Fahrenheit.
    # temperature = temperature * 9/5.0 + 32

    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))

    else:
        print('Failed to get reading. Try again!')
        # sys.exit(1)

finally:
    GPIO.cleanup()      # GPIO 상태 초기화, 없을 경우 예제 재 실행 시 사용중인 GPIO 경고 발생 

Exemplo n.º 53
0
 def read(self):
     if time() - self.last_read > 30:
         self.humidity, self.temperature = Adafruit_DHT.read_retry(
             self.sensor, self.pin)
         self.last_read = time()
Exemplo n.º 54
0
def gettemphum():
    ht = Adafruit_DHT.read_retry(11,4)
    global temp
    temp = ht[1]
    global hum
    hum = ht[0]
Exemplo n.º 55
0
def get_current_sensor_value():
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    timestamp = time.time()
    return SensorValue(timestamp, humidity, temperature)
Exemplo n.º 56
0
	data = response.read()
	conn.close()

# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
                '22': Adafruit_DHT.DHT22,
                '2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
    sensor = sensor_args[sys.argv[1]]
    pin = sys.argv[2]
else:
    print('Usage: sudo ./Adafruit_DHT.py [11|22|2302] <GPIO pin number>')
    print('Example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO pin #4')
    sys.exit(1)
while True:
	h0, t0= Adafruit_DHT.read_retry(sensor, pin)
	if h0 is not None and t0 is not None:
		print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(t0, h0))
	else:
		print('Failed to get reading. Try again!')
		sys.exit(1)
	SwitchStatus=GPIO.input(24)
	if(SwitchStatus==0):
		print('Button pressed')
	else:
		print('Button released')
	payload = {"datapoints":[{"dataChnId":"Humidity","values":{"value":h0}},
			{"dataChnId":"Temperature","values":{"value":t0}}]}
	post_to_mcs(payload)
	
	payload = {"datapoints":[{"dataChnId":"SwitchStatus","values":{"value":SwitchStatus}},
Exemplo n.º 57
0
#    errors.log:   Errors reading the sensor are logged here
#    data.json:    The last entry as JSON
#
# Released under MIT license to https://github.com/LB4FH/Templogger
# Usage: /usr/bin/python3 temp.py

import Adafruit_DHT
import time
import datetime
import json

DT = datetime.datetime.now().isoformat()
date = datetime.date.today()
filename = "/home/pi/logs/{0}.log".format(date)

humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4)

if humidity is not None and temperature is not None:
    with open(filename, "a") as f:
        f.write("{0};{1:0.1f};{2:0.1f}\n".format(DT, temperature, humidity))
    data = {}
    data['last'] = []
    data['last'].append({
        'Temperature': round(temperature, 2),
        'Humidity': round(humidity, 2),
        'Timestamp': DT
    })
    with open('data.json', 'w') as outfile:
        json.dump(data, outfile)
else:
    with open("/home/pi/errors.log", "a") as f:
Exemplo n.º 58
0
def sensorReadTable(sensor, pin, app):
    humidity, temperature = Adafruit_DHT.read_retry(sensor,
                                                    pin,
                                                    retries=2,
                                                    delay_seconds=0)
    dateTime = datetime.today()

    if humidity is not None and temperature is not None:
        if len(listTemperature) <= i[0]:
            listTemperature.append(temperature)
            listHumidity.append(humidity)
            listDateTime.append(dateTime)
        else:
            del listTemperature[i[0]]
            del listHumidity[i[0]]
            del listDateTime[i[0]]
            listTemperature.insert(i[0], temperature)
            listHumidity.insert(i[0], humidity)
            listDateTime.insert(i[0], dateTime)
        print('humidity: ', humidity)

        if (temperature > 40) and (humidity > 70):
            choice = QMessageBox.warning(
                app, 'High Temperature & Humidity Alert!',
                'Temperature is higher than the threshold of 40. \n Humidity is higher than threshold of 70 %',
                QMessageBox.Close)
        elif (temperature > 40) and (humidity < 30):
            choice = QMessageBox.warning(
                app, 'High Temperature & Low Humidity Alert!',
                'Temperature is higher than the threshold of 40 C. \n Humidity is lower than threshold of 30 %',
                QMessageBox.Close)
        elif temperature > 40:
            choice = QMessageBox.warning(
                app, 'High Temperature Alert!',
                'Temperature is higher than the threshold of 40 C.',
                QMessageBox.Close)
        elif (temperature < 10) and (humidity > 70):
            choice = QMessageBox.warning(
                app, 'Low Temperature & High Humidity Alert!',
                'Temperature is lower than the threshold of 10 C. \n Humidity is higher than threshold of 70 %',
                QMessageBox.Close)
        elif (temperature < 10) and (humidity < 30):
            choice = QMessageBox.warning(
                app, 'Low Temperature & Low Humidity Alert!',
                'Temperature is lower than the threshold of 10 C. \n Humidity is lower than threshold of 30 %',
                QMessageBox.Close)
        elif temperature < 10:
            choice = QMessageBox.warning(
                app, 'Low Temperature Alert!',
                'Temperature is lower than the threshold of 10 C.',
                QMessageBox.Close)
        elif humidity < 30:
            choice = QMessageBox.warning(
                app, 'Low Humidity Alert!',
                'Humidity is lower than the threshold of 30 %.',
                QMessageBox.Close)
        elif humidity > 70:
            choice = QMessageBox.warning(
                app, 'High Humidity Alert!',
                'Humidity is higher than the threshold of 70 %.',
                QMessageBox.Close)

        if i[0] < 99:
            i[0] = i[0] + 1
        else:
            i[0] = 0
Exemplo n.º 59
0
    fileOut.write(time.strftime("%d/%m/%Y"))
    fileOut.write(",")
    fileOut.write(time.strftime("%H:%M:%S"))
    fileOut.write(",")
    print "-------------------------------------------------------------"
    print "BMP DATA:\n"
    print "Temperatrue  : %f C" % tempC
    fileOut.write(str(tempC) + ",")
    print "Pressure  : %f hPa" % preshPa
    fileOut.write(str(preshPa) + ",")
    print "Altitude  : %f m" % altitudeM
    fileOut.write(str(altitudeM) + ",")

    print "\n\nAM2302 Data:\n"

    humidity, temperatureC = Adafruit_DHT.read_retry(
        Adafruit_DHT.AM2302, 17)  # Yellow wire on PIN 27

    print "Temperatrue : %f C" % temperatureC
    fileOut.write(str(temperatureC) + ",")
    print "humidity  : %f P" % humidity
    fileOut.write(str(humidity) + ",")
    print "-------------------------------------------------------------"
    fileOut.write("\n")

    time.sleep(10)

    if count % 3 == 0:
        subprocess.call("./test.sh")

humidity, temperatureC = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302,
                                                 DHTPIN)  # Yellow
Exemplo n.º 60
0
#!/usr/bin/python
import sys
import Adafruit_DHT

temps = ""
# for each command line arguments
# print temperature in Celsius degree and humidity in %
for i in range(1, len(sys.argv)):
    humidity, temperature = Adafruit_DHT.read_retry(11, sys.argv[i])
    temps += str('{0:0.1f}'.format(temperature)) + ' '

if len(temps) > 0:
    print temps

if len(sys.argv) < 2:
    humidity, temperature = Adafruit_DHT.read_retry(11, 4)
    print '{0:0.1f}'.format(temperature)