當前位置: 首頁>>代碼示例>>Python>>正文


Python btle.Peripheral方法代碼示例

本文整理匯總了Python中bluepy.btle.Peripheral方法的典型用法代碼示例。如果您正苦於以下問題:Python btle.Peripheral方法的具體用法?Python btle.Peripheral怎麽用?Python btle.Peripheral使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在bluepy.btle的用法示例。


在下文中一共展示了btle.Peripheral方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _dispatch_calls

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def _dispatch_calls(self):
        self._peripheral = btle.Peripheral(self._addr, self._addrType, self._iface_number)
        try:
            while not self._disconnect_event.is_set():
                try:
                    try:
                        method = self._call_queue.get(False)
                        method()
                    except queue.Empty:
                        pass
                    self._peripheral.waitForNotifications(1.)
                except Exception as ex:
                    log.exception('Exception in call dispatcher thread', exc_info=ex)
                    if PROPAGATE_DISPATCHER_EXCEPTION:
                        log.error("Terminating dispatcher thread.")
                        raise
        finally:
            self._peripheral.disconnect() 
開發者ID:undera,項目名稱:pylgbst,代碼行數:20,代碼來源:cbluepy.py

示例2: __init__

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def __init__ (self, mac, mesh_name = "unpaired", mesh_password = "1234"):
        """
        Args :
            mac: The light's MAC address as a string in the form AA:BB:CC:DD:EE:FF
            mesh_name: The mesh name as a string.
            mesh_password: The mesh password as a string.
        """
        self.mac = mac
        self.mesh_id = 0
        self.btdevice = btle.Peripheral ()
        self.session_key = None
        self.mesh_name = mesh_name.encode ()
        self.mesh_password = mesh_password.encode ()
        
        # Light status
        self.white_brightness = None
        self.white_temp = None
        self.red = None
        self.green = None
        self.blue = None 
開發者ID:Leiaz,項目名稱:python-awox-mesh-light,代碼行數:22,代碼來源:__init__.py

示例3: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def connect(self, retries=1):
        tries = 0
        while (tries < retries and self.is_connected() is False):
            tries += 1
            if self.mac_addr is None:
                self.mac_addr = self.discover()
            try:
                self._periph = btle.Peripheral(self.mac_addr)
                self._datetime_char = self._periph.getCharacteristics(uuid=self.DATETIME_UUID)[0]
                self._humidity_char = self._periph.getCharacteristics(uuid=self.HUMIDITY_UUID)[0]
                self._temperature_char = self._periph.getCharacteristics(uuid=self.TEMPERATURE_UUID)[0]
                self._radon_sta_char = self._periph.getCharacteristics(uuid=self.RADON_STA_UUID)[0]
                self._radon_lta_char = self._periph.getCharacteristics(uuid=self.RADON_LTA_UUID)[0]
            except Exception:
                if tries == retries:
                    raise
                else:
                    pass 
開發者ID:Airthings,項目名稱:wave-reader,代碼行數:20,代碼來源:read_wave.py

示例4: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def connect(self):
       if self.tx_active or self.address=="":
        return False
       self.tx_start = millis()
       if self.tx_start<self.nexttransmit:
        print("Next possible transmit ",self.nexttransmit)
        return False
       self.tx_active = True
       try:
        self.periph = Peripheral(self.address)
       except Exception as e: 
#        print("connect error",e)
        self.tx_active = False
        self.tx_end = millis()
        return False
       try:
        self.service = self.periph.getServiceByUUID(BLE_SERVICE_ID)
       except Exception as e:
#        print("service error ",e)
        self.tx_active = False
        self.tx_end = millis()
        return False
       return True 
開發者ID:enesbcs,項目名稱:rpieasy,代碼行數:25,代碼來源:_C021_BLEDirect.py

