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


Python Peripheral.getCharacteristics方法代码示例

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


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

示例1: Peripheral

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
  print "Info, trying to connect to:", sys.argv[1]
  p = Peripheral(sys.argv[1])

except BTLEException:
  print "Fatal, unable to connect!"
  
except:
  print "Fatal, unexpected error!"
  traceback.print_exc()
  raise

else:

  try:
    print "Info, connected and turning sensor on!"
    ch = p.getCharacteristics(uuid=config_uuid)[0]
    ch.write(sensorOn, withResponse=True)
    
    print "Info, reading values!"
    ch = p.getCharacteristics(uuid=data_uuid)[0]
    
    rawVals = ch.read()
    rawVal = (ord(rawVals[1])<<8)+ord(rawVals[0])
    
    #object temp and ambient temp are calculated as shown below
    mantissa = rawVal & 0x0FFF;
    exponent = (rawVal >> 12) & 0xFF;

    magnitude = pow(2.0, exponent);
    output = (mantissa * magnitude);
    
开发者ID:digitalhack,项目名称:dhSensorTag2015,代码行数:32,代码来源:getLuxometer.py

示例2: UUID

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
from bluepy.btle import UUID, Peripheral

# Message constants
MSG_LOCK = 0x10
MSG_UNLOCK = 0x11
MSG_STATE_REQ = 0x12

# Define read and write UUIDs
read_uuid = UUID(0x2221)
write_uuid = UUID(0x2222)

# Create a connection to the RFduino
#p = Peripheral("F9:D8:C2:B9:77:E9", "random")
p = Peripheral("D4:2C:92:60:C2:D5", "random")


try:

    # Create handles for read and write characteristics
    w_ch = p.getCharacteristics(uuid=write_uuid)[0]
    r_ch = p.getCharacteristics(uuid=read_uuid)[0]

    # Tell the Lockitron to lock
    msg = struct.pack('i', MSG_LOCK)
    print "Writing: " + str(msg)
    w_ch.write(msg)

finally:
    p.disconnect()

开发者ID:sparkfun,项目名称:IoT_Airlock,代码行数:31,代码来源:lock.py

示例3: Peripheral

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
    # p = Peripheral("D9:35:6A:75:9F:9D", "random") # Rfduino sur usb
    continuer = True
    while(continuer):
        try:
            p = Peripheral("D1:7F:06:ED:66:DC", "random")  # Rfduino sur pcb
            continuer = False
        except:
            print "Module bluetooth deja connecte, nouvel essai dans 3 sec..."
            time.sleep(3)
    p.withDelegate(MyDelegate())
    Analyser.set_p(p)
    print " device connected..."

    try:
        p.getServices()
        ch = p.getCharacteristics(uuid=rx_uuid)[0]
        print ("notify characteristic with uuid 0x" + rx_uuid.getCommonName())
        cccid = btle.AssignedNumbers.client_characteristic_configuration
        # Ox000F : handle of Client Characteristic Configuration descriptor Rx - (generic uuid 0x2902)
        p.writeCharacteristic(0x000F, struct.pack('<bb', 0x01, 0x00), False)

        if ch.supportsRead():
            while 1:
                p.waitForNotifications(604800)  # 1 semaine d'attente
                # handleNotification() was called
                continue

    finally:
        Analyser.ls.close()
        p.disconnect()
开发者ID:Erennor,项目名称:vibrato,代码行数:32,代码来源:BLEreading.py

示例4: UUID

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
import sys
from bluepy.btle import UUID, Peripheral

temp_uuid = UUID(0x2A00)

if len(sys.argv) != 2:
  print "Fatal, must pass device address:", sys.argv[0], "<device address>"
  quit()

p = Peripheral(sys.argv[1])

try:
    ch = p.getCharacteristics(uuid=temp_uuid)[0]
    if (ch.supportsRead()):
            print ch.read()

finally:
    p.disconnect()
开发者ID:digitalhack,项目名称:dhSensorTag2015,代码行数:20,代码来源:getDeviceName.py

