def read_temp_and_hum(): dhtreader.init() temp_and_hum = dhtreader.read(11, 4) if temp_and_hum: return temp_and_hum else: print "[Error:] Failed to read from sensor, maybe try again?"
def init(self): GPIO.setmode(GPIO.BCM) #lights self.irLightPin = 7 self.whiteLightPin = 8 GPIO.setup(self.whiteLightPin, GPIO.OUT) GPIO.setup(self.irLightPin, GPIO.OUT) GPIO.output(self.whiteLightPin, 0) GPIO.output(self.irLightPin, 0) self.whiteIsOn = 0 self.irIsOn = 0 #temp and hum self.dhttype = 22 self.dhtpin = 17 dhtreader.init() # #running wheels self.hallSensor1 = 23 #wheel 1, sensor 1 self.hallSensor2 = 24 #wheel 1, sensor 2 self.hallSensor3 = 14 #wheel 1, sensor 1 self.hallSensor4 = 15 #wheel 1, sensor 1 #sensor is always on and turn off in response to a magnet, use GPIO.PUD_UP GPIO.setup(self.hallSensor1, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.hallSensor2, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.hallSensor3, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.hallSensor4, GPIO.IN, pull_up_down=GPIO.PUD_UP) #sensors is always on, detect FALLING phase with GPIO.FALLING GPIO.add_event_detect(self.hallSensor1, GPIO.FALLING) GPIO.add_event_callback(self.hallSensor1, self.wheel_event_received) GPIO.add_event_detect(self.hallSensor2, GPIO.FALLING) GPIO.add_event_callback(self.hallSensor2, self.wheel_event_received) GPIO.add_event_detect(self.hallSensor3, GPIO.FALLING) GPIO.add_event_callback(self.hallSensor3, self.wheel_event_received) GPIO.add_event_detect(self.hallSensor4, GPIO.FALLING) GPIO.add_event_callback(self.hallSensor4, self.wheel_event_received) # #log file self.outfile = 0 self.log = {'a': [], 'b': []}
def worker(): dhtreader.init() # try this multiple times because we don't always get data on first attempt # the python driver for this sensor is still experimental for x in range(10): result = get_sensor_data() if result: # stash the data we found and exit stash_temperature(result[0]) stash_humidity(result[1]) break # wait 10 seconds before attempting another sensor reading time.sleep(10)
def read(pin): i = 0 while i<10: try: dhtreader.init() t, h = dhtreader.read(22, pin) if t and h: t = float("{0:.2f}".format(t)) h = float("{0:.2f}".format(h)) return t, h, True finally: i = i + 1 return False
def __init__(self,data): dhtreader.init() dhtreader.lastDataTime = 0 dhtreader.lastData = (None,None) self.sensorName = "DHT22" self.pinNum = int(data["pinNumber"]) self.valName = data["measurement"] self.ontology = data["ontology"] self.valUnit = data["uom_name"] self.valUnitSymbol = data["uom_symbol"] self.uom_ontology = data["uom_ontology"] self.sensor_longName = data["sensor_longName"] self.sensor_shortName= data["sensor_shortName"] self.sensor_manufacturerURL = data["sensor_manufacturerURL"] self.sensor_manufacturer = data["sensor_manufacturer"] self.sensor_URN = data["sensor_URN"]
def __init__(self, data): """Initialise. Initialise the DHT22 sensor class using parameters passed in 'data'. Instances of this class can be set to monitor either temperature ('temp') or pressure ('h'). This is determined by the contents of 'data' passed to this __init__ function. If you want to read both properties, you'll need two instances of the class. When set to read temperature, self.valname is 'Temperature-DHT' to differentiate it from other temperature sensors on the AirPi (such as the BMP). By default temperatures are read in Celsius; data["unit"] can be set to "F" to return readings in Fahrenheit instead if required. Humidity is returned as percentage relative humidity. Args: self: self. data: A dict containing the parameters to be used during setup. Return: """ dhtreader.init() dhtreader.lastDataTime = 0 dhtreader.lastData = (None, None) self.readingtype = "sample" self.pinnum = int(data["pinnumber"]) if "temp" in data["measurement"].lower(): self.sensorname = "DHT22-temp" self.valname = "Temperature-DHT" self.valunit = "Celsius" self.valsymbol = "C" if "unit" in data: if data["unit"] == "F": self.valunit = "Fahrenheit" self.valsymbol = "F" elif "h" in data["measurement"].lower(): self.sensorname = "DHT22-hum" self.valname = "Relative_Humidity" self.valsymbol = "%" self.valunit = "% Relative Humidity" if "description" in data: self.description = data["description"] else: self.description = "A combined temperature and humidity sensor." return
def __init__(self,data): dhtreader.init() dhtreader.lastDataTime = 0 dhtreader.lastData = (None,None) self.sensorName = "DHT22" self.pinNum = int(data["pinNumber"]) if "temp" in data["measurement"].lower(): self.valName = "Temperature" self.valUnit = "Celsius" self.valSymbol = "C" if "unit" in data: if data["unit"]=="F": self.valUnit = "Fahrenheit" self.valSymbol = "F" elif "h" in data["measurement"].lower(): self.valName = "Relative_Humidity" self.valSymbol = "%" self.valUnit = "% Relative Humidity" return
def Init(): global bmp Log('Initializing ...') io.setmode(io.BOARD) io.setup(pin_buzzer,io.OUT) io.setup(pin_led_red,io.OUT) io.setup(pin_led_green,io.OUT) io.setup(pin_led_blue,io.OUT) io.setup(pin_led_yellow,io.OUT) io.setup(pin_led_white,io.OUT) io.setup(pin_led_bright_yellow,io.OUT) io.setup(pin_led_big,io.OUT) io.setup(pin_reed,io.IN) io.add_event_detect(pin_reed,io.BOTH) io.add_event_callback(pin_reed,ReedToggle) dhtreader.init() bmp = BMP085(0x77) Log('Initializing done.')
def __init__(self,data): dhtreader.init() dhtreader.lastDataTime = 0 dhtreader.lastData = (None,None) self.sensorName = "DHT22" self.readingType = "sample" self.pinNum = int(data["pinNumber"]) if "temp" in data["measurement"].lower(): self.valName = "Temperature" self.valUnit = "Celsius" self.valSymbol = "C" if "unit" in data: if data["unit"] == "F": self.valUnit = "Fahrenheit" self.valSymbol = "F" elif "h" in data["measurement"].lower(): self.valName = "Relative Humidity" self.valSymbol = "%" self.valUnit = "% Relative Humidity" if "description" in data: self.description = data["description"] else: self.description = "A combined temperature and humidity sensor." return
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import dhtreader DHT11 = 11 DHT22 = 22 AM2302 = 22 dhtreader.init() if len(sys.argv) != 3: print(("usage: {0} [11|22|2302] GPIOpin#".format(sys.argv[0]))) print(("example: {0} 2302 Read from an AM2302 connected to GPIO #4".format(sys.argv[0]))) sys.exit(2) dev_type = None if sys.argv[1] == "11": dev_type = DHT11 elif sys.argv[1] == "22": dev_type = DHT22 elif sys.argv[1] == "2302": dev_type = AM2302 else: print("invalid type, only 11, 22 and 2302 are supported for now!") sys.exit(3) dhtpin = int(sys.argv[2]) if dhtpin <= 0:
def init_module(config): dhtreader.init()
def provide_temperature_and_humidity(): dhtreader.init() return dhtreader.read(dht_measurer_type, dht_measurer_pin)
def __init__(self): dhtreader.init()
def measure(self): #read data for DHT compatible if self.sensorType in ("DHT11","DHT23","AM2302"): count = 0 sType = 0 dhtreader.init() if self.sensorType == "DHT11": sType = 11 elif self.sensorType == "DHT22": sType = 22 elif self.sensorType == "AM2302": sType == 2302 else: print("invalid type, only 11, 22 and 2302 are supported for now!") return false while(count < 10): try: t, h = dhtreader.read(int(sType), int(self.sensorID)) logger.debug("t,h = {0},{1} (error in dhtreader.so?)".format(t, h)) self.temp = round(float('{0}'.format(t, h)),1) self.hum = round(float('{1}'.format(t, h)),1) except TypeError: logging.info("Failed to read from sensor '"+ self.section +"' on attempt "+ str(count+1)) count = count + 1 time.sleep(3) self.temp = None self.hum = None else: logging.info("{0}: {1}'C / {2}%".format(self.name, self.temp, self.hum)) break #read data for 1-wire if self.sensorType == "1-wire": count = 0 while(count < 10): try: f = open('/sys/bus/w1/devices/' + self.sensorID + '/w1_slave', 'r') lines = f.readlines() f.close() if lines[0].strip()[-3:] != 'YES': raise lines else: equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] self.temp = round(float(temp_string) / 1000,1) except: logging.warning("Failed to read from sensor '"+ self.section +"' on attempt "+ str(count+1)) count = count + 1 time.sleep(0.2) self.temp = None else: logging.info("{0}: {1}'C".format(self.name, self.temp)) break #read data online from KNMI if self.sensorType == "KNMI": count = 0 while(count < 10): try: data = requests.get("http://m.knmi.nl/index.php?i=Actueel&s=tabel_10min_data").text soup = BeautifulSoup(data) for row in soup.find('table').findAll('tr'): cols = row.findAll('td') if not cols: continue if cols[0].get_text() == self.sensorID: self.temp = float(cols[2].get_text().replace(' ', '').strip()) self.hum = float(cols[3].get_text().replace(' ', '').strip()) except: logger.info("error fetching data from {0} (website offline?)".format(self.sensorType + "_" + self.sensorID)) count = count + 1 time.sleep(0.2) self.temp = None self.hum = None else: logger.info("{0}: {1}'C / {2}%".format(self.sensorType + "_" + self.sensorID, self.temp, self.hum)) break #read data for internal CPU if self.sensorType == "system": count = 0 while(count < 10): try: f = open(self.sensorID, 'r') lines = f.read().strip() f.close() self.temp = round(float(lines) / 1000,1) except: logging.warning("Failed to read from sensor '"+ self.section +"' on attempt "+ str(count+1)) count = count + 1 time.sleep(0.2) self.temp = None else: logging.info("{0}: {1}'C".format(self.name, self.temp)) break self.lastMeasure = int(time.time())
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import time import dhtreader DHT11 = 11 DHT22 = 22 AM2302 = 22 dhtreader.init() if len(sys.argv) != 3: print("usage: {0} [11|22|2302] GPIOpin#".format(sys.argv[0])) print( "example: {0} 2302 4 Read from an AM2302 connected to GPIO #4".format( sys.argv[0])) sys.exit(2) dev_type = None if sys.argv[1] == "11": dev_type = DHT11 elif sys.argv[1] == "22": dev_type = DHT22 elif sys.argv[1] == "2302": dev_type = AM2302 else: print("invalid type, only 11, 22 and 2302 are supported for now!") sys.exit(3)
def __init__(self, pin=17, type=11): self.port = pin self.type = type dhtreader.init()
def dht_init(): dhtreader.init()
def main(): logging_level = loglvl_setup() logging.debug("Starting up....") if not 'SUDO_UID' in os.environ.keys(): logging.critical("This program requires super user privs.") logging.critical( "Sorry, it's because the DHTreader library accesses /dev/mem for" \ " real-time GPIO toggling to communicate with the DHT11/22") return 0 # config.ini should be in the same location as the script # get script path with some os.path hackery # check if config.ini does exist if not (os.path.exists(INI_FILE)): logging.critical("ERROR: config.ini does not exist...exiting") return 0 current_path = os.path.dirname(os.path.realpath(__file__)) config = ConfigRead(os.path.join(current_path, INI_FILE)) logging.debug("Setup Threads & Queues") upload_queue = Queue.Queue(maxsize=0) uploadThread = BackgroundUpload(upload_queue, config, logging, "UploadThread") uploadThread.start() # Open serial port for use by the XBee ser = serial.Serial(config.XbeePort, config.XbeeBaud) # The AlertMe object handles both bringing the ZB link up with the clamp # as well as pushing recieved data to teh upload queue zigbee = AlertMe(ser, upload_queue, logging) q1 = QueueObject() q1.type = QueueObject.Temp q2 = QueueObject() q2.type = QueueObject.RH # Initialise the DHTReader C Library dhtreader.init() while True: try: t, h = dhtreader.read(config.DHTtype, config.DHTpin) logging.debug("temp %d. RH %d" % (t, h)) if t and h: timestamp = datetime.datetime.utcnow() #add temperature to upload queue q1.data = format(t, '.2f') q1.timestamp = timestamp #add RH to upload queue q2.data = format(h, '.2f') q2.timestamp = timestamp #push both objects to upload queue upload_queue.put(q1) upload_queue.put(q2) else: logging.warning("Failed to read from sensor, maybe try again?") except KeyboardInterrupt: zigbee.close() logging.info("Wait until all data is uploaded") upload_queue.join() break except TypeError: #This seems to happen a fair bit with the DHT22 logging.info('NoneType return from dhtreader()') #try re-initing.... dhtreader.init() # Sleep for 30 seconds #(the RPi Python version does not send a SIGINT when in sleep) # So sleep in parts... for i in range(30): time.sleep(1)