def initConnection(address): pycom.rgbled(0xffff00) pycom.heartbeat(False) bluetooth = Bluetooth() bluetooth.start_scan(-1) bluetooth.init() while True: print("starting bluetooth") global connection devices = bluetooth.get_advertisements() try: if devices is not None and len(devices) > 0: for device in devices: uuid = ubinascii.hexlify(device.mac) if (str(uuid) == address): print("foud the arduino") connection = bluetooth.connect(device.mac) print(device) bluetooth.stop_scan() global char char = getBleChar() pycom.rgbled(0x00ff00) return device except: print("arduino refused connection trying again") pycom.heartbeat(True) closeConnection() continue time.sleep(0.05) pycom.rgbled(0xff0000) return None
def find_ble(testCase=None): bluetooth = Bluetooth() try: if isinstance(testCase, Exception): raise testCase bluetooth.start_scan(5) while bluetooth.isscanning(): adv = bluetooth.get_adv() if adv: mac = ubinascii.hexlify(adv.mac) if mac == bytearray(GATT_CLIENT_MAC): #name = bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) #print(mac, name, adv.rssi) if not testCase == 'Not found': rssi = adv.rssi bluetooth.stop_scan() break else: rssi = -10000 bluetooth.deinit() except Exception as e: return -10000 if testCase is not None and not testCase == 'Not found': rssi = testCase if rssi >= 0: return -10000 return rssi
def isOwnerNearby(self): ''' Logic here checks if a known BLE device is broadcasting nearby. If they are, return true. Else, return false ''' # TODO remove return False bt = Bluetooth() bt.start_scan(ConfigBluetooth.SCAN_ALLOW_TIME) # Scans for 10 seconds while bt.isscanning(): adv = bt.get_adv() if adv and binascii.hexlify(adv.mac) == ConfigBluetooth.MAC_ADDR: try: if self.debug: print("Owner device found: {} Mac addr {}".format( bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL), ConfigBluetooth.MAC_ADDR)) conn = bt.connect(adv.mac) time.sleep(0.05) conn.disconnect() bt.stop_scan() except Exception: bt.stop_scan() return True time.sleep(0.050) return False
class BluetoothWorker: def __init__(self, devices): self.devices = devices self.bt = Bluetooth() if self.bt.isscanning(): self.bt.stop_scan() self.bt.start_scan(-1) def get_adv(self): while True: adv = self.bt.get_adv() if adv: self.devices.add_mac(adv.mac, Devices.BLUETOOTH) else: break
def isBTDeviceNearby(): bt = Bluetooth() while True: print("Scanning for owner BT device nearby...") bt.start_scan(10) # Scans for 10 seconds while bt.isscanning(): adv = bt.get_adv() if adv and binascii.hexlify(adv.mac) == ConfigBluetooth.MAC_ADDR: try: print("Owner device found: {} Mac addr {}".format( bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL), ConfigBluetooth.MAC_ADDR)) conn = bt.connect(adv.mac) time.sleep(0.05) conn.disconnect() bt.stop_scan() except Exception as e: print("Exception {}".format(e)) bt.stop_scan() break else: time.sleep(0.050)
from network import Bluetooth import time bt = Bluetooth() bt.stop_scan() bt.start_scan(-1) while True: adv = bt.get_adv() print(adv) if adv: print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_NAME_CMPL)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_NAME_SHORT)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_FLAG)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_16SRV_PART)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_T16SRV_CMPL)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_32SRV_PART)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_32SRV_CMPL)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_128SRV_PART)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_128SRV_CMPL)) print('data %s' % bt.resolve_adv_data(adv.data, bt.ADV_TX_PWR)) time.sleep(4) if adv and bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) == 'Heart Rate': conn = bt.connect(adv.mac) services = conn.services() for service in services: time.sleep(0.050) if type(service.uuid()) == bytes: print('Reading chars from service = {}'.format(service.uuid())) else:
def BLEAndLoRaFun(): ###### First, initialize as one LoRa node device ###### # initialize LoRa in LORAWAN mode. # Please pick the region that matches where you are using the device: # Asia = LoRa.AS923 # Australia = LoRa.AU915 # Europe = LoRa.EU868 # United States = LoRa.US915 lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.US915) # create an ABP authentication params dev_addr = struct.unpack(">l", binascii.unhexlify('26021A14'))[0] nwk_swkey = binascii.unhexlify('BB515D851353D2AB5ACCD112F0F2C597') app_swkey = binascii.unhexlify('B74092CB7C5A79CAD681C384ABF925D2') # remove all the channels for channel in range(0, 72): lora.remove_channel(channel) # set all channels to the same frequency (must be before sending the OTAA join request) for channel in range(0, 72): lora.add_channel(channel, frequency=config.LORA_FREQUENCY, dr_min=0, dr_max=3) # join a network using ABP (Activation By Personalization) lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 3) # last parameter is 3 # make the socket non-blocking s.setblocking(False) ''' ###### Second, set up BLE server service ###### pycom.heartbeat(False) bluetooth = Bluetooth() #create a bluetooth object bluetooth.set_advertisement(name='LoPyServer'+str(globalvar.device_id), service_uuid=b'3333333333333333') #using callback conn_cb to check client's connection ##Function: conn_cb(callback for bluetooth object events checking) ##Description:check there is any client connected to the service def conn_cb (bt_o): events = bt_o.events()#using events to check if there is any client connected to the service if events & Bluetooth.CLIENT_CONNECTED: print("Client connected") pycom.rgbled(0x007f00) # green elif events & Bluetooth.CLIENT_DISCONNECTED: bt_o.disconnect_client() print("Client disconnected") pycom.rgbled(0x7f0000) # red time.sleep(3) bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) bluetooth.advertise(True) #set up BLE service srv1 = bluetooth.service(uuid=b'3333333333333333', isprimary=True) #set up service character chr1 = srv1.characteristic(uuid=b'3333333333333333', value=5) #char1_read_counter = 0 def char1_cb_handler(chr): #global char1_read_counter #char1_read_counter += 1 global BLEConnectionCounter events = chr.events() if events & Bluetooth.CHAR_WRITE_EVENT: print("Write request with value = {}".format(chr.value())) else: #modify here to send its device_id to other clients BLEConnectionCounter += 1 return str(globalvar.device_id)+' '+str(BLEConnectionCounter) #using the callback to send the data to other clients char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char1_cb_handler) ''' ###### Third, set up BLE client service ###### bluetooth_client = Bluetooth() #bluetooth_client.init(id=0, mode=Bluetooth.BLE, antenna=None) bluetooth_client.start_scan(10) #server_name1 = bluetooth_client.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) counter = 50 #while True: while counter > 0: print(counter) counter -= 1 #Gets an named tuple with the advertisement data received during the scanning. #The structure is (mac, addr_type, adv_type, rssi, data) adv = bluetooth_client.get_adv() #servermac = ''#save the serer mac #use resolve_adv_data to resolve the 31 bytes of the advertisement message #Here is problem: when disconnect from server, then adv will always be null... #if get a valid advertisement from one server if adv: server_name = bluetooth_client.resolve_adv_data( adv.data, Bluetooth.ADV_NAME_CMPL) #print(server_name) if checkValidServer(server_name): try: #Opens a BLE connection with the device specified by the mac_addr argument #This function blocks until the connection succeeds or fails. #print(adv.mac) #global servermac#change servermac to global #servermac = adv.mac #counter += 1 conn = bluetooth_client.connect(adv.mac) #print('connected?',conn.isconnected()) services = conn.services() #print('This is service',services) #print(services) #Yunwei - it seems that only when the type of uuid is bytes then could read the data from server for service in services: time.sleep(0.050) if type(service.uuid()) == bytes: chars = service.characteristics() for char in chars: #check if the character properties is PROP_READ properties = char.properties() print('char properties is ' + str(properties)) if (properties & Bluetooth.PROP_READ): print('char {} value = {}'.format( char.uuid(), char.read())) #Use LoRa to send the data out #s.send(char.read()) time.sleep(2) #10 & Bluetooth.PROP_WRITE #10&Bluetooth.PROP_READ if (properties & Bluetooth.PROP_WRITE): print('write to server!') char.write(b'x02') time.sleep(2) #Yunwei conn.disconnect() #bluetooth_client.deinit() bluetooth_client.stop_scan() time.sleep(3) bluetooth_client.deinit() print('deinit') time.sleep(3) bluetooth_client.init() #if(bluetooth_client.isscanning()): # bluetooth_client.stop_scan() #bluetooth_client.deinit() bluetooth_client.start_scan(10) print('connected?', conn.isconnected()) #break time.sleep(3) gc.collect() #if it's still scan, then need to stop scan first #bluetooth_client.start_scan(-1) ''' if(bluetooth_client.isscanning()): bluetooth_client.stop_scan() #then scan again bluetooth_client.start_scan(-1) ''' except: print( "Error while connecting or reading from the BLE device" ) #break time.sleep(1) if (bluetooth_client.isscanning()): bluetooth_client.stop_scan() bluetooth_client.deinit() time.sleep(1) bluetooth_client.deinit() time.sleep(1) #init again bluetooth_client.init(id=0, mode=Bluetooth.BLE, antenna=None) bluetooth_client.start_scan(10) else: bluetooth_client.deinit() time.sleep(1) bluetooth_client.init() time.sleep(1) bluetooth_client.start_scan(10) print('Scan again') else: print('adv is None!') time.sleep(3) ''' time.sleep(3) #if it's still scan, then need to stop scan first if(bluetooth_client.isscanning()): bluetooth_client.stop_scan() #then scan again bluetooth_client.start_scan(-1) ''' #bluetooth_client.stop_scan() bluetooth_client.stop_scan() bluetooth_client.deinit() print('out of loop!')
def BLEClient(): #Description: check if the BLE server is set up by another LoPy #Note: for convention reason, the LoPy server name will be "LoPyServer"+device_id def checkValidServer(server_name): if (server_name == None): return False else: #check if server_name contains "LoPyServer" if (re.match('LoPyServer*', server_name)): return True else: return False global rec_msg ###### Third, set up BLE client service ###### bluetooth_client = Bluetooth() bluetooth_client.start_scan(10) #server_name1 = bluetooth_client.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) counter = 50 #while True: while counter > 0: #Gets an named tuple with the advertisement data received during the scanning. #The structure is (mac, addr_type, adv_type, rssi, data) adv = bluetooth_client.get_adv() #servermac = ''#save the serer mac #use resolve_adv_data to resolve the 31 bytes of the advertisement message #Here is problem: when disconnect from server, then adv will always be null... #if get a valid advertisement from one server if adv: server_name = bluetooth_client.resolve_adv_data( adv.data, Bluetooth.ADV_NAME_CMPL) #print(server_name) if checkValidServer(server_name): try: #Opens a BLE connection with the device specified by the mac_addr argument #This function blocks until the connection succeeds or fails. #print(adv.mac) #global servermac#change servermac to global #servermac = adv.mac #counter += 1 conn = bluetooth_client.connect(adv.mac) #print('connected?',conn.isconnected()) services = conn.services() #print('This is service',services) #print(services) #Yunwei - it seems that only when the type of uuid is bytes then could read the data from server for service in services: time.sleep(0.050) if type(service.uuid()) == bytes: chars = service.characteristics() for char in chars: #check if the character properties is PROP_READ if (char.properties() & Bluetooth.PROP_READ): print('char {} value = {}'.format( char.uuid(), char.read())) #create lora msg rec_msg = str(char.read()) counter -= 1 #Use LoRa to send the data out #s.send(char.read()) time.sleep(5) #Yunwei conn.disconnect() print('connected?', conn.isconnected()) #break time.sleep(3) gc.collect() bluetooth_client.start_scan(10) except: print( "Error while connecting or reading from the BLE device" ) #break time.sleep(1) if (bluetooth_client.isscanning()): bluetooth_client.stop_scan() bluetooth_client.deinit() time.sleep(1) bluetooth_client.init() time.sleep(1) #init again #bluetooth_client.init(id=0, mode=Bluetooth.BLE, antenna=None) bluetooth_client.start_scan(10) else: bluetooth_client.deinit() time.sleep(1) bluetooth_client.init() time.sleep(1) bluetooth_client.start_scan(10) bluetooth_client.stop_scan() bluetooth_client.deinit()
return data[1] * 0.5 def extractPressure(data): pres = (data[4] << 8) + data[5] + 50000 return pres / 100 sendData.connectLocalBox('/flash/config.json') rtc = RTC() rtc.ntp_sync('fr.pool.ntp.org') bt = Bluetooth() try: bt.start_scan(-1) except: bt.stop_scan() bt.start_scan(-1) while True: try: adv = bt.get_adv() if adv: data = str(adv.data, "utf-8") data = str(data.split("#")[1][:8], "utf-8") data = ubinascii.a2b_base64(data) temperature = extractTemperature(data) humidity = extractHumidity(data) pressure = extractPressure(data) id = str(ubinascii.hexlify(adv.mac), "utf-8") content = '{"temperature": %s, "humidity": %s, "pressure" : %s, "mac": %s, "timestamp": "%s"}' % (
class BLEScanner(object): """ BLE scanner for beacons and tags data packages """ def __init__(self, max_list_items=25): self._beacons = [] self._tags = [] self._max_list_items = max_list_items self._ble = None def start(self, timeout=-1): """ Start beacon scanning """ log.info('Start scanning for beacons and tags') if self._ble is None: self._ble = Bluetooth() self._ble.start_scan(timeout) while self._ble.isscanning(): self.beacon_data_collect() def stop(self): """ Stop BLE """ log.info('Stop scanning for beacons and tags') if self._ble: self._ble.stop_scan() #self._ble.deinit() #self._ble = None def set_max_list_items(self, max_list_items): """ Set the max list items to return""" self._max_list_items = max_list_items def reset(self): """ Reset the retrieved beacon/tag list during scanning """ log.info('Reset beacon/tag list') self._beacons[:] = [] self._tags[:] = [] @property def beacons(self): """ Return the beacons found """ res = list(self._beacons) # make a copy return res @property def tags(self): """ Return the tags found """ res = list(self._tags) # make a copy return res def beacon_data_collect(self): """ Collect the beacon data """ adv = self._ble.get_adv() if adv: if self._ble.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) == "ITAG": binitag = binascii.hexlify(adv[0]) tag = binitag.decode('UTF-8') if tag not in self._tags: log.debug('Found tag [{}]', tag) self._tags.append(tag) else: # try to get the complete name only works with ibeacons data = self._ble.resolve_adv_data( adv.data, Bluetooth.ADV_MANUFACTURER_DATA) if data: # try to get the manufacturer data (Apple's iBeacon data is sent here) bindata = binascii.hexlify(data) beacon = bindata.decode('UTF-8') # Check if beacon is in list if beacon not in self._beacons: log.debug('Found beacon [{}]', beacon) self._beacons.append(beacon)