本文整理汇总了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()
示例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
示例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
示例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
示例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
示例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
示例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)
示例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()
示例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]
示例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')
示例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())
示例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
示例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)
示例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
示例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