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 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 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 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 __init__(self, log_func=None): if log_func: global log log = log_func self.ipcon = IPConnection() self.ipcon.connect(HOST, PORT) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.enumerate() log("Trying to find EVSE Bricklet...") while UID_EVSE == None: time.sleep(0.1) log("Found EVSE Bricklet: {0}".format(UID_EVSE)) self.evse = BrickletEVSEV2(UID_EVSE, self.ipcon) self.idai = BrickletIndustrialDualAnalogInV2(UID_IDAI, self.ipcon) self.idr = BrickletIndustrialDualRelay(UID_IDR, self.ipcon) # self.idi4 = BrickletIndustrialDigitalIn4V2(UID_IDI4, self.ipcon) self.iqr1 = BrickletIndustrialQuadRelayV2(UID_IQR1, self.ipcon) self.iqr2 = BrickletIndustrialQuadRelayV2(UID_IQR2, self.ipcon) self.iqr3 = BrickletIndustrialQuadRelayV2(UID_IQR3, self.ipcon) # self.icou = BrickletIndustrialCounter(UID_ICOU, self.ipcon) self.idai.set_sample_rate(self.idai.SAMPLE_RATE_61_SPS)
def __init__(self): LOGGER.info("Heater starting...") self.ipcon = IPConnection() while True: try: self.ipcon.connect(HOST, PORT) break except TFConnectionError as error: LOGGER.error("Connection Error: " + str(error.description)) sleep(1) except socket.error as error: LOGGER.error("Socket Error: " + str(error)) sleep(1) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) while True: try: self.ipcon.enumerate() return except TFConnectionError as error: LOGGER.error("Enumerate Error: " + str(error.description)) sleep(1)
def __init__(self): print('Lushroom Lighting init!') self.PLAY_HUE = True self.PLAY_DMX = True self.TRANSITION_TIME = 5 # milliseconds self.hue_list = [[]] self.player = None self.scheduler = None self.dmx_interpolator = DmxInterpolator() # 'last_played' seems to be the last numbered lighting event # in the SRT file self.last_played = 0 self.subs = "" # Hue self.bridge = None # DMX self.dmx = None self.tfIDs = [] self.ipcon = IPConnection() self.deviceIDs = [i[0] for i in deviceIdentifiersList] if self.PLAY_DMX: self.initDMX() if self.PLAY_HUE: self.initHUE()
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"
class Window(QtGui.QWidget): qtcb_temperature = QtCore.pyqtSignal(int) def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui.QPushButton('Refresh', self) self.button.clicked.connect(self.handle_button) self.label = QtGui.QLabel('TBD') layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button) layout.addWidget(self.label) self.ipcon = IPConnection() self.temperature = Temperature(UID_TEMPERATURE, self.ipcon) self.ipcon.connect(HOST, PORT) # We send the callback through the Qt signal/slot # system to make sure that we can change the label self.qtcb_temperature.connect(self.cb_temperature) self.temperature.register_callback(Temperature.CALLBACK_TEMPERATURE, self.qtcb_temperature.emit) # Refresh every second self.temperature.set_temperature_callback_period(1000) # Refresh once on startup self.handle_button() # Refresh by hand def handle_button(self): self.cb_temperature(self.temperature.get_temperature()) def cb_temperature(self, temperature): # Show temperature self.label.setText(u"Temperature: {0} °C".format(temperature/100.0))
class Window(QtGui.QWidget): qtcb_temperature = QtCore.pyqtSignal(int) def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui.QPushButton('Refresh', self) self.button.clicked.connect(self.handle_button) self.label = QtGui.QLabel('TBD') layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button) layout.addWidget(self.label) self.ipcon = IPConnection() self.temperature = Temperature(UID_TEMPERATURE, self.ipcon) self.ipcon.connect(HOST, PORT) # We send the callback through the Qt signal/slot # system to make sure that we can change the label self.qtcb_temperature.connect(self.cb_temperature) self.temperature.register_callback(Temperature.CALLBACK_TEMPERATURE, self.qtcb_temperature.emit) # Refresh every second self.temperature.set_temperature_callback_period(1000) # Refresh once on startup self.handle_button() # Refresh by hand def handle_button(self): self.cb_temperature(self.temperature.get_temperature()) def cb_temperature(self, temperature): # Show temperature self.label.setText(u"Temperature: {0} °C".format(temperature / 100.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 __init__(self): self.ipcon = IPConnection() while True: try: self.ipcon.connect(SmokeDetector.HOST, SmokeDetector.PORT) break except Error as e: log.error('Connection Error: ' + str(e.description)) time.sleep(1) except socket.error as e: log.error('Socket error: ' + str(e)) time.sleep(1) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) while True: try: self.ipcon.enumerate() break except Error as e: log.error('Enumerate Error: ' + str(e.description)) time.sleep(1)
def __init__(self): self.ipcon = IPConnection() # Create IP connection # Connect to brickd (retry if not possible) while True: try: self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT) break except Error as e: log.error('Connection Error: ' + str(e.description)) time.sleep(1) except socket.error as e: log.error('Socket error: ' + str(e)) time.sleep(1) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) # Enumerate Bricks and Bricklets (retry if not possible) while True: try: self.ipcon.enumerate() break except Error as e: log.error('Enumerate Error: ' + str(e.description)) time.sleep(1)
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 main(host, port, uid): ipcon = IPConnection() rs485 = BrickletRS485(uid, ipcon) ipcon.connect(host, port) # rs485.set_buffer_config(5*1024, 5*1024) print(rs485.get_buffer_status())
def __init__(self): self.led = None self.io = [] self.io16list = io16Dict() self.LEDs = [] self.LEDList = LEDStrips() self.al = [] self.drb = [] self.master = [] self.md = [] self.si = [] self.ptc = [] self.co2 = [] self.moist = None # 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) # Connect to brickd, will trigger cb_connected self.ipcon.connect(constants.ownIP, PORT) self.unknown = [] self.threadliste = []
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()
class MotorPoti: UID = "DCx" HOST = "localhost" PORT = 4223 def __init__(self): self.ipconnection = IPConnection() self.mlp = BrickletMotorizedLinearPoti(UID, self.ipconnection) self.ipconnection.connect(HOST, PORT) self.mlp.register_callback(self.mlp.CALLBACK_POSITION_REACHED, self.position_reached) def position_reached(self, position): print("Position: ", position) def open_door(self, callback): self.mlp.set_motor_position(0, self.mlp.DRIVE_MODE_SMOOTH, False) callback("opened") print("Opened door") def close_door(self, callback): self.mlp.set_motor_position(100, self.mlp.DRIVE_MODE_SMOOTH, False) callback("closed") print("Closed door")
def main(host, port, uid_rs485, uid_master): ipcon = IPConnection() rs485 = BrickletRS485(uid_rs485, ipcon) master = BrickMaster(uid_master, ipcon) ipcon.connect(host, port) print("get: " + str(rs485.get_bootloader_mode())) print("set 1: " + str(rs485.set_bootloader_mode(1)))
def main(host, port, uid): ipcon = IPConnection() rs485 = BrickletRS485(uid, ipcon) ipcon.connect(host, port) rs485.set_status_led_config(0) rs485.set_error_led_config(0) rs485.set_communication_led_config(0)
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)
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()
def __init__(self, _): self.ipcon = IPConnection() # Create IP connection self.master = BrickMaster(UID, self.ipcon) # Create device object self.ipcon.connect(HOST, PORT) self.timeout = 1 self.read_buffer = [] self.baudrate = None time.sleep(1)
def connect(): ipcon = IPConnection() # Create IP connection gps = GPS(UID, ipcon) # Create device object ipcon.connect(HOST, PORT) # Connect to brickd # Don't use device before ipcon is connected print('GPS Bricklet connected...') return gps, ipcon
def main(host, port, uid_rs485, uid_master): ipcon = IPConnection() rs485 = BrickletRS485(uid_rs485, ipcon) master = BrickMaster(uid_master, ipcon) ipcon.connect(host, port) print('Baudrate before: ' + str(master.get_spitfp_baudrate('c'))) master.set_spitfp_baudrate('c', 2000000) print('Baudrate after: ' + str(master.get_spitfp_baudrate('c')))
def main(host, port, uid): ipcon = IPConnection() rs485 = BrickletRS485(uid, ipcon) ipcon.connect(host, port) t = time.time() for _ in range(10000): rs485.write("1" * 60, 60) print(time.time() - t)
def __init__(self, tag_type, tag_size=512): self.tag_type = tag_type self.tag_size = tag_size self.ipcon = IPConnection() # Create IP connection self.nfc = NFCRFID(self.UID, self.ipcon) # Create device object self.ipcon.connect(self.HOST, self.PORT) # Connect to brickd self.nr.register_callback(self.nr.CALLBACK_STATE_CHANGED, self.state_changed)
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
class Sensors(object): def __init__(self): self.__ipcon = IPConnection('localhost', 4223) def __del__(self): self.__ipcon.destroy() def add(self, pSensor): self.__ipcon.add_device(pSensor)
def main(): if len(sys.argv) != 3: fail("Usage: {} [UID] [path to firmware.zbin]".format(sys.argv[0])) _, uid, plugin_path = sys.argv ipcon = IPConnection() ipcon.connect("localhost", 4223) bricklet = BrickletUnknown(uid, ipcon) if write_bricklet_plugin_comcu(plugin_path, bricklet): print("Done")
def setup_connection(self, host): ipcon = IPConnection() try: ipcon.connect(host['name'], host['port']) self.log.info("connection to '%s:%s' established", host['name'], host['port']) except ConnectionError: self.log.error("connection to '%s:%s' failed", host['name'], host['port']) self.__connections__.append(ipcon) return ipcon
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)
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
class Q: HOST = "localhost" PORT = 4223 UID = "aeoUQwwyAvY" # Change to your UID def __init__(self): self.base_x = 0.0 self.base_y = 0.0 self.base_z = 0.0 self.base_w = 0.0 self.imu = IMU(self.UID) # Create device object self.ipcon = IPConnection(self.HOST, self.PORT) # Create IPconnection to brickd self.ipcon.add_device(self.imu) # Add device to IP connection # Don't use device before it is added to a connection # Wait for IMU to settle print 'Set IMU to base position and wait for 10 seconds' print 'Base position will be 0 for all angles' time.sleep(10) q = self.imu.get_quaternion() self.set_base_coordinates(q.x, q.y, q.z, q.w) # Set period for quaternion callback to 10ms self.imu.set_quaternion_period(10) # Register quaternion callback self.imu.register_callback(self.imu.CALLBACK_QUATERNION, self.quaternion_cb) def quaternion_cb(self, x, y, z, w): # Use conjugate of quaternion to rotate coordinates according to base system x, y, z, w = self.make_relative_coordinates(-x, -y, -z, w) x_angle = int(math.atan2(2.0*(y*z - w*x), 1.0 - 2.0*(x*x + y*y))*180/math.pi) y_angle = int(math.atan2(2.0*(x*z + w*y), 1.0 - 2.0*(x*x + y*y))*180/math.pi) z_angle = int(math.atan2(2.0*(x*y + w*z), 1.0 - 2.0*(x*x + z*z))*180/math.pi) print 'x: {0}, y: {1}, z: {2}'.format(x_angle, y_angle, z_angle) def set_base_coordinates(self, x, y, z, w): self.base_x = x self.base_y = y self.base_z = z self.base_w = w def make_relative_coordinates(self, x, y, z, w): # Multiply base quaternion with current quaternion return ( w * self.base_x + x * self.base_w + y * self.base_z - z * self.base_y, w * self.base_y - x * self.base_z + y * self.base_w + z * self.base_x, w * self.base_z + x * self.base_y - y * self.base_x + z * self.base_w, w * self.base_w - x * self.base_x - y * self.base_y - z * self.base_z )
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 __init__(self): self.dus = None # 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) # Connect to brickd, will trigger cb_connected self.ipcon.connect(constants.ownIP, PORT)
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 __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_time = None self.timer = None
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")
def __init__(self): self.output_topic = rospy.get_param('~output_topic', '/cmd_vel') self.joy_UID = rospy.get_param('~tinkerforge_joy_UID', 'waz') self.tinkerforge_host = rospy.get_param('~tinkerforge_host', 'localhost') self.tinkerforge_port = rospy.get_param('~tinkerforge_port', 4223) self.actual_steering = 0 self.pub = rospy.Publisher(self.output_topic, Twist, queue_size=1) self.ipcon = IPConnection() # Create IP connection self.joy = BrickletJoystick(self.joy_UID, self.ipcon) self.ipcon.connect(self.tinkerforge_host, self.tinkerforge_port)
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 getTFconn( HOST=TF_HOST, PORT=TF_PORT ): try: ipcon = IPConnection() except Exception as e: errmsg = str(traceback.format_exception( *sys.exc_info() )); Logger.info( 'Tinkerforge IPConnection failed ... ' + errmsg ); sendEmail(admin,'getPower.py', 'Tinkerforge IPConnection failed ... ' + errmsg ) sys.exit(-1) # should cause rPi to reboot try: ipcon.connect(HOST, PORT) except Exception as e: errmsg = str(traceback.format_exception( *sys.exc_info() )); Logger.info( 'Tinkerforge unable to connect! ' + errmsg ); sendEmail(admin,'getPower.py', 'Tinkerforge unable to connect! ' + errmsg ) sys.exit(-1) # should cause rPi to reboot return ipcon
def __init__(self,host,port,uid,callbackPeriodMS=100): self.host=host self.port=port self.uid=uid self._imu = IMU(uid) # Create device object self._ipcon = IPConnection(self.host,self.port) # Create IPconnection to brickd self._ipcon.add_device(self._imu) # Add device to IP connection self.ready = True # Don't use device before it is added to a connection # Set period for quaternion callback (defaults to 100ms) self._imu.set_quaternion_period(callbackPeriodMS) # Register quaternion callback self._imu.register_callback(self._imu.CALLBACK_QUATERNION, self._QuaternionCallback) self._imu.leds_off() # Turn LEDs off. self._imu.set_convergence_speed(5) # 5ms convergence. # Orientation origin and most recent values q = self._imu.get_quaternion() # Get a temp quaternion from current pose. self.rel_x = q.x self.rel_y = q.y self.rel_z = q.z self.rel_w = q.w self.x = q.x self.y = q.y self.z = q.z self.w = q.w
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 __init__(self): #super(master, self).__init__() print 'init...' self.PORT = 4223 self.MENU_running = False self.BOARD_running = False ### Connection for Menu self.MENU_HOST = "192.168.0.150" # Manually Set IP of Controller Board "127.0.0.1"# self.MENU_lcdUID = "gFt" # LCD Screen self.MENU_jskUID = "hAP" # Joystick ### END MENU CONNECTION ### Connection for Board self.BOARD_HOST = "192.168.0.111" self.BOARD_mstUID = "62eUEf" # master brick self.BOARD_io1UID = "ghh" # io16 self.BOARD_lcdUID = "9ew" # lcd screen 20x4 self.BOARD_iqrUID = "eRN" # industrial quad relay self.BOARD_iluUID = "i8U" # Ambient Light #### END BOARD CONNECTION self.ipcon = IPConnection() # Create IP connection self.ipcon.connect('127.0.0.1', self.PORT) # Register Enumerate Callback self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) # Trigger Enumerate self.ipcon.enumerate() print 'ready?' #print self.start() return
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 __init__(self): #uinput Bereich self.events = ( uinput.BTN_A, #Es wird mindestens ein Button benötigt (seltsam) uinput.ABS_Z + (-150, 150, 0, 0), #Erstellt Joystick Achse Z, kleinster Wert des Potis ist -150, größter Wert ist +150 ) self.device = uinput.Device(self.events, "TF Virutal HID Joystick") #TinkerForge Bereich ipcon = IPConnection() self.poti = RotaryPoti("aBQ", ipcon) #UID ändern! ipcon.connect("127.0.0.1", 4223) #IP / Port anpassen self.poti.set_position_callback_period(50) self.poti.register_callback(self.poti.CALLBACK_POSITION, self.poti_cb) #Sobald der Callback auslöst wird die Funktion poti_cb aufgerufen
def __init__(self): # Create IP Connection self.ipcon = IPConnection() while True: try: self.ipcon.connect(led_strips.HOST, led_strips.PORT) break except Error as e: log.error('Connection error: ' + str(e.description)) time.sleep(1) except socket.error as e: log.error('Socket error: ' + str(e)) time.sleep(1) # Register IP Connection callbacks self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) while True: try: self.ipcon.enumerate() break except Error as e: log.error('Enumerate error: ' + str(e.description)) time.sleep(1)
def main(host, port, uid1, uid2, uid3, uid_master): ipcon = IPConnection() rs4851 = BrickletRS485(uid1, ipcon) rs4852 = BrickletRS485(uid2, ipcon) rs4853 = BrickletRS485(uid3, ipcon) master = BrickMaster(uid_master, ipcon) ipcon.connect(host, port) while True: print('RS485-1: ' + str(rs4851.get_spitfp_error_count())) print('RS485-2: ' + str(rs4852.get_spitfp_error_count())) print('RS485-3: ' + str(rs4853.get_spitfp_error_count())) print('Master-a: ' + str(master.get_spitfp_error_count('a'))) print('Master-b: ' + str(master.get_spitfp_error_count('b'))) print('Master-c: ' + str(master.get_spitfp_error_count('c'))) time.sleep(1)
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.initialized = False self.altitude_error_i = 0 self.acc_scale = 0.0 self.start_time = time.time() self.altitude_error = 0 self.inst_acceleration = 0.0 self.delta = 0 self.estimated_velocity = 0.0 self.estimated_altitude = 0.0 self.last_time = time.time() self.last_orig_altitude = 0 self.last_estimated_altitude = 0 ipcon = IPConnection() self.imu = IMU(UID_IMU, ipcon) self.barometer = Barometer(UID_BAROMETER, ipcon) ipcon.connect(HOST, PORT) # Turn leds and orientation calculation off, to save calculation time # for the IMU Brick. This makes sure that the measurements are taken # in equidistant 2ms intervals self.imu.leds_off() self.imu.orientation_calculation_off() # Turn averaging of in the Barometer Bricklet to make sure that # the data is without delay self.barometer.set_averaging(0, 0, 0) red_pen = QPen(Qt.red) red_pen.setWidth(5) plot_list = [#['', Qt.blue, self.get_orig_value], ['', red_pen, self.get_estimated_value] ] self.plot_widget = PlotWidget('Height [m]', plot_list) self.plot_widget.stop = False self.setCentralWidget(self.plot_widget) self.timer = QTimer() self.timer.timeout.connect(self.update) self.timer.start(6)
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 __init__(self, tag_type, tag_size=512): self.tag_type = tag_type self.tag_size = tag_size self.ipcon = IPConnection() # Create IP connection self.nr = BrickletNFCRFID(self.UID, self.ipcon) # Create device object self.ipcon.connect(self.HOST, self.PORT) # Connect to brickd self.nr.register_callback(self.nr.CALLBACK_STATE_CHANGED, self.state_changed)
class volt_cur: def __init__(self): self.vc = None # 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) # Connect to brickd, will trigger cb_connected self.ipcon.connect(constants.ownIP, PORT) #self.ipcon.enumerate() def cb_reached_vc(self): voltage = self.vc.get_voltage() dicti = {} dicti['value'] = str(voltage) dicti['name'] = 'Voltage' mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) current = self.vc.get_current() dicti = {} dicti['value'] = str(current) dicti['name'] = 'Current' mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) thread_cb_reached = Timer(60, self.cb_reached_vc, []) thread_cb_reached.start() # 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 for V/C if device_identifier == BrickletVoltageCurrent.DEVICE_IDENTIFIER: self.vc = BrickletVoltageCurrent(uid, self.ipcon) self.cb_reached_vc() 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.ipcon.enumerate()
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})
def connect(self): config.UID_LED_STRIP_BRICKLET = None self.setup.label_led_strip_found.setText('No') self.setup.label_led_strip_uid.setText('None') config.UID_MULTI_TOUCH_BRICKLET = None self.setup.label_multi_touch_found.setText('No') self.setup.label_multi_touch_uid.setText('None') config.UID_DUAL_BUTTON_BRICKLET = (None, None) self.setup.label_dual_button1_found.setText('No') self.setup.label_dual_button1_uid.setText('None') self.setup.label_dual_button2_found.setText('No') self.setup.label_dual_button2_uid.setText('None') config.UID_PIEZO_SPEAKER_BRICKLET = None self.setup.label_piezo_speaker_found.setText('No') self.setup.label_piezo_speaker_uid.setText('None') config.UID_SEGMENT_DISPLAY_4X7_BRICKLET = None self.setup.label_segment_display_found.setText('No') self.setup.label_segment_display_uid.setText('None') if self.ipcon != None: try: self.ipcon.disconnect() except: pass self.ipcon = IPConnection() host = self.setup.edit_host.text() port = self.setup.spinbox_port.value() try: self.ipcon.connect(host, port) except Error as e: self.error_msg.showMessage('Connection Error: ' + str(e.description) + "<br><br>Brickd installed and running?") return except socket.error as e: self.error_msg.showMessage('Socket error: ' + str(e) + "<br><br>Brickd installed and running?") return self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) # Wait for a second to give user visual feedback timer = QTimer(self) timer.setSingleShot(True) timer.timeout.connect(self.ipcon.enumerate) timer.start(250)