前提・実現したいこと
センサデータをBLE通信でラズパイで受け取り、クラウド環境にあげたいです。
このサイトを参考に
ラズパイのターミナルでサイトにあるようにpythonのコードを動かそうとするとエラーメッセージや受信出来ていないメッセージ?が発生して前へ進めません。
発生している問題・エラーメッセージ
1.sudoをつけてプログラム実行した場合
python
1pi@raspberrypi:~ $ sudo python env2ambientCS.py 2 3Traceback (most recent call last): 4 File "env2ambientCS.py", line 6, in <module> 5 from bluepy.btle import Peripheral, DefaultDelegate, Scanner, BTLEException, UUID 6ImportError: No module named bluepy.btle 7
2.sudoをつけないでプログラムを実行した場合
python
1pi@raspberrypi:~ $ env2ambientCS.py 2 3BTLE Exception while scannning. 4BTLE Exception while scannning. 5BTLE Exception while scannning. 6BTLE Exception while scannning. 7BTLE Exception while scannning. 8BTLE Exception while scannning. 9BTLE Exception while scannning. 10BTLE Exception while scannning. 11BTLE Exception while scannning. 12BTLE Exception while scannning. 13BTLE Exception while scannning. 14BTLE Exception while scannning. 15BTLE Exception while scannning. 16BTLE Exception while scannning. 17BTLE Exception while scannning. 18BTLE Exception while scannning. 19BTLE Exception while scannning. 20BTLE Exception while scannning. 21BTLE Exception while scannning. 22BTLE Exception while scannning. 23BTLE Exception while scannning. 24BTLE Exception while scannning. 25BTLE Exception while scannning. 26BTLE Exception while scannning. 27BTLE Exception while scannning.
該当のソースコード
python
1# -*- coding: utf-8 -*- 2# 環境センサーをスキャンし、見つけたら300秒ごとにconnectして 3# 最新データー(latest data)を取得し、Ambientに送信する 4# 1台(Single)のセンサー端末に対応 5 6from bluepy.btle import Peripheral, DefaultDelegate, Scanner, BTLEException, UUID 7import bluepy.btle 8from threading import Thread, Timer 9import time 10import sys 11import struct 12import argparse 13import ambient 14 15channelID = 100 16writeKey = 'writekey' 17 18def _OMRON_UUID(val): 19 return UUID('%08X-7700-46F4-AA96-D5E974E32A54' % (0x0C4C0000 + val)) 20 21def _MICROBIT_UUID(val): 22 return UUID('%08X-251D-470A-A062-FA1922DFA9A8' % (0xE95D0000 + val)) 23 24 25devs = { 26 'omron': {'desc': 'Short Local Name', 'value': 'Env', 'match': 'exact', 'uuid': _OMRON_UUID(0x3001)}, 27 'microbit': {'desc': 'Complete Local Name', 'value': 'BBC micro:bit', 'match': 'forward', 'uuid': _MICROBIT_UUID(0x9250)}, 28 'esp32': {'desc': 'Complete Local Name', 'value': 'AmbientEnv-01', 'match': 'exact', 'uuid': 'b0c8c0fa-6d46-11e8-adc0-fa7ae01bbebc'} 29} 30target = 'esp32' 31 32Debugging = False 33def DBG(*args): 34 if Debugging: 35 msg = " ".join([str(a) for a in args]) 36 print(msg) 37 sys.stdout.flush() 38 39Verbose = True 40def MSG(*args): 41 if Verbose: 42 msg = " ".join([str(a) for a in args]) 43 print(msg) 44 sys.stdout.flush() 45 46def timeoutRetry(addr): 47 MSG('timer expired (%s)' % addr) 48 devThread = scannedDevs[addr] 49 devThread.forceDisconnect() 50 MSG('Thread disconnected (%s)' % addr) 51 52def send2ambient(am, dataRow): 53 if target == 'esp32': 54 (seq, temp, humid, press) = struct.unpack('<Bhhh', dataRow) 55 MSG(seq, temp / 100, humid / 100, press / 10) 56 ret = am.send({'d1': temp / 100, 'd2': humid / 100, 'd3': press / 10}) 57 elif target == 'microbit': 58 temp = struct.unpack('<b', dataRow) 59 print({'d1': temp[0]}) 60 ret = am.send({'d1': temp[0]}) 61 else: 62 (seq, temp, humid, light, uv, press, noise, discom, heat, batt) = struct.unpack('<BhhhhhhhhH', dataRow) 63 MSG(seq, temp / 100, humid / 100, light, uv / 100, press / 10, noise / 100, discom / 100, heat / 100, batt / 1000) 64 ret = am.send({'d1': temp / 100, 'd2': humid / 100, 'd3': press / 10, 'd4': batt / 1000, 'd5': light, 'd6': noise / 100}) 65 MSG('sent to Ambient (ret = %d)' % ret.status_code) 66 67class EnvSensor(Thread, Peripheral): 68 def __init__(self, dev): 69 Peripheral.__init__(self) 70 Thread.__init__(self) 71 self.setDaemon(True) 72 self.dev = dev 73 self.isConnected = False 74 self.am = ambient.Ambient(channelID, writeKey) 75 76 def run(self): 77 while True: 78 t = Timer(30, timeoutRetry, [self.dev.addr]) 79 t.start() 80 while self.isConnected == False: # つながるまでconnectする 81 try: 82 self.connect(self.dev) 83 self.isConnected = True 84 except BTLEException as e: 85 MSG('BTLE Exception while connect on ', self.dev.addr) 86 MSG('type:' + str(type(e))) 87 MSG('args:' + str(e.args)) 88 # pass 89 MSG('connected to ', self.dev.addr) 90 try: 91 latestDataRow = self.getCharacteristics(uuid=devs[target]['uuid'])[0] 92 dataRow = latestDataRow.read() 93 send2ambient(self.am, dataRow) 94 t.cancel() 95 time.sleep(300.0) 96 except BTLEException as e: 97 MSG('BTLE Exception while getCharacteristics on ', self.dev.addr) 98 MSG('type:' + str(type(e))) 99 MSG('args:' + str(e.args)) 100 self.disconnect() 101 self.isConnected = False 102 t.cancel() 103 104 def forceDisconnect(self): 105 if self.isConnected: 106 self.disconnect() 107 self.isConnected = False 108 109scannedDevs = {} 110 111class ScanDelegate(DefaultDelegate): 112 def __init__(self): 113 DefaultDelegate.__init__(self) 114 115 def handleDiscovery(self, dev, isNewDev, isNewData): 116 if isNewDev: 117 for (adtype, desc, value) in dev.getScanData(): # スキャンデーターを調べる 118 if devs[target]['match'] == 'exact' and desc == devs[target]['desc'] and value == devs[target]['value'] \ 119 or devs[target]['match'] == 'forward' and desc == devs[target]['desc'] and value.startswith(devs[target]['value']): # 対象を見つけたら 120 if dev.addr in scannedDevs.keys(): # すでに見つけていたらスキップ 121 return 122 MSG('New %s %s' % (value, dev.addr)) 123 devThread = EnvSensor(dev) # EnvSensorクラスのインスタンスを生成 124 scannedDevs[dev.addr] = devThread 125 devThread.start() # スレッドを起動 126 127def main(): 128 parser = argparse.ArgumentParser() 129 parser.add_argument('-d',action='store_true', help='debug msg on') 130 parser.add_argument('-o',action='store_true', help='device is omron env sensor') 131 parser.add_argument('-b',action='store_true', help='device is BBC micro:bit') 132 133 args = parser.parse_args(sys.argv[1:]) 134 135 global Debugging 136 Debugging = args.d 137 bluepy.btle.Debugging = args.d 138 139 global target 140 if args.o: 141 target = 'omron' 142 elif args.b: 143 target = 'microbit' 144 145 scanner = Scanner().withDelegate(ScanDelegate()) 146 while True: 147 try: 148 scanner.scan(5.0) # スキャンする。デバイスを見つけた後の処理はScanDelegateに任せる 149 except BTLEException: 150 MSG('BTLE Exception while scannning.') 151 152if __name__ == "__main__": 153 main() 154
試したこと
python3でプログラムを実行したが同様の現象が起きた。
補足情報(FW/ツールのバージョンなど)
raspberryPi 3b+
python2.7.16
python3.7.3
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/02/14 06:43