本文整理汇总了Python中bluepy.btle.Peripheral.setDelegate方法的典型用法代码示例。如果您正苦于以下问题:Python Peripheral.setDelegate方法的具体用法?Python Peripheral.setDelegate怎么用?Python Peripheral.setDelegate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bluepy.btle.Peripheral
的用法示例。
在下文中一共展示了Peripheral.setDelegate方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Nuimo
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
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)
示例2: Yeelight
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
class Yeelight(DefaultDelegate):
WRITE_CHAR_UUID = b"aa7d3f34" # -2d4f-41e0-807f-52fbf8cf7443"
COMMAND_STX = "43"
COMMAND_ETX = "00"
AUTH_CMD = "67"
AUTH_ON = "02"
POWER_CMD = "40"
POWER_ON = "01"
POWER_OFF = "02"
COLOR_CMD = "41"
RGB_MODE = "65"
BRIGHT_CMD = "42"
COLORTEMP_CMD = "43"
TEMP_MODE = "65"
STATUS_CMD = "44"
COLORFLOW_CMD = "4a"
SLEEP_CMD = "7f03"
def __init__(self, address):
DefaultDelegate.__init__(self)
self.__address = address
self.__connect()
# Override
def handleNotification(self, handle, data):
if handle == 21:
format = (
'!xx' # 4345 header
'B' # switch: 01=on 02=off
'B' # mode: 01=rgb 02=warm
'BBBx' # RGB
'B' # Brightness
'H' # temp 2byte 1700 ~ 6500
'xxxxxxx'
)
(switch, mode, r, g, b,
brightness, temp) = struct.unpack(format, data)
if switch != 4:
self._switch = switch
self._mode = mode
self._rgb = '{:02x}{:02x}{:02x}'.format(r, g, b)
self._temp = temp
self._brightness = brightness
def disconnect(self, *args, **kwargs):
return self.__peripheral.disconnect(*args, **kwargs)
def __connect(self):
self.__peripheral = Peripheral(self.__address)
self.__peripheral.setDelegate(self)
characteristics = self.__peripheral.getCharacteristics()
self.__ch = next(iter(filter(lambda x: binascii.b2a_hex(x.uuid.binVal)
.startswith(self.WRITE_CHAR_UUID),
characteristics)))
# Register notification
self.__peripheral.writeCharacteristic(
0x16,
binascii.a2b_hex('0100'))
# Auth
self.__write_cmd(
self.COMMAND_STX +
self.AUTH_CMD +
self.AUTH_ON +
self.COMMAND_ETX * 15)
# Get status
self.__request_status()
def __write_cmd(self, value):
for _ in range(3):
try:
self.__ch.write(binascii.a2b_hex(value))
self.__peripheral.waitForNotifications(1.0)
except BTLEException as e:
error = e
self.__connect()
else:
break
else:
raise error
def __request_status(self):
self.__write_cmd(
self.COMMAND_STX +
self.STATUS_CMD +
self.COMMAND_ETX * 16
)
@property
#.........这里部分代码省略.........
示例3: LightBlueBean
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
class LightBlueBean(DefaultDelegate):
# https://github.com/PunchThrough/bean-documentation/blob/master/app_message_types.md
MSG_ID_SERIAL_DATA = 0x0000
MSG_ID_BT_SET_ADV = 0x0500
MSG_ID_BT_SET_CONN = 0x0502
MSG_ID_BT_SET_LOCAL_NAME = 0x0504
MSG_ID_BT_SET_PIN = 0x0506
MSG_ID_BT_SET_TX_PWR = 0x0508
MSG_ID_BT_GET_CONFIG = 0x0510
MSG_ID_BT_ADV_ONOFF = 0x0512
MSG_ID_BT_SET_SCRATCH = 0x0514
MSG_ID_BT_GET_SCRATCH = 0x0515
MSG_ID_BT_RESTART = 0x0520
MSG_ID_GATING = 0x0550
MSG_ID_BL_CMD = 0x1000
MSG_ID_BL_FW_BLOCK = 0x1001
MSG_ID_BL_STATUS = 0x1002
MSG_ID_CC_LED_WRITE = 0x2000
MSG_ID_CC_LED_WRITE_ALL = 0x2001
MSG_ID_CC_LED_READ_ALL = 0x2002
MSG_ID_CC_LED_DATA = 0x2082
MSG_ID_CC_ACCEL_READ = 0x2010
MSG_ID_CC_ACCEL_DATA = 0x2090
MSG_ID_CC_TEMP_READ = 0x2011
MSG_ID_CC_TEMP_DATA = 0x2091
MSG_ID_CC_BATT_READ = 0x2015
MSG_ID_CC_BATT_DATA = 0x2095
MSG_ID_AR_SET_POWER = 0x3000
MSG_ID_AR_GET_CONFIG = 0x3006
MSG_ID_DB_LOOPBACK = 0xFE00
MSG_ID_DB_COUNTER = 0xFE01
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()
def write(self, data):
self.sendCmd(LightBlueBean.MSG_ID_SERIAL_DATA, data)
def sendCmd(self, cmd, data = ""):
# https://github.com/PunchThrough/bean-documentation/blob/master/serial_message_protocol.md
gst = struct.pack("!BxH", len(data)+2, cmd) + data
crc = struct.pack("<H", crc16(gst, 0xFFFF))
gst += crc
gt_qty = len(gst)/19
if len(gst) % 19 != 0:
gt_qty += 1
#amnt = len(gst) / gt_qty
optimal_packet_size = 19
for ch in xrange(0, gt_qty):
data = gst[:optimal_packet_size]
gst = gst[optimal_packet_size:]
gt = 0
if ch == 0:
gt = 0x80
gt |= self.count << 5
gt |= gt_qty - ch - 1
gt = struct.pack("B", gt) + data
#print("<", hexdump(gt))
self.serial.write(gt)
#time.sleep(0.1)
self.count = (self.count + 1) % 4
def writeRaw(self, data):
self.conn.writeCharacteristic(0x0b, data, False)
def handleNotification(self, cHandle, data):
#print(">", hexdump(data))
gt = struct.unpack("B", data[0]) [0]
#gt_cntr = gt & 0x60
#.........这里部分代码省略.........
示例4: main
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
def main():
# uuid definition
targetDevice = ""
targetUUID = UUID("08590f7e-db05-467e-8757-72f6f66666d4")
# targetUUID = UUID(0x2a2b)
serviceUUID = UUID("e20a39f4-73f5-4bc4-a12f-17d1ad666661")
# scanning for Bluetooth LE device
# P.S. root permission is needed
print "scanning started..."
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(5)
print "\n\nscanning completed...\n found %d device(s)\n" % len(devices)
for dev in devices:
print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
for (adtype, desc, value) in dev.getScanData():
print " %s = %s" % (desc, value)
try:
p = Peripheral(dev.addr, "random")
ch = p.getCharacteristics(uuid=targetUUID)
if len(ch) > 0:
print "the desired target found. the address is", dev.addr
targetDevice = dev.addr
except:
# print "Unexpected error:", sys.exc_info()[0]
print "Unable to connect"
print " "
finally:
p.disconnect()
# scanning completed, now continue to connect to device
if targetDevice == "":
# the target is not found. end.
print "no target was found."
else:
# the target found, continue to subscribe.
print "\n\nthe target device is ", targetDevice
print "now try to subscribe..."
try:
# try to get the handle first
p = Peripheral(targetDevice, "random")
p.setDelegate(NotificationDelegate())
# svc = p.getServiceByUUID(serviceUUID)
ch = p.getCharacteristics(uuid=targetUUID)[0] # svc.getCharacteristics(targetUUID)[0]
handle = ch.getHandle()
print handle
ch.write(struct.pack('<bb', 0x01, 0x00))
# ch.write(bytes('aa', 'utf-8'))
# p.writeCharacteristic(handle, struct.pack('<bb', 0x01, 0x00), True)
print
# Main loop
while True:
if p.waitForNotifications(5):
# handleNotification() was called
continue
print "Waiting..."
# Perhaps do something else here
# except:
# print "Unexpected error:", sys.exc_info()[0]
finally:
p.disconnect()
示例5: OpenBCIGanglion
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
class OpenBCIGanglion(object):
"""
Handle a connection to an OpenBCI board.
Args:
port: MAC address of the Ganglion Board. "None" to attempt auto-detect.
aux: enable on not aux channels (i.e. switch to 18bit mode if set)
impedance: measures impedance when start streaming
timeout: in seconds, if set will try to disconnect / reconnect after a period without new data
-- should be high if impedance check
max_packets_to_skip: will try to disconnect / reconnect after too many packets are skipped
baud, filter_data, daisy: Not used, for compatibility with v3
"""
def __init__(self, port=None, baud=0, filter_data=False,
scaled_output=True, daisy=False, log=True, aux=False, impedance=False, timeout=2,
max_packets_to_skip=20):
# unused, for compatibility with Cyton v3 API
self.daisy = False
# these one are used
self.log = log # print_incoming_text needs log
self.aux = aux
self.streaming = False
self.timeout = timeout
self.max_packets_to_skip = max_packets_to_skip
self.scaling_output = scaled_output
self.impedance = impedance
# might be handy to know API
self.board_type = "ganglion"
print("Looking for Ganglion board")
if port == None:
port = self.find_port()
self.port = port # find_port might not return string
self.connect()
self.streaming = False
# number of EEG channels and (optionally) accelerometer channel
self.eeg_channels_per_sample = 4
self.aux_channels_per_sample = 3
self.imp_channels_per_sample = 5
self.read_state = 0
self.log_packet_count = 0
self.packets_dropped = 0
self.time_last_packet = 0
# Disconnects from board when terminated
atexit.register(self.disconnect)
def getBoardType(self):
""" Returns the version of the board """
return self.board_type
def setImpedance(self, flag):
""" Enable/disable impedance measure """
self.impedance = bool(flag)
def connect(self):
""" Connect to the board and configure it. Note: recreates various objects upon call. """
print("Init BLE connection with MAC: " + self.port)
print("NB: if it fails, try with root privileges.")
self.gang = Peripheral(self.port, 'random') # ADDR_TYPE_RANDOM
print("Get mainservice...")
self.service = self.gang.getServiceByUUID(BLE_SERVICE)
print("Got:" + str(self.service))
print("Get characteristics...")
self.char_read = self.service.getCharacteristics(BLE_CHAR_RECEIVE)[0]
print("receive, properties: " + str(self.char_read.propertiesToString()) +
", supports read: " + str(self.char_read.supportsRead()))
self.char_write = self.service.getCharacteristics(BLE_CHAR_SEND)[0]
print("write, properties: " + str(self.char_write.propertiesToString()) +
", supports read: " + str(self.char_write.supportsRead()))
self.char_discon = self.service.getCharacteristics(BLE_CHAR_DISCONNECT)[0]
print("disconnect, properties: " + str(self.char_discon.propertiesToString()) +
", supports read: " + str(self.char_discon.supportsRead()))
# set delegate to handle incoming data
self.delegate = GanglionDelegate(self.scaling_output)
self.gang.setDelegate(self.delegate)
# enable AUX channel
if self.aux:
print("Enabling AUX data...")
try:
self.ser_write(b'n')
except Exception as e:
print("Something went wrong while enabling aux channels: " + str(e))
print("Turn on notifications")
# nead up-to-date bluepy, cf https://github.com/IanHarvey/bluepy/issues/53
self.desc_notify = self.char_read.getDescriptors(forUUID=0x2902)[0]
try:
self.desc_notify.write(b"\x01")
except Exception as e:
#.........这里部分代码省略.........
示例6: UUID
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
p.writeCharacteristic(handler, struct.pack('<bb', 0x00, 0x00) ,False)
#UUID 가져온다.
washer_service_uuid = UUID("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
battery_service_uuid = UUID("180F")
#washer service Characteristics의 센서에서 전송하는 정보이며 Access Permisson은 Notify
washerTX_char_uuid = UUID("6e400003-b5a3-f393-e0a9-e50e24dcca9e")
battery_level_uuid = UUID("00002a19-0000-1000-8000-00805f9b34fb")
#if len(sys.argv) != 2:
# print ("Fatal, must pass device address:", sys.argv[0], "<device address="">")
# quit()
p = Peripheral("c7:74:31:9A:F8:D1","random")
p.setDelegate( MyDelegate(p) )
#WasherService, BatteryService를 가져온다.
WasherService=p.getServiceByUUID(washer_service_uuid)
BatteryService =p.getServiceByUUID(battery_service_uuid)
#TX의 Characteristics를 가져온다.
WasherTX_C = WasherService.getCharacteristics(washerTX_char_uuid)[0]
#battey의 Characteristics를 가져온다.
Battery_C = BatteryService.getCharacteristics(battery_level_uuid)[0]
# Client Characteristic Descriptor의 handler
# 0x13 은 washerTX, 0x0F는 battery
# notifications의 비트를 1로 바꿔 활성화한다.
示例7: len
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
if len(sys.argv) != 2:
print "Fatal, must pass device address:", sys.argv[0], "<device address>"
quit()
try:
print "Info, trying to connect to:", sys.argv[1]
p = Peripheral(sys.argv[1])
print "Info, connected and turning notify and sensor on!"
ch = p.getCharacteristics(uuid=config_uuid)[0]
ch.write(sensorOn, withResponse=True)
# With bluepy if you need to read or write a Descriptor you have to
# access it using Peripheral readCharacteristic or writeCharacteristic
# and the appropriate handle
p.setDelegate( MyDelegate("keys") )
p.writeCharacteristic(notifyHnd, notifyOn)
while True:
try:
if p.waitForNotifications(1.0):
# handleNotification() was called
if keys & 0x01:
print "Info, Right Button"
if keys & 0x02:
print "Info, Left Button"
if keys & 0x04:
print "Info, Reed Switch"
except KeyboardInterrupt:
print "exiting..."
示例8: onBtleData
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
def onBtleData(data):
print "got data: " + data.getName().toUri()
el = BtleNode(onBtleData, None, None)
em = ElementReader(el)
class MyDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
em.onReceivedData(data[2:])
p.setDelegate(MyDelegate())
p.writeCharacteristic(p.getCharacteristics(uuid=my_uuid)[0].valHandle + 1, "\x01\x00")
while True:
if p.waitForNotifications(1.0):
continue
"""
try:
#p.writeCharacteristic(0x2221, bytes(0x01), True)
#print p.getCharacteristics()
ch = p.getCharacteristics(uuid=my_uuid)[0]
if (ch.supportsRead()):
while True:
val = ch.read()
print binascii.hexlify(bytearray(val))
示例9: BtlePeripheral
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
class BtlePeripheral():
def __init__(self, addr, producer, loop, receive_uuid = 0x2221, send_uuid = 0x2222, security = False):
self._addr = addr
self._producer = producer
self._receive_uuid = receive_uuid
self._send_uuid = send_uuid
self._loop = loop
self._security = security
self._p = None
def start(self):
# init btle ElementReader
el = BtleNode(self._producer.onBtleData, None, None)
em = ElementReader(el)
class MyDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
# TODO: this should handle incorrect format caused by packet losses
try:
em.onReceivedData(data[2:])
except ValueError as e:
print "Decoding value error: " + str(e)
# connect ble
while not self._p:
try:
self._p = Peripheral(self._addr, "random")
except BTLEException as e:
print "Failed to connect: " + str(e) + "; trying again"
self._p = None
# tell rfduino we are ready for notifications
self._p.setDelegate(MyDelegate())
self._p.writeCharacteristic(self._p.getCharacteristics(uuid = self._receive_uuid)[0].valHandle + 1, "\x01\x00")
self._loop.create_task(self.btleNotificationListen())
if self._security:
# send our public key if configured to do so
print "security on, sending our public key"
interest = self._producer.makePublicKeyInterest()
# write characteristics
data = interest.wireEncode().toRawStr()
num_fragments = int(math.ceil(float(len(data)) / 18))
print "length of data: " + str(len(data)) + "; number of fragments: " + str(num_fragments)
current = 0
for i in range(0, num_fragments - 1):
fragment = struct.pack(">B", i) + struct.pack(">B", num_fragments) + data[current:current + 18]
current += 18
self._p.writeCharacteristic(self._p.getCharacteristics(uuid = self._send_uuid)[0].valHandle, fragment)
print " ".join(x.encode('hex') for x in fragment)
fragment = struct.pack(">B", num_fragments - 1) + struct.pack(">B", num_fragments) + data[current:]
self._p.writeCharacteristic(self._p.getCharacteristics(uuid = self._send_uuid)[0].valHandle, fragment)
print " ".join(x.encode('hex') for x in fragment)
@asyncio.coroutine
def btleNotificationListen(self):
try:
while True:
if self._p.waitForNotifications(0.2):
pass
time.sleep(0.01)
yield None
except BTLEException as e:
print("Btle exception: " + str(e) + "; try to restart")
self._p = None
self.start()
示例10: handleNotification
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import setDelegate [as 别名]
DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
print "inside notification"
print "Heart rate:", ord(data[1]), "Energy=" ,int(binascii.b2a_hex((data[::-1])[0:2]),16) # This script was tested on ubuntu 14.04
# To solve the endianess problem reverse the
# string to find exact value
devices = Scanner() # Scanner Object
temp=devices.scan(10) # Start Scan
try:
for dev in temp:
if dev.getScanData()[3][2] == "mr. singh": # Check for the target BLE device name
if dev.connectable:
p = Peripheral(dev.addr, "random")
p.setDelegate(ScanDelegate()) # Create internal Object of scandelegate class to handle the notifications
except (RuntimeError, TypeError, NameError):
print "Device not found"
exit(1)
################### Check for the Services and its characteristics #################
print p.getServices()[0]
print p.getServices()[1]
print p.getServices()[2]
Heart_Rate_Measurement = p.getServiceByUUID(0x180D).getCharacteristics()[0]
Body_Sensor_Location = p.getServiceByUUID(0x180D).getCharacteristics()[1]
Heart_Rate_Control_Point = p.getServiceByUUID(0x180D).getCharacteristics()[2]
print Heart_Rate_Measurement , Heart_Rate_Measurement.uuid # Print characteristic and its uuid
print Body_Sensor_Location , Body_Sensor_Location.uuid
print Heart_Rate_Control_Point , Heart_Rate_Control_Point.uuid
################## Print the Value ###########################