本文整理汇总了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:
#.........这里部分代码省略.........
示例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)
示例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)
示例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
示例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)
示例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)
示例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 = {}
示例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()
示例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
示例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
示例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
示例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')
示例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)
示例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)
示例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)