当前位置: 首页>>代码示例>>Python>>正文


Python IPConnection.enumerate方法代码示例

本文整理汇总了Python中tinkerforge.ip_connection.IPConnection.enumerate方法的典型用法代码示例。如果您正苦于以下问题:Python IPConnection.enumerate方法的具体用法?Python IPConnection.enumerate怎么用?Python IPConnection.enumerate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tinkerforge.ip_connection.IPConnection的用法示例。


在下文中一共展示了IPConnection.enumerate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TinkerforgeConnection

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
class TinkerforgeConnection(object):
    # Connection to the Brick Daemon on localhost and port 4223
    ipcon = None
    current_entries = dict()

    # noinspection PyUnusedLocal
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier,
                     enumeration_type):

        if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED:
            del self.current_entries[uid]

        else:
            if device_identifier == 13:
                self.current_entries.update({uid: "Master Brick"})
            elif device_identifier == 21:
                self.current_entries.update({uid: "Ambient Light Bricklet"})
            elif device_identifier == 229:
                self.current_entries.update({uid: "Distance US Bricklet"})
            elif device_identifier == 235:
                self.current_entries.update({uid: "RemoteSwitchBricklet"})
            else:
                self.current_entries.update(
                    {uid: "device_identifier = {0}".format(device_identifier)})

    def switch_socket(self, uid, address, unit, state):
        rs = BrickletRemoteSwitch(uid, self.ipcon)
        rs.switch_socket_b(address, unit, state)

    def dim_socket(self, uid, address, unit, value):
        rs = BrickletRemoteSwitch(uid, self.ipcon)
        rs.dim_socket_b(address, unit, value)

    def get_illuminance(self, uid):
        try:
            al = BrickletAmbientLight(uid, self.ipcon)
            return al.get_illuminance() / 10
        except Exception:
            log.warn(uid + " not connected")
            return -1

    def get_distance(self, uid):
        try:
            dus = BrickletDistanceUS(uid, self.ipcon)
            return dus.get_distance_value()
        except Exception:
            log.warn(uid + " not connected")
            return -1

    def __init__(self, ip_address):
        self.ipcon = IPConnection()
        self.ipcon.connect(ip_address, 4223)
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
        self.ipcon.enumerate()
开发者ID:JonathanH5,项目名称:meinHeim,代码行数:56,代码来源:modules.py

示例2: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
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()    
开发者ID:chrihuc,项目名称:satellite,代码行数:55,代码来源:tf_class.py

