def switchOFFmotor(): import time from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_dual_relay import BrickletDualRelay HOST = "192.168.1.103" PORT = 4223 UID = "Aci" # Change XYZ to the UID of your Dual Relay Bricklet ipcon = IPConnection() # Create IP connection dr = BrickletDualRelay(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected print dr.get_state() time.sleep(0.5) dr.set_state(False, False) time.sleep(0.5) print dr.get_state() ipcon.disconnect()
def __init__(self): LOGGER.info("Heater starting...") self._init_pid() self.ipcon = IPConnection() while True: try: self.ipcon.connect(HOST, PORT) break except TFConnectionError as error: LOGGER.error("Connection Error: " + str(error.description)) sleep(1) except socket.error as error: LOGGER.error("Socket Error: " + str(error)) sleep(1) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) if self.logging_mode: logfile_path = f"{datetime.now().timestamp():0f}_heated_data.csv" self.data_logger = getLogger("data-logger") self.data_logger.setLevel(INFO) self.data_logger.addHandler(FileHandler(logfile_path)) self.data_logger.addHandler(STDOUT_HANDLER) self.data_logger.info( f"Timestamp, Temp (°C), Setpoint (°C), Power (%), Kp, Ki, Kd, Cp, Ci, Cd" ) while True: try: self.ipcon.enumerate() return except TFConnectionError as error: LOGGER.error("Enumerate Error: " + str(error.description)) sleep(1)
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
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 __init__(self, host, port, secret, timeout, verbose): self.host = host self.port = port self.secret = secret self.timeout = timeout self.verbose = verbose self.device_type = None self.ptc = None self.temp = None self.al = None self.hum = None self.dist = None self.motion = None self.type_ptc = "ptc" self.type_temperature = "temperature" self.type_ambient_light = "ambient_light" self.type_humidity = "humidity" self.type_distance = "distance" self.type_motion = "motion" self.ipcon = IPConnection() self.ipcon.set_timeout(self.timeout)
def setup_devices(): ipcon = IPConnection() # Create IP connection stepper = SilentStepper(STEPPER_UID, ipcon) # Create device object # ir ti = BrickletThermalImaging(IR_UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # setup ir ti.set_image_transfer_config(ti.IMAGE_TRANSFER_MANUAL_TEMPERATURE_IMAGE) ti.set_resolution(BrickletThermalImaging.RESOLUTION_0_TO_655_KELVIN) # Don't use device before ipcon is connected stepper.set_motor_current(800) # 800 mA stepper.set_step_configuration(stepper.STEP_RESOLUTION_1, True) # 1/8 steps (interpolated) stepper.set_max_velocity(2000) # Velocity 2000 steps/s # Slow acceleration (500 steps/s^2), # Fast deacceleration (5000 steps/s^2) stepper.set_speed_ramping(500, 5000) stepper.enable() return stepper, ti
def __init__(self, log_func=None): if log_func: global log log = log_func self.ipcon = IPConnection() self.ipcon.connect(HOST, PORT) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.enumerate() log("Trying to find EVSE Bricklet...") while UID_EVSE == None: time.sleep(0.1) log("Found EVSE Bricklet: {0}".format(UID_EVSE)) self.evse = BrickletEVSE(UID_EVSE, self.ipcon) self.idai = BrickletIndustrialDualAnalogInV2(UID_IDAI, self.ipcon) self.ido4 = BrickletIndustrialDigitalOut4V2(UID_IDO4, self.ipcon) self.idi4 = BrickletIndustrialDigitalIn4V2(UID_IDI4, self.ipcon) self.iqr1 = BrickletIndustrialQuadRelayV2(UID_IQR1, self.ipcon) self.iqr2 = BrickletIndustrialQuadRelayV2(UID_IQR2, self.ipcon) self.icou = BrickletIndustrialCounter(UID_ICOU, self.ipcon)
def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui.QPushButton('Refresh', self) self.button.clicked.connect(self.handle_button) self.label = QtGui.QLabel('TBD') layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button) layout.addWidget(self.label) self.ipcon = IPConnection() self.temperature = Temperature(UID_TEMPERATURE, self.ipcon) self.ipcon.connect(HOST, PORT) # We send the callback through the Qt signal/slot # system to make sure that we can change the label self.qtcb_temperature.connect(self.cb_temperature) self.temperature.register_callback(Temperature.CALLBACK_TEMPERATURE, self.qtcb_temperature.emit) # Refresh every second self.temperature.set_temperature_callback_period(1000) # Refresh once on startup self.handle_button()
def setPins(output1,output2,output3,output4): ipcon = IPConnection() # Create IP connection relay = BrickletIndustrialQuadRelay(UID_RELAY, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected relayValue = 0 if output1: relayValue |= (1 << 0) if output2: relayValue |= (1 << 1) if output3: relayValue |= (1 << 2) if output4: relayValue |= (1 << 3) relay.set_value(relayValue) ipcon.disconnect()
def onHeartbeat(self): self.HeartbeatCounter = self.HeartbeatCounter + 1 Domoticz.Debug("onHeartbeat called. Counter=" + str(self.HeartbeatCounter * self.HeartbeatInterval) + " (Heartbeat=" + Parameters["Mode5"] + ")") # Flag to check if connected to the master brick self.ipConnected = 0 # check the heartbeatcounter against the heartbeatinterval if (self.HeartbeatCounter * self.HeartbeatInterval) % int(Parameters["Mode5"]) == 0: # Get the moisture value try: # Create IP connection ipcon = IPConnection() # Create device objects using the UID as defined in the parameter Mode1 # The string contains multiple UIDs separated by comma (,). This enables to define more bricklets. brickletUIDParam = Parameters["Mode1"] Domoticz.Debug("UIDs:" + brickletUIDParam ) # Split the parameter string into a list of UIDs brickletUIDList = brickletUIDParam.split(',') # Check the list length (3 because 3 bricklet UIDs) and create the device objects if len(brickletUIDList) == 3: mb = BrickletMoisture(brickletUIDList[0], ipcon) sb = BrickletSegmentDisplay4x7(brickletUIDList[1], ipcon) lb = BrickletRGBLED(brickletUIDList[2], ipcon) # Connect to brickd using Host and Port try: ipcon.connect(Parameters["Address"], int(Parameters["Port"])) self.ipConnected = 1 Domoticz.Debug("IP Connection - OK") except: Domoticz.Debug("[ERROR] IP Connection failed") # Don't use device before ipcon is connected if self.ipConnected == 0: Devices[2].Update( nValue=0, sValue="[ERROR] Can not connect to Master Brick. Check settings, correct and restart Domoticz." ) Domoticz.Log(Devices[2].sValue) return # Get current moisture value moisturetf = mb.get_moisture_value() Domoticz.Debug("Tinkerforge value:" + str(moisturetf) ) moisturedom = converttfvalue(moisturetf) Domoticz.Debug("Domoticz value:" + str(moisturedom) ) # Moisture Device and Text Device # Update the value - only nValue is used, but mandatory to add an sValue Devices[1].Update( nValue=moisturedom, sValue="0") # Tinkerforge Bricklet Updates # Segment Display set the value between 0(dry) - 100(wet) # Inverse the Domoticz moisure value moistureled = DOMOTICZMOISTUREDRY - moisturedom l = list(str(moistureled)) # dry if len(l) == 1: segments = (DIGITS[0], DIGITS[0], DIGITS[0], DIGITS[int(l[0])]) # irrigation advice if len(l) == 2: segments = (DIGITS[0], DIGITS[0], DIGITS[int(l[0])], DIGITS[int(l[1])]) # adequate if len(l) == 3: segments = (DIGITS[0], DIGITS[int(l[0])], DIGITS[int(l[1])], DIGITS[int(l[2])]) # not used if len(l) == 4: segments = (DIGITS[int(l[0])], DIGITS[int(l[1])], DIGITS[int(l[2])], DIGITS[int(l[3])]) # Write the moisture value to the display with full brightness without colon sb.set_segments(segments, 7, False) Domoticz.Debug("Segment Display updated") # Set the color of the RGB LED indicator # The indicator uses own scheme to keep simple: dry < 20; irrigation advice 20-40; wet > 40 Domoticz.Debug("RGB LED updated. Brightness=" + Parameters["Mode4"]) lbbrightness = int(Parameters["Mode4"]) if lbbrightness < RGBBRIGHTNESSMIN: lbbrightness = RGBBRIGHTNESSMIN if lbbrightness > RGBBRIGHTNESSMAX: lbbrightness = RGBBRIGHTNESSMIN # Turn the LED on with color RGB depending LED value - 0(dry) - 100(wet) # dry = RED if moistureled < 20: lb.set_rgb_value(lbbrightness, 0, 0) # irrigation advice = YELLOW if moistureled >= 20 and moistureled <= 40: lb.set_rgb_value(lbbrightness, lbbrightness, 0) # wet = GREEN if moistureled > 40: lb.set_rgb_value(0, lbbrightness, 0) # Disconnect ipcon.disconnect() # Log Message Devices[2].Update( nValue=0, sValue="Polling OK: TF=" + str(moisturetf)+", Dom="+str(moisturedom)+", LED="+str(moistureled)) Domoticz.Log(Devices[2].sValue) except: # Error # Important to close the connection - if not, the plugin can not be disabled if self.ipConnected == 1: ipcon.disconnect() Devices[2].Update( nValue=0, sValue="[ERROR] Check settings, correct and restart Domoticz." ) Domoticz.Log(Devices[2].sValue)
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 get_bricklet_data(): # Create the JSON object data = {} # Connect to the master brick and get the data from the air quality bricklet try: # Create IP connection ipcon = IPConnection() # Create device object aq = BrickletAirQuality(TFUID, ipcon) # Connect to brickd ipcon.connect(TFHOST, TFPORT) # Don't use device before ipcon is connected # Get calibration duration log.info("Calibration Duration Days [0=4,1=28]:" + str(aq.get_background_calibration_duration())) # Set status LED aq.set_status_led_config(IQA_STATUS_LED) log.info("Status LED:" + str(aq.get_status_led_config())) # Set temperature offset by 2°C (10=0.1°C, measured against real room temperature) # Note: Check from time-to-time if still ok aq.set_temperature_offset(200) log.info("Temperature Offset:" + str(aq.get_temperature_offset() * 0.01)) # Get all values iaq_index, iaq_index_accuracy, temperature, humidity, \ air_pressure = aq.get_all_values() # Assign the values to the JSON object data['iaqindex'] = iaq_index log.info("IAQ Index:" + str(iaq_index)) # IAQ index range 0-500:0-50(good),51-100(average),101-150(little bad),151-200(bad),201-300(worse),301-500(very bad). iaq_quality = IQA_QUALITY_UNKNOWN if iaq_index >= 0 and iaq_index < 51: iaq_quality = IQA_QUALITY_GOOD elif iaq_index > 50 and iaq_index < 101: iaq_quality = IQA_QUALITY_AVERAGE elif iaq_index > 100 and iaq_index < 150: iaq_quality = IQA_QUALITY_LITTLEBAD elif iaq_index > 150 and iaq_index < 201: iaq_quality = IQA_QUALITY_BAD elif iaq_index > 200 and iaq_index < 301: iaq_quality = IQA_QUALITY_WORSE elif iaq_index > 300 and iaq_index < 501: iaq_quality = IQA_QUALITY_VERYBAD data['iaqquality'] = iaq_quality log.info("IAQ Quality:" + iaq_quality) iaq_accuracy = "Unknown" if iaq_index_accuracy == aq.ACCURACY_UNRELIABLE: iaq_accuracy = "Unreliable" elif iaq_index_accuracy == aq.ACCURACY_LOW: iaq_accuracy = "Low" elif iaq_index_accuracy == aq.ACCURACY_MEDIUM: iaq_accuracy = "Medium" elif iaq_index_accuracy == aq.ACCURACY_HIGH: iaq_accuracy = "High" data['iaqaccuracy'] = iaq_accuracy log.info("IAQ Index Accuracy:" + iaq_accuracy) data['temperature'] = temperature/100.0 log.info("Temperature:" + str(temperature/100.0) + " °C") data['humidity'] = humidity/100.0 log.info("Humidity:" + str(humidity/100.0) + " %RH") data['airpressure'] = air_pressure/100.0 log.info("Air Pressure:" + str(air_pressure/100.0) + " hPa") # Disconnect ipcon.disconnect() data['status'] = "OK" data['title'] = "get_bricklet_data" log.info(data['status'] + ","+ data['title']) # Handle errors except OSError as e: data['status'] = "ERR" data['title'] = "OS Error: " + str(e.strerror) log.error(data['status'] + ","+ data['title']) time.sleep(1) # Return the data return json.dumps(data)
def write_lines(unit): Domoticz.Debug("write_lines: Unit=%d,ID=%d,JSON=%s" % (unit, Devices[unit].ID, Devices[unit].sValue)) EMPTYLINE = " " jsonstring = Devices[unit].sValue if len(jsonstring) == 0: status_to_log( STATUSLEVELERROR, "No JSON string defined for the text device (Unit sValue empty).") return try: # Create IP connection ipConn = IPConnection() # Create device object lcdDev = BrickletLCD20x4(Parameters["Mode1"], ipConn) # Connect to brickd using Host and Port ipConn.connect(Parameters["Address"], int(Parameters["Port"])) # Define the lcd function write_line parameter line = 0 position = 0 text = "" clear = 0 # parse the json string json_array = json.loads(jsonstring, encoding=None) Domoticz.Debug("write_lines: Lines: %d" % (len(json_array))) for item in json_array: line = int(item["line"]) position = int(item["position"]) text = item["text"] clear = int(item["clear"]) # Domoticz.Debug("write_lines: Items (l,p,t,c): %d,%d,%s,%d" % (line,position,text,clear) ) # Checks if (line < 0 or line > 3): status_to_log( STATUSLEVELERROR, "write_lines: Wrong line number: %d. Ensure 0-3." % (line)) return if (position < 0 or position > 19): status_to_log( STATUSLEVELERROR, "write_lines: Wrong position number: %d. Ensure 0-19." % (position)) return # Clear action: 1=clear line;2=clear display if clear == 1: lcdDev.write_line(line, 0, EMPTYLINE) if clear == 2: lcdDev.clear_display() # Write text lcdDev.write_line(line, position, text) status_to_log( STATUSLEVELOK, "write_lines: Line=%d,Position=%d,Text=%s" % (line, position, text)) # Disconnect ipConn.disconnect() Domoticz.Debug("write_lines: OK") except: status_to_log( STATUSLEVELERROR, "write_lines: Failed writing text (Unit=%d,ID=%d,JSON=%s). Check JSON definition." % (unit, Devices[unit].ID, Devices[unit].sValue)) return
def main(): # host = "localhost" # port = 4223 # segment_display_uid = "abc" # uid of the sensor to display on the 7-segment display # segment_display_brightness = 2 # brightness of the 7-segment display (0-7) settings = read_config(os.environ) parser = OptionParser() parser.add_option("--host", dest="host", default=settings['host'], help="host/ipaddress of the tinkerforge device", metavar="ADDRESS") parser.add_option("--port", dest="port", default=settings['port'], type=int, help="port of the tinkerforge device", metavar="PORT") parser.add_option( "--segment_display_uid", dest="uid", default=settings['segment_display_uid'], help= "uid of the bricklet which will be displayed in the 7-segment display", metavar="UID") parser.add_option("--segment_display_brightness", type=int, dest="brightness", default=settings['segment_display_brightness'], help="brightness of the 7-segment display (0-7)") parser.add_option( "--install", action="store_true", help="install tinkerforge python api to same directory as the plugin") options = parser.parse_args()[0] settings = { 'host': options.host, 'port': options.port, 'segment_display_uid': options.uid, 'segment_display_brightness': options.brightness } if options.install: return install() try: from tinkerforge.ip_connection import IPConnection # type: ignore[import] except ImportError: sys.stdout.write("<<<tinkerforge:sep(44)>>>\n") sys.stdout.write("master,0.0.0,tinkerforge api isn't installed\n") return 1 conn = IPConnection() conn.connect(settings['host'], settings['port']) device_handlers = init_device_handlers() try: sys.stdout.write("<<<tinkerforge:sep(44)>>>\n") cb = lambda uid, connected_uid, position, hardware_version, firmware_version, \ device_identifier, enumeration_type: \ enumerate_callback(conn, device_handlers, settings, \ uid, connected_uid, position, \ hardware_version, firmware_version, \ device_identifier, enumeration_type) conn.register_callback(IPConnection.CALLBACK_ENUMERATE, cb) conn.enumerate() # bricklets respond asynchronously in callbacks and we have no way of knowing # what bricklets to expect time.sleep(0.1) if segment_display is not None: if segment_display_value is not None: display_on_segment( conn, settings, "%d%s" % (segment_display_value, segment_display_unit)) else: display_on_segment(conn, settings, "") finally: conn.disconnect()
def main(): global speed, direction, timeout, ser rospy.init_node('ros_stepper') ipcon = IPConnection() # Create IP connection current = 800 max_velocity = 4000 ramping_speed = 65000 motor_umfang = 0.188496 HOST = "localhost" PORT = 4223 ipcon.connect(HOST, PORT) # Connect to brickd stepper_l = Motor_row(UID_l1, UID_l2, ipcon, current, max_velocity, ramping_speed, 'l') stepper_r = Motor_row(UID_r1, UID_r2, ipcon, current, max_velocity, ramping_speed, 'r') rospy.Subscriber("/cmd_vel", Twist, callback) r = rospy.Rate(100) # Hz vel_tp = [0] * 50 # 50 sample low-pass for speed dir_tp = [0] * 10 # 10 sample low-pass for steering stepper_l.enable_motors() stepper_r.enable_motors() while not rospy.is_shutdown(): vel_tp[len(vel_tp) - 1] = speed #if not timeout > TIMEOUT else 0 vel_tp[:-1] = vel_tp[1:] dir_tp[len(dir_tp) - 1] = direction dir_tp[:-1] = dir_tp[1:] tx_speed = (sum(vel_tp) / len(vel_tp)) tx_dir = (sum(dir_tp) / len(dir_tp)) # rospy.loginfo("Speed: %f", tx_speed) # rospy.loginfo("Steering: %f", tx_dir) motorR = tx_speed + tx_dir motorL = tx_speed - tx_dir # rospy.loginfo("MotorR: %f", motorR) # rospy.loginfo("MotorL: %f", motorL) steps_motor_l = motorL / motor_umfang * 8 #1600 steps_motor_r = motorR / motor_umfang * 8 #1600 rospy.loginfo("MotorR S/s %f", steps_motor_r) rospy.loginfo("MotorL S/s %f", steps_motor_l) stepper_logic(stepper_l, steps_motor_l) stepper_logic(stepper_r, steps_motor_r) timeout += 1 r.sleep() stepper_l.disable() stepper_r.disable()
def build(self): self.title = 'Tinkerforge Sensors' # self.layout = BoxLayout(padding=10) self.layout = GridLayout(cols=columns_number, padding=10, spacing=10) self.sensors = [] self.buttons = [] self.ipcon = None self.influx_client = None if tfConnect: # Create connection and connect to brickd self.ipcon = IPConnection() self.ipcon.connect(HOST, PORT) # Register Enumerate Callback self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate) # Trigger Enumerate self.ipcon.enumerate() sleep(2) #raw_input("Press key to exit\n") # Use input() in Python 3 if debug: print(tfIDs) # Connect to InfluxDB server if send_to_influx: print("Connecting to InfluxDB server %s" % INFLUX_AUTH["host"]) # self.influx_client = InfluxDBClient(INFLUXserver, INFLUXport, INFLUXdbuser, INFLUXdbuser_password, INFLUXdbname) try: self.influx_client = InfluxDBClient( host=INFLUX_AUTH["host"], port=INFLUX_AUTH["port"], username=INFLUX_AUTH["user"], password=INFLUX_AUTH["pass"], database=INFLUX_AUTH["db"], ssl=INFLUX_AUTH["ssl"], timeout=1, retries=5, ) except Exception as e: print("Error connecting to InfluxDB:") print(e) for tf in tfIDs: # try: if True: # print(len(tf[0])) if len( tf[0] ) <= 3: # if the device UID is 3 characters it is a bricklet #self.addButton(label=getIdentifier(tf)) if tf[1] in deviceIDs: bricklet = deviceIdentifiersDict[tf[1]]["class"]( tf[0], self.ipcon) self.sensors.append(bricklet) quantity = getattr( bricklet, deviceIdentifiersDict[tf[1]]["value_func"])() + 1 v = eval(deviceIdentifiersDict[tf[1]]["correction"] % quantity) unit = deviceIdentifiersDict[tf[1]]["unit"] if debug: print( quantity, deviceIdentifiersDict[tf[1]]["correction"] % quantity) print(tf[0], getIdentifier(tf), deviceIdentifiersDict[tf[1]], v, unit) kv_button = Button(text=tf[0] + "\n" + getIdentifier(tf) + "\n" + str(v) + " " + unit, font_size=50) self.buttons.append(kv_button) self.layout.add_widget(kv_button) # if tf[1] == 259: # al = BrickletAmbientLightV2(tf[0], ipcon) # print(al.get_identity()) # # al.register_callback(al.CALLBACK_ILLUMINANCE, cb_illuminance) # #al.set_illuminance_callback_period(1000) # self.sensors.append(al) # kv_button = Button(text=tf[0]+"\n"+getIdentifier(tf)+"\n"+str(al.get_illuminance()/100.0)+" lux",font_size=50) # self.buttons.append(kv_button) # self.layout.add_widget(kv_button) # if tf[1] == 216: # al = BrickletTemperature(tf[0], ipcon) # print(al.get_identity()) # # al.register_callback(al.CALLBACK_ILLUMINANCE, cb_illuminance) # #al.set_illuminance_callback_period(1000) # self.sensors.append(al) # kv_button = Button(text=tf[0]+"\n"+getIdentifier(tf)+"\n"+str(al.get_temperature()/100.0)+" ºC",font_size=50) # self.buttons.append(kv_button) # self.layout.add_widget(kv_button) # if tf[1] == 27: # al = BrickletHumidity(tf[0], ipcon) # print(al.get_identity()) # # al.register_callback(al.CALLBACK_ILLUMINANCE, cb_illuminance) # #al.set_illuminance_callback_period(1000) # self.sensors.append(al) # kv_button = Button(text=tf[0]+"\n"+getIdentifier(tf)+"\n"+str(al.get_humidity()/10.0)+" %RH",font_size=50) # self.buttons.append(kv_button) # self.layout.add_widget(kv_button) # except: # pass Clock.schedule_interval(self.cb_sensors, reading_interval) imgs = getImages(imgPath) # print(imgs) for img in imgs: fn = join(imgPath, img) im = CoreImage(fn) # print(dir(im))] # print(im.size) kv_button = Button(background_normal=fn) # print(dir(kv_button)) kv_button.texture_size = [100, 100] #im.size # print(kv_button.texture_size) self.layout.add_widget(kv_button) return (self.layout)
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)
#!/usr/bin/env python # -*- coding: utf-8 -*- HOST = "localhost" PORT = 4223 UIDm = "9p19drqHQdS" # Change to your UID from tinkerforge.ip_connection import IPConnection from tinkerforge.brick_master import Master #from tinkerforge.brick_dc import DC #from tinkerforge.bricklet_lcd_20x4 import LCD20x4 ipcon = IPConnection(HOST, PORT) # Create IP connection to brickd master = Master(UIDm) # Create device object ipcon.add_device(master) # Add device to IP connection # Get voltage and current from stack (in mV/mA) voltage = master.get_stack_voltage() current = master.get_stack_current() tempera = master.get_chip_temperature() # Print Voltage, Current and Temperature from Master print('Stack Voltage: ' + str(voltage / 1000.0) + ' V') print('Stack Current: ' + str(current / 1000.0) + ' A') print('Stack Tempera: ' + str(tempera / 10) + ' °C')
def setUpModule(): print "Setting up the Tests..." Helper.ipcon = IPConnection() Helper.ipcon.connect(Helper.HOST, Helper.PORT) Helper.red = RED(Helper.UID, Helper.ipcon)
PORT = 4223 UID = "qA9" # Auf die ID aus dem BrickViewer ändern! from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_lcd_20x4 import BrickletLCD20x4 # Callback function, wird aufgerufen wenn eine Taste gedrückt wird def cb_button_pressed(button): print("Button gedrückt: " + str(button)) # Callback function, wird aufgerufen wenn eine Taste losgelassen wird def cb_button_released(button): print("Button losgelassen: " + str(button)) # Ab hier fängt das "eigentliche Programm" an ipcon = IPConnection() # Verbindung mit dem Master herstellen lcd = BrickletLCD20x4(UID, ipcon) # Eine Verbindung zum LC-Display anlegen ipcon.connect(HOST, PORT) # Verbinden # Callbacks registrieren, sonst wird nichts beim drücken / loslassen aufgerufen! lcd.register_callback(lcd.CALLBACK_BUTTON_PRESSED, cb_button_pressed) lcd.register_callback(lcd.CALLBACK_BUTTON_RELEASED, cb_button_released) input("Drücke ENTER zum beenden\n" ) # Auf irgendetwas warten, sonst habt Ihr keine Zeit etwas zu tun ipcon.disconnect() # Die Verbindung wieder abbauen
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
def main(): # host = "localhost" # port = 4223 # segment_display_uid = "abc" # uid of the sensor to display on the 7-segment display # segment_display_brightness = 2 # brightness of the 7-segment display (0-7) settings = read_config() parser = OptionParser() parser.add_option( "--host", dest="host", default=settings["host"], help="host/ipaddress of the tinkerforge device", metavar="ADDRESS", ) parser.add_option( "--port", dest="port", default=settings["port"], type=int, help="port of the tinkerforge device", metavar="PORT", ) parser.add_option( "--segment_display_uid", dest="uid", default=settings["segment_display_uid"], help="uid of the bricklet which will be displayed in the 7-segment display", metavar="UID", ) parser.add_option( "--segment_display_brightness", type=int, dest="brightness", default=settings["segment_display_brightness"], help="brightness of the 7-segment display (0-7)", ) options, _args = parser.parse_args() settings = { "host": options.host, "port": options.port, "segment_display_uid": options.uid, "segment_display_brightness": options.brightness, } try: from tinkerforge.ip_connection import IPConnection except ImportError: print("<<<tinkerforge:sep(44)>>>") print("master,0.0.0,tinkerforge api isn't installed") return 1 conn = IPConnection() try: conn.connect(settings["host"], settings["port"]) except socket.error as e: sys.stderr.write("%s\n" % e) return 1 device_handlers = init_device_handlers() try: print("<<<tinkerforge:sep(44)>>>") def cb( uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type, ): enumerate_callback( conn, device_handlers, settings, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type, ) conn.register_callback(IPConnection.CALLBACK_ENUMERATE, cb) conn.enumerate() # bricklets respond asynchronously in callbacks and we have no way of knowing # what bricklets to expect time.sleep(0.1) if segment_display is not None: if segment_display_value is not None: display_on_segment( conn, settings, "%d%s" % (segment_display_value, segment_display_unit) ) else: display_on_segment(conn, settings, "") finally: conn.disconnect()
def main(): global uids result = {"start": now()} with urllib.request.urlopen( "https://download.tinkerforge.com/latest_versions.txt") as f: latest_versions = f.read().decode("utf-8") match = re.search(r"bricklets:evse:(\d)\.(\d)\.(\d)", latest_versions) major = match.group(1) minor = match.group(2) patch = match.group(3) if not os.path.exists("firmwares"): os.mkdir("firmwares") evse_path = "bricklet_evse_firmware_{}_{}_{}.zbin".format( major, minor, patch) if not os.path.exists(evse_path): urllib.request.urlretrieve( 'https://download.tinkerforge.com/firmwares/bricklets/evse/{}'. format(evse_path), os.path.join("firmwares", evse_path)) evse_path = os.path.join("firmwares", evse_path) #with urllib.request.urlopen("https://www.warp-charger.com/") as f: # warp_charger_page = f.read().decode("utf-8") #match = re.search(r'<a href="firmwares/(warp_firmware_\d_\d_\d_[0-9a-f]{8}_merged.bin)" class="btn btn-primary btn-lg" id="download_latest_firmware">', #warp_charger_page) #firmware_path = match.group(1) #if not os.path.exists(firmware_path): # urllib.request.urlretrieve('https://www.warp-charger.com/firmwares/{}'.format(firmware_path), os.path.join("firmwares", firmware_path)) #firmware_path = os.path.join("firmwares", firmware_path) #T:WARP-CS-11KW-50-CEE;V:2.17;S:5000000001;B:2021-01;O:SO/B2020123;I:1/1;; pattern = r'^T:WARP-C(B|S|P)-(11|22)KW-(50|75)(|-CEE);V:(\d+\.\d+);S:(5\d{9});B:(\d{4}-\d{2});O:(SO/B?[0-9]+);I:(\d+/\d+)(?:;E:(\d+))?;;;*$' qr_code = my_input("Scan the docket QR code") match = re.match(pattern, qr_code) while not match: qr_code = my_input("Scan the docket QR code", red) match = re.match(pattern, qr_code) docket_variant = match.group(1) docket_power = match.group(2) docket_cable_len = match.group(3) docket_has_cee = match.group(4) docket_hw_version = match.group(5) docket_serial = match.group(6) docket_built = match.group(7) docket_order = match.group(8) docket_item = match.group(9) docket_supply_cable_extension = match.group(10) if docket_supply_cable_extension == None: docket_supply_cable_extension = 0 else: docket_supply_cable_extension = int(docket_supply_cable_extension) print("Docket QR code data:") print(" WARP Charger {}".format({ "B": "Basic", "S": "Smart", "P": "Pro" }[docket_variant])) print(" {} kW".format(docket_power)) print(" {:1.1f} m".format(int(docket_cable_len) / 10.0)) print(" CEE: {}".format("Yes" if docket_has_cee == "-CEE" else "No")) print(" HW Version: {}".format(docket_hw_version)) print(" Serial: {}".format(docket_serial)) print(" Build month: {}".format(docket_built)) print(" Order: {}".format(docket_order)) print(" Item: {}".format(docket_item)) print( " Supply Cable Extension: {}".format(docket_supply_cable_extension)) result["order"] = docket_order result["order_item"] = docket_item result["supply_cable_extension"] = docket_supply_cable_extension result["docket_qr_code"] = match.group(0) #T:WARP-CS-11KW-50-CEE;V:2.17;S:5000000001;B:2021-01;; pattern = r'^T:WARP-C(B|S|P)-(11|22)KW-(50|75)(|-CEE);V:(\d+\.\d+);S:(5\d{9});B:(\d{4}-\d{2});;;*$' qr_code = my_input("Scan the wallbox QR code") match = re.match(pattern, qr_code) while not match: qr_code = my_input("Scan the wallbox QR code", red) match = re.match(pattern, qr_code) qr_variant = match.group(1) qr_power = match.group(2) qr_cable_len = match.group(3) qr_has_cee = match.group(4) qr_hw_version = match.group(5) qr_serial = match.group(6) qr_built = match.group(7) if docket_variant != qr_variant or \ docket_power != qr_power or \ docket_cable_len != qr_cable_len or \ docket_has_cee != qr_has_cee or \ docket_hw_version != qr_hw_version or \ docket_serial != qr_serial or \ docket_built != qr_built: fatal_error("Docket and wallbox QR code do not match!") print("Wallbox QR code data:") print(" WARP Charger {}".format({ "B": "Basic", "S": "Smart", "P": "Pro" }[qr_variant])) print(" {} kW".format(qr_power)) print(" {:1.1f} m".format(int(qr_cable_len) / 10.0)) print(" CEE: {}".format("Yes" if qr_has_cee == "-CEE" else "No")) print(" HW Version: {}".format(qr_hw_version)) print(" Serial: {}".format(qr_serial)) print(" Build month: {}".format(qr_built)) result["serial"] = qr_serial result["qr_code"] = match.group(0) if qr_variant != "B": pattern = r"^WIFI:S:(esp32|warp)-([{BASE58}]{{3,6}});T:WPA;P:([{BASE58}]{{4}}-[{BASE58}]{{4}}-[{BASE58}]{{4}}-[{BASE58}]{{4}});;$".format( BASE58=BASE58) qr_code = getpass.getpass(green("Scan the ESP Brick QR code")) match = re.match(pattern, qr_code) while not match: qr_code = getpass.getpass(red("Scan the ESP Brick QR code")) match = re.match(pattern, qr_code) hardware_type = match.group(1) esp_uid_qr = match.group(2) passphrase_qr = match.group(3) print("ESP Brick QR code data:") print(" Hardware type: {}".format(hardware_type)) print(" UID: {}".format(esp_uid_qr)) if not os.path.exists(PORT): fatal_error( "/dev/ttyUSB0 does not exist. Is the USB cable plugged in?") set_voltage_fuses, set_block_3, passphrase, uid = get_espefuse_tasks() output = esptool(['--port', PORT, '--after', 'hard_reset', 'flash_id']) if set_voltage_fuses: fatal_error("Voltage fuses not set!") if set_block_3: fatal_error("Block 3 fuses not set!") if esp_uid_qr != uid: fatal_error( "ESP UID written in fuses ({}) does not match the one on the QR code ({})" .format(uid, esp_uid_qr)) if passphrase_qr != passphrase: fatal_error( "Wifi passphrase written in fuses does not match the one on the QR code" ) result["uid"] = uid run(["systemctl", "restart", "NetworkManager.service"]) ssid = "warp-" + uid print("Waiting for ESP wifi. Takes about one minute.") if not wait_for_wifi(ssid, 120): fatal_error("ESP wifi not found after 120 seconds") with wifi(ssid, passphrase): try: with urllib.request.urlopen( "http://10.0.0.1/hidden_proxy/enable") as f: f.read() except Exception as e: print("Failed to enable hidden proxy. Flashing new firmware.") print(e) print("Erasing flash") erase_flash() print("Flashing firmware") flash_firmware( os.path.join('..', '..', '..', 'warp_firmware_1_2_3_60cb5c5b_merged.bin')) result["firmware"] = "warp_firmware_1_2_3_60cb5c5b_merged.bin" run(["systemctl", "restart", "NetworkManager.service"]) print("Waiting for ESP wifi. Takes about one minute.") if not wait_for_wifi(ssid, 120): fatal_error("ESP wifi not found after 120 seconds") output = "\n".join( run([ "nmcli", "dev", "wifi", "connect", ssid, "password", passphrase ])) if "successfully activated with" not in output: run(["nmcli", "con", "del", ssid]) fatal_error("Failed to connect to wifi.", "nmcli output was:", output) with urllib.request.urlopen( "http://10.0.0.1/hidden_proxy/enable") as f: f.read() ipcon = IPConnection() try: ipcon.connect("10.0.0.1", 4223) except Exception as e: fatal_error("Failed to connect to ESP proxy") run_bricklet_tests(ipcon, result, qr_variant, qr_power) else: result["uid"] = None ipcon = IPConnection() ipcon.connect("localhost", 4223) run_bricklet_tests(ipcon, result, qr_variant, qr_power) print("Flashing EVSE") run(["python3", "comcu_flasher.py", result["evse_uid"], evse_path]) result["evse_firmware"] = evse_path print("Checking if EVSE was tested...") if not exists_evse_test_report(result["evse_uid"]): print("No test report found. Checking for new test reports...") with ChangedDirectory(os.path.join("..", "..", "wallbox")): run(["git", "pull"]) if not exists_evse_test_report(result["evse_uid"]): fatal_error("No test report found for EVSE {}.".format( result["evse_uid"])) print("EVSE test report found") result["evse_test_report_found"] = True if qr_variant == "B": ssid = "warp-" + result["evse_uid"] result["end"] = now() with open( "{}_{}_report_stage_2.json".format(ssid, now().replace(":", "-")), "w") as f: json.dump(result, f, indent=4) if qr_variant != "B": with wifi(ssid, passphrase): my_input( "Pull the USB cable, do the electrical tests and press any key when done" ) # Restart NetworkManager to reconnect to the "default" wifi run(["systemctl", "restart", "NetworkManager.service"])
def connect(self, uid, host, port): self.ipcon = IPConnection() self.ipcon.connect(host, port) self.rb = BrickRED(uid, self.ipcon)
sleep(1) ipcon.destroy() if __name__ == "__main__": # Initialisiere PyGame um die Steuerung zu realisieren pygame.init() # Defeniere die groesse des unnoetigen PyGame fensters, # hier soll spaeter die Webcam gezeigt werden screen = pygame.display.set_mode((200, 200)) # Wird benoetigt um die KeyWiederholung zu realisieren clock = pygame.time.Clock() # Create IP connection to brickd ipcon = IPConnection(HOST, PORT) # Create device objects dc0 = DC(UIDdc0) dc1 = DC(UIDdc1) lcd = LCD20x4(UIDdpl) mst = Master(UIDmaster) # Connect to devices ipcon.add_device(dc0) ipcon.add_device(dc1) ipcon.add_device(lcd) ipcon.add_device(mst) # Hier wird ein Initial Program gestartet um eventuelle sonderwuensche entgegenzunehmen velol = 0
Ys = [y1, y2, y3, y4, y5, y6, y7, y8, y9, y10] for y in range(anzahl): if g_index % 2 == 0: r_index = Ys[y] - 1 else: r_index = 10 - Ys[y] red[g_index - 1][r_index] = r green[g_index - 1][r_index] = g blue[g_index - 1][r_index] = b if __name__ == "__main__": ipcon = IPConnection() ls = BrickletLEDStrip(UID, ipcon) ipcon.connect(HOST, PORT) fClear() sleep(1) setColor(255, 255, 255) yLine(1) yLine(10) fOn() while True:
def get_switches(): tinkerforge_connection = IPConnection() tinkerforge = False # # get a list of all switches for this client # sql = """SELECT switches.id AS switches_id, switches.title AS switches_title, switches.argA, switches.argB, switches.argC, switches.argD, switch_types.title AS switches_typ FROM switches, switch_types, clients WHERE clients.ip = %s AND switches.switch_types_id = switch_types.id AND switches.clients_id = clients.id""" mysql_cursor.execute(sql, str(DEVICE_IP)) results = mysql_cursor.fetchall() for result in results: switches_info[result['switches_id'], "title"] = result['switches_title'] switches_info[result['switches_id'], "argA"] = result['argA'] switches_info[result['switches_id'], "argB"] = result['argB'] switches_info[result['switches_id'], "argC"] = result['argC'] switches_info[result['switches_id'], "argD"] = result['argD'] logger.debug('get_switches... %s id=%s (%s)' % (result['switches_title'], result['switches_id'], result['switches_typ'])) # # set up Tinkerforge switches # if result['switches_typ'] == "tf_ind_quad_relay": switches_info[result['switches_id'], "index"] = result['argA'] switches[switches_info[result['switches_id'], "index"]] = BrickletQuadRelay( result['argA'], result['switches_id'], DEVICE_IP, tinkerforge_connection, logger, consumers) tinkerforge = True elif result['switches_typ'] == "tf_dual": switches_info[result['switches_id'], "index"] = result['argA'] switches[switches_info[result['switches_id'], "index"]] = BrickletDualRelay( result['argA'], result['switches_id'], DEVICE_IP, tinkerforge_connection, logger, consumers) tinkerforge = True elif result['switches_typ'] == "tf_remote": switches_info[result['switches_id'], "index"] = result['argA'] switches[switches_info[result['switches_id'], "index"]] = BrickletRemote( result['argA'], result['switches_id'], DEVICE_IP, tinkerforge_connection, logger, consumers) tinkerforge = True # # set up SIS USB switch # elif result['switches_typ'] == "sis_usb_socket": switches_info[result['switches_id'], "index"] = "sis_usb_socket" switches[switches_info[result['switches_id'], "index"]] = lib_sispm.Sispm( result['switches_id'], DEVICE_IP, logger, consumers) # # set up SimpliBoxIO # elif result['switches_typ'] == "simplibox_io_usb": switches_info[result['switches_id'], "index"] = "simplibox_io_usb" switches[switches_info[result['switches_id'], "index"]] = lib_simpliboxio.SimpliBoxIO( result['switches_id'], DEVICE_IP, logger, consumers) # # set up raspi gpio pins # elif result['switches_typ'] == "raspi_gpio": switches_info[result['switches_id'], "index"] = "raspi_gpio" switches[switches_info[result['switches_id'], "index"]] = lib_gpio.RaspiGPIO( result['switches_id'], DEVICE_IP, logger, consumers) # # set up raspi i2c Bus # elif result['switches_typ'] == "raspi_i2c": switches_info[result['switches_id'], "index"] = "raspi_i2c" switches[switches_info[result['switches_id'], "index"]] = lib_i2c.RaspiI2C( result['switches_id'], DEVICE_IP, logger, consumers) if tinkerforge: tinkerforge_connection.connect(DEVICE_IP, 4223) logger.info('Tinkerforge ... System online')
#!/usr/bin/env python # -*- coding: utf-8 -*- HOST = "localhost" PORT = 4223 UID = "XYZ" # Change XYZ to the UID of your Laser Range Finder Bricklet import time from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_laser_range_finder import BrickletLaserRangeFinder if __name__ == "__main__": ipcon = IPConnection() # Create IP connection lrf = BrickletLaserRangeFinder(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected # Turn laser on and wait 250ms for very first measurement to be ready lrf.enable_laser() time.sleep(0.25) # Get current distance (unit is cm) distance = lrf.get_distance() print("Distance: " + str(distance) + " cm") raw_input("Press key to exit\n") # Use input() in Python 3 lrf.disable_laser() # Turn laser off ipcon.disconnect()
def set_configuration(backlight, cursor, blinking): Domoticz.Debug("set_configuration") try: # Create IP connection ipConn = IPConnection() # Create device object lcdDev = BrickletLCD20x4(Parameters["Mode1"], ipConn) # Connect to brickd using Host and Port ipConn.connect(Parameters["Address"], int(Parameters["Port"])) # Update the configuration if backlight == True: lcdDev.backlight_on() else: lcdDev.backlight_off() lcdDev.set_config(cursor, blinking) # Set Custom Characters with index 0-7 as max 8 custom characters can be defined. # dzVents Lua scripts: # The \ character needs to be escaped, i.e. line = string.format(line, l, p, "\\u0008", domoticz.helpers.isnowhhmm(domoticz) ) # Ensure to write in unicode \u00NN and NOT \xNN - Example: lcdDev.write_line(0, 0, "Battery: " + "\u0008") # JSON has no hex escape \xNN but supports unicode escape \uNNNN # # Example custom character definition and write to the lcd: # battery = [14,27,17,17,17,17,17,31] # clock = [31,17,10,4,14,31,31,0] # lcdDev.set_custom_character(0, clock) # # JSON File # Read the custom characters from JSON array file as defined by constant CUSTOMCHARFILE # JSON format examplewith 2 characters: # [ # {"id":0,"name":"battery","char":"14,27,17,17,17,17,17,31"}, # {"id":1,"name":"clock","char":"31,17,10,4,14,31,31,0"} # ] # Use exception handling in case file not found # The id must be in range 0-7 as max 8 custom characters can be defined try: with open(CUSTOMCHARFILE) as f: json_char_array = json.load(f) Domoticz.Debug("Customchar: #characters defined: %d" % (len(json_char_array))) if len(json_char_array) > 0: for item in json_char_array: id = int(item["id"]) name = item["name"] char = item["char"].strip().split(",") # Check if the character id is in range 0-7 if id >= 0 and id <= 7: lcdDev.set_custom_character(id, char) Domoticz.Debug( "Customchar: Index=%d,Name=%s,Char=%s" % (id, name, item["char"])) else: status_to_log( STATUSLEVELERROR, "Customchar: Index=%d not in range 0-7." % (id)) else: status_to_log( STATUSLEVELERROR, "Customchar: No or wrong characters defined.") except: status_to_log( STATUSLEVELERROR, "Customchar: Can not open file=%s." % (CUSTOMCHARFILE)) # Disconnect ipConn.disconnect() Domoticz.Debug("set_configuration: OK") except: status_to_log(STATUSLEVELERROR, MSGERRSETCONFIG) return