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


Python btle.Peripheral类代码示例

本文整理汇总了Python中bluepy.btle.Peripheral的典型用法代码示例。如果您正苦于以下问题:Python Peripheral类的具体用法?Python Peripheral怎么用?Python Peripheral使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: RileyLink

class RileyLink(PacketRadio):
    def __init__(self):
        self.peripheral = None
        self.pa_level_index = PA_LEVELS.index(0x84)
        self.data_handle = None
        self.logger = getLogger()
        self.address = None
        if os.path.exists(RILEYLINK_MAC_FILE):
            with open(RILEYLINK_MAC_FILE, "r") as stream:
                self.address = stream.read()
        self.service = None
        self.response_handle = None
        self.notify_event = Event()
        self.initialized = False

    def connect(self, force_initialize=False):
        try:
            if self.address is None:
                self.address = self._findRileyLink()

            if self.peripheral is None:
                self.peripheral = Peripheral()

            try:
                state = self.peripheral.getState()
                if state == "conn":
                    return
            except BTLEException:
                pass

            self._connect_retry(3)

            self.service = self.peripheral.getServiceByUUID(RILEYLINK_SERVICE_UUID)
            data_char = self.service.getCharacteristics(RILEYLINK_DATA_CHAR_UUID)[0]
            self.data_handle = data_char.getHandle()

            char_response = self.service.getCharacteristics(RILEYLINK_RESPONSE_CHAR_UUID)[0]
            self.response_handle = char_response.getHandle()

            response_notify_handle = self.response_handle + 1
            notify_setup = b"\x01\x00"
            self.peripheral.writeCharacteristic(response_notify_handle, notify_setup)

            while self.peripheral.waitForNotifications(0.05):
                self.peripheral.readCharacteristic(self.data_handle)

            if self.initialized:
                self.init_radio(force_initialize)
            else:
                self.init_radio(True)
        except BTLEException:
            if self.peripheral is not None:
                self.disconnect()
            raise

    def disconnect(self, ignore_errors=True):
        try:
            if self.peripheral is None:
                self.logger.info("Already disconnected")
                return
            self.logger.info("Disconnecting..")
            if self.response_handle is not None:
                response_notify_handle = self.response_handle + 1
                notify_setup = b"\x00\x00"
                self.peripheral.writeCharacteristic(response_notify_handle, notify_setup)
        except BTLEException:
            if not ignore_errors:
                raise
        finally:
            try:
                if self.peripheral is not None:
                    self.peripheral.disconnect()
                    self.peripheral = None
            except BTLEException:
                if ignore_errors:
                    self.logger.exception("Ignoring btle exception during disconnect")
                else:
                    raise

    def get_info(self):
        try:
            self.connect()
            bs = self.peripheral.getServiceByUUID(XGATT_BATTERYSERVICE_UUID)
            bc = bs.getCharacteristics(XGATT_BATTERY_CHAR_UUID)[0]
            bch = bc.getHandle()
            battery_value = int(self.peripheral.readCharacteristic(bch)[0])
            self.logger.debug("Battery level read: %d", battery_value)
            version, v_major, v_minor = self._read_version()
            return { "battery_level": battery_value, "mac_address": self.address,
                    "version_string": version, "version_major": v_major, "version_minor": v_minor }
        except BTLEException as btlee:
            raise PacketRadioError("Error communicating with RileyLink") from btlee
        finally:
            self.disconnect()

    def _read_version(self):
        version = None
        try:
            if os.path.exists(RILEYLINK_VERSION_FILE):
                with open(RILEYLINK_VERSION_FILE, "r") as stream:
#.........这里部分代码省略.........
开发者ID:scudrunner,项目名称:omnipy,代码行数:101,代码来源:pr_rileylink.py

示例2: __init__

    def __init__(self,addr,version=AUTODETECT):
        Peripheral.__init__(self,addr)
        if version==AUTODETECT:
            svcs = self.discoverServices()
            if _TI_UUID(0xAA70) in svcs:
                version = SENSORTAG_2650
            else:
                version = SENSORTAG_V1

        fwVers = self.getCharacteristics(uuid=AssignedNumbers.firmwareRevisionString)
        if len(fwVers) >= 1:
            self.firmwareVersion = fwVers[0].read().decode("utf-8")
        else:
            self.firmwareVersion = u''

        if version==SENSORTAG_V1:
            self.IRtemperature = IRTemperatureSensor(self)
            self.accelerometer = AccelerometerSensor(self)
            self.humidity = HumiditySensor(self)
            self.magnetometer = MagnetometerSensor(self)
            self.barometer = BarometerSensor(self)
            self.gyroscope = GyroscopeSensor(self)
            self.keypress = KeypressSensor(self)
            self.lightmeter = None
        elif version==SENSORTAG_2650:
            self._mpu9250 = MovementSensorMPU9250(self)
            self.IRtemperature = IRTemperatureSensorTMP007(self)
            self.accelerometer = AccelerometerSensorMPU9250(self._mpu9250)
            self.humidity = HumiditySensorHDC1000(self)
            self.magnetometer = MagnetometerSensorMPU9250(self._mpu9250)
            self.barometer = BarometerSensorBMP280(self)
            self.gyroscope = GyroscopeSensorMPU9250(self._mpu9250)
            self.keypress = KeypressSensor(self)
            self.lightmeter = OpticalSensorOPT3001(self)
            self.battery = BatterySensor(self)