示例5: firmware_version

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def firmware_version(self):
        if (self.battery==255) or (self._firmware_version=="") or (datetime.now() - timedelta(hours=1) > self._fw_last_read) and (self.busy==False): # 1 hour timeout fixed
          self._fw_last_read = datetime.now()
          try:
            self.busy = True
            peripheral = btle.Peripheral(self.address,iface=self.interface)
            received_bytes = bytearray(peripheral.readCharacteristic(_HANDLE_READ_VERSION_BATTERY))
            self.battery = received_bytes[0]
            self._firmware_version = "".join(map(chr, received_bytes[2:]))
            peripheral.disconnect()
            self.busy = False
          except:
            self.busy = False
            self.battery = 255
            self._firmware_version = ""
        return self._firmware_version 
開發者ID:enesbcs,項目名稱:rpieasy,代碼行數:18,代碼來源:lib_miflora.py

示例6: __enter__

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def __enter__(self):
        """
        Context manager __enter__ for connecting the device
        :rtype: btle.Peripheral
        :return:
        """
        self._conn = btle.Peripheral()
        self._conn.withDelegate(self)
        _LOGGER.debug("Trying to connect to %s", self._mac)
        try:
            self._conn.connect(self._mac)
        except btle.BTLEException as ex:
            _LOGGER.debug("Unable to connect to the device %s, retrying: %s", self._mac, ex)
            try:
                self._conn.connect(self._mac)
            except Exception as ex2:
                _LOGGER.debug("Second connection try to %s failed: %s", self._mac, ex2)
                raise

        _LOGGER.debug("Connected to %s", self._mac)
        return self 
開發者ID:rytilahti,項目名稱:python-eq3bt,代碼行數:23,代碼來源:connection.py

示例7: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def connect(self, mac: str):
        """Connect to a device."""
        from bluepy.btle import Peripheral
        match_result = re.search(r'hci([\d]+)', self.adapter)
        if match_result is None:
            raise BluetoothBackendException(
                'Invalid pattern "{}" for BLuetooth adpater. '
                'Expetected something like "hci0".'.format(self.adapter))
        iface = int(match_result.group(1))
        self._peripheral = Peripheral(mac, iface=iface, addrType=self.address_type) 
開發者ID:ChristianKuehnel,項目名稱:btlewrap,代碼行數:12,代碼來源:bluepy.py

示例8: get_data

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def get_data(self, now = None):
        try:
            from bluepy import btle

            p = btle.Peripheral(self.address)

            #self.name = ''.join(map(chr, p.readCharacteristic(0x3)))
            #self.firmware = ''.join(map(chr, p.readCharacteristic(0x24)))
            if self.last_battery is None or (utcnow() - self.last_battery).seconds >= 3600:
                self.battery = p.readCharacteristic(0x18)[0]
                self.last_battery = utcnow()

            delegate = XiomiHygroThermoDelegate()
            p.withDelegate( delegate )
            p.writeCharacteristic(0x10, bytearray([1, 0]), True)
            while not delegate.received:
                p.waitForNotifications(30.0)

            self.temperature = delegate.temperature
            self.humidity = delegate.humidity

            ok = True
        except Exception as ex:
            if isinstance(ex, btle.BTLEException):
                _LOGGER.warning("BT connection error: {}".format(ex))
            else:
                _LOGGER.error("Unexpected error: {}".format(ex))
            ok = False

        for i in [0, 1]:
            changed = self.entities[i].set_state(ok, self.battery, self.temperature if i == 0 else self.humidity)
            if (not now is None) and changed:
                self.entities[i].async_schedule_update_ha_state() 
開發者ID:dolezsa,項目名稱:Xiaomi_Hygrothermo,代碼行數:35,代碼來源:sensor.py

示例9: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def connect(self):
        # Auto-discover device on first connection
        if (self.MacAddr is None):
            scanner     = Scanner().withDelegate(DefaultDelegate())
            searchCount = 0
            while self.MacAddr is None and searchCount < 50:
                devices      = scanner.scan(0.1) # 0.1 seconds scan period
                searchCount += 1
                for dev in devices:
                    ManuData = dev.getValueText(255)
                    SN = parseSerialNumber(ManuData)
                    if (SN == self.SN):
                        self.MacAddr = dev.addr # exits the while loop on next conditional check
                        break # exit for loop
            
            if (self.MacAddr is None):
                print "ERROR: Could not find device."
                print "GUIDE: (1) Please verify the serial number."
                print "       (2) Ensure that the device is advertising."
                print "       (3) Retry connection."
                sys.exit(1)
        
        # Connect to device
        if (self.periph is None):
            self.periph = Peripheral(self.MacAddr)
        if (self.curr_val_char is None):
            self.curr_val_char = self.periph.getCharacteristics(uuid=self.uuid)[0] 
