def SetRGBLEDStatusLed(self, state): Domoticz.Debug("SetRGBLEDStatusLed - UID:" + self.UIDList[UIDINDEXRGBLED]) try: # Create IP connection ipcon = IPConnection() # Create device object rl = BrickletRGBLEDV2(self.UIDList[UIDINDEXRGBLED], ipcon) # Connect to brickd ipcon.connect(Parameters["Address"], int(Parameters["Port"])) # Don't use device before ipcon is connected if state == 0: rl.set_status_led_config(state) Domoticz.Log("RGB LED Status LED disabled.") if state == 1: rl.set_status_led_config(state) Domoticz.Log("RGB LED Status LED enabled.") ipcon.disconnect() return 1 except: # Error Domoticz.Log("[ERROR] Can not set RGB LED Status LED.") return 0
def SetBrickletRGB(self, r, g, b): Domoticz.Debug("SetBrickletRGB: R=%d,G=%d,B=%d" % (r, g, b)) try: # Create IP connection ipConn = IPConnection() # Create device object rgbDev = BrickletRGBLEDV2(Parameters["Mode1"], ipConn) # Connect to brickd using Host and Port ipConn.connect(Parameters["Address"], int(Parameters["Port"])) # Assign the color and update the domoticz dimmer switches state = 1 self.r = r Devices[UNITCHANNELR].Update(nValue=state, sValue=str(self.r)) self.g = g Devices[UNITCHANNELG].Update(nValue=state, sValue=str(self.g)) self.b = b Devices[UNITCHANNELB].Update(nValue=state, sValue=str(self.b)) # Update the tinkerforge rgbled device with mapped values rm = MapRange(self.r, 0, 100, 0, 255) gm = MapRange(self.g, 0, 100, 0, 255) bm = MapRange(self.b, 0, 100, 0, 255) Domoticz.Debug("Bricklet Update: R=%d,G=%d,B=%d" % (rm, gm, bm)) rgbDev.set_rgb_value(rm, gm, bm) # Disconnect ipConn.disconnect() Domoticz.Debug("SetBrickletRGB: OK") except: Domoticz.Error("[ERROR] SetBrickletRGB failed. Check bricklet.") return
def SetBrickletConfiguration(self): Domoticz.Debug("SetBrickletConfiguration") try: # Create IP connection ipConn = IPConnection() # Create device object rgbDev = BrickletRGBLEDV2(Parameters["Mode1"], ipConn) # Connect to brickd using Host and Port ipConn.connect(Parameters["Address"], int(Parameters["Port"])) # Update the configuration rgbDev.set_status_led_config(rgbDev.STATUS_LED_CONFIG_OFF) Domoticz.Debug("Set Status LED OFF") # Disconnect ipConn.disconnect() Domoticz.Debug("SetBrickletConfiguration OK") except: Domoticz.Error( "[ERROR] SetBrickletConfiguration failed. Check bricklet.") return
def SetBrickletColor(self, Unit, Command, Level): Domoticz.Debug("SetBrickletColor: Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level) + ", ID=" + str(Devices[Unit].ID)) SetCommand = str(Command) try: # Create IP connection ipConn = IPConnection() # Create device object rgbDev = BrickletRGBLEDV2(Parameters["Mode1"], ipConn) # Connect to brickd using Host and Port ipConn.connect(Parameters["Address"], int(Parameters["Port"])) # Assign the color and update the domoticz dimmerswitches state = 1 if SetCommand == "Off": state = 0 Level = 0 if Unit == UNITCHANNELR: self.r = Level Devices[UNITCHANNELR].Update(nValue=state, sValue=str(self.r)) if Unit == UNITCHANNELG: self.g = Level Devices[UNITCHANNELG].Update(nValue=state, sValue=str(self.g)) if Unit == UNITCHANNELB: self.b = Level Devices[UNITCHANNELB].Update(nValue=state, sValue=str(self.b)) # Update the tinkerforge rgbled device with mapped values rm = MapRange(self.r, 0, 100, 0, 255) gm = MapRange(self.g, 0, 100, 0, 255) bm = MapRange(self.b, 0, 100, 0, 255) rgbDev.set_rgb_value(rm, gm, bm) Domoticz.Debug("Bricklet Update: R=%d,G=%d,B=%d" % (rm, gm, bm)) # Disconnect ipConn.disconnect() Domoticz.Debug("SetBrickletColor: OK") except: Domoticz.Error("[ERROR] SetBrickletColor failed. Check bricklet.") return
#!/usr/bin/env python # -*- coding: utf-8 -*- HOST = "localhost" PORT = 4223 UID = "XYZ" # Change XYZ to the UID of your RGB LED Bricklet 2.0 from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_rgb_led_v2 import BrickletRGBLEDV2 if __name__ == "__main__": ipcon = IPConnection() # Create IP connection rl = BrickletRGBLEDV2(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected # Set light blue color rl.set_rgb_value(0, 170, 234) input("Press key to exit\n") # Use raw_input() in Python 2 ipcon.disconnect()
def main(): global uids global PORT if len(sys.argv) != 1: print("Usage: {}") sys.exit(0) result = {"start": now()} try: with socket.create_connection((PRINTER_HOST, PRINTER_PORT)): print("Label printer is online") except: if input("Failed to reach label printer. Continue anyway? [y/n]" ) != "y": sys.exit(0) print("Checking ESP state") mac_address = check_if_esp_is_sane_and_get_mac() print("MAC Address is {}".format(mac_address)) result["mac"] = mac_address set_voltage_fuses, set_block_3, passphrase, uid = get_espefuse_tasks() if set_voltage_fuses or set_block_3: print("Fuses are not set. Re-run stage 0!") esptool(["--after", "hard_reset", "chip_id"]) result["uid"] = uid ssid = "warp-" + uid run(["systemctl", "restart", "NetworkManager.service"]) print("Waiting for ESP wifi. Takes about one minute.") if not wait_for_wifi(ssid, 90): print("ESP wifi not found after 90 seconds") sys.exit(0) print("Testing ESP Wifi.") with wifi(ssid, passphrase): with urllib.request.urlopen( "http://10.0.0.1/hidden_proxy/enable") as f: f.read() ipcon = IPConnection() ipcon.connect("10.0.0.1", 4223) result["wifi_test_successful"] = True print("Connected. Testing bricklet ports") # Register Enumerate Callback ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate) # Trigger Enumerate ipcon.enumerate() start = time.time() while time.time() - start < 5: if len(uids) == 6: break time.sleep(0.1) if len(uids) != 6: print("Expected 6 RGB LED 2.0 bricklets but found {}".format( len(uids))) sys.exit(0) uids = sorted(uids, key=lambda x: x[0]) bricklets = [(uid[0], BrickletRGBLEDV2(uid[1], ipcon)) for uid in uids] error_count = 0 for bricklet_port, rgb in bricklets: rgb.set_rgb_value(127, 127, 0) time.sleep(0.5) if rgb.get_rgb_value() == (127, 127, 0): rgb.set_rgb_value(0, 127, 0) else: print("Setting color failed on port {}.".format(bricklet_port)) error_count += 1 if error_count != 0: sys.exit(0) result["bricklet_port_test_successful"] = True stop_event = threading.Event() blink_thread = threading.Thread(target=blink_thread_fn, args=([x[1] for x in bricklets], stop_event)) blink_thread.start() input("Bricklet ports seem to work. Press any key to continue") stop_event.set() blink_thread.join() ipcon.disconnect() led0 = input("Does LED 0 blink blue? [y/n]") while led0 != "y" and led0 != "n": led0 = input("Does LED 0 blink blue? [y/n]") result["led0_test_successful"] = led0 == "y" if led0 == "n": print("LED 0 does not work") sys.exit(0) led1 = input( "Press IO0 button (for max 3 seconds). Does LED 1 glow green? [y/n]") while led1 != "y" and led1 != "n": led1 = input( "Press IO0 Button (for max 3 seconds). Does LED 1 glow green? [y/n]" ) result["led1_io0_test_successful"] = led1 == "y" if led1 == "n": print("LED 1 or IO0 button does not work") sys.exit(0) led0_stop = input( "Press EN button. Does LED 0 stop blinking for some seconds? [y/n]") while led0_stop != "y" and led0_stop != "n": led0_stop = input( "Press EN button. Does LED 0 stop blinking for some seconds? [y/n]" ) result["enable_test_successful"] = led0_stop == "y" if led0_stop == "n": print("EN button does not work") sys.exit(0) result["tests_successful"] = True run(["python3", "print-esp32-label.py", ssid, passphrase, "-c", "3"]) label_success = input( "Stick one label on the esp, put esp and the other two labels in the ESD bag. [y/n]" ) while label_success != "y" and label_success != "n": label_success = input( "Stick one label on the esp, put esp and the other two labels in the ESD bag. [y/n]" ) result["labels_printed"] = label_success == "y" result["end"] = now() with open( "{}_{}_report_stage_1.json".format(ssid, now().replace(":", "-")), "w") as f: json.dump(result, f, indent=4)
def InitBricks(self): Domoticz.Debug("InitBricks") try: # Create IP connection ipcon = IPConnection() # Create device objects master = BrickMaster(self.UIDList[UIDINDEXMASTER], ipcon) rl = BrickletRGBLEDV2(self.UIDList[UIDINDEXRGBLED], ipcon) aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon) lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon) # Connect to brickd ipcon.connect(Parameters["Address"], int(Parameters["Port"])) # Settings ## Master - Turn status led off master.disable_status_led() Domoticz.Log("Master Status LED disabled.") ## RGB LED - Turn status led off rl.set_status_led_config(0) Domoticz.Log("RGB LED Status LED disabled.") ## Air Quality - Config ## Turn off status led aq.set_status_led_config(0) Domoticz.Log("Air Quality Status LED disabled.") # Set temperature offset with resolution 1/100°C. Offset 10 = decrease measured temperature by 0.1°C, 100 = 1°C. # offset - int # Test with 2°C = 200 aq.set_temperature_offset(200) # The Air Quality Bricklet uses an automatic background calibration mechanism to calculate the IAQ Index. # This calibration mechanism considers a history of measured data. Duration history = 4 days (0) or 28 days (1). # duration - int 0 | 1 # Test with 0 = 4 days aq.set_background_calibration_duration(0) ## LCD - Turn backlight ON (ensure to update the domoticz switch device), set initial welcome text. lcd.backlight_on() Devices[UNITSWITCHBACKLIGHT].Update(nValue=1, sValue=str(0)) SetLCDText(self, "Indoor Air Quality", "Station " + PLUGINVERSION, "", "2019 by rwbl") # Disconnect and return OK ipcon.disconnect() Domoticz.Debug("InitBricks OK") self.isError = 0 return 1 except: # Error self.isError = 1 Domoticz.Log("[ERROR] Can not init the bricks.") return 0 return
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)
if "G" in args: G = args["G"] if "B" in args: B = args["B"] # Check the json parse result # print("JSON:H={},P={},U={},R={},G={},B={}".format(HOST,PORT,UID,R,G,B)) else: status = 0 result = { "status" : "ERROR", "title" : "Wrong number of arguments." } if status == 1: try: # Create IP connection ipcon = IPConnection() # Create device object rl = BrickletRGBLEDV2(UID, ipcon) # Connect to brickd ipcon.connect(HOST, PORT) # Check if the bricklet is reachable - else error is triggered # In case the bricklet is not reacable, it takes 1-2 seconds befor a response is given rl.read_uid() # Set the color rl.set_rgb_value(R,G,B) result = { "status" : "OK", "title" : "{},{},{}".format(R,G,B) } # Disconnect ipcon.disconnect() except: result = { "status" : "ERROR", "title" : "set_rgb_value failed. Check master & bricklet." } # Print the result which is used by the dzVents Lua script print(json.dumps(result))
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 == BrickletLCD128x64.DEVICE_IDENTIFIER: try: self.lcd128x64 = BrickletLCD128x64(uid, self.ipcon) self.lcd128x64.set_response_expected_all(True) # Register touch gesture callback to function cb_touch_gesture self.lcd128x64.register_callback(self.lcd128x64.CALLBACK_TOUCH_GESTURE, self.cb_touch_gesture) self.lcd128x64.register_callback(self.lcd128x64.CALLBACK_GUI_TAB_SELECTED, self.cb_gui_tab_selected) self.lcd128x64.register_callback(self.lcd128x64.CALLBACK_GUI_SLIDER_VALUE, self.cb_gui_slider_value) self.lcd128x64.set_touch_gesture_callback_configuration(10, True) self.lcd128x64.set_gui_tab_selected_callback_configuration(100, True) self.lcd128x64.set_gui_slider_value_callback_configuration(100, True) screen_set_lcd(self.lcd128x64) log.info('LCD 128x64 Bricklet initialized') except Error as e: log.error('LCD 128x64 Bricklet init failed: ' + str(e.description)) self.lcd128x64 = None screen_set_lcd(None) elif device_identifier == BrickletAirQuality.DEVICE_IDENTIFIER: try: self.air_quality = BrickletAirQuality(uid, self.ipcon) # Update data once directly on initial enumerate self.cb_air_quality_all_values(*self.air_quality.get_all_values()) self.air_quality.register_callback(self.air_quality.CALLBACK_ALL_VALUES, self.cb_air_quality_all_values) self.air_quality.set_all_values_callback_configuration(1000, False) log.info('Air Quality Bricklet initialized') except Error as e: log.error('Air Quality Bricklet init failed: ' + str(e.description)) self.air_quality = None elif device_identifier == BrickletSoundPressureLevel.DEVICE_IDENTIFIER: try: self.sound_pressure = BrickletSoundPressureLevel(uid, self.ipcon) # Update data once directly on initial enumerate self.cb_sound_pressure_decibel(self.sound_pressure.get_decibel()) self.sound_pressure.register_callback(self.sound_pressure.CALLBACK_DECIBEL, self.cb_sound_pressure_decibel) self.sound_pressure.set_decibel_callback_configuration(1000, False, 'x', 0, 100) log.info('Sound Pressure Bricklet initialized') except Error as e: log.error('Sound Pressure Bricklet init failed: ' + str(e.description)) self.sound_pressure = None elif device_identifier == BrickletOutdoorWeather.DEVICE_IDENTIFIER: try: self.outdoor_weather = BrickletOutdoorWeather(uid, self.ipcon) # Update data once directly on initial enumerate for i in self.outdoor_weather.get_station_identifiers(): self.cb_outdoor_weather_station_data(i, *self.outdoor_weather.get_station_data(i)) for i in self.outdoor_weather.get_sensor_identifiers(): self.cb_outdoor_weather_sensor_data(i, *self.outdoor_weather.get_sensor_data(i)) self.outdoor_weather.register_callback(self.outdoor_weather.CALLBACK_STATION_DATA, self.cb_outdoor_weather_station_data) self.outdoor_weather.set_station_callback_configuration(True) self.outdoor_weather.register_callback(self.outdoor_weather.CALLBACK_SENSOR_DATA, self.cb_outdoor_weather_sensor_data) self.outdoor_weather.set_sensor_callback_configuration(True) log.info('Outdoor Weather Bricklet initialized') except Error as e: log.error('Outdoor Weather Bricklet init failed: ' + str(e.description)) self.outdoor_weather = None elif device_identifier == BrickletRGBLEDV2.DEVICE_IDENTIFIER: try: self.led = BrickletRGBLEDV2(uid, self.ipcon) self.led.set_rgb_value(0,127,0) log.info('RGB initialized') except Error as e: log.error('RGB Bricklet init failed: ' + str(e.description)) self.led = None
def main(): global uids global PORT return if len(sys.argv) not in [2, 3, 4]: print("Usage: {} [[--reflash port] test_firmware] [--bootloader port]") sys.exit(0) if "--bootloader" in sys.argv: port_idx = sys.argv.index("--bootloader") + 1 PORT = sys.argv[port_idx] # TODO: use argparse sys.argv = sys.argv[:port_idx - 1] + sys.argv[port_idx + 1:] output = esptool(['--port', PORT, '--after', 'no_reset', 'chip_id']) return reflash = "--reflash" in sys.argv if reflash: reflash = True port_idx = sys.argv.index("--reflash") + 1 PORT = sys.argv[port_idx] # TODO: use argparse sys.argv = sys.argv[:port_idx - 1] + sys.argv[port_idx + 1:] if not os.path.exists(sys.argv[1]): print("Test firmware {} not found.".format(sys.argv[1])) result = {"start": now()} if reflash: set_voltage_fuses, set_block_3, passphrase, uid = get_espefuse_tasks() if set_voltage_fuses or set_block_3: print("This ESP was not provisioned yet!") sys.exit(-1) ssid = "warp-" + uid result["uid"] = uid result["test_firmware"] = sys.argv[1] flash_firmware(sys.argv[1]) result["end"] = now() with open( "{}_{}_report_stage_1_reflash.json".format( ssid, now().replace(":", "-")), "w") as f: json.dump(result, f, indent=4) return try: with socket.create_connection((PRINTER_HOST, PRINTER_PORT)): print("Label printer is online") except: if input("Failed to reach label printer. Continue anyway? [y/n]" ) != "y": sys.exit(0) print("Checking ESP state") mac_address = check_if_esp_is_sane_and_get_mac() print("MAC Address is {}".format(mac_address)) result["mac"] = mac_address set_voltage_fuses, set_block_3, passphrase, uid = get_espefuse_tasks() result["set_voltage_fuses"] = set_voltage_fuses result["set_block_3"] = set_block_3 handle_voltage_fuses(set_voltage_fuses) uid, passphrase = handle_block3_fuses(set_block_3, uid, passphrase) if set_voltage_fuses or set_block_3: print("Verifying eFuses") _set_voltage_fuses, _set_block_3, _passphrase, _uid = get_espefuse_tasks( ) if _set_voltage_fuses: print("Failed to verify voltage eFuses! Are they burned in yet?") sys.exit(0) if _set_block_3: print("Failed to verify block 3 eFuses! Are they burned in yet?") sys.exit(0) if _passphrase != passphrase: print( "Failed to verify block 3 eFuses! Passphrase is not the expected value" ) sys.exit(0) if _uid != uid: print( "Failed to verify block 3 eFuses! UID {} is not the expected value {}" .format(_uid, uid)) sys.exit(0) result["uid"] = uid print("Erasing flash") erase_flash() print("Flashing test firmware") flash_firmware(sys.argv[1]) result["test_firmware"] = sys.argv[1] ssid = "warp-" + uid run(["systemctl", "restart", "NetworkManager.service"]) print("Waiting for ESP wifi. Takes about one minute.") if not wait_for_wifi(ssid, 90): print("ESP wifi not found after 90 seconds") sys.exit(0) print("Testing ESP Wifi.") with wifi(ssid, passphrase): ipcon = IPConnection() ipcon.connect("10.0.0.1", 4223) result["wifi_test_successful"] = True print("Connected. Testing bricklet ports") # Register Enumerate Callback ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate) # Trigger Enumerate ipcon.enumerate() start = time.time() while time.time() - start < 5: if len(uids) == 6: break time.sleep(0.1) if len(uids) != 6: print("Expected 6 RGB LED 2.0 bricklets but found {}".format( len(uids))) sys.exit(0) uids = sorted(uids, key=lambda x: x[0]) bricklets = [(uid[0], BrickletRGBLEDV2(uid[1], ipcon)) for uid in uids] error_count = 0 for bricklet_port, rgb in bricklets: rgb.set_rgb_value(127, 127, 0) time.sleep(0.5) if rgb.get_rgb_value() == (127, 127, 0): rgb.set_rgb_value(0, 127, 0) else: print("Setting color failed on port {}.".format(bricklet_port)) error_count += 1 if error_count != 0: sys.exit(0) result["bricklet_port_test_successful"] = True stop_event = threading.Event() blink_thread = threading.Thread(target=blink_thread_fn, args=([x[1] for x in bricklets], stop_event)) blink_thread.start() input("Bricklet ports seem to work. Press any key to continue") stop_event.set() blink_thread.join() ipcon.disconnect() led0 = input("Does LED 0 blink blue? [y/n]") while led0 != "y" and led0 != "n": led0 = input("Does LED 0 blink blue? [y/n]") result["led0_test_successful"] = led0 == "y" if led0 == "n": print("LED 0 does not work") sys.exit(0) led1 = input( "Press IO0 button (for max 3 seconds). Does LED 1 glow green? [y/n]") while led1 != "y" and led1 != "n": led1 = input( "Press IO0 Button (for max 3 seconds). Does LED 1 glow green? [y/n]" ) result["led1_io0_test_successful"] = led1 == "y" if led1 == "n": print("LED 1 or IO0 button does not work") sys.exit(0) led0_stop = input( "Press EN button. Does LED 0 stop blinking for some seconds? [y/n]") while led0_stop != "y" and led0_stop != "n": led0_stop = input( "Press EN button. Does LED 0 stop blinking for some seconds? [y/n]" ) result["enable_test_successful"] = led0_stop == "y" if led0_stop == "n": print("EN button does not work") sys.exit(0) result["tests_successful"] = True run(["python3", "print-esp32-label.py", ssid, passphrase, "-c", "3"]) label_success = input( "Stick one label on the esp, put esp and the other two labels in the ESD bag. [y/n]" ) while label_success != "y" and label_success != "n": label_success = input( "Stick one label on the esp, put esp and the other two labels in the ESD bag. [y/n]" ) result["labels_printed"] = label_success == "y" result["end"] = now() with open( "{}_{}_report_stage_0+1.json".format(ssid, now().replace(":", "-")), "w") as f: json.dump(result, f, indent=4)