开发者ID:IanHarvey,项目名称:bluepy,代码行数:35,代码来源:sensortag.py

示例3: __init__

    def __init__(self, addr):
        Peripheral.__init__(self, addr, addrType=ADDR_TYPE_RANDOM)

        # Thingy configuration service not implemented
        self.battery = BatterySensor(self)
        self.environment = EnvironmentService(self)
        self.ui = UserInterfaceService(self)
        self.motion = MotionService(self)
        self.sound = SoundService(self)
开发者ID:IanHarvey,项目名称:bluepy,代码行数:9,代码来源:thingy52.py

示例4: __init__

 def __init__(self, addr):
     print("Press the Angel Sensor's button to continue...")
     while True:
         try:
             Peripheral.__init__(self, addr, addrType=ADDR_TYPE_PUBLIC)
         except BTLEException:
             time.sleep(0.5)
             continue
         break
开发者ID:vaggos2002,项目名称:py-angel-sensor,代码行数:9,代码来源:main.py

示例5: Nuimo

class Nuimo(object):

    SERVICE_UUIDS = [
        UUID('0000180f-0000-1000-8000-00805f9b34fb'), # Battery
        UUID('f29b1525-cb19-40f3-be5c-7241ecb82fd2'), # Sensors
        UUID('f29b1523-cb19-40f3-be5c-7241ecb82fd1')  # LED Matrix
    ]

    CHARACTERISTIC_UUIDS = {
        UUID('00002a19-0000-1000-8000-00805f9b34fb'): 'BATTERY',
        UUID('f29b1529-cb19-40f3-be5c-7241ecb82fd2'): 'BUTTON',
        UUID('f29b1528-cb19-40f3-be5c-7241ecb82fd2'): 'ROTATION',
        UUID('f29b1527-cb19-40f3-be5c-7241ecb82fd2'): 'SWIPE',
        UUID('f29b1526-cb19-40f3-be5c-7241ecb82fd2'): 'FLY',
        UUID('f29b1524-cb19-40f3-be5c-7241ecb82fd1'): 'LED_MATRIX'
    }

    NOTIFICATION_CHARACTERISTIC_UUIDS = [
        'BATTERY', # Uncomment only if you are not using the iOS emulator (iOS does't support battery updates without authentication)
        'BUTTON',
        'ROTATION',
        'SWIPE',
        'FLY']

    # Notification data
    NOTIFICATION_ON = struct.pack("BB", 0x01, 0x00)
    NOTIFICATION_OFF = struct.pack("BB", 0x00, 0x00)

    def __init__(self, mac_address):
        self.macAddress = mac_address
        self.delegate=NuimoDelegate(self)

    def set_delegate(self, delegate):
        self.delegate = delegate

    def connect(self):
        self.peripheral = Peripheral(self.macAddress, addrType='random')
        # Retrieve all characteristics from desired services and map them from their UUID
        characteristics = list(itertools.chain(*[self.peripheral.getServiceByUUID(uuid).getCharacteristics() for uuid in Nuimo.SERVICE_UUIDS]))
        characteristics = dict((c.uuid, c) for c in characteristics)
        # Store each characteristic's value handle for each characteristic name
        self.characteristicValueHandles = dict((name, characteristics[uuid].getHandle()) for uuid, name in Nuimo.CHARACTERISTIC_UUIDS.items())
        # Subscribe for notifications
        for name in Nuimo.NOTIFICATION_CHARACTERISTIC_UUIDS:
            self.peripheral.writeCharacteristic(self.characteristicValueHandles[name] + 1, Nuimo.NOTIFICATION_ON, True)
        self.peripheral.setDelegate(self.delegate)

    def wait_for_notifications(self):
        self.peripheral.wait_for_notifications(1.0)

    def display_led_matrix(self, matrix, timeout, brightness=1.0):
        matrix = '{:<81}'.format(matrix[:81])
        bites = list(map(lambda leds: reduce(lambda acc, led: acc + (1 << led if leds[led] not in [' ', '0'] else 0), range(0, len(leds)), 0), [matrix[i:i+8] for i in range(0, len(matrix), 8)]))
        self.peripheral.writeCharacteristic(self.characteristicValueHandles['LED_MATRIX'], struct.pack('BBBBBBBBBBBBB', bites[0], bites[1], bites[2], bites[3], bites[4], bites[5], bites[6], bites[7], bites[8], bites[9], bites[10], max(0, min(255, int(255.0 * brightness))), max(0, min(255, int(timeout * 10.0)))), True)
