Raspberry PiでBLE Notifyを確認する
LightBlueのLogだとつらい
前回PSoC63でBLEペリフェラルを作りました。
Terminalから文字列を入力するとBLE Notifyとして送信されるというものでした。
LightBlueで簡単に確認するのには便利ですが、センサ情報などを1日中収集するような用途には向きません。
参考サイト
ここのコードをほぼそのまま利用させていただきました。MTUの文字数を変更したくらいでしょうか
ラズパイのセットアップ(bluepy)
ラズパイ上で行う作業です
Python3は導入済みといたします。
sudo apt install cu sudo pip3 install bluepy nano ble_notify_central.py
コードを書きます。
#!/usr/bin/python3 # -*- coding: utf-8 -*- Cy63ble Button Event Notification import sys import time from bluepy.btle import * class ControlCy63ble: def __init__(self, mac): self._data = {} try: self.p = Peripheral(mac, ADDR_TYPE_PUBLIC) self.p.setDelegate(NotificationDelegate()) self.p.setMTU(256) print('Cy63ble connected !') except BTLEException: self.p = 0 print('Connection to Cy63ble failed !', mac) raise def _enableNotification(self): try: # Enable notification print('Notifications enabled') except BTLEException as err: print(err) self.p.disconnect() def _disableNotification(self): try: # Disble notification print('Notifications disabled') except BTLEException as err: print(err) self.p.disconnect() def monitorCy63ble(self): try: # Enable notification self._enableNotification() # Wait for notifications print('Waiting for button pushed 180 second') while self.p.waitForNotifications(180.0): # handleNotification() was called continue print('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): try: if cHandle == 0x10: print('data :',data.decode()) else: print('handle=', cHandle,":", data) except BTLEException as err: print(err) self.p.disconnect() # main program if __name__== '__main__': print("Cy63blenotify start") argvs = sys.argv argc = len(argvs) if (argc < 2): print("Require Bluetooth address [XX:XX:XX:XX:XX:XX]") quit() Cy63ble_mac_addr = argvs[1] myCy63ble = ControlCy63ble(Cy63ble_mac_addr) print("Cy63ble found :",Cy63ble_mac_addr) myCy63ble.monitorCy63ble()
保存したら
chmod +x ble_notify_central.py
PSoC63ボードをRaspberryPiにUSB接続
この時ハイバネートモードにしない方が楽だと思います。
ラズパイのコンソールを2つ開きます。
コンソール1つ目
cu -l /dev/ttyACM0 -s 115200 Connected. ....
/dev/ttyACM0
は /dev/ttyAMA0
、 /dev/ttyUSB0
、/dev/ttyACM1
などの場合もあります。
コンソール2つ目
./ble_notify_Central.py 00:A0:50:00:00:00 Cy63blenotify start Cy63ble connected ! Cy63ble found : 00:A0:50:00:00:00 Notifications enabled Waiting for button pushed 180 second ...
ここの 00:A0:50:00:00:00
は前回プログラムしたPSoC63基板のBLEデバイスのMACアドレスです。
コンソール1つ目に戻ってなにか文字を打ち込み、最後にリターンキーを押します。(例えばtesttesttest
)
コンソール2つ目をみると、こうなっています。
data : testtesttest
できました!おしまい。