def connect_sensors(sensors, uids, ipcon): """ Creates Bricklet Instances :param sensors: connected sensors, as dictionary :param uids: bricklets uids, as dictionary :param ipcon: ipconnection from tinkerforge :return: Dictionary with all instances from connected sensors """ # Dictionary with all connected sensors con_sensors = {} for sensor in sensors: if sensor == "ambient_light": al = BrickletAmbientLightV2(uids["ambient_light"], ipcon) con_sensors.update({"ambient_light": al}) if sensor == "barometer": barometer = BrickletBarometer(uids["barometer"], ipcon) con_sensors.update({"barometer": barometer}) if sensor == "humidity": humidity = BrickletHumidity(uids["humidity"], ipcon) con_sensors.update({"humidity": humidity}) if sensor == "lcd": lcd = BrickletLCD20x4(uids["lcd"], ipcon) con_sensors.update({"lcd": lcd}) if sensor == "moisture": moisture = BrickletMoisture(uids["moisture"], ipcon) con_sensors.update({"moisture": moisture}) if sensor == "temperature": temperature = BrickletTemperature(uids["temperature"], ipcon) con_sensors.update({"temperature": temperature}) if sensor == "thermocouple": thermo = BrickletThermocouple(uids["thermocouple"], ipcon) con_sensors.update({"thermocouple": thermo}) return con_sensors
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 == BrickletLCD20x4.DEVICE_IDENTIFIER: try: self.lcd = BrickletLCD20x4(uid, self.ipcon) self.lcd.clear_display() self.lcd.backlight_on() self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.cb_lcd_button_pressed) log.info('LCD 20x4 initialized') except Error as e: log.error('LCD 20x4 init failed: ' + str(e.description)) self.lcd = None elif device_identifier == BrickletAmbientLightV2.DEVICE_IDENTIFIER: try: self.al_v2 = BrickletAmbientLightV2(uid, self.ipcon) self.al_v2.set_configuration(self.al_v2.ILLUMINANCE_RANGE_64000LUX, self.al_v2.INTEGRATION_TIME_200MS) self.al_v2.set_illuminance_callback_period(1000) self.al_v2.register_callback(self.al_v2.CALLBACK_ILLUMINANCE, self.cb_illuminance_v2) log.info('Ambient Light 2.0 initialized') except Error as e: log.error('Ambient Light 2.0 init failed: ' + str(e.description)) self.al_v2 = None elif device_identifier == BrickletHumidityV2.DEVICE_IDENTIFIER: try: self.hum_v2 = BrickletHumidityV2(uid, self.ipcon) self.hum_v2.set_humidity_callback_configuration(1000, True, 'x', 0, 0) self.hum_v2.register_callback(self.hum_v2.CALLBACK_HUMIDITY, self.cb_humidity_v2) log.info('Humidity 2.0 initialized') except Error as e: log.error('Humidity 2.0 init failed: ' + str(e.description)) self.hum_v2 = None elif device_identifier == BrickletBarometer.DEVICE_IDENTIFIER: try: self.baro = BrickletBarometer(uid, self.ipcon) self.baro.set_air_pressure_callback_period(1000) self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE, self.cb_air_pressure) log.info('Barometer initialized') except Error as e: log.error('Barometer init failed: ' + str(e.description)) self.baro = None elif device_identifier == BrickMaster.DEVICE_IDENTIFIER: try: self.master = BrickMaster(uid, self.ipcon) self.master.disable_status_led() log.info('MasterBrick initialized') except Error as e: log.error('MasterBrick init failed: ' + str(e.description)) self.baro = None
def index(): ipcon = IPConnection() # Create IP connection humidity_bricklet = BrickletHumidityV2(HUMIDITY_UID, ipcon) # Create device object barometer_bricklet = BrickletBarometer(BAROMETER_UID, ipcon) ambient_light_bricklet = BrickletAmbientLightV2(AMBIENT_LIGHT_UID, ipcon) ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected temperature = humidity_bricklet.get_temperature()/100.0 humidity = humidity_bricklet.get_humidity()/100.0 air_pressure = barometer_bricklet.get_air_pressure()/1000.0 illuminance = ambient_light_bricklet.get_illuminance()/100.0 ipcon.disconnect() return render_template('index.html', temperature=temperature, humidity=humidity, illuminance=illuminance, air_pressure=air_pressure)
def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED: return # Note: The order is important, detect PTC before Humidity # # https://www.tinkerforge.com/en/doc/Software/Bricklets/PTCV2_Bricklet_Python.html if device_identifier == BrickletPTCV2.DEVICE_IDENTIFIER: self.ptc = BrickletPTCV2(uid, self.ipcon) self.device_type = self.type_ptc # https://www.tinkerforge.com/en/doc/Software/Bricklets/Temperature_Bricklet_Python.html if device_identifier == Temperature.DEVICE_IDENTIFIER: self.temp = Temperature(uid, self.ipcon) self.device_type = self.type_temperature # https://www.tinkerforge.com/en/doc/Software/Bricklets/AmbientLightV2_Bricklet_Python.html if device_identifier == BrickletAmbientLightV2.DEVICE_IDENTIFIER: self.al = BrickletAmbientLightV2(uid, self.ipcon) self.device_type = self.type_ambient_light # https://www.tinkerforge.com/en/doc/Software/Bricklets/HumidityV2_Bricklet_Python.html if device_identifier == BrickletHumidityV2.DEVICE_IDENTIFIER: self.hum = BrickletHumidityV2(uid, self.ipcon) self.device_type = self.type_humidity # https://www.tinkerforge.com/en/doc/Software/Bricklets/DistanceIRV2_Bricklet_Python.html if device_identifier == BrickletDistanceIRV2.DEVICE_IDENTIFIER: self.dist = BrickletDistanceIRV2(uid, self.ipcon) self.device_type = self.type_distance # https://www.tinkerforge.com/de/doc/Software/Bricklets/MotionDetectorV2_Bricklet_Python.html if device_identifier == BrickletMotionDetectorV2.DEVICE_IDENTIFIER: self.dist = BrickletMotionDetectorV2(uid, self.ipcon) self.device_type = self.type_motion if self.verbose: print("UID: " + uid) print("Enumeration Type: " + str(enumeration_type)) print("Connected UID: " + connected_uid) print("Position: " + position) print("Hardware Version: " + str(hardware_version)) print("Firmware Version: " + str(firmware_version)) print("Device Identifier: " + str(device_identifier)) print("Device Type: " + str(self.device_type)) print("")
def connect_sensors(): global al global barometer global humidity global lcd global moisture global temperature global thermo if sensors["ambient_light"] == 1: al = BrickletAmbientLightV2(UID_AMBIENT, ipcon) if sensors["barometer"] == 1: barometer = BrickletBarometer(UID_BAROMETER, ipcon) if sensors["humidity"] == 1: humidity = BrickletHumidity(UID_HUMIDITY, ipcon) if sensors["lcd"] == 1: lcd = BrickletLCD20x4(UID_LCD, ipcon) if sensors["moisture"] == 1: moisture = BrickletMoisture(UID_MOISTURE, ipcon) if sensors["temperature"] == 1: temperature = BrickletTemperature(UID_TEMPERATURE, ipcon) if sensors["thermo_couple"] == 1: thermo = BrickletThermocouple(UID_THERMO, ipcon)
def SetBrickletIlluminance(Unit): Domoticz.Debug("GetBrickletIlluminance: Unit " + str(Unit) + ", ID=" + str(Devices[Unit].ID)) try: # Create IP connection ipConn = IPConnection() # Create device object alDev = BrickletAmbientLightV2(Parameters["Mode1"], ipConn) # Connect to brickd using Host and Port ipConn.connect(Parameters["Address"], int(Parameters["Port"])) # Get current illuminance illuminance = alDev.get_illuminance() if illuminance > 0: illuminance = illuminance / 100.0 Devices[Unit].Update(nValue=0, sValue=str(illuminance)) Domoticz.Log("Illuminance updated: " + str(illuminance)) # Disconnect ipConn.disconnect() Domoticz.Debug("GetBrickletIlluminance: OK") except: Domoticz.Error( "[ERROR] SetBrickletIlluminance failed. Check bricklet.") return illuminance
def print_ambient_light_v2(conn, settings, uid): from tinkerforge.bricklet_ambient_light_v2 import BrickletAmbientLightV2 # type: ignore[import] br = BrickletAmbientLightV2(uid, conn) print_generic(settings, "ambient", br.get_identity(), 0.01, "L", br.get_illuminance())
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) self.setWindowTitle( 'Tinkerforge CES Demo: Thermal Imaging Bricklet by FLIR') self.qtcb_ipcon_enumerate.connect(self.cb_ipcon_enumerate) self.qtcb_ipcon_connected.connect(self.cb_ipcon_connected) self.qtcb_high_contrast_image.connect(self.cb_high_contrast_image) self.image = QImage(QSize(80, 60), QImage.Format_RGB32) # Add Tinkerforge logo # Adapt this path self.label_logo.setPixmap( QPixmap('/home/pi/Desktop/demo/logo_klein.png')) # create and setup ipcon self.ipcon = IPConnection() self.ipcon.connect(HOST, PORT) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.qtcb_ipcon_enumerate.emit) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.qtcb_ipcon_connected.emit) self.ti = BrickletThermalImaging(UID_TI, self.ipcon) self.ti.register_callback(self.ti.CALLBACK_HIGH_CONTRAST_IMAGE, self.qtcb_high_contrast_image.emit) self.ti.set_image_transfer_config( self.ti.IMAGE_TRANSFER_CALLBACK_HIGH_CONTRAST_IMAGE) self.ti.set_spotmeter_config([35, 25, 45, 35]) #print(ti.get_spotmeter_config()) al = BrickletAmbientLightV2(UID_AL, self.ipcon) al.register_callback(al.CALLBACK_ILLUMINANCE, self.cb_illuminance) al.set_illuminance_callback_period(500) hu = BrickletHumidityV2(UID_HU, self.ipcon) hu.register_callback(hu.CALLBACK_HUMIDITY, self.cb_humidity) hu.set_humidity_callback_configuration(500, False, "x", 0, 0) bm = BrickletBarometer(UID_BM, self.ipcon) bm.register_callback(bm.CALLBACK_AIR_PRESSURE, self.cb_air_pressure) bm.set_air_pressure_callback_period(500) self.rgb_lookup = [] for x in range(256): x /= 255.0 r = int(round(255 * math.sqrt(x))) g = int(round(255 * pow(x, 3))) if math.sin(2 * math.pi * x) >= 0: b = int(round(255 * math.sin(2 * math.pi * x))) else: b = 0 self.rgb_lookup.append((r, g, b)) def paintEvent(event): painter = QPainter(self.label_image) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) w = self.label_image.size().width() h = self.label_image.size().height() painter.scale(w / 80.0, h / 60.0) painter.drawImage(0, 0, self.image) if 35 != None and 45 != None: pen = QPen() pen.setColor(Qt.white) pen.setWidth(0.2) painter.setPen(pen) from_x, from_y, to_x, to_y = [35, 25, 45, 35] from_x = from_x * self.image_pixel_width + 1 from_y = from_y * self.image_pixel_width + 1 to_x = to_x * self.image_pixel_width + 1 to_y = to_y * self.image_pixel_width + 1 cross_x = from_x + (to_x - from_x) / 2.0 cross_y = from_y + (to_y - from_y) / 2.0 if to_x - from_x > 5 or to_y - from_y > 5: lines = [ QLine(from_x, from_y, from_x + self.crosshair_width, from_y), QLine(from_x, from_y, from_x, from_y + self.crosshair_width), QLine(to_x, to_y, to_x, to_y - self.crosshair_width), QLine(to_x, to_y, to_x - self.crosshair_width, to_y), QLine(from_x, to_y, from_x, to_y - self.crosshair_width), QLine(from_x, to_y, from_x + self.crosshair_width, to_y), QLine(to_x, from_y, to_x, from_y + self.crosshair_width), QLine(to_x, from_y, to_x - self.crosshair_width, from_y) ] painter.drawLines(lines) lines = [ QLine(cross_x - self.crosshair_width, cross_y, cross_x + self.crosshair_width, cross_y), QLine(cross_x, cross_y - self.crosshair_width, cross_x, cross_y + self.crosshair_width) ] painter.drawLines(lines) self.update_spotmeter_roi_label() self.label_image.paintEvent = paintEvent
PORT = 4223 UID = "XYZ" # Change XYZ to the UID of your Ambient Light Bricklet 2.0 from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_ambient_light_v2 import BrickletAmbientLightV2 # Callback function for illuminance reached callback (parameter has unit Lux/100) def cb_illuminance_reached(illuminance): print("Illuminance: " + str(illuminance / 100.0) + " Lux") print("Too bright, close the curtains!") if __name__ == "__main__": ipcon = IPConnection() # Create IP connection al = BrickletAmbientLightV2(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected # Get threshold callbacks with a debounce time of 10 seconds (10000ms) al.set_debounce_period(10000) # Register illuminance reached callback to function cb_illuminance_reached al.register_callback(al.CALLBACK_ILLUMINANCE_REACHED, cb_illuminance_reached) # Configure threshold for illuminance "greater than 500 Lux" (unit is Lux/100) al.set_illuminance_callback_threshold(">", 500 * 100, 0) raw_input("Press key to exit\n") # Use input() in Python 3
def print_ambient_light_v2(conn, settings, uid): from tinkerforge.bricklet_ambient_light_v2 import BrickletAmbientLightV2 # type: ignore[import] # pylint: disable=import-error,import-outside-toplevel br = BrickletAmbientLightV2(uid, conn) print_generic(settings, "ambient", br.get_identity(), 0.01, "L", br.get_illuminance())
def onHeartbeat(self): self.HeartbeatCounter = self.HeartbeatCounter + 1 Domoticz.Debug("onHeartbeat called. Counter=" + str(self.HeartbeatCounter * self.HeartbeatInterval) + " (Heartbeat=" + Parameters["Mode5"] + ")") # Reset ipconnected flag self.ipConnected = 0 # check the heartbeatcounter against the heartbeatinterval if (self.HeartbeatCounter * self.HeartbeatInterval) % int( Parameters["Mode5"]) == 0: try: # Create IP connection ipcon = IPConnection() Domoticz.Debug("IP Connected created") # Create the device objects master = BrickMaster(self.UIDList[UIDINDEXMASTER], ipcon) aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon) lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon) rl = BrickletRGBLEDV2(self.UIDList[UIDINDEXRGBLED], ipcon) al = BrickletAmbientLightV2(self.UIDList[UIDINDEXAMBIENTLIGHT], ipcon) Domoticz.Debug("Devices created - OK") # Connect to brickd using Host and Port try: ipcon.connect(Parameters["Address"], int(Parameters["Port"])) self.ipConnected = 1 Domoticz.Debug("IP Connection - OK") except: self.isError = 1 Domoticz.Debug("[ERROR] IP Connection failed") # Don't use device before ipcon is connected # Set Alert Indicator to Orange with ERROR text if self.ipConnected == 0: ## Alert device (5)nvalue=LEVEL - (0=gray, 1=green, 2=yellow, 3=orange, 4=red),svalue=TEXT # Devices[ALERTDEVICE].Update( nValue=3, sValue="ERROR") #Domoticz.Debug(Devices[ALERTDEVICE].Name + "-nValue=" + str(Devices[ALERTDEVICE].nValue) + ",sValue=" + Devices[ALERTDEVICE].sValue ) Devices[UNITTEXTSTATUS].Update( nValue=0, sValue= "[ERROR] Can not connect to the Master Brick. Check device or settings." ) Domoticz.Log(Devices[UNITTEXTSTATUS].sValue) self.isError = 1 return # If there was an error in the connection,init the bricks again if self.isError == 1 and self.ipConnected == 1: InitBricks(self) self.isError = 0 # AIR QUALITY # Get current all values iaq_index, iaq_index_accuracy, temperature, humidity, air_pressure = aq.get_all_values( ) ## TESTdata with using the air quality bricklet ''' iaq_index = 69 # 0 -200 iaq_index_accuracy = 21 temperature = 2432 humidity = 6894 air_pressure = 102412 ''' # Update the devices # IAQ (Indoor Air Quality) Index ## nValue=0 ## sValue=string value Devices[UNITAIRQUALITYIAQINDEX].Update(nValue=0, sValue=str(iaq_index)) # Devices[UNITAIRQUALITYIAQINDEX].Update( nValue=iaq_index, sValue="0") Domoticz.Debug(Devices[UNITAIRQUALITYIAQINDEX].Name + "-IAQ Index:" + str(iaq_index)) # IAQ Index Accuracy ## nvalue=LEVEL - (0=gray, 1=green, 2=yellow, 3=orange, 4=red) ## svalue=TEXT iaqaccuracylevel = 0 if iaq_index_accuracy == aq.ACCURACY_UNRELIABLE: iaqaccuracylevel = 4 elif iaq_index_accuracy == aq.ACCURACY_LOW: iaqaccuracylevel = 3 elif iaq_index_accuracy == aq.ACCURACY_MEDIUM: iaqaccuracylevel = 2 elif iaq_index_accuracy == aq.ACCURACY_HIGH: iaqaccuracylevel = 1 iaqaccuracytext = AIRQUALITYACCURACY[iaqaccuracylevel] Devices[UNITALERTIAQINDEXACCURACY].Update( nValue=iaqaccuracylevel, sValue=iaqaccuracytext) Domoticz.Debug(Devices[UNITALERTIAQINDEXACCURACY].Name + "-IAQ IndexAccuracy:" + str(iaqaccuracylevel) + "," + iaqaccuracytext) # Air Quality ## nvalue=LEVEL - see xml definition ## svalue=TEXT airqualitylevel = 0 if iaq_index >= 0 and iaq_index <= AIRQUALITYLEVELLIMIT[1]: airqualitylevel = 1 if iaq_index > AIRQUALITYLEVELLIMIT[ 1] and iaq_index <= AIRQUALITYLEVELLIMIT[2]: airqualitylevel = 2 if iaq_index > AIRQUALITYLEVELLIMIT[ 2] and iaq_index <= AIRQUALITYLEVELLIMIT[3]: airqualitylevel = 3 if iaq_index > AIRQUALITYLEVELLIMIT[ 3] and iaq_index <= AIRQUALITYLEVELLIMIT[4]: airqualitylevel = 4 if iaq_index > AIRQUALITYLEVELLIMIT[ 4] and iaq_index <= AIRQUALITYLEVELLIMIT[5]: airqualitylevel = 5 if iaq_index > AIRQUALITYLEVELLIMIT[5]: airqualitylevel = 6 airqualitytext = AIRQUALITYLEVELCONDITION[airqualitylevel] Devices[UNITALERTAIRQUALITY].Update(nValue=airqualitylevel, sValue=airqualitytext) Domoticz.Debug("Air Quality:" + str(airqualitylevel) + "," + airqualitytext) # Temperature ## nvalue=0 ## svalue=temperature/100 ## print("Temperature: " + str(temperature/100.0) + " °C") if temperature > 0: temperature = int(round(temperature / 100.0)) Devices[UNITTEMPERATURE].Update(nValue=0, sValue=str(temperature)) Domoticz.Debug(Devices[UNITTEMPERATURE].Name + "-Temperature:" + str(temperature)) # Humidity # nvalue=humidity # svalue=humiditystatus - 0=Normal,1=Comfortable,2=Dry,3=Wet # print("Humidity: " + str(humidity/100.0) + " %RH") if humidity > 0: humidity = int(round(humidity / 100.0)) humiditystatus = GetHumidityStatus(humidity) Devices[UNITHUMIDITY].Update(nValue=humidity, sValue=str(humiditystatus)) Domoticz.Debug(Devices[UNITHUMIDITY].Name + "-Humidity:" + str(humidity)) # Air Pressure # nvalue=0 # svalue=airpressure/100;prediction # print("Air Pressure: " + str(air_pressure/100.0) + " mbar") if air_pressure > 0: air_pressure = int(round(air_pressure / 100.0)) Devices[UNITBAROMETER].Update(nValue=0, sValue=str(air_pressure) + ";0") Domoticz.Debug(Devices[UNITBAROMETER].Name + "-Air Pressure:" + str(air_pressure)) Domoticz.Debug("Air Quality Devices updated") # AMBIENT LIGHT ## Get current illuminance ## nvalue=0 ## svalue=illuminance/100 illuminance = al.get_illuminance() if illuminance > 0: illuminance = int(round(illuminance / 100.0)) #print("Illuminance: " + str(illuminance/100.0) + " lx") Devices[UNITILLUMINATION].Update(nValue=0, sValue=str(illuminance)) Domoticz.Debug(Devices[UNITILLUMINATION].Name + "-Lux:" + str(illuminance)) # ## Tinkerforge Bricklet Updates # Domoticz.Debug("Tinkerforge updating...") ## LCD Display ## Writes text to a specific line (0 to 3) with a specific position (0 to 19). The text can have a maximum of 20 characters. ## Turn backlight on NOTE: done in onStart ## lcd.backlight_on() ## Domoticz.Debug("LCD Backlight ON") ## Clear the display lcd.clear_display() Domoticz.Debug("LCD Display cleared") ## Get the values as strings to write on the lcd ## AQI lcdaqi = str(iaq_index) ## TT:HH - TT=Temperature,HH=Humidity lcdtemperature = str(temperature) lcdhumidity = "HH" if humidity < 100: lcdhumidity = str(humidity) ## airpressure lcdairpressure = str(air_pressure) ## illuminance lcdilluminance = str(illuminance) ## write to the lcd: line (int,0-3),pos(int,0-19),text lcd.write_line(0, 0, "Q: " + lcdaqi + " ppm " + airqualitytext) lcd.write_line(1, 0, "T: " + lcdtemperature + " C") lcd.write_line(1, 14, "H: " + lcdhumidity + "%") lcd.write_line(2, 0, "P: " + lcdairpressure + " mbar") lcd.write_line(3, 0, "L: " + lcdilluminance + " lx") lcd.write_line(3, 14, PLUGINVERSION) Domoticz.Debug("LCD Lines written") ## rgb led set color depending indoor air quality index ## Set the brightness using the value of the parameter Mode2 lbbrightness = int(Parameters["Mode2"]) if lbbrightness < RGBBRIGHTNESSMIN: lbbrightness = RGBBRIGHTNESSMIN if lbbrightness > RGBBRIGHTNESSMAX: lbbrightness = RGBBRIGHTNESSMAX rl.set_rgb_value( SetRGBColor(AIRQUALITYLEVELCOLOR[airqualitylevel][0], lbbrightness), SetRGBColor(AIRQUALITYLEVELCOLOR[airqualitylevel][1], lbbrightness), SetRGBColor(AIRQUALITYLEVELCOLOR[airqualitylevel][2], lbbrightness)) Domoticz.Debug("RGB LED Color set") # Log Message Devices[UNITTEXTSTATUS].Update( nValue=0, sValue="OK: " + lcdaqi + "," + lcdtemperature + "," + lcdhumidity + "," + lcdairpressure) Domoticz.Log(Devices[UNITTEXTSTATUS].sValue) # Disconnect ipcon.disconnect() # Log Message Domoticz.Debug("Update OK.") except: # Error self.isError == 1 # Important to close the connection - if not, the plugin can not be disabled if self.ipConnected == 1: ipcon.disconnect() Devices[UNITTEXTSTATUS].Update( nValue=0, sValue= "[ERROR] Check settings, correct and restart Domoticz.") Domoticz.Log(Devices[UNITTEXTSTATUS].sValue)
def check(self, uid, warning, critical): # PTC # https://www.tinkerforge.com/en/doc/Software/Bricklets/PTCV2_Bricklet_Python.html if self.device_type == self.type_ptc: ticks = 0 if uid: self.ptc = BrickletPTCV2(uid, self.ipcon) else: # TODO: refactor while not self.ptc: time.sleep(0.1) ticks = ticks + 1 if ticks > self.timeout * 10: output("Timeout %s s reached while detecting bricklet. " "Please use -u to specify the device UID." % self.timeout, 3) ptc_value = self.ptc.get_temperature() / 100.0 status = self.eval_thresholds(ptc_value, warning, critical) perfdata = { "temperature": ptc_value } output("Temperature is %s degrees celcius" % ptc_value, status, [], perfdata) # Temperature # https://www.tinkerforge.com/en/doc/Software/Bricklets/Temperature_Bricklet_Python.html if self.device_type == self.type_temperature: ticks = 0 if uid: self.temp = Temperature(uid, self.ipcon) else: # TODO: refactor while not self.temp: time.sleep(0.1) ticks = ticks + 1 if ticks > self.timeout * 10: output("Timeout %s s reached while detecting bricklet. " "Please use -u to specify the device UID." % self.timeout, 3) temp_value = self.temp.get_temperature() / 100.0 status = self.eval_thresholds(temp_value, warning, critical) perfdata = { "temperature": temp_value } output("Temperature is %s degrees celcius" % temp_value, status, [], perfdata) # Ambient Light # https://www.tinkerforge.com/en/doc/Software/Bricklets/AmbientLightV2_Bricklet_Python.html if self.device_type == self.type_ambient_light: ticks = 0 if uid: self.al = BrickletAmbientLightV2(uid, self.ipcon) else: # TODO: refactor while not self.al: time.sleep(0.1) ticks = ticks + 1 if ticks > self.timeout * 10: output("Timeout %s s reached while detecting bricklet. " "Please use -u to specify the device UID." % self.timeout, 3) al_value = self.al.get_illuminance() / 100.0 status = self.eval_thresholds(al_value, warning, critical) perfdata = { "illuminance": al_value } output("Illuminance is %s lx" % al_value, status, [], perfdata) # Humidity # https://www.tinkerforge.com/en/doc/Software/Bricklets/HumidityV2_Bricklet_Python.html if self.device_type == self.type_humidity: ticks = 0 if uid: self.hum = BrickletHumidityV2(uid, self.ipcon) else: # TODO: refactor while not self.hum: time.sleep(0.1) ticks = ticks + 1 if ticks > self.timeout * 10: output("Timeout %s s reached while detecting bricklet. " "Please use -u to specify the device UID." % self.timeout, 3) hum_value = self.hum.get_humidity() / 100.0 hum_temp_value = self.hum.get_temperature() / 100.0 status = self.eval_thresholds(hum_value, warning, critical) perfdata = { "humidity": hum_value, "temperature": hum_temp_value } output("Humidity is %s %%HR (Temperature is %s degrees celcius)" % (hum_value, hum_temp_value), status, [], perfdata) # Distance # https://www.tinkerforge.com/en/doc/Software/Bricklets/DistanceIRV2_Bricklet_Python.html if self.device_type == self.type_distance: ticks = 0 if uid: self.dist = BrickletDistanceIRV2(uid, self.ipcon) else: # TODO: refactor while not self.dist: time.sleep(0.1) ticks = ticks + 1 if ticks > self.timeout * 10: output("Timeout %s s reached while detecting bricklet. " "Please use -u to specify the device UID." % self.timeout, 3) dist_value = self.dist.get_distance() / 10.0 status = self.eval_thresholds(dist_value, warning, critical) perfdata = { "distance": dist_value, } output("Distance is %s cm" % dist_value, status, [], perfdata) # Motion # https://www.tinkerforge.com/de/doc/Software/Bricklets/MotionDetectorV2_Bricklet_Python.html if self.device_type == self.type_motion: ticks = 0 if uid: self.motion = BrickletMotionDetectorV2(uid, self.ipcon) else: # TODO: refactor while not self.motion: time.sleep(0.1) ticks = ticks + 1 if ticks > self.timeout * 10: output("Timeout %s s reached while detecting bricklet. " "Please use -u to specify the device UID." % self.timeout, 3) motion_value = self.motion.get_motion_detected() perfdata = { "motion": motion_value } if motion_value: output("Motion detected!", motion_value, [], perfdata) else: output("No motion detected", motion_value, [], perfdata)
def create_instance(self, uid, ipcon): return BrickletAmbientLightV2(uid, ipcon)
def main(): global tfIDs mqttc = mqtt.Client("") mqttc.username_pw_set(USERNAME, password=PASSWORD) mqttc.tls_set(ca_certs="{}/fakelerootx1.pem".format(os.getcwd()), certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLS, ciphers=None) mqttc.connect(MQTT_ADAPTER_IP, MQTT_ADAPTER_PORT) # mqtt.abc.re.je == 35.242.131.248:30883 mqttc.loop_start() if TF_CONNECT: # Create connection and connect to brickd ipcon = IPConnection() TPS1_bricklet = BrickletTemperature(TPS1_UID, ipcon) HMS1_bricklet = BrickletHumidity(HMS1_UID, ipcon) LPS1_bricklet = BrickletAmbientLightV2(LPS1_UID, ipcon) ipcon.connect(TF_HOST, TF_PORT) # Register Enumerate Callback ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate) # Trigger Enumerate ipcon.enumerate() time.sleep(2) if DEBUG: print(tfIDs) if PUBLISH: # Get current temperature TPS1 = TPS1_bricklet.get_temperature() / 100.0 HMS1 = HMS1_bricklet.get_humidity() / 10.0 LPS1 = LPS1_bricklet.get_illuminance() / 100.0 today = dt.now().strftime("%Y-%m-%d %H:%M") today_0 = dt.now().strftime("%Y-%m-%d 00:00") t = dt.now().strftime("%H:%M") # dtt = dateutil.parser.parse(today) dtt = dt.utcnow() points_TPS1 = {} points_TPS1["temperature"] = {"present_value": TPS1} points_HMS1 = {} points_HMS1["humidity"] = {"present_value": HMS1} points_LPS1 = {} points_LPS1["illuminance"] = {"present_value": LPS1} udmi_payload_TPS1 = str(udmi.Pointset(dtt, points_TPS1)) # print(udmi_payload_TPS1) udmi_payload_HMS1 = str(udmi.Pointset(dtt, points_HMS1)) # print(udmi_payload_HMS1) udmi_payload_LPS1 = str(udmi.Pointset(dtt, points_LPS1)) # print(udmi_payload_LPS1) payload_norm_TPS1 = json_normalize( json.loads(udmi_payload_TPS1)).to_json( orient='records').strip('[]') print(payload_norm_TPS1) payload_norm_HMS1 = json_normalize( json.loads(udmi_payload_HMS1)).to_json( orient='records').strip('[]') print(payload_norm_HMS1) payload_norm_LPS1 = json_normalize( json.loads(udmi_payload_LPS1)).to_json( orient='records').strip('[]') print(payload_norm_LPS1) # msg = json.dumps({"wind": wind, "humidity": humidity, "temperature": temperature}) # infot = mqttc.publish("telemetry", udmi_payload, qos=1) # print("Sending {}".format(udmi_payload_TPS1)) infot = mqttc.publish("telemetry/myapp.iot/{}".format("TPS-1"), payload_norm_TPS1, qos=1) # print("Sending {}".format(udmi_payload_HMS1)) infot = mqttc.publish("telemetry/myapp.iot/{}".format("HMS-1"), payload_norm_HMS1, qos=1) # print("Sending {}".format(udmi_payload_LPS1)) infot = mqttc.publish("telemetry/myapp.iot/{}".format("LPS-1"), payload_norm_LPS1, qos=1) infot.wait_for_publish()