开发者ID:mikesmth,项目名称:Nuimo-Matrix-Tester,代码行数:54,代码来源:nuimo.py

示例6: __init__

 def __init__(self, address, pincode):
     print("Connecting to %s..." % address)
     self.pincode = pincode
     self.periph = Peripheral(address)
     self._ipcamservice()
     self.name = self.periph.getCharacteristics(uuid=0x2a00)[0].read().decode() # wellknown name characteristic
     print("Connected to '%s'" % self.name)
开发者ID:bmork,项目名称:defogger,代码行数:7,代码来源:dcs8000lh-configure.py

示例7: __init__

 def __init__(self, peripheral):
   self.mac = peripheral.addr
   self.sent_alert = False
   self.amb_temp = None
   self.temp_job_id = None
   self.peripheral = Peripheral(peripheral)
   self.characteristics = {}
开发者ID:daviessm,项目名称:heating,代码行数:7,代码来源:temp_sensor.py

示例8: __init__

    def __init__(self, mac):
        self.conn = Peripheral(mac)
        self.conn.setDelegate(self)
        self.count = 0
        self.buffin = [None]*10
        self.got1 = False
        print('connected')
        
        self.service = self.conn.getServiceByUUID(_LBN_UUID(0x10))
        self.serial = self.service.getCharacteristics(_LBN_UUID(0x11)) [0]
        
        #print(self.serial.propertiesToString())

        # Turn on notificiations
        self.conn.writeCharacteristic(0x2f, '\x01\x00', False)
        
        i = 0
        while True:
            #print(self.serial.read())
            self.write("a" * 60)
            #self.write("a" * 5)
            #self.sendCmd(LightBlueBean.MSG_ID_CC_ACCEL_READ)
            
            self.conn.waitForNotifications(1)
            time.sleep(1)
        self.conn.disconnect()
开发者ID:Sherpakirk,项目名称:blynk-library,代码行数:26,代码来源:lightbluebean-reorder.py

示例9: write

    def write(self, characteristic, data):
        try:
            dev = Peripheral(self, self.addrType)

            services = sorted(dev.services, key=lambda s: s.hndStart)

            print_status("Searching for characteristic {}".format(characteristic))
            char = None
            for service in services:
                if char is not None:
                    break

                for _, c in enumerate(service.getCharacteristics()):
                    if str(c.uuid) == characteristic:
                        char = c
                        break

            if char:
                if "WRITE" in char.propertiesToString():
                    print_success("Sending {} bytes...".format(len(data)))

                    wwrflag = False

                    if "NO RESPONSE" in char.propertiesToString():
                        wwrflag = True

                    try:
                        char.write(data, wwrflag)
                        print_success("Data sent")
                    except Exception as err:
                        print_error("Error: {}".format(err))

                else:
                    print_error("Not writable")

            dev.disconnect()

        except Exception as err:
            print_error(err)

        try:
            dev.disconnect()
        except Exception:
            pass

        return None
开发者ID:Sushink,项目名称:routersploit,代码行数:46,代码来源:btle_device.py

示例10: __init__

    def __init__(self, addr ):
        if addr and len(addr) != 17 :
            raise Exception( 'ERROR: device address must be in the format NN:NN:NN:NN:NN:NN' )
        Peripheral.__init__(self, addr)
        if addr:
            logger.info( 'connected to {}'.format( addr ) )
#        self.svcs = self.discoverServices()

        self.name = ''
        self.modelNumber = None
        self.serialNumber = None
        self.firmwareRevision = None
        self.hardwareRevision = None
        self.softwareRevision = None
        self.manufacturer = None
        
        self.temperature = None
        self.humidity = None
        self.battery = None
开发者ID:druxx,项目名称:ha-utils,代码行数:19,代码来源:bbw200.py

示例11: enumerate_services

    def enumerate_services(self):
        print_status("Starting enumerating {} ({} dBm) ...".format(self.addr, self.rssi))

        try:
            dev = Peripheral(self, self.addrType)

            services = sorted(dev.services, key=lambda s: s.hndStart)

            data = []
            for service in services:
                if service.hndStart == service.hndEnd:
                    continue

                data.append([
                    "{:04x} -> {:04x}".format(service.hndStart, service.hndEnd),
                    self._get_svc_description(service),
                    "",
                    "",
                ])

                for _, char in enumerate(service.getCharacteristics()):
                    desc = self._get_char_description(char)
                    props = char.propertiesToString()
                    hnd = char.getHandle()
                    value = self._get_char(char, props)

                    data.append([
                        "{:04x}".format(hnd), desc, props, value
                    ])

            dev.disconnect()

            return data

        except Exception as err:
            print_error(err)

        try:
            dev.disconnect()
        except Exception as err:
            print_error(err)

        return None