示例5: Yeelight

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [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
#.........这里部分代码省略.........
开发者ID:Kjwon15,项目名称:yeelight,代码行数:103,代码来源:yeelight.py

示例6: main

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
def main():

    global g_mainloop
    global g_command

    # Reset camera to prevent black/pink images on first run through
    pygame.camera.init()
    cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
    cam.start()
    img = cam.get_image()
    pygame.image.save(img, IMG_NAME)
    cam.stop()
    pygame.camera.quit()
    img = None

    # Initialize GPIO
    in_success = mraa.Gpio(SUCCESS_PIN)
    in_failure = mraa.Gpio(FAILURE_PIN)
    in_status_0 = mraa.Gpio(STATUS_PIN_0)
    in_status_1 = mraa.Gpio(STATUS_PIN_1)
    doorbell = mraa.Gpio(DOORBELL_PIN)
    reed_outer = mraa.Gpio(REED_OUTER_PIN)
    reed_inner = mraa.Gpio(REED_INNER_PIN)
    deny_button = mraa.Gpio(DENY_PIN)
    approve_button = mraa.Gpio(APPROVE_PIN)
    prev_success = 0
    prev_failure = 0
    prev_approve = 0
    prev_doorbell = 0
    prev_deny = 0

    # Set direction of GPIO
    in_success.dir(mraa.DIR_IN)
    in_failure.dir(mraa.DIR_IN)
    in_status_0.dir(mraa.DIR_IN)
    in_status_1.dir(mraa.DIR_IN)
    doorbell.dir(mraa.DIR_IN)
    reed_outer.dir(mraa.DIR_IN)
    reed_inner.dir(mraa.DIR_IN)
    deny_button.dir(mraa.DIR_IN)
    approve_button.dir(mraa.DIR_IN)
    
    # Create Bluetooth connections to the RFduinos on the doors
    if DEBUG > 0:
        print 'Connecting to RFduinos...'
    inner_door = Peripheral(INNER_ADDR, 'random')
    outer_door = Peripheral(OUTER_ADDR, 'random')
    
    # Create handles to the Bluetooth read and write characteristics
    inner_r_ch = inner_door.getCharacteristics(uuid=READ_UUID)[0]
    inner_w_ch = inner_door.getCharacteristics(uuid=WRITE_UUID)[0]
    outer_r_ch = outer_door.getCharacteristics(uuid=READ_UUID)[0]
    outer_w_ch = outer_door.getCharacteristics(uuid=WRITE_UUID)[0]
    
    # Set up camera
    pygame.camera.init()
    cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
    
    # Connect to Twitter
    if DEBUG > 0:
        print 'Connecting to Twitter...'
    tf = TweetFeed({'app_key': APP_KEY, \
                    'app_secret': APP_SECRET, \
                    'oauth_token': OAUTH_TOKEN, \
                    'oauth_token_secret': OAUTH_TOKEN_SECRET})

    # Send a good morning Tweet
    tf.tweet(ONLINE_MSG)

    # Register 'ctrl+C' signal handler
    signal.signal(signal.SIGINT, signalHandler)

    # Main loop
    g_mainloop = True
    if DEBUG > 0:
        print 'Starting door'
    while g_mainloop:
        
        # Poll pins for success or failure (falling edge)
        state_success = in_success.read()
        state_failure = in_failure.read()
        state_doorbell = doorbell.read()
        state_deny = deny_button.read()
        state_approve = approve_button.read()
        
        # Look for success in access panel
        if (state_success == 0) and (prev_success == 1):
            openDoor(inner_door, inner_w_ch, reed_inner)
            person_ind = (2 * in_status_1.read()) + in_status_0.read()
            if person_ind == 0:
                if DEBUG > 0:
                    print 'Success!'
                    print 'No one in particular.'
                tf.tweet(SUCCESS_MSG)
            else:
                if DEBUG > 0:
                    print 'Success!'
                    print 'Person = ' + NAMES[person_ind - 1]
                tf.tweet(SUCCESS_MSG + NAMES[person_ind - 1])

#.........这里部分代码省略.........
开发者ID:sparkfun,项目名称:IoT_Airlock,代码行数:103,代码来源:door.py

示例7: UUID

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
import binascii
import struct
import time
from bluepy.btle import UUID, Peripheral

uuid = UUID("d96a513d-a6d8-4f89-9895-ca131a0935cb")

p = Peripheral("00:07:80:77:C4:5A", "public")

try:
    ch = p.getCharacteristics()[0]
    if (ch.supportsRead()):
        while 1:
            val = binascii.b2a_hex(ch.read())
            print str(val) + ""
            time.sleep(1)

finally:
    p.disconnect()
开发者ID:ehime,项目名称:library-mimobabymonitor,代码行数:21,代码来源:readturtle.py

示例8: BleCam

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
class BleCam(object):
    locked = True
    
    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)

    def _ipcamservice(self):
        try:
            print("Verifying IPCam service")
            self.service = self.periph.getServiceByUUID(0xd001)
            self.handles = self.service.getCharacteristics()
        except BTLEEException:
            print("no IPCam service found for %s" % periph.address)

    def dumpchars(self):
        print("%s supports these characteristics:" % self.name)
        for h in self.handles:
            print("%s - Handle=%#06x (%s)" % (h.uuid, h.getHandle(), h.propertiesToString()))

    def unlock(self):
        if not self.locked:
            return True
        auth = self.service.getCharacteristics(0xa001)[0]
        state = kv2dict(auth.read().decode())

        # already unlocked?
        if state["M"] == 0:
            self.locked = False
            return True

        self.challenge = state["C"]
        hashit = self.name + self.pincode + self.challenge
        self.key = base64.b64encode(hashlib.md5(hashit.encode()).digest())[:16]
        try:
            auth.write("M=0;K=".encode() + self.key, True)
            self.locked = False
        except:
            print("ERROR: failed to unlock %s - wrong pincode?" % self.name)
        return not self.locked

    def get_ipconfig(self):
        if not self.unlock(): return
        return kv2dict(self.service.getCharacteristics(0xa104)[0].read().decode())

    def get_wificonfig(self):
        if not self.unlock(): return
        return kv2dict(self.service.getCharacteristics(0xa101)[0].read().decode())

    def wifilink(self):
        if not self.unlock(): return
        r = kv2dict(self.service.getCharacteristics(0xa103)[0].read().decode())
        return r["S"] == "1"

    def sysinfo(self):
        if not self.unlock(): return
        return kv2dict(self.service.getCharacteristics(0xa200)[0].read().decode())

    def setup_wifi(self, essid, passwd):
        for net in self.wifi_scan():
            if net["I"] == essid:
                cfg = "M=" + net["M"] + ";I=" + essid + ";S=" + net["S"] + ";E=" + net["E"] + ";K=" + passwd
                print("Will configure: %s" % cfg)
                self.service.getCharacteristics(0xa101)[0].write(cfg.encode(), True)
                self.service.getCharacteristics(0xa102)[0].write("C=1".encode(), True)
                return True
        print("%s cannot see the '%s' network" % (self.name, essid))
        return False
    
    def wifi_scan(self):
        def _wifi2dict(wifistr):
            return kv2dict(wifistr[2:], ",")
        
        if not self.unlock(): return
        print("%s is scanning for WiFi networks..." % self.name)
        scan = self.service.getCharacteristics(0xa100)[0]
        p = -1
        n = 0
        result = ""
        while p < n:
            t = scan.read().decode().split(";", 3)
            result = result + t[2]
            if not t[0].startswith("N=") or not t[1].startswith("P="):
                return
            n = int(t[0].split("=",2)[1])
            p = int(t[1].split("=",2)[1])
            # print("read page %d of %d" % (p, n))
        return map(_wifi2dict, result.split("&", 50))
                    
    def run_command(self, command):
        if not self.unlock(): return
        
        run = "P=" + self.pincode + ";N=" + self.pincode + "&&(" + command + ")&"
        if len(run) > 128:
            print("ERROR: command is too long")
            return
