ラズパイでBLEタグ – サンプルスクリプト [seek2notify.py]
サンプルスクリプト [seek2notify.py]
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# SEEK2 Button Event Notification
import sys
import logging
import time
from bluepy.btle import *
# uncomment the following line to get debug information
logging.basicConfig(format='%(asctime)s: %(message)s', level=logging.DEBUG)
class ControlSeek2:
def __init__(self, mac):
self._data = {}
try:
self.p = Peripheral(mac, ADDR_TYPE_RANDOM)
self.p.setDelegate(NotificationDelegate())
logging.debug('Seek2 connected !')
except BTLEException:
self.p = 0
logging.debug('Connection to Seek2 failed ! [%s]', mac)
raise
def _enableNotification(self):
try:
# Enable [button event] notification
self.p.writeCharacteristic(0x001c, b'\x01\x00')
logging.debug('Notifications enabled')
except BTLEException as err:
print(err)
self.p.disconnect()
def _disableNotification(self):
try:
# Enable [button event] notification
self.p.writeCharacteristic(0x001c, b'\x00\x00')
logging.debug('Notifications disabled')
except BTLEException as err:
print(err)
self.p.disconnect()
def monitorSeek2(self):
try:
# Enable notification
self._enableNotification()
# Wait for notifications
logging.debug('Wainting for button pushed 10 second')
while self.p.waitForNotifications(10.0):
# handleNotification() was called
continue
logging.debug('Notification timeout')
self._disableNotification()
except:
return None
def disconnect(self):
self.p.disconnect()
class NotificationDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
if cHandle == 0x1b:
print("Button push detected !!!")
else:
logging.debug('handle %x', cHandle)
# main program
if __name__== '__main__':
print("seek2notify start")
argvs = sys.argv
argc = len(argvs)
if (argc < 2):
print("Require Bluetooth address [XX:XX:XX:XX:XX:XX]")
quit()
seek2_mac_addr = argvs[1]
mySeek2 = ControlSeek2(seek2_mac_addr)
print("SEEK2 found %s" % seek2_mac_addr)
mySeek2.monitorSeek2()