From 48e460b9c6a1292c1636d60f37f2b49bdcb49d4b Mon Sep 17 00:00:00 2001 From: Shin'ichiro Kawasaki Date: Fri, 31 Dec 2021 14:49:51 +0900 Subject: [PATCH] BLESession: Add _getDevName() helper function GitHub issue #31 reported that Intelino Smart Train is not connected with pyscrlink. It also reported that getValueText(0x9) call for the device instead of getValueText(0x8) avoids the failure. This implies that the Intelino Smart Train does not report AdType 0x8 "Shortened local name" but it reports AdType 0x9 "Complete local name". To get local name of the BLE devices regardless AdType support status of those devices, introduce a helper function _getDevName(). It gets the AdType 0x9 "Complete local name" first. If it is not available, get AdType 0x8 "Shortened local name". Use this helper function at all places to get the device name. Signed-off-by: Shin'ichiro Kawasaki --- pyscrlink/scratch_link.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/pyscrlink/scratch_link.py b/pyscrlink/scratch_link.py index 64591f7..d78c0d7 100755 --- a/pyscrlink/scratch_link.py +++ b/pyscrlink/scratch_link.py @@ -362,6 +362,14 @@ class BLESession(Session): scan_lock = threading.RLock() scan_started = False + @staticmethod + def _getDevName(dev): + """ + Get AdType 0x09 (Completed local name). If it is not available, + get AdType 0x08 (Shortened local name). + """ + return dev.getValueText(0x9) or dev.getValueText(0x8) + class BLEThread(threading.Thread): """ Separated thread to control notifications to Scratch. @@ -381,7 +389,7 @@ def run(self): for d in devices: params = { 'rssi': d.rssi } params['peripheralId'] = devices.index(d) - params['name'] = d.getValueText(0x9) or d.getValueText(0x8) + params['name'] = BLESession._getDevName(d) self.session.notify('didDiscoverPeripheral', params) time.sleep(1) elif self.session.status == self.session.CONNECTED: @@ -504,7 +512,7 @@ def matches(self, dev, filters): return True if 'namePrefix' in f: # 0x08: Shortened Local Name - deviceName = dev.getValueText(0x08) + deviceName = self._getDevName(dev) if not deviceName: continue logger.debug(f"Name of \"{deviceName}\" begins with: \"{f['namePrefix']}\"?") @@ -620,7 +628,7 @@ def handle_request(self, method, params): elif self.status == self.DISCOVERY and method == 'connect': logger.debug("connecting to the BLE device") self.device = BLESession.found_devices[params['peripheralId']] - self.deviceName = self.device.getValueText(0x9) or self.device.getValueText(0x8) + self.deviceName = self._getDevName(self.device) try: self.perip = Peripheral(self.device) logger.info(f"connected to the BLE peripheral: {self.deviceName}")