def humidity(connection, table): ipcon = IPConnection() h = Humidity(HUMIDITY_UID, ipcon) ipcon.connect(HOST, PORT) value = h.get_humidity() / 10.0 insert(connection, table, time.time(), value) ipcon.disconnect()
class BrickletHumidity: _QUOTIENT = 10.0 def __init__(self, uid, connection, logging_daemon, queue, value=0.0, trigger_difference=0.1): self.bricklet = Humidity(uid, connection) self._value = value self._value_old = value self.trigger_difference = trigger_difference self._rising = False self._falling = False self.uid = uid self._logging_daemon = logging_daemon self._queue = queue self._logging_daemon.info('Tinkerforge ... Humidity-Bricklet UID "%s" initialisiert' % uid) def set_callback(self, timeframe=5000): self.bricklet.set_humidity_callback_period(timeframe) self.bricklet.register_callback(self.bricklet.CALLBACK_HUMIDITY, self._changed) self._logging_daemon.debug('Tinkerforge ... Humidity-Bricklet UID "%s" Callback gesetzt' % self.uid) def read(self): return self.bricklet.get_humidity() / self._QUOTIENT def read_rising(self): return self._rising def read_falling(self): return self._falling def _changed(self, tmp_value): tmp_value = (tmp_value / self._QUOTIENT) if abs(self._value - tmp_value) >= self.trigger_difference: if tmp_value > self._value_old: self._rising = True self._falling = False elif tmp_value < self._value_old: self._rising = False self._falling = True self._logging_daemon.debug( 'Tinkerforge ... Humidity-Bricklet UID "%s" , Neu = %f , Alt = %f , rising = %s , falling = %s' % ( self.uid, tmp_value, self._value_old, self._rising, self._falling)) self._value_old = tmp_value self._value = tmp_value tmp_json = json.dumps(["send_changed_data", self.uid, "sensor", "humidity", self._value]) for consumer in self._queue: consumer(tmp_json) self._logging_daemon.info( 'Tinkerforge ... Humidity-Bricklet UID "%s" , neuer Wert %f -> SocketServer Warteschlange ' % ( self.uid, self._value)) humidity = property(read) rising = property(read_rising) falling = property(read_falling)
def read_data(fake=None): """ Reads data from all weather sensors and returns it as Dictionary. In case of an error or outlier None is returned""" if fake: return weather_data try: ipcon = IPConnection() temp_bricklet = Temperature('qnk', ipcon) humidity_bricklet = Humidity('nLC', ipcon) barometer_bricklet = Barometer('k5g', ipcon) ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port'])) temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW) temp = temp_bricklet.get_temperature() / 100.0 if 45 < temp < -30: weather_data['temperature'] = None logger.warn( 'Got temperature value of %s Grade which is out of range' % temp) else: weather_data['temperature'] = temp humidity = humidity_bricklet.get_humidity() / 10.0 if humidity < 5: weather_data['humidity'] = None logger.warn('Got humidity value of %s RH which is out of range' % humidity) else: weather_data['humidity'] = humidity pressure = barometer_bricklet.get_air_pressure() / 1000.0 if 1080 < pressure < 930: weather_data['pressure'] = None logger.warn('Got pressure value of %s mbar which is out of range' % pressure) else: weather_data['pressure'] = pressure ipcon.disconnect() return weather_data except Exception as e: logger.error('Cloud not connect to weather sensors: %s' % str(e)) return
def get_humidity(id): cfg = configparser.ConfigParser() cfg.read(cfg_filename) # open config file to read from port = cfg.getint('Connection', 'Port') # get port entry from config file host = cfg.get('Connection', 'Host') # get host entry from config file uid = cfg.get('Humidity', 'bricklet_uid') # uid port entry from config file ipcon = IPConnection() # Create IP connection ipcon.connect(host, port) # Connect to brickd h = Humidity(uid, ipcon) # Create device object rh = h.get_humidity()/10.0 # Get current humidity (unit is %RH/10) db = sqlite3.connect(local_db) # build connection to local database c = db.cursor() # create cursor c.execute(wd_table) # create weatherdata table c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,rh,'rel. humidity', id,'humidity',)) # insert the uid, device name the id from the date table an die humdity value into the weather table db.commit() # save creates and inserts permanent print() print('Relative Humidity: ' + str(rh) + ' %RH') print() ipcon.disconnect() return(rh)
def read_data(): try: ipcon = IPConnection() temp_bricklet = Temperature('qnk', ipcon) humidity_bricklet = Humidity('nLC', ipcon) barometer_bricklet = Barometer('k5g', ipcon) ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port'])) temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW) temp = temp_bricklet.get_temperature() / 100.0 if 45 < temp < -30: weather_data['temperature'] = None logger.warn('Got temperature value of %s Grade which is out of range' % temp) else: weather_data['temperature'] = temp humidity = humidity_bricklet.get_humidity() / 10.0 if humidity < 5: weather_data['humidity'] = None logger.warn('Got humidity value of %s RH which is out of range' % humidity) else: weather_data['humidity'] = humidity pressure = barometer_bricklet.get_air_pressure() / 1000.0 if 1090 < pressure < 920: weather_data['pressure'] = None logger.warn('Got pressure value of %s mbar which is out of range' % pressure) else: weather_data['pressure'] = pressure ipcon.disconnect() return weather_data except Exception as e: logger.error('Cloud not connect to weather sensors: %s' % str(e)) return
class BrickletHumidity: _QUOTIENT = 10.0 def __init__(self, uid, connection, logging_daemon, queue, value=0.0, trigger_difference=0.1): self.bricklet = Humidity(uid, connection) self._value = value self._value_old = value self.trigger_difference = trigger_difference self._rising = False self._falling = False self.uid = uid self._logging_daemon = logging_daemon self._queue = queue self._logging_daemon.info( 'Tinkerforge ... Humidity-Bricklet UID "%s" initialisiert' % uid) def set_callback(self, timeframe=5000): self.bricklet.set_humidity_callback_period(timeframe) self.bricklet.register_callback(self.bricklet.CALLBACK_HUMIDITY, self._changed) self._logging_daemon.debug( 'Tinkerforge ... Humidity-Bricklet UID "%s" Callback gesetzt' % self.uid) def read(self): return self.bricklet.get_humidity() / self._QUOTIENT def read_rising(self): return self._rising def read_falling(self): return self._falling def _changed(self, tmp_value): tmp_value = (tmp_value / self._QUOTIENT) if abs(self._value - tmp_value) >= self.trigger_difference: if tmp_value > self._value_old: self._rising = True self._falling = False elif tmp_value < self._value_old: self._rising = False self._falling = True self._logging_daemon.debug( 'Tinkerforge ... Humidity-Bricklet UID "%s" , Neu = %f , Alt = %f , rising = %s , falling = %s' % (self.uid, tmp_value, self._value_old, self._rising, self._falling)) self._value_old = tmp_value self._value = tmp_value tmp_json = json.dumps([ "send_changed_data", self.uid, "sensor", "humidity", self._value ]) for consumer in self._queue: consumer(tmp_json) self._logging_daemon.info( 'Tinkerforge ... Humidity-Bricklet UID "%s" , neuer Wert %f -> SocketServer Warteschlange ' % (self.uid, self._value)) humidity = property(read) rising = property(read_rising) falling = property(read_falling)
class ClimateSensors: def __init__(self, host, port): self.hum = None self.hum_value = 0.0 self.temp = None self.temp_value = 0.0 self.lcd = None self.port = port self.host = host self.conn = IPConnection() self.conn.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.conn.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) def update_display(self): if self.lcd is not None: self.lcd.write_line(1, 2, 'Temp: {:3.2f} C'.format(self.temp_value)) self.lcd.write_line(2, 2, 'RelHum: {:3.2f} %'.format(self.hum_value)) def connect(self): if self.conn.get_connection_state() == self.conn.CONNECTION_STATE_DISCONNECTED: self.conn.connect(self.host, self.port) self.conn.enumerate() def disconnect(self): if self.conn.get_connection_state() != self.conn.CONNECTION_STATE_DISCONNECTED: if self.lcd is not None: self.lcd.backlight_off() self.lcd.clear_display() self.conn.disconnect() def cb_connected(self, connected_reason): self.conn.enumerate() def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED: # print("DISCONNECTED") return if device_identifier == Temperature.DEVICE_IDENTIFIER: self.temp = Temperature(uid, self.conn) self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, self.cb_temperature) self.update_temperature(self.temp.get_temperature()) self.temp.set_temperature_callback_period(UPDATE_PERIOD) if device_identifier == Humidity.DEVICE_IDENTIFIER: self.hum = Humidity(uid, self.conn) self.hum.register_callback(self.hum.CALLBACK_HUMIDITY, self.cb_humidity) self.update_humidity(self.hum.get_humidity()) self.hum.set_humidity_callback_period(UPDATE_PERIOD) if device_identifier == LCD20x4.DEVICE_IDENTIFIER: self.lcd = LCD20x4(uid, self.conn) self.lcd.backlight_on() def cb_temperature(self, temperature): self.update_temperature(temperature) self.update_display() def update_temperature(self, raw_temperature): self.temp_value = raw_temperature / 100.0 def cb_humidity(self, humidity): self.update_humidity(humidity) self.update_display() def update_humidity(self, raw_humidity): self.hum_value = raw_humidity / 10.0
class WeatherStation: HOST = "localhost" PORT = 4223 ipcon = None lcd = None lcd_clear = False al = None hum = None baro = None def __init__(self): self.ipcon = IPConnection() while True: try: self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT) break except Error as e: log.error('Connection Error: ' + str(e.description)) timer.sleep(1) except socket.error as e: log.error('Socket error: ' + str(e)) timer.sleep(1) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) while True: try: self.ipcon.enumerate() break except Error as e: log.error('Enumerate Error: ' + str(e.description)) timer.sleep(1) def start(self): t = 10 extended_timer = 10 try: while True: if self.lcd: self.write_date(0, 0) self.write_time(1, 0) t = t + 1 if t >= extended_timer: if self.baro: self.write_temperatur(2, 0) if self.hum: self.write_humidity(3, 0) t = 0 timer.sleep(1) except KeyboardInterrupt: if weather_station.ipcon != None: weather_station.ipcon.disconnect() return def init_lcd(self, uid): try: self.lcd = LCD20x4(uid, self.ipcon) self.lcd.clear_display() self.lcd.backlight_on() log.info('LCD 20x4 initialized') except Error as e: log.error('LCD 20x4 init failed: ' + str(e.description)) self.lcd = None def init_ambientlight(self, uid): try: self.al = AmbientLight(uid, self.ipcon) self.al.set_illuminance_callback_period(1000) self.al.register_callback(self.al.CALLBACK_ILLUMINANCE, self.cb_illuminance) except Error as e: log.error('Ambient Light init failed: ' + str(e.description)) self.al = None def init_barometer(self, uid): try: self.baro = Barometer(uid, self.ipcon) except Error as e: log.error('Barometer init failed: ' + str(e.description)) self.baro = None def init_humidity(self, uid): try: self.hum = Humidity(uid, self.ipcon) except Error as e: log.error('Humidity init failed: ' + str(e.description)) self.hum = None def write_time(self, line, start_position): lt = localtime() hour, minute, second = lt[3:6] self.lcd.write_line(line, start_position, "Time: %02i:%02i:%02i" % (hour, minute, second)) def write_date(self, line, start_position): lt = localtime() year, month, day = lt[0:3] self.lcd.write_line(line, start_position, "Date: %02i.%02i.%04i" % (day, month, year)) def write_temperatur(self, line, start_position): try: temperature = self.baro.get_chip_temperature() text = 'Temp: %5.2f \xDFC' % (temperature / 100.0) self.lcd.write_line(line, start_position, text) except Error as e: log.error('Could not get temperature: ' + str(e.description)) return def write_humidity(self, line, start_position): try: h = self.hum.get_humidity() text = 'Humidity: %6.2f %%' % (h / 10.0) self.lcd.write_line(line, start_position, text) except Error as e: log.error('Could not get temperature: ' + str(e.description)) return def cb_illuminance(self, illuminance): if self.lcd is not None: i = illuminance / 10.0 if i < 0.5 and self.lcd.is_backlight_on(): self.lcd.backlight_off() elif i >= 0.5 and not self.lcd.is_backlight_on(): self.lcd.backlight_on() def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \ enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE: if device_identifier == LCD20x4.DEVICE_IDENTIFIER: self.init_lcd(uid) elif device_identifier == AmbientLight.DEVICE_IDENTIFIER: self.init_ambientlight(uid) elif device_identifier == Humidity.DEVICE_IDENTIFIER: self.init_humidity(uid) elif device_identifier == Barometer.DEVICE_IDENTIFIER: self.init_barometer(uid) def cb_connected(self, connected_reason): if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT: log.info('Auto Reconnect') while True: try: self.ipcon.enumerate() break except Error as e: log.error('Enumerate Error: ' + str(e.description)) timer.sleep(1)
#!/usr/bin/env python # -*- coding: utf-8 -*- import time HOST = "localhost" PORT = 4223 UID = "hRd" # Change to your UID from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_humidity import Humidity if __name__ == "__main__": ipcon = IPConnection() # Create IP connection h = Humidity(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd rh = h.get_humidity()/10.0 ts = int(time.time()) with open('/home/pi/Weatherstation/humidity.csv', 'a') as f: f.write('{}\t{}\n'.format(ts, rh)) ipcon.disconnect()
while True: air_pressure = b.get_air_pressure()/1000.0 altitude = b.get_altitude()/100.0 illuminance = al.get_illuminance()/10.0 bartemp = b.get_chip_temperature()/100.0 esszimm = temp1.get_temperature()/100.0 flur = temp2.get_temperature()/100.0 voltage = master.get_stack_voltage() current = master.get_stack_current() wifi = master.get_wifi_configuration() wifistatus = master.get_wifi_status() wifipower = master.get_wifi_power_mode() wifihost = master.get_wifi_hostname() usbvoltage = master.get_usb_voltage() masterid = master.get_identity() feuchte = h.get_humidity()/10.0 os.system('clear') luxwert = 10 print "Datum/Zeit: " ,datetime.datetime.now().strftime("%d.%m.%y - %H:%M") print ('') # Werte in die Konsole schreiben print ('Display Ein/Aus Schalten') print ('Ist: ' + str(illuminance) + ' LUX') print ('Soll: ' + str(luxwert) + ' LUX') print ('')