開發者ID:Airthings,項目名稱:waveplus-reader,代碼行數:29,代碼來源:read_waveplus.py

示例10: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def connect(self):
        self.p = Peripheral(self.addr, addrType=ADDR_TYPE_PUBLIC)
        self.p.setDelegate(NotifyDelegate())
        # Start listening for notification
        self.p.writeCharacteristic(0x39,b'\x01\x00') 
開發者ID:pentestpartners,項目名稱:snippets,代碼行數:7,代碼來源:unlock-bozzys.py

示例11: setAddr

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def setAddr(self,addr):
        self.addr=addr
        self.p = Peripheral(self.addr, addrType=ADDR_TYPE_PUBLIC)
        self.p.setDelegate(NotifyDelegate()) 
開發者ID:pentestpartners,項目名稱:snippets,代碼行數:6,代碼來源:unlock-nokelock.py

示例12: __init__

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def __init__(self, mac, notification_timeout=5.0):
        self._mac = mac
        self._peripheral = btle.Peripheral()
        self._notification_timeout = notification_timeout
        self._handles = {}
        self._tz_offset = None
        self._data = SensorData(None, None)
        self._history_data = collections.OrderedDict()
        self._context_depth = 0 
開發者ID:h4,項目名稱:lywsd02,代碼行數:11,代碼來源:client.py

示例13: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def connect(self):
        self._p = Peripheral(deviceAddr=self._mac, iface=self._iface)
        self._p.setDelegate(self) 
開發者ID:drndos,項目名稱:mikettle,代碼行數:5,代碼來源:mikettle.py

示例14: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def connect(mac_list, debug=False):
    #Try to connect to each device in mac_list in order, returning after the first successful connection, or returning None after all attempts fail.
    device=None
    for mac in mac_list:
        try:
            if debug:
                print("[+] Connecting to device %s" % mac)
            device = btle.Peripheral(mac, addrType=btle.ADDR_TYPE_PUBLIC)
            return device
        except btle.BTLEException as err:
            if debug:
                print("[-] A connection error has occured: %s" % str(err))
    return None 
開發者ID:nkaminski,項目名稱:csrmesh,代碼行數:15,代碼來源:gatt.py

示例15: send_packet

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Peripheral [as 別名]
def send_packet(dest, handle, p, debug=False):
    #Send the packet, dest may either be one or more MAC addresses represented as a comma separated string, or a btle.Peripheral object connected to the target
    #First 20 bytes to handle, if more than 20 bytes send the next bytes to handle+3

    #Make a connection if we were given an address, otherwise reuse the handle we were given
    if isinstance(dest, btle.Peripheral):
        if debug:
            print("[+] Reusing connection handle")
        device=dest
    else:
        device=connect(dest.split(','), debug)
        if not device:
            if debug:
                print("[-] Connection to mesh failed")
            return False

    #Write to the device
    try:
        gatt_write(device, handle, p[0:20], debug)
        if len(p) > 20:
            gatt_write(device, handle+3, p[20:], debug)

    except btle.BTLEException as err:
        if debug:
            print("[-] A communication error has occured: %s" % str(err))
        return False

    finally:
        #Disconnect from the device, but only if we made the connection
        if not isinstance(dest, btle.Peripheral):
            disconnect(device, debug)
        if debug:
            print("[+] Communication complete")

    return True 
開發者ID:nkaminski,項目名稱:csrmesh,代碼行數:37,代碼來源:gatt.py


注:本文中的bluepy.btle.Peripheral方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。