From 8958594cf9198f802aa4240647035ef4c2c04636 Mon Sep 17 00:00:00 2001 From: Shin'ichiro Kawasaki Date: Fri, 1 May 2020 11:22:16 +0900 Subject: [PATCH] scratch_link.py: Enrich log information In the GitHub issue "Scratux support #9", it was noticed that bluepy-scratch-link is not so informative to tell what is happening. Especially when BLE controllers or BLE devices are not available, no information is printed. Enrich log information so that users can tell what is happening easier. Signed-off-by: Shin'ichiro Kawasaki --- scratch_link.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/scratch_link.py b/scratch_link.py index e5ca4b2..bbc5867 100755 --- a/scratch_link.py +++ b/scratch_link.py @@ -16,7 +16,7 @@ import bluetooth # for BLESession (e.g. BBC micro:bit) from bluepy.btle import Scanner, UUID, Peripheral, DefaultDelegate -from bluepy.btle import BTLEDisconnectError +from bluepy.btle import BTLEDisconnectError, BTLEManagementError import threading import time @@ -432,17 +432,28 @@ class BLESession(Session): logger.debug(params) res = { "jsonrpc": "2.0" } + err_msg = None if self.status == self.INITIAL and method == 'discover': scanner = Scanner() - devices = scanner.scan(1.0) - for dev in devices: - if self.matches(dev, params['filters']): - self.found_devices.append(dev) - if len(self.found_devices) == 0: - err_msg = f"BLE service not found for {params['filters']}" + try: + devices = scanner.scan(1.0) + for dev in devices: + if self.matches(dev, params['filters']): + self.found_devices.append(dev) + except BTLEManagementError as e: + logger.error(e); + err_msg = "Can not scan BLE devices. Check BLE controller." + logger.error(err_msg); res["error"] = { "message": err_msg } self.status = self.DONE + + if len(self.found_devices) == 0 and not err_msg: + err_msg = (f"BLE service not found: {params['filters']}. " + "Check BLE device.") + res["error"] = { "message": err_msg } + logger.error(err_msg) + self.status = self.DONE else: res["result"] = None self.status = self.DISCOVERY @@ -551,7 +562,8 @@ start_server = websockets.serve( while True: try: asyncio.get_event_loop().run_until_complete(start_server) + logger.info("Started scratch-link") asyncio.get_event_loop().run_forever() except Exception as e: - logger.info("restart server...") + logger.info("Restarting scratch-link...")