示例3: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
class WeatherStation:
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    al = None
    hum = None
    baro = None

    def __init__(self):
        self.xively = Xively()
        self.ipcon = IPConnection()
        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)

        while True:
            try:
                self.ipcon.enumerate()
                break
            except Error as e:
                log.error('Enumerate Error: ' + str(e.description))
                time.sleep(1)

    def cb_illuminance(self, illuminance):
        if self.lcd is not None:
            text = 'Illuminanc %6.2f lx' % (illuminance/10.0)
            self.lcd.write_line(0, 0, text)
            self.xively.put('AmbientLight', illuminance/10.0)
            log.info('Write to line 0: ' + text)

    def cb_humidity(self, humidity):
        if self.lcd is not None:
            text = 'Humidity   %6.2f %%' % (humidity/10.0)
            self.lcd.write_line(1, 0, text)
            self.xively.put('Humidity', humidity/10.0)
            log.info('Write to line 1: ' + text)

    def cb_air_pressure(self, air_pressure):
        if self.lcd is not None:
            text = 'Air Press %7.2f mb' % (air_pressure/1000.0)
            self.lcd.write_line(2, 0, text)
            self.xively.put('AirPressure', air_pressure/1000.0)
            log.info('Write to line 2: ' + text)

            temperature = self.baro.get_chip_temperature()/100.0
            # \xDF == ° on LCD 20x4 charset
            text = 'Temperature %5.2f \xDFC' % temperature
            self.lcd.write_line(3, 0, text)
            self.xively.put('Temperature', temperature)
            log.info('Write to line 3: ' + text.replace('\xDF', '°'))

    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()
                    log.info('LCD20x4 initialized')
                except Error as e:
                    log.error('LCD20x4 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)
                    log.info('AmbientLight initialized')
                except Error as e:
                    log.error('AmbientLight 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)
                    log.info('Humidity initialized')
                except Error as e:
                    log.error('Humidity init failed: ' + str(e.description))
                    self.hum = None
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:
                try:
#.........这里部分代码省略.........
开发者ID:darumwarum,项目名称:tinkerforge-base-weatherstation,代码行数:103,代码来源:weather_xively.py

示例4: master

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
class master():
    """docstring for master"""
    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 help(self):
        return "\nCommands: \n" \
               "     - start\n" \
               "     - status\n" \
               "     - beep\n" \
               "     - light\n" \
               "     - startMenu\n" \
               "     - startBoard\n" \
               "     - stop\n"


    def start(self):
        if self.BOARD_running: print 'Board already running!'
        else: self.startBoard(); print 'Board Started!'

        if self.MENU_running: print 'Menu already running!'
        elif self.BOARD_running: self.startMenu(); print 'Menu Started!'
        return 'Started!'

    def toggleLight(self):
        if self.BOARD_running:
            print self.BB.status('light')
            return 'Light Toggled!'
        else: return 'Board is offline!'

    def toggleBeep(self):
        if self.BOARD_running:
            print self.BB.status('beep')
            return 'Beep Toggled!'
        else: return 'Board is offline!'


    def status(self):
        if self.BOARD_running:
            if self.BB.status('door'): doorState = 'Open'
            else: doorState = 'Closed'

            tempState = self.BB.status('temp')

            RunningString = 'Board: '+str(self.BOARD_running)+'\nMenu: '+str(self.MENU_running)
            StateString   = 'Door: ' + str(doorState) + '\nTemperature: ' + str(tempState) + '°C'

            return RunningString + '\n' + StateString
        return 'all offline'


    def startBoard(self):
        if self.BOARD_running: return 'Board already running!'

        if isOpen(self.BOARD_HOST, self.PORT):

            self.BOARD_running = True

            self.BOARD_ipcon = IPConnection() # Create IP connection

            self.mst = Master(self.BOARD_mstUID, self.BOARD_ipcon)   # Master Brick
            self.io1 = IO16(self.BOARD_io1UID, self.BOARD_ipcon)       # io16
            self.lcd1 = LCD20x4(self.BOARD_lcdUID, self.BOARD_ipcon)  # lcd20x4
            self.iqr = IndustrialQuadRelay(self.BOARD_iqrUID, self.BOARD_ipcon) # Create device object
            self.ilu = AmbientLight(self.BOARD_iqrUID, self.BOARD_ipcon) # Create device object

            self.BOARD_ipcon.connect(self.BOARD_HOST, self.PORT) # Connect to brickd

            # create Board instance 
#.........这里部分代码省略.........
开发者ID:DeathPoison,项目名称:roomControll,代码行数:103,代码来源:twistedMaster.py

示例5: cb_enumerate

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
#!/usr/bin/env python
# -*- coding: utf-8 -*-  
# this one creates an array of connected devices called dev
# and acts as enum in standalone mode 

from tinkerforge.ip_connection import IPConnection
from settings import HOST, PORT

dev = []
def cb_enumerate(uid, name, stack_id, is_new):
    
    if is_new:
        print("New device:")
        dev.append([name, uid, stack_id])
    else:
        print("Removed device:")
        for i in dev:
            if i[1] == uid:
                dev.remove(i)
    if __name__ == "__main__":
        print(" Name:     " + name)
        print(" UID:      " + uid)
        print(" Stack ID: " + str(stack_id))
        print("")
     
if __name__ == "__main__":
    ipcon = IPConnection(HOST, PORT) # Create IP connection to brickd
    ipcon.enumerate(cb_enumerate) # Enumerate Bricks and Bricklets

    raw_input('Press key to exit\n') # Use input() in Python 3
    ipcon.destroy()
开发者ID:miefda,项目名称:krebsling,代码行数:33,代码来源:enum.py

示例6: Blinkenlights

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]

#.........这里部分代码省略.........
        self.main.setWindowTitle("Starter Kit: Blinkenlights Demo " + config.DEMO_VERSION)
        self.main.show()

    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)

    def tab_changed_slot(self, tabIndex):
        self.active_project.stop()
        self.active_project = self.projects[tabIndex]
        self.active_project.start()

    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 == LEDStrip.DEVICE_IDENTIFIER:
                config.UID_LED_STRIP_BRICKLET = uid
                self.setup.label_led_strip_found.setText('Yes')
                self.setup.label_led_strip_uid.setText(uid)
            elif device_identifier == MultiTouch.DEVICE_IDENTIFIER:
                config.UID_MULTI_TOUCH_BRICKLET = uid
                self.setup.label_multi_touch_found.setText('Yes')
                self.setup.label_multi_touch_uid.setText(uid)
            elif device_identifier == DualButton.DEVICE_IDENTIFIER:
                if config.UID_DUAL_BUTTON_BRICKLET[0] == None:
                    config.UID_DUAL_BUTTON_BRICKLET = (uid, None)
                    self.setup.label_dual_button1_found.setText('Yes')
                    self.setup.label_dual_button1_uid.setText(uid)
                else:
                    config.UID_DUAL_BUTTON_BRICKLET = (config.UID_DUAL_BUTTON_BRICKLET[0], uid)
                    self.setup.label_dual_button2_found.setText('Yes')
                    self.setup.label_dual_button2_uid.setText(uid)
            elif device_identifier == PiezoSpeaker.DEVICE_IDENTIFIER:
                config.UID_PIEZO_SPEAKER_BRICKLET = uid
                self.setup.label_piezo_speaker_found.setText('Yes')
                self.setup.label_piezo_speaker_uid.setText(uid)
            elif device_identifier == SegmentDisplay4x7.DEVICE_IDENTIFIER:
                config.UID_SEGMENT_DISPLAY_4X7_BRICKLET = uid
                self.setup.label_segment_display_found.setText('Yes')
                self.setup.label_segment_display_uid.setText(uid)

    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)
