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


Python Peripheral.writeCharacteristic方法代码示例

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


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

示例1: RileyLink

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

示例2: Nuimo

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import writeCharacteristic [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)
开发者ID:mikesmth,项目名称:Nuimo-Matrix-Tester,代码行数:56,代码来源:nuimo.py

示例3: Peripheral

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import writeCharacteristic [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: Yeelight

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import writeCharacteristic [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

示例5: LightBlueBean

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

示例6: quit

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import writeCharacteristic [as 别名]
  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..."
      ctrl_c=True
开发者ID:digitalhack,项目名称:dhSensorTag2015,代码行数:33,代码来源:testKeys.py

示例7: onBtleData

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import writeCharacteristic [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

示例8: Peripheral

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import writeCharacteristic [as 别名]
# noinspection PyUnresolvedReferences
from bluepy.btle import Scanner, DefaultDelegate, Peripheral

# perf = Peripheral("00:07:80:BD:23:BE")
perf = Peripheral("00:07:80:BD:1C:3A")
print("Firmware: ", perf.readCharacteristic(0x000a))
print("Hardware: ", perf.readCharacteristic(0x000c))

val = perf.writeCharacteristic(0x001a, chr(20), withResponse=False)
print("test: ", perf.readCharacteristic(0x001a), val)

# perf.writeCharacteristic(0x001a,chr(1) + chr(0) + chr(1) + chr(100) + chr(1) + chr(0) +
# chr(200)+ chr(2) + chr(0) + chr(200)+ chr(3) + chr(0) + chr(200))
# perf.writeCharacteristic(0x001a,chr(0) + chr(0) + chr(1) + chr(2) + chr(3))
开发者ID:wintersandroid,项目名称:sbrick-controller,代码行数:16,代码来源:simple.py

示例9: BtlePeripheral

# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import writeCharacteristic [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.writeCharacteristic方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。