#.........这里部分代码省略.........
开发者ID:bmork,项目名称:defogger,代码行数:103,代码来源:dcs8000lh-configure.py

示例9: main

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [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()
开发者ID:gtrdp,项目名称:cs-rug-internship,代码行数:70,代码来源:bluetooth-server.py

示例10: print

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]

service = p.getServiceByUUID(Service_UUID)


for Character in service.getCharacteristics():
  print(Character.uuid)
  for x in range(len(MainCharacteristics_head)):
    if Character.uuid.getCommonName().startswith(MainCharacteristics_head[Characteristics[x]]):
      print(Characteristics[x]," Get!")
      MainCharacteristics[Characteristics[x]] = Character.uuid
    pass
  


Balance_GATT = p.getCharacteristics(uuid=MainCharacteristics['Balance_UUID'])[0]


print(AES_Key)
print(len(AES_Key))

AES_Key  =  bytes(bytearray.fromhex(AES_Key) )
print(AES_Key)
print(len(AES_Key))
print("IV:",_IV.hex())


print("Writing Balance msg...")


addr = bytearray.fromhex(Address) 
开发者ID:crossgate10,项目名称:HITCON-Badge-2018,代码行数:32,代码来源:updateBalance.py

示例11: print

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]

service = p.getServiceByUUID(Service_UUID)