开发者ID:Sushink,项目名称:routersploit,代码行数:43,代码来源:btle_device.py

示例12: __init__

 def __init__(self, addr):
     log.debug('connetion...')
     Peripheral.__init__(self, addr)
     log.debug('discovery...')
     self.discoverServices()
     self.notify_ch = None
     s = self.getServiceByUUID('fff0')
     self.cccd, = s.getCharacteristics('fff2')
     self.cccn, = s.getCharacteristics('fff1')
     log.debug('cccd: uuid=%s, commonName=%s, properties=%s' % (
         self.cccd.uuid,
         self.cccd.uuid.getCommonName(), 
         self.cccd.propertiesToString()))
     log.debug('cccn: uuid=%s, commonName=%s, properties=%s' % (
         self.cccn.uuid,
         self.cccn.uuid.getCommonName(), 
         self.cccn.propertiesToString()))
     self.cccd.write(b'\x01\x00')
     self.cccn.write(b'\x01\x00')
开发者ID:matthewg42,项目名称:fire_pong,代码行数:19,代码来源:btle.py

示例13: __init__

 def __init__(self,address):
     """
     address is the yeelight blue ble hardware address
     """
     self.data = dict()
     self.address = address
     self.delegate = YeelightService.NotifyDelegate()
     self.peripher = Peripheral(deviceAddr = address)
     self.service = self.peripher.getServiceByUUID(YeelightService.SERVICE)
     self.peripher.withDelegate(self.delegate)
开发者ID:izhaohui,项目名称:yeelight_blue_python,代码行数:10,代码来源:YeelightService.py

示例14: connect

 def connect(self):
     self.peripheral = Peripheral(self.macAddress, addrType='random')
     # Retrieve all characteristics from desires services and map them from their UUID
     characteristics = list(itertools.chain(*[self.peripheral.getServiceByUUID(uuid).getCharacteristics() for uuid in Nuimo.SERVICE_UUIDS]))
     characteristics = dict((c.uuid, c) for c in characteristics)
     # Store each characteristic's value handle for each characteristic name
     self.characteristicValueHandles = dict((name, characteristics[uuid].getHandle()) for uuid, name in Nuimo.CHARACTERISTIC_UUIDS.items())
     # Subscribe for notifications
     for name in Nuimo.NOTIFICATION_CHARACTERISTIC_UUIDS:
         self.peripheral.writeCharacteristic(self.characteristicValueHandles[name] + 1, Nuimo.NOTIFICATION_ON, True)
     self.peripheral.setDelegate(self.delegate)
开发者ID:shaftoe,项目名称:nuimo-raspberrypi-demo,代码行数:11,代码来源:nuimo.py

示例15: run

    def run(self):
        try:
            monotime = 0.0

            self.SBrickPeripheral = Peripheral()
            self.SBrickPeripheral.connect(self.sBrickAddr)
            service = self.SBrickPeripheral.getServiceByUUID('4dc591b0-857c-41de-b5f1-15abda665b0c')
            characteristics = service.getCharacteristics('02b8cbcc-0e25-4bda-8790-a15f53e6010f')
            for characteristic in characteristics:
                if characteristic.uuid == '02b8cbcc-0e25-4bda-8790-a15f53e6010f':
                    self.characteristicRemote = characteristic

            if self.characteristicRemote is None:
                return

            self.emit('sbrick_connected')

            self.need_authentication = self.get_need_authentication()
            self.authenticated = not self.need_authentication
            if self.need_authentication:
                if self.password_owner is not None:
                    self.authenticate_owner(self.password_owner)

            while not self.stopFlag:
                if self.authenticated:
                    if monotonic.monotonic() - monotime >= 0.05:
                        self.send_command()
                        monotime = monotonic.monotonic()
                    self.eventSend.wait(0.01)
                    for channel in self.brickChannels:
                        if channel.decrement_run_timer():
                            monotime = 0.0
                            self.drivingLock.release()
                            # print("stop run normal")
                            self.emit("sbrick_channel_stop", channel.channel)
                        if channel.decrement_brake_timer():
                            self.drivingLock.release()
                            # print("stop brake timer")
                            monotime = 0.0
                            self.emit("sbrick_channel_stop", channel.channel)

            if self.authenticated:
                self.stop_all()
                self.send_command()
            self.SBrickPeripheral.disconnect()
            self.emit('sbrick_disconnected_ok')
        except BTLEException as ex:
            self.emit("sbrick_disconnected_error", ex.message)
开发者ID:wintersandroid,项目名称:sbrick-controller,代码行数:48,代码来源:SBrickCommunications.py


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