开发者ID:chuangke365,项目名称:blinkenlights,代码行数:104,代码来源:demo.py

示例7: write_bricklets_into_configfile

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
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:
#.........这里部分代码省略.........
开发者ID:wegtam,项目名称:weather-client,代码行数:103,代码来源:create_cfg.py

示例8: str

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
        if str(uid) == '6R3jeY':
            print 'WLAN Controller connected...'
    else:
        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("")

if __name__ == "__main__":
    # Create connection and connect to brickd
    ipcon = IPConnection()
    ipcon.connect(HOST, PORT)

    # Register Enumerate Callback
    ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate)

    # Trigger Enumerate
    ipcon.enumerate()

    raw_input("Press key to exit\n") # Use input() in Python 3
    ipcon.disconnect()
开发者ID:DeathPoison,项目名称:roomControll,代码行数:32,代码来源:enumerate.py

示例9: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
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):
#.........这里部分代码省略.........
开发者ID:Tinkerforge,项目名称:red-brick,代码行数:103,代码来源:rtc_time.py

示例10: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
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:            
#.........这里部分代码省略.........
开发者ID:tyunkeow,项目名称:beleidigungsmaschine,代码行数:103,代码来源:tinkerforge_stack.py

示例11: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
class ExampleRugged:
    HOST = "localhost"
    PORT = 4223

    def __init__(self):
        self.lcd = None
        self.temp = 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(ExampleRugged.HOST, ExampleRugged.PORT) 

        self.ipcon.enumerate()

    # Callback switches lcd backlight on/off based on lcd button 0
    def cb_button_pressed(self, button):
        if self.lcd:
            if button == 0:
                if self.lcd.is_backlight_on():
                    self.lcd.backlight_off()
                else:
                    self.lcd.backlight_on()

    # Callback updates temperature displayed on lcd
    def cb_temperature(self, temperature):
        if self.lcd:
            self.lcd.clear_display()
            s = 'Temperature: {0:.2f}{1:c}C'.format(temperature/100.0, 0xdf)
            self.lcd.write_line(0, 0, s)

    # 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 LCD Bricklet
            if device_identifier == LCD20x4.DEVICE_IDENTIFIER:
                # Create lcd device object
                self.lcd = LCD20x4(uid, self.ipcon) 
                self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, 
                                           self.cb_button_pressed)
                self.lcd.clear_display()
                self.lcd.backlight_on()
            # Enumeration is for Temperature Bricklet
            if device_identifier == Temperature.DEVICE_IDENTIFIER:
                # Create temperature device object
                self.temp = Temperature(uid, self.ipcon) 
                self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, 
                                            self.cb_temperature)

                self.temp.set_temperature_callback_period(50)

    # 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.ipcon.enumerate()
开发者ID:Tinkerforge,项目名称:doc,代码行数:70,代码来源:example_rugged.py

示例12: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
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
#.........这里部分代码省略.........
开发者ID:Tinkerforge,项目名称:red-brick,代码行数:103,代码来源:gps_time.py