for Character in service.getCharacteristics():
  print(Character.uuid)
  for x in range(len(MainCharacteristics_head)):
    if Character.uuid.getCommonName().startswith(MainCharacteristics_head[Characteristics[x]]):
      print(Characteristics[x]," Get!")
      MainCharacteristics[Characteristics[x]] = Character.uuid
    pass
  


Transaction_GATT = p.getCharacteristics(uuid=MainCharacteristics['Transaction_UUID'])[0]


print("Writing Tx msg...")


addr = bytearray.fromhex(sys.argv[1]) 
Value_eth = float(sys.argv[2])
GasPrice_int = int(sys.argv[3])
GasLimit_int = int(sys.argv[4])
Noice_int = int(sys.argv[5])
data_byte = bytearray.fromhex(sys.argv[6]) 


Value_int = int(Value_eth*1000000000*1000000000)
开发者ID:crossgate10,项目名称:HITCON-Badge-2018,代码行数:31,代码来源:tx.py

示例12: TempSensor

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [as 别名]
class TempSensor(object):
  _scanning_lock = threading.Lock()

  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 = {}

  def connect(self):
    self.tag.connect()

  def disconnect(self):
    self.tag.disconnect()

  def get_ambient_temp(self):
    pass

  def _write_uuid(self, uuid, data):
    try:
      if not uuid in self.characteristics:
        self.characteristics[uuid] = self.peripheral.getCharacteristics(uuid=uuid)[0]

      #If there's still no characteristic, error
      if not uuid in self.characteristics:
        raise Exception('UUID ' + str(uuid) + ' not found on device ' + self.mac)

      self.characteristics[uuid].write(data)
    except BTLEException as e:
      logger.warn(self.mac + ' disconnected. Try to reconnect.')
      raise DisconnectedException(e.message)

  def _read_uuid(self, uuid):
    try:
      if not uuid in self.characteristics:
        self.characteristics[uuid] = self.peripheral.getCharacteristics(uuid=uuid)[0]

      #If there's still no characteristic, error
      if not uuid in self.characteristics:
        raise Exception('UUID ' + str(uuid) + ' not found on device ' + self.mac)

      return self.characteristics[uuid].read()
    except BTLEException as e:
      logger.warn(self.mac + ' disconnected. Try to reconnect.')
      raise DisconnectedException(e.message)

  @staticmethod
  def find_temp_sensors(sensors):
    TempSensor._scanning_lock.acquire()
    logger.debug('Scanning for devices')
    scanner = Scanner().withDelegate(ScanDelegate())
    try:
      devices = scanner.scan(10.0)
      if sensors is None:
        sensors = {}
      for device in devices:
        if device.addr in sensors:
          continue
        name = ''
        if device.getValueText(9):
          name = device.getValueText(9)
        elif device.getValueText(8):
          name = device.getValueText(8)
        logger.debug('Device name: ' + name)
        if 'SensorTag' in name:
          logger.info('Found SensorTag with address: ' + device.addr)
          sensors[device.addr] = SensorTag(device)
        elif 'MetaWear' in name:
          logger.info('Found MetaWear with address: ' + device.addr)
          sensors[device.addr] = MetaWear(device)
      logger.debug('Finished scanning for devices')
      TempSensor._scanning_lock.release()
      if len(sensors) == 0:
        raise NoTagsFoundException('No sensors found!')
    except BTLEException as e:
      scanner.stop()
      logger.warn('Got exception ' + e.message)
      TempSensor._scanning_lock.release()
    return sensors
开发者ID:daviessm,项目名称:heating,代码行数:83,代码来源:temp_sensor.py

示例13: onBtleData

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [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))
            if len(val) > 5:
开发者ID:remap,项目名称:ndn-flow,代码行数:33,代码来源:ble_test.py

示例14: BtlePeripheral

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getCharacteristics [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()    
开发者ID:remap,项目名称:ndn-flow,代码行数:73,代码来源:rpi_helper.py


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