def temperature(connection, table): ipcon = IPConnection() t = Temperature(TEMPERATURE_UID, ipcon) ipcon.connect(HOST, PORT) value = t.get_temperature() / 100.0 insert(connection, table, time.time(), value) ipcon.disconnect()
def humidity(connection, table): ipcon = IPConnection() h = Humidity(HUMIDITY_UID, ipcon) ipcon.connect(HOST, PORT) value = h.get_humidity() / 10.0 insert(connection, table, time.time(), value) ipcon.disconnect()
def collect_data(suffix): global SAMPLE_RATE global w1 global row print "Now recording " + suffix ipcon = IPConnection() # Create IP connection imu = IMU(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected # Set period for quaternion callback to 1s imu.set_all_data_period(SAMPLE_RATE) imu.set_orientation_period(SAMPLE_RATE) imu.set_quaternion_period(SAMPLE_RATE) f1 = open('data/letters/all_data_'+suffix+'.csv', 'wb') w1 = csv.writer(f1) row = [] # Register quaternion callback imu.register_callback(imu.CALLBACK_ALL_DATA, cb_all_data) imu.register_callback(imu.CALLBACK_ORIENTATION, cb_orientation_data) imu.register_callback(imu.CALLBACK_QUATERNION, cb_quaternion_data) raw_input('Press key to quit recording ' + suffix + ' \n') # Use input() in Python 3 ipcon.disconnect()
def barometer(connection, table): ipcon = IPConnection() b = Barometer(BAROMETER_UID, ipcon) ipcon.connect(HOST, PORT) value = b.get_air_pressure() / 1000.0 # Get current air pressure (unit is mbar/1000) insert(connection, table, time.time(), value) ipcon.disconnect()
def ambient(connection, table): ipcon = IPConnection() al = AmbientLight(AMBIENT_UID, ipcon) ipcon.connect(HOST, PORT) value = al.get_illuminance() / 10.0 # Get current illuminance (unit is Lux/10) insert(connection, table, time.time(), value) ipcon.disconnect()
def SetMasterStatusLed(self, state): Domoticz.Debug("SetMasterStatusLed - UID:" + self.UIDList[UIDINDEXMASTER]) try: # Create IP connection ipcon = IPConnection() # Create device object master = BrickMaster(self.UIDList[UIDINDEXMASTER], ipcon) # Connect to brickd ipcon.connect(Parameters["Address"], int(Parameters["Port"])) # Don't use device before ipcon is connected if state == 0: master.disable_status_led() Domoticz.Log("Master Status LED disabled.") if state == 1: master.enable_status_led() Domoticz.Log("Master Status LED enabled.") ipcon.disconnect() return 1 except: # Error Domoticz.Log("[ERROR] Can not set Master Status LED.") return 0
def SetLCDText(self, line1, line2, line3, line4): Domoticz.Debug("SetLCDText - UID:" + self.UIDList[UIDINDEXLCD]) try: # Create IP connection ipcon = IPConnection() # Create device object lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon) # Connect to brickd ipcon.connect(Parameters["Address"], int(Parameters["Port"])) # Don't use device before ipcon is connected ## write to the lcd: line (int,0-3),pos(int,0-19),text lcd.clear_display() lcd.write_line(0, 0, line1) lcd.write_line(1, 0, line2) lcd.write_line(2, 0, line3) lcd.write_line(3, 0, line4) ipcon.disconnect() return 1 except: # Error Domoticz.Log("[ERROR] Can not set Master Status LED.") return 0
def ConfigAirQuality(self): Domoticz.Debug("ConfigAirQuality - UID:" + self.UIDList[UIDINDEXAIRQUALITY]) try: # Create IP connection ipcon = IPConnection() # Create device object aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon) # Connect to brickd ipcon.connect(Parameters["Address"], int(Parameters["Port"])) # Don't use device before ipcon is connected # 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) ipcon.disconnect() return 1 except: # Error Domoticz.Log("[ERROR] Can not set Air Quality Status LED.") return 0
def SetAirQualityStatusLed(self, state): Domoticz.Debug("SetAirQualityStatusLed - UID:" + self.UIDList[UIDINDEXAIRQUALITY]) try: # Create IP connection ipcon = IPConnection() # Create device object aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon) # Connect to brickd ipcon.connect(Parameters["Address"], int(Parameters["Port"])) # Don't use device before ipcon is connected if state == 0: aq.set_status_led_config(state) Domoticz.Log("Air Quality Status LED disabled.") if state == 1: aq.set_status_led_config(state) Domoticz.Log("Air Quality Status LED enabled.") ipcon.disconnect() return 1 except: # Error Domoticz.Log("[ERROR] Can not set Air Quality Status LED.") return 0
class PressureSensor(): def __init__(self, uid, host): self._host = host self._port = 4223 self._uid = uid # Change XYZ to the UID of your Load Cell Bricklet 2.0 self._connect() def _connect(self): print(self._host) print(self._port) print(self._uid) self._ipcon = IPConnection() # Create IP connection self._lc = BrickletLoadCellV2(self._uid, self._ipcon) # Create device object self._ipcon.connect(self._host, self._port) # Connect to brickd def disconnect(self): self._ipcon.disconnect() def get(self): return self._lc.get_weight()
def SetLCDBacklight(self, state): Domoticz.Debug("SetLCDBacklight - UID:" + self.UIDList[UIDINDEXLCD]) try: # Create IP connection ipcon = IPConnection() # Create device object lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon) # Connect to brickd ipcon.connect(Parameters["Address"], int(Parameters["Port"])) # Don't use device before ipcon is connected if state == 'Off': lcd.backlight_off() Domoticz.Log("LCD Backlight OFF.") if state == 'On': lcd.backlight_on() Domoticz.Log("LCD Backlight ON.") ipcon.disconnect() return 1 except: # Error Domoticz.Log("[ERROR] Can not set Master Status LED.") return 0
def setPins(mcuReset, pcuReset, mcuBoot, pcuBoot): 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 mcuReset: relayValue |= (1 << 0) if mcuBoot: relayValue |= (1 << 1) if pcuReset: relayValue |= (1 << 2) if pcuBoot: relayValue |= (1 << 3) relay.set_value(relayValue) ipcon.disconnect()
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
class sound_activated(modes.standard.abstractMode): _ipcon = None _si = None def __init__(self): ''' Constructor ''' modes.standard.abstractMode.__init__(self) config = ConfigParser.ConfigParser() config.read("config.ini") if config.has_section("Tinkerforge") and config.has_option('Tinkerforge', 'HOST') and config.has_option('Tinkerforge', 'PORT') and config.has_option('Tinkerforge', 'UID'): HOST = config.get('Tinkerforge', 'HOST') PORT = config.getint('Tinkerforge', 'PORT') UID = config.get('Tinkerforge', 'UID') else: print "Can't load Tinkerforge Settings from config.ini" self._ipcon = IPConnection() # Create IP connection self._si = SoundIntensity(UID, self._ipcon) # Create device object self._ipcon.connect(HOST, PORT) # Connect to brickd def __del__(self): self._ipcon.disconnect() def myround(self, x, base=5): return int(base * round(float(x) / base)) def start(self): high = 0.0 count = 0 while True: intensity = self._si.get_intensity() # reset high_level after a Song if count > 100: high = intensity count = 0 if intensity > high: high = intensity else: count += 1 if high > 0: level = self.myround((100 / float(high)) * float(intensity)) else: level = 0 RED = BLUE = GREEN = 0 if level <= 33: BLUE = 100 elif level <= 66: GREEN = 100 else: RED = 100 self.setRGB([RED, GREEN, BLUE]) time.sleep(self._DELAY) def getName(self): return "Sound Activated"
def start_app(): # Create Tinkerforge instances ip_con = IPConnection() ip_con.set_timeout(10) ip_con.connect('localhost', 4223) controller.BrickletHandler.monitor_ip_connection(ip_con=ip_con) bricklet_factory = controller.BrickletFactory() quad_relay_1 = bricklet_factory. \ create_and_configure_bricklet('quad_relay', 'BC8', ip_con) quad_relay_2 = bricklet_factory. \ create_and_configure_bricklet('quad_relay', 'BCE', ip_con) rs232 = bricklet_factory. \ create_and_configure_bricklet('rs232', 'Cvu', ip_con) analog_in = bricklet_factory. \ create_and_configure_bricklet('analog_in', 'CNA', ip_con) # controller Setup channel = controller.ChannelController(quad_relay_1, quad_relay_2) co2flow = controller.Co2FlowController(rs232) airflow = controller.AirFlowController(analog_in) sensor = controller.SensorController(analog_in) concentration = controller.ConcentrationController(sensor, airflow, co2flow) sequence = controller.SequenceController(concentration, channel) # logging data_logger = data.DataLogger() log_dir = 'log' if not os.path.exists(log_dir): os.mkdir(log_dir) prefix = time.strftime('%y%m%d_%H%M%S') data_file_path = os.path.join(log_dir, f'{prefix}_data.csv') log_file_path = os.path.join(log_dir, f'{prefix}_log.txt') logger.set_log_file(log_file_path) data_logger.set_file(data_file_path) # main components main_controller = controller.MainController( channel_controller=channel, co2_flow_controller=co2flow, air_flow_controller=airflow, sensor_controller=sensor, concentration_controller=concentration, sequence_controller=sequence, data_logger=data_logger ) gui = tk_gui.MainFrame() main_controller.set_gui(gui) # Start app main_controller.initialize() gui.mainloop() # Wrap up main_controller.set_co2_flow(flow_rate=0) main_controller.set_channel(data.Channels.NONE) ip_con.disconnect()
def relay_flash(baudrate, tty, firmware, uid_iqr, uid_master): ipcon = IPConnection() iqr = BrickletIndustrialQuadRelay(uid_iqr, ipcon) master = BrickMaster(uid_master, ipcon) ipcon.connect('localhost', 4223) # reset_usb() # time.sleep(1) i = 10 while True: if i == 10: master.get_chibi_error_log() iqr.set_value(MASK_DATA) time.sleep(0.2) iqr.set_value(MASK_POWER | MASK_DATA) i = 0 i += 1 try: time.sleep(0.01) xmc_flash(baudrate, tty, firmware) break except Exception as e: print(str(e)) iqr.set_value(MASK_POWER) master.reset() ipcon.disconnect()
class RedBrickResource: def connect(self, uid, host, port): self.ipcon = IPConnection() self.ipcon.connect(host, port) self.rb = BrickRED(uid, self.ipcon) def disconnect(self): self.ipcon.disconnect()
class CheckTFTemperature(object): def __init__(self, host='localhost', port=4223): self.host = host self.port = port self.ipcon = IPConnection() def connect(self, type, uid): self.ipcon.connect(self.host, self.port) self.connected_type = type if self.connected_type == TYPE_PTC: ptc = PTC(uid, self.ipcon) self.func = ptc.get_temperature elif self.connected_type == TYPE_TEMPERATURE: temperature = Temperature(uid, self.ipcon) self.func = temperature.get_temperature def disconnect(self): self.ipcon.disconnect() def read_temperature(self): return self.func()/100.0 def read(self, warning, critical, mode='none', warning2=0, critical2=0): temp = self.read_temperature() if mode == 'none': print "temperature %s °C" % temp else: if mode == 'low': warning2 = warning critical2 = critical if temp >= critical and (mode == 'high' or mode == 'range'): print "CRITICAL : temperature too high %s °C" % temp return CRITICAL elif temp >= warning and (mode == 'high' or mode == 'range'): print "WARNING : temperature is high %s °C" % temp return WARNING elif temp <= critical2 and (mode == 'low' or mode == 'range'): print "CRITICAL : temperature too low %s °C" % temp return CRITICAL elif temp <= warning2 and (mode == 'low' or mode == 'range'): print "WARNING : temperature is low %s °C" % temp return WARNING elif (temp < warning and mode == 'high') or \ (temp > warning2 and mode == 'low') or \ (temp < warning and temp > warning2 and mode == 'range'): print "OK : %s°C " % temp return OK else: print "UNKNOWN : can't read temperature" return UNKNOWN
def index(): ipcon = IPConnection() # Create IP connection t = Temperature(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected # Get current temperature (unit is °C/100) temperature = t.get_temperature()/100.0 ipcon.disconnect() return PAGE.format(temperature)
def lies_temp(host, port, uid): temp = None try: ipcon = IPConnection() b = BrickletTemperature(uid, ipcon) ipcon.connect(host, port) temp = b.get_temperature() / 100.0 ipcon.disconnect() except: print("Temperaturabfrage fehlgeschlagen") return temp
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 read_data(fake=None): """ Reads data from all weather sensors and returns it as Dictionary. In case of an error or outlier None is returned""" if fake: return weather_data try: ipcon = IPConnection() temp_bricklet = Temperature('qnk', ipcon) humidity_bricklet = Humidity('nLC', ipcon) barometer_bricklet = Barometer('k5g', ipcon) ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port'])) temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW) temp = temp_bricklet.get_temperature() / 100.0 if 45 < temp < -30: weather_data['temperature'] = None logger.warn( 'Got temperature value of %s Grade which is out of range' % temp) else: weather_data['temperature'] = temp humidity = humidity_bricklet.get_humidity() / 10.0 if humidity < 5: weather_data['humidity'] = None logger.warn('Got humidity value of %s RH which is out of range' % humidity) else: weather_data['humidity'] = humidity pressure = barometer_bricklet.get_air_pressure() / 1000.0 if 1080 < pressure < 930: weather_data['pressure'] = None logger.warn('Got pressure value of %s mbar which is out of range' % pressure) else: weather_data['pressure'] = pressure ipcon.disconnect() return weather_data except Exception as e: logger.error('Cloud not connect to weather sensors: %s' % str(e)) return
def 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 CheckIPConnection(self): Domoticz.Debug("CheckIPConnection - " + Parameters["Address"] + ":" + str(int(Parameters["Port"]))) self.isError = 0 try: # Create IP connection > connect to the brickd > disconnect ipcon = IPConnection() ipcon.connect(Parameters["Address"], int(Parameters["Port"])) ipcon.disconnect() Domoticz.Debug("IPConnection: OK") return 1 except: # Error Devices[UNITTEXTSTATUS].Update( nValue=0, sValue="[ERROR] Can not connect to the Master Brick.") Domoticz.Log(Devices[UNITTEXTSTATUS].sValue) self.isError = 1 return 0
def lies_temp(host, port, uid): temp = None try: ipcon = IPConnection() b = BrickletBarometer(uid, ipcon) ipcon.connect(host, port) tt = 0.0 for i in range(10): tt = tt + b.get_chip_temperature() ipcon.disconnect() except: print("Temperaturabfrage fehlgeschlagen") temp = tt / 1000.0 return temp
def __init__(self): rospy.init_node('imu_brick_v2') prctl.set_name("imu_brick_v2") self.pub_imu = rospy.Publisher("imu", Imu, queue_size=16) host = rospy.get_param('~host', 'localhost') port = rospy.get_param('~port', 4223) uid = rospy.get_param('~uid') ipcon = IPConnection() # Create IP connection imu = BrickIMUV2(uid, ipcon) # Create device object ipcon.connect(host, port) # Connect to brickd imu.leds_off() #imu.disable_status_led() imu.register_callback(imu.CALLBACK_ALL_DATA, self.cb_all_data) imu.set_all_data_period(20) # ms rospy.spin() ipcon.disconnect()
def get_airpressure(id): cfg = configparser.ConfigParser() cfg.read(cfg_filename) # open config file to read from if cfg.has_section("Barometer") == True: port = cfg.getint('Connection', 'Port') # get port entry from config file host = cfg.get('Connection', 'Host') # get host entry from config file uid = cfg.get('Barometer', 'bricklet_uid') # uid port entry from config file ipcon = IPConnection() # Create IP connection ipcon.connect(host, port) # Connect to brickd b = Barometer(uid, ipcon) # Create device object air_pressure = b.get_air_pressure()/1000.0 # Get current air pressure (unit is mbar/1000) altitude = b.get_altitude()/100.0 db = sqlite3.connect(local_db) # build connection to local database c = db.cursor() # create cursor c.execute(wd_table) # create weatherdata table c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,air_pressure,'air_pressure',id,'barometer',)) # insert the uid, device name the id from the date table an die humdity value into the weather table c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,altitude,'altitude',id,'barometer',)) db.commit() # save creates and inserts permanent ipcon.disconnect() return({"air_pressure": air_pressure, "altitude": altitude})
class IMU: """ The IMU Brick by TinkerForge. \n This unit will automatically configure itself to the IMU located in boat Anna. """ def __init__(self, debug = False): self.HOST = "localhost" self.PORT = 4223 self.UID = "62Bous" self.REFRESH_TIME = 50 self.debug = debug self.ipcon = IPConnection() self.imu = BrickIMUV2(self.UID, self.ipcon) def get_all_data(self): """ This will return all data collected by the IMU """ data = self.imu.get_all_data() return data def connect(self): """ Calling this function will connect the client with the IMU brick. """ try: self.ipcon.connect(self.HOST, self.PORT) except Exception: print("Can't connect to the IMU brick") return False # Refresh the timer of the Callback to REFRESH_TIME self.imu.set_all_data_period(self.REFRESH_TIME) return True def disconnect(self): """ Disconnect from IMU brick """ self.ipcon.disconnect()
def discover(): HOST = "localhost" PORT = 4223 global ipcon ipcon = IPConnection() ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, cb_connected) ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate) try: ipcon.connect(HOST, PORT) w = threading.Thread(target=wait) w.start() w.join() print("baromenter id: " + str(barometerid)) print("humidity id: " + str(humidityid)) print("ambient id: " + str(ambientid)) print("lcd id: " + str(lcdid)) ipcon.disconnect() except socket.error, e: global discovery_timed_out discovery_timed_out = True print("Error: ipconnection failed " + str(e))
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 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 get_humidity(id): cfg = configparser.ConfigParser() cfg.read(cfg_filename) # open config file to read from port = cfg.getint('Connection', 'Port') # get port entry from config file host = cfg.get('Connection', 'Host') # get host entry from config file uid = cfg.get('Humidity', 'bricklet_uid') # uid port entry from config file ipcon = IPConnection() # Create IP connection ipcon.connect(host, port) # Connect to brickd h = Humidity(uid, ipcon) # Create device object rh = h.get_humidity()/10.0 # Get current humidity (unit is %RH/10) db = sqlite3.connect(local_db) # build connection to local database c = db.cursor() # create cursor c.execute(wd_table) # create weatherdata table c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,rh,'rel. humidity', id,'humidity',)) # insert the uid, device name the id from the date table an die humdity value into the weather table db.commit() # save creates and inserts permanent print() print('Relative Humidity: ' + str(rh) + ' %RH') print() ipcon.disconnect() return(rh)
def 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 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 read_data(): try: ipcon = IPConnection() temp_bricklet = Temperature('qnk', ipcon) humidity_bricklet = Humidity('nLC', ipcon) barometer_bricklet = Barometer('k5g', ipcon) ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port'])) temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW) temp = temp_bricklet.get_temperature() / 100.0 if 45 < temp < -30: weather_data['temperature'] = None logger.warn('Got temperature value of %s Grade which is out of range' % temp) else: weather_data['temperature'] = temp humidity = humidity_bricklet.get_humidity() / 10.0 if humidity < 5: weather_data['humidity'] = None logger.warn('Got humidity value of %s RH which is out of range' % humidity) else: weather_data['humidity'] = humidity pressure = barometer_bricklet.get_air_pressure() / 1000.0 if 1090 < pressure < 920: weather_data['pressure'] = None logger.warn('Got pressure value of %s mbar which is out of range' % pressure) else: weather_data['pressure'] = pressure ipcon.disconnect() return weather_data except Exception as e: logger.error('Cloud not connect to weather sensors: %s' % str(e)) return
class Sensors(object): """Docstring for MyClass. """ def __init__(self): self.HOST = "192.168.178.3" self.PORT = 4223 self.TEMP_UID = "tfj" self.SOUND_UID = "voE" self.LIGHT_UID = "xpa" self.ipcon = IPConnection() def get_temperature(self): try: t = BrickletTemperature(self.TEMP_UID, self.ipcon) self.ipcon.connect(self.HOST, self.PORT) temperature = t.get_temperature() self.ipcon.disconnect() return float(temperature / 100.0) except: return None def get_light(self): try: uvl = BrickletUVLight(self.LIGHT_UID, self.ipcon) self.ipcon.connect(self.HOST, self.PORT) self.ipcon.disconnect() return float(uv_light) except: return None def get_sound(self): try: si = BrickletSoundIntensity(self.SOUND_UID, self.ipcon) self.ipcon.connect(self.HOST, self.PORT) intensity = si.get_intensity() self.ipcon.disconnect() return float(intensity) except: return None
class GPSTimeToLinuxTime: def __init__(self): # Create IP connection self.ipcon = IPConnection() # Connect to brickd self.ipcon.connect(HOST, PORT) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.enumerate() self.enumerate_handshake = Semaphore(0) self.gps_uid = None self.gps_class = None self.gps_has_fix_function = None self.gps_datetime = None self.gps_has_fix = None self.timer = None # go trough the functions to update date and time def __enter__(self): if self.is_ntp_present(): return -1, None if not self.get_gps_uid(): return -2, None if not self.get_gps_time(): return -3, None if not self.gps_has_fix: return 2, None if self.are_times_equal(): return 1, self.gps_time if not self.set_linux_time(): return -5, None return 0, self.gps_datetime def __exit__(self, type, value, traceback): try: self.timer.cancel() except: pass try: self.ipcon.disconnect() except: pass def is_ntp_present(self): # FIXME: Find out if we have internet access and ntp is working, in # that case we don't need to use the GPS time. return False def get_gps_uid(self): try: # Release semaphore after 1 second (if no GPS Bricklet is found) self.timer = Timer(1, self.enumerate_handshake.release) self.timer.start() self.enumerate_handshake.acquire() except: return False return True def get_gps_time(self): if self.gps_uid == None: return False try: self.gps = BrickletGPSV2(self.gps_uid, self.ipcon) self.gps_has_fix = self.gps_has_fix_function(self.gps) if not self.gps_has_fix: return True gps_date, gps_time = self.gps.get_date_time() gps_year = 2000 + (gps_date % 100) gps_date //= 100 gps_month = gps_date % 100 gps_date //= 100 gps_day = gps_date gps_microsecond = 1000 * (gps_time % 1000) gps_time //= 1000 gps_second = gps_time % 100 gps_time //= 100 gps_minute = gps_time % 100 gps_time //= 100 gps_hour = gps_time self.gps_datetime = datetime(gps_year, gps_month, gps_day, gps_hour, gps_minute, gps_second, gps_microsecond, tzinfo=timezone.utc) except: return False return True def are_times_equal(self): return False # Are we more than 1 seconds off? return abs((self.gps_datetime - self.local_datetime) / timedelta(seconds=1)) < 1 def set_linux_time(self): if self.gps_datetime == None: return False try: # Set date as root timestamp = int( (self.gps_datetime - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1) * 1000000000) command = [ '/usr/bin/sudo', '-S', '-p', '', '/bin/date', '+%s.%N', '-u', '-s', '@{0}.{1:09}'.format(timestamp // 1000000000, timestamp % 1000000000) ] subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE).communicate(SUDO_PASSWORD) except: return False return True def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): # If more then one GPS Bricklet is connected we will use the first one that we find if device_identifier == BrickletGPS.DEVICE_IDENTIFIER: self.gps_uid = uid self.gps_class = BrickletGPS self.gps_has_fix_function = lambda gps: gps.get_status( ).fix != gps.FIX_NO_FIX self.enumerate_handshake.release() elif device_identifier == BrickletGPSV2.DEVICE_IDENTIFIER: self.gps_uid = uid self.gps_class = BrickletGPSV2 self.gps_has_fix_function = lambda gps: gps.get_status().has_fix self.enumerate_handshake.release()
class TinkerforgeController: def __init__(self, host, port): print("hello - connecting to %s %s" % (host, port)) # Create connection and connect to brickd self.ipcon = IPConnection() self.ipcon.connect(host, port) print("connected") self.devices = {} # Register Enumerate Callback self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, EnumerateCallback(self)) # Trigger Enumerate self.ipcon.enumerate() def run(self): while True: try: time.sleep(1) self.next() except KeyboardInterrupt: self.stop() print("goodbye") break def next(self): print("tick") def __getattr__(self, name): if name in self.devices: return self.devices[name] else: return None def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): device_class = device_factory.get_device_class(device_identifier) device = device_class(uid, self.ipcon) device_name = device_class.DEVICE_URL_PART counter = 2 while device_name in self.devices: if device.uid == self.devices[device_name].uid: return device_name = "%s_%s" % (device_name, counter) counter += 1 print("found %s" % device_name) self.devices[device_name] = device # print("UID: " + uid) # print("Enumeration Type: " + str(enumeration_type)) # # if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED: # print("") # return # # 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("") def stop(self): self.ipcon.disconnect() print("\ndisconnected")
class WeatherStation(QApplication): HOST = "localhost" PORT = 4223 ipcon = None lcd = None al = None hum = None baro = None projects = [] active_project = None error_msg = None def __init__(self, args): super(QApplication, self).__init__(args) self.error_msg = QErrorMessage() self.ipcon = IPConnection() signal.signal(signal.SIGINT, self.exit_demo) signal.signal(signal.SIGTERM, self.exit_demo) timer = QTimer(self) timer.setSingleShot(True) timer.timeout.connect(self.connect) timer.start(1) def exit_demo(self, signl=None, frme=None): try: self.ipcon.disconnect() self.timer.stop() self.tabs.destroy() except: pass sys.exit() def open_gui(self): self.main = MainWindow(self) self.main.setFixedSize(730, 430) self.main.setWindowIcon(QIcon(os.path.join(ProgramPath.program_path(), "demo-icon.png"))) self.tabs = QTabWidget() widget = QWidget() layout = QVBoxLayout() layout.addWidget(self.tabs) widget.setLayout(layout) self.main.setCentralWidget(widget) self.projects.append(ProjectEnvDisplay(self.tabs, self)) self.projects.append(ProjectStatistics(self.tabs, self)) self.projects.append(ProjectXively(self.tabs, self)) self.tabs.addTab(self.projects[0], "Display Environment Measurements") self.tabs.addTab(self.projects[1], "Show Statistics with Button Control") self.tabs.addTab(self.projects[2], "Connect to Xively") self.active_project = self.projects[0] self.tabs.currentChanged.connect(self.tabChangedSlot) self.main.setWindowTitle("Starter Kit: Weather Station Demo " + config.DEMO_VERSION) self.main.show() def connect(self): try: self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT) except Error as e: self.error_msg.showMessage('Connection Error: ' + str(e.description) + "\nBrickd installed and running?") return except socket.error as e: self.error_msg.showMessage('Socket error: ' + str(e) + "\nBrickd installed and running?") return self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) try: self.ipcon.enumerate() except Error as e: self.error_msg.showMessage('Enumerate Error: ' + str(e.description)) return self.open_gui() def tabChangedSlot(self, tabIndex): if self.lcd is not None: self.lcd.clear_display() self.active_project = self.projects[tabIndex] def cb_illuminance(self, illuminance): for p in self.projects: p.update_illuminance(illuminance) def cb_humidity(self, humidity): for p in self.projects: p.update_humidity(humidity) def cb_air_pressure(self, air_pressure): for p in self.projects: p.update_air_pressure(air_pressure) try: temperature = self.baro.get_chip_temperature() except Error as e: print('Could not get temperature: ' + str(e.description)) return for p in self.projects: p.update_temperature(temperature) def configure_custom_chars(self): c = [[0x00 for x in range(8)] for y in range(8)] c[0] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff] c[1] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff] c[2] = [0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff] c[3] = [0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff] c[4] = [0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff] c[5] = [0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] c[6] = [0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] c[7] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] for i in range(len(c)): self.lcd.set_custom_character(i, c[i]); def cb_button_pressed(self, button): for p in self.projects: p.button_pressed(button) def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \ enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE: if device_identifier == LCD20x4.DEVICE_IDENTIFIER: try: self.lcd = LCD20x4(uid, self.ipcon) self.lcd.clear_display() self.lcd.backlight_on() self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.cb_button_pressed) self.configure_custom_chars() except Error as e: self.error_msg.showMessage('LCD 20x4 init failed: ' + str(e.description)) self.lcd = None elif device_identifier == AmbientLight.DEVICE_IDENTIFIER: try: self.al = AmbientLight(uid, self.ipcon) self.al.set_illuminance_callback_period(1000) self.al.register_callback(self.al.CALLBACK_ILLUMINANCE, self.cb_illuminance) except Error as e: self.error_msg.showMessage('Ambient Light init failed: ' + str(e.description)) self.al = None elif device_identifier == Humidity.DEVICE_IDENTIFIER: try: self.hum = Humidity(uid, self.ipcon) self.hum.set_humidity_callback_period(1000) self.hum.register_callback(self.hum.CALLBACK_HUMIDITY, self.cb_humidity) except Error as e: self.error_msg.showMessage('Humidity init failed: ' + str(e.description)) self.hum = None elif device_identifier == Barometer.DEVICE_IDENTIFIER: try: self.baro = Barometer(uid, self.ipcon) self.baro.set_air_pressure_callback_period(1000) self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE, self.cb_air_pressure) except Error as e: self.error_msg.showMessage('Barometer init failed: ' + str(e.description)) self.baro = None def cb_connected(self, connected_reason): if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT: while True: try: self.ipcon.enumerate() break except Error as e: self.error_msg.showMessage('Enumerate Error: ' + str(e.description)) time.sleep(1)
class CheckTFTemperature(object): def __init__(self, host='localhost', port=4223): self.host = host self.port = port self.ipcon = IPConnection() self.name = 'unknown' self.unit = 'unknown' def connect(self, type, uid): self.ipcon.connect(self.host, self.port) self.connected_type = type if self.connected_type == TYPE_PTC: ptc = PTC(uid, self.ipcon) self.func = ptc.get_temperature self.name = 'temperature' self.unit = '°C' elif self.connected_type == TYPE_TEMPERATURE: temperature = Temperature(uid, self.ipcon) self.func = temperature.get_temperature self.name = 'temperature' self.unit = '°C' elif self.connected_type == TYPE_HUMIDITY: humidity = Humidity(uid, self.ipcon) self.func = humidity.get_humidity self.name = 'humidity' self.unit = '%RH' elif self.connected_type == TYPE_MOTION_DETECTOR: md = MotionDetector(uid, self.ipcon) self.func = md.get_motion_detected elif self.connected_type == TYPE_SEGMENT_DISPLAY_4X7: display = SegmentDisplay4x7(uid, self.ipcon) self.func = display.set_segments def disconnect(self): self.ipcon.disconnect() def error(self, e): if e == "true": self.func((0, 80, 80, 121), 8, False) else: self.func((0, 0, 0, 0), 8, False) def read_sensor(self): if self.connected_type == TYPE_HUMIDITY: return self.func()/10.0 elif self.connected_type == TYPE_MOTION_DETECTOR: return self.func() else: # Temperature, PTC return self.func()/100.0 def read(self, warning, critical, mode='none', warning2=0, critical2=0): val = self.read_sensor() if self.connected_type == TYPE_MOTION_DETECTOR: if val == 1: print "motion detected" return MOTION_DETECTED else: print "no motion detected" return NO_MOTION_DETECTED else: if mode == 'none': print "%s %s %s" % (self.name, val, self.unit) else: if mode == 'low': warning2 = warning critical2 = critical if val >= critical and (mode == 'high' or mode == 'range'): print "CRITICAL : %s too high %s %s" % (self.name, val, self.unit) return CRITICAL elif val >= warning and (mode == 'high' or mode == 'range'): print "WARNING : %s is high %s %s" % (self.name, val, self.unit) return WARNING elif val <= critical2 and (mode == 'low' or mode == 'range'): print "CRITICAL : %s too low %s %s" % (self.name, val, self.unit) return CRITICAL elif val <= warning2 and (mode == 'low' or mode == 'range'): print "WARNING : %s is low %s %s" % (self.name, val, self.unit) return WARNING elif (val < warning and mode == 'high') or \ (val > warning2 and mode == 'low') or \ (val < warning and val > warning2 and mode == 'range'): print "OK : %s %s" % (val, self.unit) return OK else: print "UNKNOWN : can't read %s" % self.name return UNKNOWN
class PiTinkerforgeStack: host = '192.168.178.27' #raspi #host = '127.0.0.1' #localhost port = 4223 uid_master = '6JKxCC' uid_motion = 'oRL' uid_poti_left = 'ejC' uid_poti_right = 'ejm' uid_io = 'hcs' female = False def __init__(self): self.con = IPConnection() self.master = Master(self.uid_master, self.con) self.motion = MotionDetector(self.uid_motion, self.con) self.poti_left = RotaryPoti(self.uid_poti_left, self.con) self.poti_right = RotaryPoti(self.uid_poti_right, self.con) self.io = IO4(self.uid_io, self.con) print "---" + str(15^15) print "---" + str(15^14) def connect(self): print "Connecting to host " + self.host + " on port " + str(self.port) self.con.connect(self.host, self.port) self.set_ziel_geschlecht(self.io.get_value()) def disconnect(self): print "Disconnecting from host " + self.host self.con.disconnect() def motion_detected(self): print "CALLBACK!!" self.insult() def insult(self): ziel_geschlecht = "m" if self.female: ziel_geschlecht = "f" speak_next_insult(ziel_geschlecht, self.poti_left.get_position(), self.poti_right.get_position()) def motion_cycle_ended(self): print "READY for motion detection!" def io_switch(self, interrupt_mask, value_mask): print "IO4 triggered" print('Interrupt by: ' + str(bin(interrupt_mask))) print('Value: ' + str(bin(value_mask))) #print('Val1: ' + str(value_mask)) if interrupt_mask == 1: print "Sex switched..." # button 1 switched self.set_ziel_geschlecht(value_mask) elif interrupt_mask == 2: print "Insult button pressed..." button_up = value_mask&2 print "value_mask =" + str(button_up) if button_up == 2: self.insult() print "io_switch() end" def set_ziel_geschlecht(self, value_mask): is_on = value_mask^14 if is_on: print "MALE" self.female = False else: print "FEMALE" self.female = True def register_callbacks(self): print "Registering callback to motion detector..." #self.motion.register_callback(self.motion.CALLBACK_MOTION_DETECTED, self.motion_detected) self.motion.register_callback(self.motion.CALLBACK_DETECTION_CYCLE_ENDED, self.motion_cycle_ended) self.io.set_debounce_period(1000) self.io.register_callback(self.io.CALLBACK_INTERRUPT, self.io_switch) # Enable interrupt on pin 0 self.io.set_interrupt((1 << 0) | (1 << 1)) #self.io.set_interrupt(1 << 1) print "register done"
class GPSTimeToLinuxTime: def __init__(self): # Create IP connection self.ipcon = IPConnection() # Connect to brickd self.ipcon.connect(HOST, PORT) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.enumerate() self.enum_sema = Semaphore(0) self.gps_uid = None self.gps_time = None self.timer = None # go trough the functions to update date and time def __enter__(self): if self.is_ntp_present(): return -1, None if not self.get_gps_uid(): return -2, None if not self.get_gps_time(): return -3, None if self.are_times_equal(): return 1, self.gps_time if self.is_time_crazy(): return -4, None if not self.set_linux_time(): return -5, None return 0, self.gps_time def __exit__(self, type, value, traceback): try: self.timer.cancel() except: pass try: self.ipcon.disconnect() except: pass def is_ntp_present(self): # FIXME: Find out if we have internet access and ntp is working, in # that case we don't need to use the GPS time. return False def get_gps_uid(self): try: # Release semaphore after 1 second (if no GPS Bricklet is found) self.timer = Timer(1, self.enum_sema.release) self.timer.start() self.enum_sema.acquire() except: return False return True def get_gps_time(self): if self.gps_uid == None: return False try: # Create GPS device object self.gps = BrickletGPS(self.gps_uid, self.ipcon) date, time = self.gps.get_date_time() yy = date % 100 yy += 2000 date //= 100 mm = date % 100 date //= 100 dd = date time //= 1000 ss = time % 100 time //= 100 mins = time % 100 time //= 100 hh = time self.gps_time = datetime.datetime(yy, mm, dd, hh, mins, ss) except: return False return True def are_times_equal(self): # Are we more then 3 seconds off? if abs(int(self.gps_time.strftime("%s")) - time.time()) > 3: return False return True def is_time_crazy(self): try: return self.gps_time.year < 2014 except: return True def set_linux_time(self): if self.gps_time == None: return False try: # Set date as root timestamp = (self.gps_time - datetime.datetime(1970, 1, 1)) / datetime.timedelta(seconds=1) command = ['/usr/bin/sudo', '-S'] command.extend('/bin/date +%s -u -s @{0}'.format(timestamp).split(' ')) Popen(command, stdout=PIPE, stdin=PIPE).communicate(SUDO_PASSWORD) except: return False return True def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): # If more then one GPS Bricklet is connected we will use the first one that we find if device_identifier == BrickletGPS.DEVICE_IDENTIFIER: self.gps_uid = uid self.enum_sema.release()
class GuiControl(): def __init__(self): self._name = "[GuiControl]" # ipcon self._ipcon = None self._HOST = "localhost" self._PORT = 4223 #DualButton States self._db = None self._DB_UID = "mAo" self.recognition_running = True self.recognition_state = False #TODO bad idea? self.recognition_progress = False # NFC/RFID self._nfc = None self._NFC_UID = "oDg" self._nfc_cb_to_profiler = None self._nfc_write_mode = False self._nfc_write_name = None def start_ipcon(self): if self._ipcon != None: EventLogger.warning(self.name + " tried to start IPCON, but IPCON was already started!") return self._ipcon = IPConnection() # Init Components self._db = DualButton(self._DB_UID, self._ipcon) self._nfc = NFCRFID(self._NFC_UID, self._ipcon) try: self._ipcon.connect(self._HOST, self._PORT) except Exception as e: EventLogger.critical("A critical error occur: " + str(e)) raise Exception("A critical error occur: " + str(e)) #Init Callbacks self._db.register_callback(DualButton.CALLBACK_STATE_CHANGED, self.__cb_db_state_changed) self._nfc.register_callback(self._nfc.CALLBACK_STATE_CHANGED, lambda x, y: self.__cb_nfc_state_changed(x, y, self._nfc)) def stop_ipcon(self): if self._ipcon == None: EventLogger.warning(self.name + " tried to disconnect IPCON, but IPCON was not connected!") return self._ipcon.disconnect() self._ipcon = None # DualButton Functions def __cb_db_state_changed(self, button_l, button_r, led_r, led_l): #Button Right = Programm Control => True = Program Quit if button_r == DualButton.BUTTON_STATE_PRESSED: led_r = DualButton.LED_STATE_OFF self._db.set_selected_led_state(DualButton.LED_RIGHT, led_r) # exit program self.recognition_running = False if not self.recognition_progress: if button_l == DualButton.BUTTON_STATE_PRESSED: led_l = DualButton.LED_STATE_ON self._db.set_selected_led_state(DualButton.LED_LEFT, led_l) self.recognition_state = True else: led_l = DualButton.LED_STATE_OFF self._db.set_selected_led_state(DualButton.LED_LEFT, led_l) self.recognition_state = False def _db_start_state(self): self._db.set_selected_led_state(DualButton.LED_LEFT, DualButton.LED_STATE_OFF) self._db.set_selected_led_state(DualButton.LED_RIGHT, DualButton.LED_STATE_ON) def _db_end_state(self): self._db.set_selected_led_state(DualButton.LED_LEFT, DualButton.LED_STATE_OFF) self._db.set_selected_led_state(DualButton.LED_RIGHT, DualButton.LED_STATE_OFF) def _db_recognizer_state_off(self): self._db.set_selected_led_state(DualButton.LED_LEFT, DualButton.LED_STATE_OFF) self.recognition_state = False self.recognition_progress = False def __cb_nfc_state_changed(self, state, idle, nr): name = "NO NAME" if state == nr.STATE_REQUEST_TAG_ID_READY: EventLogger.debug('Tag found') # Write 16 byte to pages 5-8 if self._nfc_write_mode: data_write = Utils.string_to_byte_array(self._nfc_write_name) nr.write_page(5, data_write) EventLogger.debug('Writing data...') else: nr.request_page(5) EventLogger.debug('Requesting data...2') elif state == nr.STATE_WRITE_PAGE_READY: # only when writing before! # Request pages 5-8 nr.request_page(5) EventLogger.debug('Requesting data...') elif state == nr.STATE_REQUEST_PAGE_READY: # Get and print pages data = nr.get_page() name = str(Utils.byte_array_to_string(data)) EventLogger.debug('Read data:' + name) if self._nfc_cb_to_profiler != None: self._nfc_cb_to_profiler(name) elif state & (1 << 6): # All errors have bit 6 set if state == self._nfc.STATE_REQUEST_TAG_ID_ERROR: EventLogger.info( 'No NFC/RFID Tag found! TODO: Message - Token @ Lesegereat -> Button') # TODO: Message - Token @ Lesegeraet -> Button else: EventLogger.debug('Error: ' + str(state)) # TODO check for errors in coding! #EventLogger.error(self._name + "_nfc_cb_to_profiler was None! DEBUG ONLY!") def _debug_print(self): print "self.recognition_running = " + str(self.recognition_running) + "\nself.recognition_state = " + str( self.recognition_state) + "\nself.recognition_progress = " + str(self.recognition_progress) + "\n"
class RSBController(object): def __init__(self): self.__ipcon = IPConnection() # Create IP connection self.__rs = BrickletRemoteSwitch(CONFIG.uid, self.__ipcon) # Create device object self.__ipcon.connect(CONFIG.host, CONFIG.port) # Connect to brickd self.__operations = deque() self.__operations_worker = Thread(target=self.__work_operations) self.__keep_worker_running = True self.__operations_worker.start() self.__mqtt = None LOG.info("RSBController running") # noinspection PyAttributeOutsideInit def inject_mqtt_processor(self, mqtt): """ Add an mqtt processor that may be used for message publishing. :param mqtt: the mqtt processor """ self.__mqtt = mqtt def add_socket_switch_operation_to_queue(self, address, unit, state): """ Add a switch operation for the given socket to the RSBController. :param address: the address of the socket :param unit: the unit of the socket :param state: 0 (off) or 1 (on) """ self.__operations.append([int(address), int(unit), int(state)]) def shutdown(self): LOG.info("RSBController stopping") self.__keep_worker_running = False while self.__operations_worker.isAlive(): LOG.debug("Waiting for operations worker to stop") time.sleep(1) self.__ipcon.disconnect() LOG.info("RSBController shutdown") def __work_operations(self): LOG.info("Operations worker running") while self.__keep_worker_running: if self.__operation_open(): operation = self.__dequeueOperation() # valid assumptions, as operations can only be added through 'RSBController.add_socket_switch_operation_to_queue' self.__switch_socket_B(operation[0], operation[1], operation[2]) time.sleep(0.01) def __operation_open(self): if self.__operations: return True return False def __dequeueOperation(self): return self.__operations.popleft() def __switch_socket_B(self, address, unit, state): """ Switch socket of type B :param address: the address of the socket :param unit: the unit of the socket :param state: 0 (off) or 1 (on) """ try: if state == 0: LOG.debug("Switching {0}-{1} to off".format(address, unit)) elif state == 1: LOG.debug("Switching {0}-{1} to on".format(address, unit)) else: LOG.warning( "State {0} is no valid switching value".format(state)) tries = 0 while self.__rs.get_switching_state() == 1 and tries < 100: # wait until ready to switch time.sleep(0.01) tries += 1 if tries == 100: LOG.warning( "Sender was not ready to switch again after 100 tries") return self.__rs.switch_socket_b(address, unit, state) self.__mqtt.publish(address, unit, state) except Error as err: LOG.error(err.description)
class RTCTimeToLinuxTime: def __init__(self): # Create IP connection self.ipcon = IPConnection() # Connect to brickd self.ipcon.connect(HOST, PORT) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.enumerate() self.enum_sema = Semaphore(0) self.rtc_uid = None self.rtc_device_identifier = None self.rtc = None self.rtc_time = None self.timer = None # go trough the functions to update date and time def __enter__(self): if self.is_ntp_present(): return -1, None if not self.get_rtc_uid(): return -2, None if not self.get_rtc_time(): return -3, None if self.are_times_equal(): return 1, self.rtc_time if not self.set_linux_time(): return -4, None return 0, self.rtc_time def __exit__(self, type, value, traceback): try: self.timer.cancel() except: pass try: self.ipcon.disconnect() except: pass def is_ntp_present(self): # FIXME: Find out if we have internet access and ntp is working, in # that case we don't need to use the RTC time. return False def get_rtc_uid(self): try: # Release semaphore after 1 second (if no Real-Time Clock Bricklet is found) self.timer = Timer(1, self.enum_sema.release) self.timer.start() self.enum_sema.acquire() except: return False return True def get_rtc_time(self): if self.rtc_uid == None: return False try: # Create Real-Time Clock device object if self.rtc_device_identifier == BrickletRealTimeClock.DEVICE_IDENTIFIER: self.rtc = BrickletRealTimeClock(self.rtc_uid, self.ipcon) year, month, day, hour, minute, second, centisecond, _ = self.rtc.get_date_time() else: self.rtc = BrickletRealTimeClockV2(self.rtc_uid, self.ipcon) year, month, day, hour, minute, second, centisecond, _, _ = self.rtc.get_date_time() self.rtc_time = datetime.datetime(year, month, day, hour, minute, second, centisecond * 10000) except: return False return True def are_times_equal(self): # Are we more then 3 seconds off? if abs(int(self.rtc_time.strftime("%s")) - time.time()) > 3: return False return True def set_linux_time(self): if self.rtc_time == None: return False try: # Set date as root command = ['/usr/bin/sudo', '-S', '/bin/date', self.rtc_time.strftime('%m%d%H%M%Y.%S')] Popen(command, stdout=PIPE, stdin=PIPE).communicate(SUDO_PASSWORD) except: return False return True def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): # If more then one Real-Time Clock Bricklet is connected we will use the first one that we find if device_identifier in [BrickletRealTimeClock.DEVICE_IDENTIFIER, BrickletRealTimeClockV2.DEVICE_IDENTIFIER]: self.rtc_uid = uid self.rtc_device_identifier = device_identifier self.enum_sema.release()
class Master(object): def __init__(self, host='localhost', port=4223): self.__ipcon = None self.__host = host self.__port = port self.__inobjectmap = {} self.__nfcinobjectmap = {} self.__io16inobjectmap = {} self.__tagtypes = {} self.__shutingdown = False logging.debug('Tinkerforge Master created.') def shutdown(self): self.__shutingdown = True self.disconnect() def startup(self): self.__ipcon = IPConnection() self.__ipcon.connect(self.__host, self.__port) logging.debug('Connecting TF Master to {}'.format(self.__host)) def disconnect(self): if self.__ipcon is not None: self.__ipcon.disconnect() def __getattr__(self, name): # This is dirty, we have to work around the fact, that the tinkerforge # API can't pass additional information to the callback. # # We would need the UID of the bricklet so that we could figure out, on # which bricklet an which pin what happend. If we have that information # we can workout which inobject to call. # # As we can't pass the UID to the callback we have to pass the UID by # calling a function "callback_uid" As we can't create those functions # in advance, as we don't know the UIDs, we have to use getattr to # figure out the name! As I said, dirty. But all for the simplicity of # the in and out objects! # # Acutall we don't need this I think, we can use a lambda function # to create a new function that will be called. def method(*args): if name.startswith('self.callback_io16_'): uid = name.replace('self.callback_io16_', '') for i in range(0, 16): if (args[0] & (1 << i)): # Pin "i" fired and it went if (args[1] & (1 << i)): state = 'up' else: state = 'down' if uid in self.__inobjectmap: self.__io16inobjectmap[uid].uplink([i, state]) def callback_digin(self, mask, flank, uid): for i in range(0, 4): if (mask & (1 << i)): # Pin "i" fired and it went if (flank & (1 << i)): state = 'up' else: state = 'down' if uid in self.__inobjectmap: self.__inobjectmap[uid].uplink([i, state]) def callback_nfc(self, state, idle, nfc, uid): if not self.__shutingdown: # Cycle through all types if uid in self.__tagtypes: tag_type = self.__tagtypes[uid] if idle: self.__tagtypes[uid] = (tag_type + 1) % 3 nfc.request_tag_id(tag_type) if state == nfc.STATE_REQUEST_TAG_ID_READY: logging.debug('TF Master, NFC Callback called, new ID to read.') ret = nfc.get_tag_id() tagtype = str(ret.tag_type) tagid = ''.join(map( str, map(int, ret.tid[:ret.tid_length]))) if uid in self.__nfcinobjectmap: self.__nfcinobjectmap[uid].uplink([tagtype, tagid]) def connect(self, bricklethandler, uid, io16_layout = None): if type(bricklethandler) == DigIn: self._connectIndustrialDigitalIn(bricklethandler, uid) if type(bricklethandler) == DigOut: logging.debug('Connecting DigOut with UID: {}'.format(uid)) return self._connectIndustrialDigitalOut(uid) if type(bricklethandler) == IdSender: logging.debug('Connecting NFC/IDESENDER with UID: {}'.format(uid)) self._connectNfcBricklet(bricklethandler, uid) if type(bricklethandler) == Io16: return self._connectIo16Bricklet(bricklethandler, uid, io16_layout) def _connectNfcBricklet(self, bricklethandler, uid): nfc = NFCRFID(uid, self.__ipcon) logging.debug('Registering callback fo NFC') nfc.register_callback(nfc.CALLBACK_STATE_CHANGED, lambda x, y: self.callback_nfc(x, y, nfc, uid)) if uid not in self.__nfcinobjectmap: self.__nfcinobjectmap[uid] = {} if uid not in self.__tagtypes: self.__tagtypes[uid] = 0 nfc.request_tag_id(self.__tagtypes[uid]) # We don't have to return anything here, as there is no way # for the bricklethandler to request anything from such a port. self.__nfcinobjectmap[uid] = bricklethandler def _connectIo16Bricklet(self, bricklethandler, uid, io16_layout): # Connecting an Io16 means we have to register interrupts # for all output pins. io16 = IO16(uid, self.__ipcon) io16.register_callback( io16.CALLBACK_INTERRUPT, getattr(self, "self.callback_io16_" + uid)) # Enable for all input pins the interrupt and set the others # to output. for i in range(0, 16): bank = 'a' if i > 7: bank = 'b' if i in io16_layout: if io16_layout[i] == 'out': io16.set_port_configuration(bank, i << 0, IO16.DIRECTION_OUT, False) else: io16.set_port_configuration(bank, i << 0, IO16.DIRECTION_IN, False) io16.set_port_interrupt(bank, i << 2) else: io16.set_port_configuration(bank, i << 0, IO16.DIRECTION_IN, False) io16.set_port_interrupt(bank, i << 2) self.__io16inobjectmap[uid] = bricklethandler return io16 def _connectIndustrialDigitalIn(self, bricklethandler, uid): # Connecting a IndustrialDigitalIn basically means # to register Callbacks for all of it's pins. # This has to be done here not in the In Object # because it can only be done once per connection! idin4 = IndustrialDigitalIn4(uid, self.__ipcon) idin4.register_callback( idin4.CALLBACK_INTERRUPT, lambda x, y: self.callback_digin(x, y, uid)) # Enable interrupt on all 4 pins idin4.set_interrupt(idin4.get_interrupt() | (1 << 0)) idin4.set_interrupt(idin4.get_interrupt() | (1 << 1)) idin4.set_interrupt(idin4.get_interrupt() | (1 << 2)) idin4.set_interrupt(idin4.get_interrupt() | (1 << 3)) # We need to connect the UID to the bricklet object so that we can call # the ports of the bricklet object once we get a callback on the # interrrupt. if uid not in self.__inobjectmap: self.__inobjectmap[uid] = {} self.__inobjectmap[uid] = bricklethandler def _connectIndustrialDigitalOut(self, uid): # Create a DigitialIndustrialOut Object ret = IndustrialDigitalOut4(uid, self.__ipcon) logging.debug ('Return Tinkerforge IndustrialDigitalOut API Object for uid: {}, {}'.format(uid, ret)) return ret
class ClimateSensors: def __init__(self, host, port): self.hum = None self.hum_value = 0.0 self.temp = None self.temp_value = 0.0 self.lcd = None self.port = port self.host = host self.conn = IPConnection() self.conn.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.conn.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) def update_display(self): if self.lcd is not None: self.lcd.write_line(1, 2, 'Temp: {:3.2f} C'.format(self.temp_value)) self.lcd.write_line(2, 2, 'RelHum: {:3.2f} %'.format(self.hum_value)) def connect(self): if self.conn.get_connection_state() == self.conn.CONNECTION_STATE_DISCONNECTED: self.conn.connect(self.host, self.port) self.conn.enumerate() def disconnect(self): if self.conn.get_connection_state() != self.conn.CONNECTION_STATE_DISCONNECTED: if self.lcd is not None: self.lcd.backlight_off() self.lcd.clear_display() self.conn.disconnect() def cb_connected(self, connected_reason): self.conn.enumerate() def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED: # print("DISCONNECTED") return if device_identifier == Temperature.DEVICE_IDENTIFIER: self.temp = Temperature(uid, self.conn) self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, self.cb_temperature) self.update_temperature(self.temp.get_temperature()) self.temp.set_temperature_callback_period(UPDATE_PERIOD) if device_identifier == Humidity.DEVICE_IDENTIFIER: self.hum = Humidity(uid, self.conn) self.hum.register_callback(self.hum.CALLBACK_HUMIDITY, self.cb_humidity) self.update_humidity(self.hum.get_humidity()) self.hum.set_humidity_callback_period(UPDATE_PERIOD) if device_identifier == LCD20x4.DEVICE_IDENTIFIER: self.lcd = LCD20x4(uid, self.conn) self.lcd.backlight_on() def cb_temperature(self, temperature): self.update_temperature(temperature) self.update_display() def update_temperature(self, raw_temperature): self.temp_value = raw_temperature / 100.0 def cb_humidity(self, humidity): self.update_humidity(humidity) self.update_display() def update_humidity(self, raw_humidity): self.hum_value = raw_humidity / 10.0
class LRF: HOST = "localhost" PORT = 4223 PROG_PATH = "/home/pi/SICKRPi-Scanner/" #PROG_PATH = "/home/gus484/Programme/octomap_ibeo/" TIMER_MS = 1.0 def __init__(self): self.db = None self.is_scan = False self.led_l_blink = False self.led_r_blink = False self.run = True self.ipcon = None self.pro = None self.bat_lv = None try: # create ip connection self.ipcon = IPConnection() # register ip connection callbacks self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) self.ipcon.connect(LRF.HOST, LRF.PORT) #self.ipcon.enumerate() except: self.run = False print "no connection to tinkerforge devices!" exit(0) def release(self): if self.ipcon != None: # turn off leds self.db.set_led_state(DualButton.LED_STATE_OFF,DualButton.LED_STATE_OFF) # disconnect self.ipcon.disconnect() print "quit" self.run = False # thread: start laserscan def call_laser(self): # nicht blockierend self.pro = subprocess.Popen(LRF.PROG_PATH+"bin/main", shell=False, preexec_fn=os.setsid) # callback handles device connections and configures possibly lost # configuration of lcd and temperature callbacks, backlight etc. 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: # enumeration is for dual button bricklet if device_identifier == DualButton.DEVICE_IDENTIFIER: if self.db != None: return # create dual button device object self.db = DualButton(uid, self.ipcon) # register button push callback to function cb_state_changed self.db.register_callback(self.db.CALLBACK_STATE_CHANGED, self.cb_state_changed) # set led state self.db.set_led_state(DualButton.LED_STATE_ON, DualButton.LED_STATE_OFF) Timer(LRF.TIMER_MS, self.led_blink).start() # callback handles reconnection of ip connection def cb_connected(self, connected_reason): self.ipcon.enumerate() # callback function for interrupts def cb_state_changed(self, button_l, button_r, led_l, led_r): # check for both interrupts if button_l == DualButton.BUTTON_STATE_PRESSED and button_r == DualButton.BUTTON_STATE_PRESSED: print "stop script" #if self.is_scan: execfile(LRF.PROG_PATH+"quit.py") time.sleep(0.5) try: print "terminate process" #os.killpg(self.pro.pid, signal.SIGTERM) self.pro.terminate() except: print "..." self.run = False # check start interrupt elif button_l == DualButton.BUTTON_STATE_PRESSED: if self.is_scan == False: print "start scan" self.led_l_blink = False self.db.set_selected_led_state(DualButton.LED_RIGHT,DualButton.LED_STATE_ON) self.is_scan = True # start laser thread start_new_thread(self.call_laser,()) # check stop interrupt elif button_r == DualButton.BUTTON_STATE_PRESSED: if self.is_scan: print "stop scan" self.led_l_blink = False self.db.set_selected_led_state(DualButton.LED_RIGHT,DualButton.LED_STATE_OFF) execfile(LRF.PROG_PATH+"quit.py") self.is_scan = False def led_blink(self): if self.db != None and self.run == True: # get led state ls = self.db.get_led_state() if self.led_l_blink: if ls[0] == DualButton.LED_STATE_ON: l = DualButton.LED_STATE_OFF else: l = DualButton.LED_STATE_ON # set led state self.db.set_selected_led_state(DualButton.LED_LEFT,l) if self.led_r_blink: if ls[1] == DualButton.LED_STATE_ON: l = DualButton.LED_STATE_OFF else: l = DualButton.LED_STATE_ON # set led state self.db.set_selected_led_state(DualButton.LED_RIGHT,l) if self.run == True: Timer(LRF.TIMER_MS, self.led_blink).start() def check_battery_level(self): try: #open serial dev s = serial.Serial() s.port = "/dev/ttyAMA0" s.baudrate = 38400 s.timeout = 0.15 s.open() if not s.isOpen(): return s.write("@EPR"+'\r\n') #s.write("@USB"+'\r\n') if s.readable(): msg = s.read(1000) msg = msg.split(":") msg = msg[1].split("V") self.bat_lv = float(msg[0]) print "Voltage:" + str(self.bat_lv) s.close() except: self.bat_lv = None
class PiTinkerforgeStack: #host = '192.168.178.36' #raspi #host = '127.0.0.1' #localhost host = 'brickd' port = 4223 female = False io = None poti_left = None poti_volume = None master = None def __init__(self): syslog.openlog('insultr-tf', 0, syslog.LOG_LOCAL4) self.con = IPConnection() # Register IP Connection callbacks self.con.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.con.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) self.insultr = Insultr() self.set_volume(50) self.log("---" + str(15^15)) self.log("---" + str(15^14)) def log(self, msg): syslog.syslog(msg) print msg def connect(self): self.log("Connecting to host " + self.host + " on port " + str(self.port)) self.con.connect(self.host, self.port) self.con.enumerate() def disconnect(self): self.log("Disconnecting from host " + self.host) self.con.disconnect() # Callback handles device connections and configures possibly lost # configuration of lcd and temperature callbacks, backlight etc. 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: self.log("cb_enumerate() id {} - Found device: ident={}, position={}".format(uid, device_identifier, position)) if device_identifier == IO4.DEVICE_IDENTIFIER: self.log("cb_enumerate() id {} - Creating IO4 device object".format(uid)) self.io = IO4(uid, self.con) self.io.set_debounce_period(1000) if position == 'a': self.log("cb_enumerate() id {} - Configuring IO4 device object at position a (switches).".format(uid)) self.io.register_callback(self.io.CALLBACK_INTERRUPT, self.io_switch) self.io.set_configuration(15, 'i', True) # Enable interrupt on pin 0 and 1 self.io.set_interrupt(1 << 0) self.io.set_interrupt(1 << 1) self.set_ziel_geschlecht(self.io.get_value()) else: self.log("cb_enumerate() id {} - Configuring IO4 device object at position ? (lights, shutdown).".format(uid)) self.io.set_configuration((1 << 0) | (1 << 1), "o", True) elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER: self.log("cb_enumerate() id {} - Creating RotaryPoti device object".format(uid)) self.poti_volume = RotaryPoti(uid, self.con) self.poti_volume.set_position_callback_period(100) self.poti_volume.register_callback(self.poti_volume.CALLBACK_POSITION, self.poti_volume_changed) elif device_identifier == Master.DEVICE_IDENTIFIER: self.log("cb_enumerate() id {} - Creating Master device object".format(uid)) self.master = Master(uid, self.con) else: self.log("cb_enumerate() id {} - Could not register unknown device bricklet".format(uid)) # Callback handles reconnection of IP Connection def cb_connected(self, connected_reason): # Enumerate devices again. If we reconnected, the Bricks/Bricklets # may have been offline and the configuration may be lost. # In this case we don't care for the reason of the connection self.con.enumerate() def motion_detected(self): self.log("CALLBACK!!") self.insult() def insult(self): self.insultr.speak_next_insult() def set_volume(self, volume_percent=50): set_volume_cmd = 'amixer sset Master {}%'.format(volume_percent) self.log("set_volume() Setting volume with command: " + set_volume_cmd) os.system(set_volume_cmd) def set_volume_from_poti(self): if self.poti_volume: position = self.poti_volume.get_position() self.poti_volume_changed(position) else: self.set_volume(50) def poti_volume_changed(self, position=0): self.log("poti_volume_changed() poti was set to position {}".format(position)) if position > 150: position = 150 if position < -150: position = -150 MIN_VOLUME = 25.0 MAX_VOLUME = 90.0 poti_percent = ((position + 150.0) / 300.0) # between 0.0 and 1.0 volume_percent = MIN_VOLUME + ((MAX_VOLUME-MIN_VOLUME)*poti_percent) self.set_volume(volume_percent) def motion_cycle_ended(self): self.log("READY for motion detection!") def io_switch(self, interrupt_mask, value_mask): self.log("io_switch() IO4 triggered") self.log("io_switch() Interrupt by {} / {} ".format(str(bin(interrupt_mask)), interrupt_mask)) self.log('io_switch() Value: ' + str(bin(value_mask))) try: self.set_volume_from_poti() if interrupt_mask == 1: self.log("io_switch() Sex switched...") # button 1 switched self.set_ziel_geschlecht(value_mask) elif interrupt_mask == 2: self.log("io_switch() Insult button pressed...") button_up = value_mask&2 self.log("io_switch() value_mask =" + str(button_up)) if button_up == 2: self.insult() else: self.log("io_switch() Don't know what to do with interrupt_mask {}".format(interrupt_mask)) except Error as e: self.log("io_switch() ERROR:{}".format(e)) self.log("io_switch() end") def set_ziel_geschlecht(self, value_mask): is_on = value_mask^14 if is_on: self.log("sex was set to MALE") self.female = False self.insultr.set_maennlich() self.io.set_configuration(1 << 0, "o", True) self.io.set_configuration(1 << 1, "o", False) else: self.log("sex was set to FEMALE") self.female = True self.insultr.set_weiblich() self.io.set_configuration(1 << 0, "o", False) self.io.set_configuration(1 << 1, "o", True) def register_callbacks(self): self.log("Registering callback to motion detector...") self.motion.register_callback(self.motion.CALLBACK_MOTION_DETECTED, self.motion_detected) self.motion.register_callback(self.motion.CALLBACK_DETECTION_CYCLE_ENDED, self.motion_cycle_ended) self.io.set_debounce_period(1000) self.io.register_callback(self.io.CALLBACK_INTERRUPT, self.io_switch) # Enable interrupt on pin 0 self.io.set_interrupt((1 << 0) | (1 << 1)) #self.io.set_interrupt(1 << 1) self.log("register done")
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()
class DeviceManager(object): """ Diese Klasse implementiert den Gerätemanager einer ORBIT-Anwendung. **Parameter** ``core`` Ein Verweis auf den Anwendungskern der ORBIT-Anwendung. Eine Instanz der Klasse :py:class:`Core`. **Beschreibung** Der Gerätemanager baut eine Verbindung zu einem TinkerForge-Server auf, ermittelt die angeschlossenen Bricks und Bricklets und stellt den Komponenten in den Jobs die jeweils geforderten Geräte zur Verfügung. Dabei behält der Gerätemanager die Kontrolle über den Gerätezugriff. Das bedeutet, dass der Gerätemanager die Autorität hat, einer Komponente ein Gerät zur Verügung zu stellen, aber auch wieder zu entziehen. Eine Komponente bekommt ein von ihm angefordertes Gerät i.d.R. dann zugewiesen, wenn die Komponente aktiv und das Gerät verfügbar ist. Wird die Verbindung zum TinkerForge-Server unterbrochen oder verliert der TinkerForge-Server die Verbindung zum Master-Brick (USB-Kabel herausgezogen), entzieht der Gerätemanager der Komponente automatisch das Gerät, so dass eine Komponente i.d.R. keine Verbindungsprobleme behandeln muss. Umgesetzt wird dieses Konzept mit Hilfe der Klassen :py:class:`SingleDeviceHandle` und :py:class:`MultiDeviceHandle`. """ def __init__(self, core): self._core = core self._connected = False self._devices = {} self._device_handles = [] self._device_callbacks = {} self._device_initializers = {} self._device_finalizers = {} # initialize IP connection self._conn = IPConnection() self._conn.set_auto_reconnect(True) self._conn.register_callback(IPConnection.CALLBACK_ENUMERATE, self._cb_enumerate) self._conn.register_callback(IPConnection.CALLBACK_CONNECTED, self._cb_connected) self._conn.register_callback(IPConnection.CALLBACK_DISCONNECTED, self._cb_disconnected) def trace(self, text): """ Schreibt eine Nachverfolgungsmeldung mit dem Ursprung ``DeviceManager`` auf die Konsole. """ if self._core.configuration.device_tracing: self._core._trace_function(text, 'DeviceManager') @property def devices(self): """ Ein Dictionary mit allen zur Zeit verfügbaren Geräten. Die UID des Geräts ist der Schlüssel und der Wert ist eine Instanz der TinkerForge-Geräte-Klasse (wie z.B. ``tinkerforge.bricklet_lcd_20x4.BrickletLCD20x4``). """ return self._devices def start(self): """ Startet den Gerätemanager und baut eine Verbindung zu einem TinkerForge-Server auf. Die Verbindungdaten für den Server werden der ORBIT-Konfiguration entnommen. Gibt ``True`` zurück, wenn die Verbindung aufgebaut werden konnte, sonst ``False``. Siehe auch: :py:meth:`stop` """ if self._conn.get_connection_state() == IPConnection.CONNECTION_STATE_DISCONNECTED: host = self._core.configuration.host port = self._core.configuration.port retry_time = self._core.configuration.connection_retry_time self.trace("connecting to %s:%d ..." % (host, port)) connected = False while not connected: try: self._conn.connect(host, port) connected = True except KeyboardInterrupt: connected = False break except: connected = False self.trace("... connection failed, waiting %d, retry ..." % retry_time) try: time.sleep(retry_time) except KeyboardInterrupt: break if connected: self.trace("... connected") return connected def stop(self): """ Trennt die Verbindung zum TinkerForge-Server und beendet den Gerätemanager. Vor dem Trennen der Verbindung wird die Zuordnung zwischen den Geräten und den Komponenten aufgehoben. Siehe auch: :py:meth:`start` """ self._finalize_and_unbind_devices() if self._conn.get_connection_state() != IPConnection.CONNECTION_STATE_DISCONNECTED: self.trace("disconnecting") self._conn.disconnect() def _cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE or \ enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED: # initialize device configuration and bindings self.trace("device present '%s' [%s]" % (device_name(device_identifier), uid)) if known_device(device_identifier): # bind device and notify components self._bind_device(device_identifier, uid) else: self.trace("could not create a device binding for device identifier " + device_identifier) if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED: # recognize absence of device self.trace("device absent '%s' [%s]" % (device_name(device_identifier), uid)) # unbind device and notify components self._unbind_device(uid) def _cb_connected(self, reason): self._connected = True # recognize connection if reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT: self.trace("connection established (auto reconnect)") else: self.trace("connection established") # enumerate devices self._conn.enumerate() def _cb_disconnected(self, reason): self._connected = False # recognize lost connection if reason == IPConnection.DISCONNECT_REASON_ERROR: self.trace("connection lost (error)") elif reason == IPConnection.DISCONNECT_REASON_SHUTDOWN: self.trace("connection lost (shutdown)") else: self.trace("connection lost") def _bind_device(self, device_identifier, uid): self.trace("binding '%s' [%s]" % (device_name(device_identifier), uid)) # create binding instance device = device_instance(device_identifier, uid, self._conn) # add passive identity attribute identity = device.get_identity() device.identity = identity # initialize device self._initialize_device(device) # store reference to binding instance self.devices[uid] = device # register callbacks if uid in self._device_callbacks: callbacks = self._device_callbacks[uid] for event in callbacks: self.trace("binding dispatcher to '%s' [%s] (%s)" % (device_name(device_identifier), uid, event)) mcc = callbacks[event] device.register_callback(event, mcc) # notify device handles for device_handle in self._device_handles: device_handle.on_bind_device(device) def _unbind_device(self, uid): if uid in self._devices: device = self._devices[uid] self.trace("unbinding '%s' [%s]" % (device_name(device.identity[5]), uid)) # notify device handles for device_handle in self._device_handles: device_handle.on_unbind_device(device) # delete reference to binding interface del(self._devices[uid]) # delete reference to multicast callbacks if uid in self._device_callbacks: del(self._device_callbacks[uid]) else: self.trace("attempt to unbind not bound device [%s]" % uid) def _finalize_and_unbind_devices(self): for uid in list(self._devices.keys()): self._finalize_device(self._devices[uid]) self._unbind_device(uid) def add_device_initializer(self, device_identifier, initializer): """ Richtet eine Initialisierungsfunktion für einen Brick- oder Bricklet-Typ ein. **Parameter** ``device_identifier`` Die Geräte-ID der TinkerForge-API. Z.B. ``tinkerforge.bricklet_lcd_20x4.BrickletLCD20x4.DEVICE_IDENTIFIER`` ``initializer`` Eine Funktion, welche als Parameter eine Instanz der TinkerForge-Geräteklasse entgegennimmt. **Beschreibung** Sobald der Gerätemanager ein neues Gerät entdeckt, zu dem er bisher keine Verbindung aufgebaut hatte, ruft er alle Initialisierungsfunktionen für die entsprechende Geräte-ID auf. *Siehe auch:* :py:meth:`add_device_finalizer` """ if device_identifier not in self._device_initializers: self._device_initializers[device_identifier] = [] self._device_initializers[device_identifier].append(initializer) self.trace("added initializer for '%s'" % (device_name(device_identifier))) def _initialize_device(self, device): device_identifier = device.identity[5] if device_identifier in self._device_initializers: self.trace("initializing '%s' [%s]" % (device_name(device.identity[5]), device.identity[0])) for initializer in self._device_initializers[device_identifier]: try: initializer(device) except Error as err: if err.value != -8: # connection lost self.trace("Error during initialization of : %s" % err.description) except Exception as exc: self.trace("Exception caught during device initialization:\n%s" % exc) def add_device_finalizer(self, device_identifier, finalizer): """ Richtet eine Abschlussfunktion für einen Brick- oder Bricklet-Typ ein. **Parameter** ``device_identifier`` Die Geräte-ID der TinkerForge-API. Z.B. ``tinkerforge.bricklet_lcd_20x4.BrickletLCD20x4.DEVICE_IDENTIFIER`` ``finalizer`` Eine Funktion, welche als Parameter eine Instanz der TinkerForge-Geräteklasse entgegennimmt. **Beschreibung** Sobald der Gerätemanager die Verbindung zu einem Gerät selbstständig aufgibt (d.h. die Verbindung nicht durch eine Störung unterbrochen wurde), ruft er alle Abschlussfunktionen für die entsprechende Geräte-ID auf. *Siehe auch:* :py:meth:`add_device_initializer` """ if device_identifier not in self._device_finalizers: self._device_finalizers[device_identifier] = [] self._device_finalizers[device_identifier].append(finalizer) self.trace("added finalizer for '%s'" % device_name(device_identifier)) def _finalize_device(self, device): device_identifier = device.identity[5] if device_identifier in self._device_finalizers: self.trace("finalizing '%s' [%s]" % (device_name(device.identity[5]), device.identity[0])) for finalizer in self._device_finalizers[device_identifier]: try: finalizer(device) except Error as err: if err.value != -8: # connection lost self.trace("Error during device finalization: %s" % err.description) except Exception as exc: self.trace("Exception caught during device finalization:\n%s" % exc) def add_handle(self, device_handle): """ Richtet eine Geräteanforderung (Geräte-Handle) ein. Eine Geräteanforderung ist eine Instanz einer Sub-Klasse von :py:class:`DeviceHandle`. Das kann entweder eine Instanz von :py:class:`SingleDeviceHandle` oder von :py:class:`MultiDeviceHandle` sein. Das übergebene Geräte-Handle wird über alle neu entdeckten Geräte mit einem Aufruf von :py:meth:`DeviceHandle.on_bind_device` benachrichtigt. Je nach Konfiguration nimmt das Handle das neue Gerät an oder ignoriert es. Verliert der Gerätemanager die Verbindung zu einem Gerät, wird das Geräte-Handle ebenfalls mit einem Aufruf von :py:meth:`DeviceHandle.on_unbind_device` benachrichtigt. *Siehe auch:* :py:meth:`remove_handle` """ if device_handle in self._device_handles: return self._device_handles.append(device_handle) device_handle.on_add_handle(self) for device in self._devices.values(): device_handle.on_bind_device(device) def remove_handle(self, device_handle): """ Entfernt eine Geräteanforderung (Geräte-Handle). Eine Geräteanforderung ist eine Instanz einer Sub-Klasse von :py:class:`DeviceHandle`. Das kann entweder eine Instanz von :py:class:`SingleDeviceHandle` oder von :py:class:`MultiDeviceHandle` sein. *Siehe auch:* :py:meth:`add_handle` """ if device_handle not in self._device_handles: return for device in self._devices.values(): device_handle.on_unbind_device(device) device_handle.on_remove_handle() self._device_handles.remove(device_handle) def add_device_callback(self, uid, event, callback): """ Richtet eine Callback-Funktion für ein Ereignis eines Bricks oder eines Bricklets ein. **Parameter** ``uid`` Die UID des Gerätes für das ein Ereignis abgefangen werden soll. ``event`` Die ID für das abzufangene Ereignis. Z.B. ``tinkerforge.bricklet_lcd_20x4.BrickletLCD20x4.CALLBACK_BUTTON_PRESSED`` ``callback`` Eine Callback-Funktion die bei Auftreten des Ereignisses aufgerufen werden soll. **Beschreibung** Da jedes Ereignis andere Ereignisparameter besitzt, muss die richtige Signatur für die Callbackfunktion der TinkerForge-Dokumentation entnommen werden. Die Ereignisparameter werden in der API-Dokumentation für jeden Brick und jedes Bricklet im Abschnitt *Callbacks* beschrieben. .. note:: Der Gerätemanager stellt einen zentralen Mechanismus für die Registrierung von Callbacks für Geräteereignisse zur Verfügung, weil die TinkerForge-Geräteklassen nur ein Callback per Ereignis zulassen. Der Gerätemanager hingegen unterstützt beliebig viele Callbacks für ein Ereignis eines Gerätes. *Siehe auch:* :py:meth:`remove_device_callback` """ if uid not in self._device_callbacks: self._device_callbacks[uid] = {} callbacks = self._device_callbacks[uid] if event not in callbacks: self.trace("creating dispatcher for [%s] (%s)" % (uid, event)) mcc = MulticastCallback() callbacks[event] = mcc if uid in self._devices: device = self._devices[uid] self.trace("binding dispatcher to [%s] (%s)" % (uid, event)) device.register_callback(event, mcc) mcc = callbacks[event] self.trace("adding callback to dispatcher for [%s] (%s)" % (uid, event)) mcc.add_callback(callback) def remove_device_callback(self, uid, event, callback): """ Entfernt eine Callback-Funktion von einem Ereignis eines Bricks oder eines Bricklets. **Parameter** ``uid`` Die UID des Gerätes für das ein Callback aufgehoben werden soll. ``event`` Die ID für das Ereignis. Z.B. ``tinkerforge.bricklet_lcd_20x4.BrickletLCD20x4.CALLBACK_BUTTON_PRESSED`` ``callback`` Die registrierte Callback-Funktion die entfernt werde soll. **Beschreibung** Für die Aufhebung des Callbacks muss die gleiche Funktionsreferenz übergeben werden wie bei der Einrichtung des Callback. *Siehe auch:* :py:meth:`add_device_callback` """ if uid in self._device_callbacks: callbacks = self._device_callbacks[uid] if event in callbacks: mcc = callbacks[event] self.trace("removing callback from dispatcher for [%s] (%s)" % (uid, event)) mcc.remove_callback(callback)
#!/usr/bin/env python # -*- coding: utf-8 -*- HOST = "localhost" PORT = 4223 UID = "XYZ" # Change XYZ to the UID of your Current12 Bricklet from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_current12 import BrickletCurrent12 if __name__ == "__main__": ipcon = IPConnection() # Create IP connection c = BrickletCurrent12(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected # Get current current (unit is mA) current = c.get_current() print("Current: " + str(current / 1000.0) + " A") raw_input("Press key to exit\n") # Use input() in Python 3 ipcon.disconnect()
def write_bricklets_into_configfile(): #if path.isfile(PATH) and access(PATH, R_OK) and access(PATH, W_OK) == True: # check if config file exists and is readable and writeable #if __name__ == "__main__": ipcon = IPConnection() cfg = configparser.ConfigParser() cfg.read(cfg_filename) # open config file to read port = cfg.getint('Connection', 'Port') # get port entry from config file host = cfg.get('Connection', 'Host') # get host entry from config file sleeptime = cfg.getfloat('Connection', 'SleepTime') # get the sleeptime from config file ipcon.connect(HOST, PORT) ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, bricklet_callback) ipcon.enumerate() time.sleep(sleeptime) # sleeptime until all bricklets have answered #----------------------------------put barometer entrys into config file ---------------------------------------- if cfg.has_section(barometer_brick["Bricklet_Name"]) == False: cfg.add_section(barometer_brick["Bricklet_Name"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Section Barometer erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(barometer_brick["Bricklet_Name"], 'Bricklet_UID') == False: cfg.set(barometer_brick["Bricklet_Name"], 'Bricklet_UID', barometer_brick["Bricklet_UID"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag UID erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(barometer_brick["Bricklet_Name"], 'Bricklet_Position') == False: cfg.set(barometer_brick["Bricklet_Name"], 'Bricklet_Position', barometer_brick["Bricklet_Position"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Position erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(barometer_brick["Bricklet_Name"], 'Bricklet_Firmware') == False: cfg.set(barometer_brick["Bricklet_Name"], 'Bricklet_Firmware', str(barometer_brick["Bricklet_Firmware"])) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Firmware erstellt') else: #print ('Eintrag existiert')""" #----------------------------------put gps entrys into config file ---------------------------------------- if cfg.has_section(gps_brick["Bricklet_Name"]) == False: cfg.add_section(gps_brick["Bricklet_Name"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Section Barometer erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(gps_brick["Bricklet_Name"], 'Bricklet_UID') == False: cfg.set(gps_brick["Bricklet_Name"], 'Bricklet_UID', gps_brick["Bricklet_UID"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag UID erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(gps_brick["Bricklet_Name"], 'Bricklet_Position') == False: cfg.set(gps_brick["Bricklet_Name"], 'Bricklet_Position', gps_brick["Bricklet_Position"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Position erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(gps_brick["Bricklet_Name"], 'Bricklet_Firmware') == False: cfg.set(gps_brick["Bricklet_Name"], 'Bricklet_Firmware', str(gps_brick["Bricklet_Firmware"])) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Firmware erstellt') else: print ('Eintrag existiert')""" #----------------------------------put humidity entrys into config file ---------------------------------------- if cfg.has_section(humidity_brick["Bricklet_Name"]) == False: cfg.add_section(humidity_brick["Bricklet_Name"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Section Barometer erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(humidity_brick["Bricklet_Name"], 'Bricklet_UID') == False: cfg.set(humidity_brick["Bricklet_Name"], 'Bricklet_UID', humidity_brick["Bricklet_UID"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag UID erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(humidity_brick["Bricklet_Name"], 'Bricklet_Position') == False: cfg.set(humidity_brick["Bricklet_Name"], 'Bricklet_Position', humidity_brick["Bricklet_Position"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Position erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(humidity_brick["Bricklet_Name"], 'Bricklet_Firmware') == False: cfg.set(humidity_brick["Bricklet_Name"], 'Bricklet_Firmware', str(humidity_brick["Bricklet_Firmware"])) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Firmware erstellt') else: print ('Eintrag existiert')""" #----------------------------------put illuminance entrys into config file ---------------------------------------- if cfg.has_section(illuminance_brick["Bricklet_Name"]) == False: cfg.add_section(illuminance_brick["Bricklet_Name"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Section Barometer erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(illuminance_brick["Bricklet_Name"], 'Bricklet_UID') == False: cfg.set(illuminance_brick["Bricklet_Name"], 'Bricklet_UID', illuminance_brick["Bricklet_UID"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag UID erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(illuminance_brick["Bricklet_Name"], 'Bricklet_Position') == False: cfg.set(illuminance_brick["Bricklet_Name"], 'Bricklet_Position', illuminance_brick["Bricklet_Position"]) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Position erstellt') else: print ('Eintrag existiert')""" if cfg.has_option(illuminance_brick["Bricklet_Name"], 'Bricklet_Firmware') == False: cfg.set(illuminance_brick["Bricklet_Name"], 'Bricklet_Firmware', str(illuminance_brick["Bricklet_Firmware"])) with open(cfg_filename, 'w') as configfile: cfg.write(configfile) """print ('Eintrag Firmware erstellt') else: print ('Eintrag existiert')""" ipcon.disconnect() # disconnect connection between masterbrick and bricklet
class LEDmatrixConnect(object): """ init() wird automatisch nach der Erzeugung der Instanz aufgerufen. (-> magische Methode) Erstellt ein device Objekt und baut die Verbindung zu brickd auf. (Verbindung zu Master Brick????) """ # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect[POST]) def __init__(self): # Attribute importiert self.__UIDmaster = matrixProperties.UIDmaster # "6et15y" self.__UIDbricklet = matrixProperties.UIDbricklet # "wVj" self.__HOST = matrixProperties.HOST # "localhost" self.__PORT = matrixProperties.PORT # 4223 self.__matrixIndexRed = matrixProperties.IndexRed # 0 self.__matrixIndexGreen = matrixProperties.IndexGreen # 1 self.__matrixIndexBlue = matrixProperties.IndexBlue # 2 self.__rows = matrixProperties.ROWS # 10 self.__columns = matrixProperties.COLUMNS # 20 self.__LEDnr = matrixProperties.LEDnr # Liste LED-Nummern 0 bis 199 self.__numLEDS = matrixProperties.NUM_LEDS # 16 self.__rgb = [[0 for i in range(self.__numLEDS)] for i in range(3)] # RGB-Array self.__image = matrixProperties.defaultImage # Default-Bild setzen self.__imageIndexRed = 0 self.__imageIndexGreen = 1 self.__imageIndexBlue = 2 # Instanzvariablen self.__light = True # Boolean: True / False # Objekte print("Instanz LEDmatrix wurde erstellt.") self.__ipcon = IPConnection() # Create IP connection self.__masterBrick = BrickMaster(self.__UIDmaster, self.__ipcon) self.__brickletLEDstrip = BrickletLEDStrip(self.__UIDbricklet, self.__ipcon) # Create device object # Connect to brickd --> Verbindung Masterbrick? richtiger RGB-Kanal einstellen? self.__ipcon.connect(self.__HOST, self.__PORT) print("Verbindung zu brickd hergestellt.") self.__brickletLEDstrip.set_frame_duration(20) # Anzeigedauer Bild: 20ms ergibt 20 Bilder pro Sekunde self.__brickletLEDstrip.set_channel_mapping(self.__brickletLEDstrip.CHANNEL_MAPPING_RGB) # CHANNEL_MAPPING_RGB = 6 -> Farbkanal definieren (RGB statt BGR) # Callback starten self.__brickletLEDstrip.register_callback(self.__brickletLEDstrip.CALLBACK_FRAME_RENDERED, lambda x: self.__loadPicture__()) print("Callback aktiviert.") # ======= private Methoden ========================================================================== # fillRGBs(), fillAsc(), fillDesc(), loadPicture() def __fillRGBs__(self, yMatrix, xImage, yImage): """ Private Methode: Füllt die Farbinformationen für einen Pixel in die einzelnen RGB-Arrays ab. """ self.__rgb[self.__matrixIndexRed][yMatrix] = self.__image[xImage][yImage][self.__imageIndexRed] self.__rgb[self.__matrixIndexGreen][yMatrix] = self.__image[xImage][yImage][self.__imageIndexGreen] self.__rgb[self.__matrixIndexBlue][yMatrix] = self.__image[xImage][yImage][self.__imageIndexBlue] def __fillAsc__(self, xImage, yMatrix): """ Private Methode: Füllt eine Spalte für die LED-Matrix aus (von unten nach oben) """ # 0 bis 9 yImage = 0 i = 0 while (i < self.__rows): # i < 10 self.__fillRGBs__(yMatrix, xImage, yImage) i += 1 yImage += 1 yMatrix += 1 if (yMatrix >= self.__rows): yMatrix = 0 def __fillDesc__(self, xImage, yMatrix): """ Private Methode: Füllt eine Spalte für die LED-Matrix aus (von oben nach unten) """ # 9 bis 0 yImage = 0 i = 0 while (i < self.__rows): # i < 10 self.__fillRGBs__(yMatrix, xImage, yImage) i += 1 yImage += 1 yMatrix -= 1 if (yMatrix < 0): yMatrix = self.__rows - 1 def __loadPicture__(self): """ Methode lädt ein ganzes Bild, sofern self.__light auf True gesetzt ist => Licht an. """ if (self.__light is True): xMatrix = 0 yMatrix = 0 xImage = 0 columns = self.__columns # 20 while (columns > 0): if (xMatrix % 2 == 0): # Farbwerte von image-array nach rgb-array bei gerader Spalte y = 0 self.__fillAsc__(xImage, yMatrix) else: # Farbwerte von image-array nach rgb-array bei ungerader Spalte y = self.__rows - 1 self.__fillDesc__(xImage, self.__rows - (yMatrix + 1)) # Aufrufen der Methode set_rgb_values(index, length, r, g, b). (r, g, b, verlangen 16er-Array's) self.__brickletLEDstrip.set_rgb_values(self.__LEDnr[xMatrix][y], self.__rows, # self.__rows = 10 self.__rgb[self.__matrixIndexRed], self.__rgb[self.__matrixIndexGreen], self.__rgb[self.__matrixIndexBlue]) columns -= 1 xImage += 1 xMatrix += 1 if xMatrix >= self.__columns: xMatrix = 0 xImage = 0 # ======= public Methoden ================================================== # connect(), finish(), setVelocity(), lightOff(), setImage(), getImage() # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect/connect[PUT]) def connect(self): """ Verbindungsaufbau """ self.__ipcon.connect(self.__HOST, self.__PORT) print("Verbindung zu brickd hergestellt.") # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect/finish[PUT]) def finish(self): """ Beendet die Verbindung. """ # input("Press key to exit\n") self.__ipcon.disconnect() print("Verbindung beendet.") # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect/setVelocity/<int:frequenz>[PUT]) def setFrameDuration(self, millisec: int = 20): """ Set frame duration to 50ms (20 frames per second). Verändert die Anzeigedauer eines Frames. :param millisec: int """ self.__brickletLEDstrip.set_frame_duration(millisec) # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect/getFrameDuration[GET]) def getFrameDuration(self) -> int: """ Gibt einen int-Wert zurück. Anzeigedauer der Frames auf dem LED-Display. (20ms entspricht 50 Bilder/Sekunde) :return frame duration: int """ return self.__brickletLEDstrip.get_frame_duration() # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect/light/<boolean:status>[PUT]) def light(self, status: bool = True): # status = boolean True / False """ Licht-Regelung auf 'unterster' Stufe, wirkt sich auf den gesamten LED-Display. True = 'Licht an', False = 'Licht aus' :param status: boolean """ self.__light = status time.sleep(1) if (status is False): i = 0 while i < self.__columns: # hier 20 self.__brickletLEDstrip.set_rgb_values(i * 10, 10, [0] * self.__numLEDS, [0] * self.__numLEDS, [0] * self.__numLEDS) i += 1 # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect/setImage/<list:image>[PUT]) def setImage(self, image: list): """ Liste mit den RGB-Werten der Form [[[red, green, blue] for i in range(x columns)] for i in range(y rows)] :param image: list """ self.__image = image # @LEDmatrix.route('ledmatrix.bfh.ch/api/v1.0/LEDmatrixConnect/setImageRGBindex/<int:red>/<int:green>/<int:blue>[PUT]) def setImageRGBindex(self, red: int, green: int, blue: int): """ Werte: 0 bis 2, Default: red = 0, green = 1, blue = 2 :param red: int :param green: int :param blue: int """ self.__imageIndexRed = red self.__imageIndexGreen = green self.__imageIndexBlue = blue
class CheckTFTemperature(object): def __init__(self, host = 'localhost', port = 4223): self.host = host self.port = port self.ipcon = IPConnection() self.name = 'unknown' self.unit = 'unknown' self.is_humidity_v2 = False def connect(self, type, uid): self.ipcon.connect(self.host, self.port) self.connected_type = type if self.connected_type == TYPE_PTC: ptc = PTC(uid, self.ipcon) if ptc.get_identity().device_identifier == PTCV2.DEVICE_IDENTIFIER: ptc = PTCV2(uid, self.ipcon) self.func = ptc.get_temperature self.name = 'temperature' self.unit = '°C' elif self.connected_type == TYPE_TEMPERATURE: temperature = Temperature(uid, self.ipcon) if temperature.get_identity().device_identifier == TemperatureV2.DEVICE_IDENTIFIER: temperature = TemperatureV2(uid, self.ipcon) self.func = temperature.get_temperature self.name = 'temperature' self.unit = '°C' elif self.connected_type == TYPE_HUMIDITY: humidity = Humidity(uid, self.ipcon) if humidity.get_identity().device_identifier == HumidityV2.DEVICE_IDENTIFIER: humidity = HumidityV2(uid, self.ipcon) self.is_humidity_v2 = True else: self.is_humidity_v2 = False self.func = humidity.get_humidity self.name = 'humidity' self.unit = '%RH' elif self.connected_type == TYPE_MOTION_DETECTOR: md = MotionDetector(uid, self.ipcon) if md.get_identity().device_identifier == MotionDetectorV2.DEVICE_IDENTIFIER: md = MotionDetectorV2(uid, self.ipcon) self.func = md.get_motion_detected elif self.connected_type == TYPE_AMBIENT_LIGHT: al = AmbientLight(uid, self.ipcon) if al.get_identity().device_identifier == AmbientLightV2.DEVICE_IDENTIFIER: al = AmbientLightV2(uid, self.ipcon) elif al.get_identity().device_identifier == AmbientLightV3.DEVICE_IDENTIFIER: al = AmbientLightV3(uid, self.ipcon) self.func = al.get_illuminance self.name = 'Illuminance' self.unit = 'lux' elif self.connected_type == TYPE_SEGMENT_DISPLAY_4X7: display = SegmentDisplay4x7(uid, self.ipcon) self.func = display.set_segments def disconnect(self): self.ipcon.disconnect() def error(self, e): if e == 'true': self.func((0, 80, 80, 121), 8, False) else: self.func((0, 0, 0, 0), 8, False) def read_sensor(self): if self.connected_type == TYPE_HUMIDITY: if not self.self.is_humidity_v2: return self.func()/10.0 else: return self.func()/100.0 elif self.connected_type == TYPE_MOTION_DETECTOR: return self.func() else: # Temperature, PTC, Ambient Light. return self.func()/100.0 def read(self, warning, critical, mode = 'none', warning2 = 0, critical2 = 0): val = self.read_sensor() if self.connected_type == TYPE_MOTION_DETECTOR: if val == 1: print 'motion detected' return MOTION_DETECTED else: print 'no motion detected' return NO_MOTION_DETECTED else: if mode == 'none': print "%s %s %s" % (self.name, val, self.unit) else: if mode == 'low': warning2 = warning critical2 = critical if val >= critical and (mode == 'high' or mode == 'range'): print "CRITICAL : %s too high %s %s" % (self.name, val, self.unit) return CRITICAL elif val >= warning and (mode == 'high' or mode == 'range'): print "WARNING : %s is high %s %s" % (self.name, val, self.unit) return WARNING elif val <= critical2 and (mode == 'low' or mode == 'range'): print "CRITICAL : %s too low %s %s" % (self.name, val, self.unit) return CRITICALs elif val <= warning2 and (mode == 'low' or mode == 'range'): print "WARNING : %s is low %s %s" % (self.name, val, self.unit) return WARNING elif (val < warning and mode == 'high') or \ (val > warning2 and mode == 'low') or \ (val < warning and val > warning2 and mode == 'range'): print "OK : %s %s" % (val, self.unit) return OK else: print "UNKNOWN : can't read %s" % self.name return UNKNOWN
#!/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()
class Proxy(object): def __init__(self, brickd_host, brickd_port, broker_host, broker_port, update_interval): self.brickd_host = brickd_host self.brickd_port = brickd_port self.broker_host = broker_host self.broker_port = broker_port self.update_interval = update_interval self.ipcon = IPConnection() self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.ipcon_cb_connected) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.ipcon_cb_enumerate) self.client = mqtt.Client() self.client.on_connect = self.mqtt_on_connect self.client.on_disconnect = self.mqtt_on_disconnect self.client.on_message = self.mqtt_on_message self.device_proxies = {} self.device_proxy_classes = {} for subclass in DeviceProxy.__subclasses__(): self.device_proxy_classes[subclass.DEVICE_CLASS.DEVICE_IDENTIFIER] = subclass def connect(self): self.client.connect(self.broker_host, self.broker_port) self.client.loop_start() while True: try: time.sleep(ENUMERATE_INTERVAL) self.ipcon.enumerate() except KeyboardInterrupt: self.client.disconnect() break except: pass self.client.loop_stop() def publish_as_json(self, topic, payload, *args, **kwargs): self.client.publish(GLOBAL_TOPIC_PREFIX + topic, json.dumps(payload, separators=(',',':')), *args, **kwargs) def publish_enumerate(self, changed_uid, connected): device_proxy = self.device_proxies[changed_uid] topic_prefix = device_proxy.TOPIC_PREFIX if connected: topic = 'enumerate/connected/' + topic_prefix else: topic = 'enumerate/disconnected/' + topic_prefix self.publish_as_json(topic, device_proxy.get_enumerate_entry()) enumerate_entries = [] for uid, device_proxy in self.device_proxies.items(): if not connected and uid == changed_uid or device_proxy.TOPIC_PREFIX != topic_prefix: continue enumerate_entries.append(device_proxy.get_enumerate_entry()) self.publish_as_json('enumerate/available/' + topic_prefix, enumerate_entries, retain=True) def ipcon_cb_connected(self, connect_reason): self.ipcon.enumerate() def ipcon_cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED: if uid in self.device_proxies: self.publish_enumerate(uid, False) self.device_proxies[uid].destroy() del self.device_proxies[uid] elif device_identifier in self.device_proxy_classes and uid not in self.device_proxies: self.device_proxies[uid] = self.device_proxy_classes[device_identifier](uid, connected_uid, position, hardware_version, firmware_version, self.ipcon, self.client, self.update_interval) self.publish_enumerate(uid, True) def mqtt_on_connect(self, client, user_data, flags, result_code): if result_code == 0: self.ipcon.connect(self.brickd_host, self.brickd_port) def mqtt_on_disconnect(self, client, user_data, result_code): self.ipcon.disconnect() for uid in self.device_proxies: self.device_proxies[uid].destroy() self.device_proxies = {} def mqtt_on_message(self, client, user_data, message): logging.debug('Received message for topic ' + message.topic) topic = message.topic[len(GLOBAL_TOPIC_PREFIX):] if topic.startswith('brick/') or topic.startswith('bricklet/'): topic_prefix1, topic_prefix2, uid, topic_suffix = topic.split('/', 3) topic_prefix = topic_prefix1 + '/' + topic_prefix2 if uid in self.device_proxies and topic_prefix == self.device_proxies[uid].TOPIC_PREFIX: payload = message.payload.strip() if len(payload) > 0: try: payload = json.loads(message.payload.decode('UTF-8')) except: logging.warn('Received message with invalid payload for topic ' + message.topic) # FIXME return else: payload = {} self.device_proxies[uid].handle_message(topic_suffix, payload) return logging.debug('Unknown topic ' + message.topic)