示例13: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
class led_strips:
    HOST = "localhost"
    PORT = 4223

    UID_LED_STRIP_ONE = "jGy"
    UID_LED_STRIP_TWO = "jHE"

    MODE = 0
    MODE_HUE = 1
    MODE_SATURATION = 2
    MODE_VALUE = 3
    MODE_VELOCITY = 4
    MODE_COLOR_GRADIENT = 5
    MODE_COLOR_DOT = 6
    MODE_COLOR_FADING = 7
    MODE_COLOR_RANDOMLY = 8
    MODE_LEDS = 9
    MODE_OFF = 10

    MODE_STRIPS = 0
    MODE_LEFT_STRIP = 1
    MODE_RIGHT_STRIP = 2
    MODE_BOTH_STRIPS = 3

    POSITION_HUE = 1
    POSITION_SATURATION = 1
    POSITION_VALUE = 0.3
    POSITION_VELOCITY = 1

    R = [255]*16
    G = [0]*16
    B = [0]*16
    
    MAX_LEDS = 16
    ACTIVE_LEDS = 16

    ipcon = None
    led_strip_1 = None
    led_strip_2 = None
    multi_touch = None
    rotary_poti = None

    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)

    # Callback handels device connections and configures possibly lost configuration
    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 == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_ONE: #LED-Strip 1
                try:
                    self.led_strip_1 = LEDStrip(uid, self.ipcon)
                    log.info('LED-Strip 1 initialized.')
                except Error as e:
                    log.error('LED-Strip 1 init failed: ' + str(e.description))
                    self.led_strip_1 = None
            elif device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_TWO: #LED-Strip 2
                try:
                    self.led_strip_2 = LEDStrip(uid, self.ipcon)
                    log.info('LED-Strip 2 initialized.')
                except Error as e:
                    log.error('LED-Strip 2 init failed: ' + str(e.description))
                    self.led_strip_2 = None
            elif device_identifier == MultiTouch.DEVICE_IDENTIFIER: # MulitTouch for changing colors etc.
                try:
                    self.multi_touch = MultiTouch(uid, self.ipcon)
                    self.multi_touch.register_callback(self.multi_touch.CALLBACK_TOUCH_STATE, self.cb_buttons)
                    self.multi_touch.set_electrode_config(0x0FFF)
                    self.multi_touch.recalibrate()
                    log.info('Set proximity off.')
                    log.info('Multi-Touch initialized.')
                except Error as e:
                    log.error('Multi-Touch init failed: ' + str(e.description))
                    self.multi_touch = None
            elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER: # Rotary Poti for picking a color or changing the saturation
                try:
                    self.rotary_poti = RotaryPoti(uid, self.ipcon)
                    self.rotary_poti.register_callback(self.rotary_poti.CALLBACK_POSITION, self.cb_position)
#.........这里部分代码省略.........
开发者ID:Infides,项目名称:LED-Strips,代码行数:103,代码来源:LED-Strips.py

示例14: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
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
开发者ID:chaquotay,项目名称:IndoorClimateStation,代码行数:72,代码来源:ClimateSensors.py

示例15: __init__

# 需要导入模块: from tinkerforge.ip_connection import IPConnection [as 别名]
# 或者: from tinkerforge.ip_connection.IPConnection import enumerate [as 别名]
class SmokeDetector:
    HOST = 'localhost'
    PORT = 4223

    ipcon = None
    idi4 = None

    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 cb_interrupt(self, interrupt_mask, value_mask):
        if value_mask > 0:
            log.warn('Fire! Fire!')

    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 == IndustrialDigitalIn4.DEVICE_IDENTIFIER:
                try:
                    self.idi4 = IndustrialDigitalIn4(uid, self.ipcon)
                    self.idi4.set_debounce_period(10000)
                    self.idi4.set_interrupt(15)
                    self.idi4.register_callback(IndustrialDigitalIn4.CALLBACK_INTERRUPT,
                                                self.cb_interrupt)
                    log.info('Industrial Digital In 4 initialized')
                except Error as e:
                    log.error('Industrial Digital In 4 init failed: ' + str(e.description))
                    self.idi4 = None

    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
            log.info('Auto Reconnect')

            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    log.error('Enumerate Error: ' + str(e.description))
                    time.sleep(1)
开发者ID:AxelRb,项目名称:hardware-hacking,代码行数:66,代码来源:smoke_detector.py


注:本文中的tinkerforge.ip_connection.IPConnection.enumerate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。