def power_off_bluetooth(self): """We don't use Bluetooth yet.""" if self.platform_info.vendor == self.platform_info.MICROPYTHON.Vanilla: log.warning("FIXME: Skip touching Bluetooth on vanilla MicroPython " "platforms as we don't use Bluetooth yet") return log.info('Turning off Bluetooth') try: from network import Bluetooth bluetooth = Bluetooth() bluetooth.deinit() except Exception as ex: log.exc(ex, 'Shutting down Bluetooth failed')
def BlueToothFun(): global deviceID global connectionCounter #Also act as a server pycom.heartbeat(False) bluetooth = Bluetooth() #create a bluetooth object bluetooth.set_advertisement(name='LoPyServer1', service_uuid=b'1234567890123456') #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: print("Client disconnected") pycom.rgbled(0x7f0000) # red bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) # bluetooth.advertise(True) srv1 = bluetooth.service(uuid=b'1234567890123456', isprimary=True) chr1 = srv1.characteristic(uuid=b'ab34567890123456', value=5) #char1_read_counter = 0 def char1_cb_handler(chr): #global char1_read_counter #char1_read_counter += 1 global connectionCounter events = chr.events() if events & Bluetooth.CHAR_WRITE_EVENT: print("Write request with value = {}".format(chr.value())) else: #modify here to send message to other clients #connectionCounter += 1 return str(deviceID) #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) '''srv2 = bluetooth.service(uuid=1234, isprimary=True)
def BLEServer(): ###### 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: #2 print("Client connected") pycom.rgbled(0x007f00) # green elif events & Bluetooth.CLIENT_DISCONNECTED: #4 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', properties=Bluetooth.PROP_READ | Bluetooth.PROP_WRITE, value=5) #char1_read_counter = 0 def char1_cb_handler(chr): #global char1_read_counter #char1_read_counter += 1 global BLEConnectionCounter events = chr.events() print('events is ' + str(events)) if events & Bluetooth.CHAR_WRITE_EVENT: #16 print("Write request with value = {}".format(chr.value())) elif events & Bluetooth.CHAR_READ_EVENT: #8 #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 chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char1_cb_handler)
def __init__(self): if bt_enabled: self.ble = Bluetooth() self.chr1 = None self.ble.set_advertisement(name="jitback", service_uuid=POSITION_SERVICE) self.ble.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=self.__cb_ble_conn) self.promote(BT_PROMOTE) if wifi_enable and wifi_config: # TODO wifi staffs and get configuration to set_advertisement pass if lora_enabled: # TODO wifi staffs and get configuration to set_advertisement pass
def getBluetoothNetworks(): bl_networks = {} tmp_mac = [] bl_index = 0 nb_scan = 0 bl = Bluetooth() while nb_scan < NB_SCAN_BL: print("scan : %d" % nb_scan) bl.start_scan(10) #Duration of scan to be define !!!! while bl.isscanning(): adv = bl.get_adv() if adv: if adv.mac not in tmp_mac: tmp_mac.append(adv.mac) bl_networks[str(bl_index)] = { "id": str(ubinascii.hexlify(adv.mac, ":"))[2:19], "rssi": str(adv.rssi) } print("NAME = %s -- MAC : %s -- RSSI = %d" % (bl.resolve_adv_data(adv.data, bl.ADV_NAME_CMPL), ubinascii.hexlify(adv.mac, ":"), adv.rssi)) bl_index += 1 nb_scan += 1 tmp_mac = [] utime.sleep(BL_DELAY_SCAN_SEC) print("getBluetoothNetworks - Done!") return bl_networks
def writeToServer(): bt = Bluetooth() adv = bluetooth.get_adv() print("Writing to client with MAC: {}".format(ubinascii.hexlify(adv.mac))) global connectedMAC connectedMAC = adv.mac print(connectedMAC) # return(0) pass
def __init__(self, mesh_mac): self.status = { 'connected' : False } bluetooth = Bluetooth(modem_sleep=False) bluetooth.set_advertisement(name='PyGo (mac:' + str(mesh_mac) + ')', service_uuid=0xec00) bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=self.conn_cb) bluetooth.advertise(True) srv_rx = bluetooth.service(uuid=0xec00, isprimary=True) self.chr_rx = srv_rx.characteristic(uuid=0xec0e, value=0) srv_tx = bluetooth.service(uuid=0xed00, isprimary=True) self.chr_tx = srv_tx.characteristic(uuid=0xed0e, value=0) self.unpacker = None
def setBluetoothAdvertisement(self, mode): if mode == 0: print("Bluetooth Basic activated") self.nodeName = self.data.get('name') print("Advertising on bluetooth with:") print(self.nodeName) self.bluetooth = Bluetooth() self.bluetooth.init() ## service_uuid is dummy, is there an existing profile we should use? self.bluetooth.set_advertisement(name=self.nodeName, service_uuid=self.service_uuid) self.bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=self.conn_cb) self.bluetooth.advertise(True) ## Below is dummy code, only for testing purposes, services and characteristics should become classes self.srv1 = self.bluetooth.service(uuid=self.service_uuid, isprimary=True) self.chr1 = self.srv1.characteristic(uuid=self.characteristic_uuid, value=b'123') self.char1_cb = self.chr1.callback( trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=self.unlock_handler) self.srv1.start() self.srv2 = self.bluetooth.service(uuid=self.service_uuid2, isprimary=True) self.chr2 = self.srv2.characteristic( uuid=self.characteristic_uuid2, value=b'chr2') self.chr3 = self.srv2.characteristic( uuid=self.characteristic_uuid2, value=b'chr3') self.char2_cb = self.chr2.callback( trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=self.interface_handler) self.srv2.start() self.main.start_main_state()
def __init__(self): self.bluetooth = Bluetooth() self.bluetooth.set_advertisement(name=ble_device_name, manufacturer_data=manufacturer_data, service_data=None, service_uuid=private_UUID) self.bluetooth.advertise(True) #service_acc self.service_acc = self.bluetooth.service(uuid=service_acc_UUID, isprimary=True, nbr_chars=3, start=True) self.character_acc_x = self.service_acc.characteristic( uuid=character_acc_x_UUID, properties=None, value=33) self.character_acc_y = self.service_acc.characteristic( uuid=character_acc_y_UUID, properties=None, value=34) self.character_acc_z = self.service_acc.characteristic( uuid=character_acc_z_UUID, properties=None, value=35)
def _init(self): self.status = {'connected': False} bluetooth = Bluetooth(modem_sleep=False) adv_name = self.ble_name bluetooth.set_advertisement(name=adv_name, service_uuid=0xec00) print("BLE name:", adv_name) bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=self.conn_cb) bluetooth.advertise(True) srv_rx = bluetooth.service(uuid=0xec00, isprimary=True) self.chr_rx = srv_rx.characteristic(uuid=0xec0e, value=0) srv_tx = bluetooth.service(uuid=0xed00, isprimary=True) self.chr_tx = srv_tx.characteristic(uuid=0xed0e, value=0) self.unpacker = None
def startSending(dataList: list, callback, shouldClear): global data global call global bluetooth global clear clear = shouldClear call = callback pycom.rgbled(0x70000ff) data = dataList print("data" + str(data)) bluetooth = Bluetooth() bluetooth.set_advertisement(name='Loy', service_uuid=b'1234567890123456') bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) bluetooth.advertise(True) srv1 = bluetooth.service(uuid=b'serviceA90123456', isprimary=True) srv2 = bluetooth.service(uuid=b'serviceB90123456', isprimary=True) srv3 = bluetooth.service(uuid=b'serviceC90123456', isprimary=True) srv4 = bluetooth.service(uuid=b'serviceD90123456', isprimary=True) chr1 = srv1.characteristic(uuid=b'temp567890123456', value="") chr2 = srv2.characteristic(uuid=b'light67890123456', value="") chr3 = srv3.characteristic(uuid=b'time567890123456', value="") chr4 = srv4.characteristic(uuid=b'id34567890123456', value="") chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char1_cb_handler) chr2.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char2_cb_handler) chr3.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char3_cb_handler) chr4.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char4_cb_handler)
def connect(self): bluetooth = Bluetooth() bluetooth.set_advertisement(name='Blynk') def conn_cb(bt): events = bt.events() if events & Bluetooth.CLIENT_CONNECTED: self.bout = b'' print("Client connected") elif events & Bluetooth.CLIENT_DISCONNECTED: print("Client disconnected") BlynkProtocol.disconnect(self) bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) nus = bluetooth.service( uuid=unhex('6E400001-B5A3-F393-E0A9-E50E24DCCA9E'), isprimary=True, nbr_chars=2) self.rx = nus.characteristic( uuid=unhex('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), properties=Bluetooth.PROP_WRITE | Bluetooth.PROP_WRITE_NR, value='') self.tx = nus.characteristic( uuid=unhex('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), properties=Bluetooth.PROP_READ | Bluetooth.PROP_NOTIFY, value='') bluetooth.advertise(True) def rx_cb(chr): data = chr.value() print('>', data) self.process(bytes(data)) def tx_subsc(chr): print("Client subscribed", chr) BlynkProtocol.connect(self, login=False) self.tx.callback(trigger=Bluetooth.CHAR_SUBSCRIBE_EVENT, handler=tx_subsc) self.rx.callback(trigger=Bluetooth.CHAR_WRITE_EVENT, handler=rx_cb)
def bt_check(self): av = AV() av.blue() bluetooth = Bluetooth() bluetooth.set_advertisement(name=BLE_DEVICE_NAME, manufacturer_data=BLE_DEVICE_NAME, service_uuid=0001) bluetooth.advertise(True) srv1 = bluetooth.service(uuid=0001, isprimary=True) chr1 = srv1.characteristic(uuid=0002, value=5) if self.config["state"] == 0: lock_state = 0 else: lock_state = 1 def char1_cb_handler(chr): if chr.value() == bytes(BLE_SECRET_KEY, "utf-8"): if self.config["state"] == 0: self.lock() av.locked() return 'good' else: self.unlock() av.unlocked() return 'good' srv2 = bluetooth.service(uuid=0003, isprimary=True) chr2 = srv2.characteristic(uuid=0004, value=lock_state) char1_cb = chr2.callback(trigger=Bluetooth.CHAR_WRITE_EVENT, handler=char1_cb_handler) time.sleep(20) av.off() bluetooth.advertise(False)
class bluetooth: def __init__(self): time.sleep_ms(100) self.bluetooth = Bluetooth() self.bluetooth.set_advertisement(name=ble_device_name, manufacturer_data=manufacturer_data, service_data=None, service_uuid=private_UUID) self.bluetooth.advertise(True) #service_acc self.service_acc = self.bluetooth.service(uuid=service_acc_UUID, isprimary=True, nbr_chars=3, start=True) self.character_acc_x = self.service_acc.characteristic( uuid=character_acc_x_UUID, properties=None, value=33) self.character_acc_y = self.service_acc.characteristic( uuid=character_acc_y_UUID, properties=None, value=34) self.character_acc_z = self.service_acc.characteristic( uuid=character_acc_z_UUID, properties=None, value=35) def updateValue(self, accelerate=None, gps=None): if (accelerate != None): float_bytes = struct.pack('f', accelerate[0]) #print(float_bytes) print(accelerate[0], accelerate[1], accelerate[2]) total_bytes = b'' total_bytes = struct.pack('<f', accelerate[0]) + struct.pack( '<f', accelerate[1]) + struct.pack( '<f', accelerate[2]) + struct.pack( '<f', gps[0]) + struct.pack('<f', gps[1]) self.character_acc_x.value(total_bytes) self.character_acc_y.value(total_bytes) self.character_acc_z.value(total_bytes)
class Blues: # Initialization method. def __init__(self): print('Advertising Bluetooth...') self.mBluetooth = Bluetooth() self.mEvents = self.mBluetooth.events() # self.mBluetooth.init([id=0, mode=Bluetooth.BLE, antenna=Bluetooth.INT_ANT, modem_sleep=False, pin=None, privacy=True, secure_connections=True, mtu=200]) self.mBluetooth.set_advertisement( name='FiPy', service_uuid=2) self.mBluetooth.callback(trigger=self.mBluetooth.CLIENT_CONNECTED | self.mBluetooth.CLIENT_DISCONNECTED, handler=self.Connection) self.mBluetooth.advertise(True) # Create Service & Characteristic self.CreateServChar() self.mCharacteristic.callback( trigger=self.mBluetooth.CHAR_WRITE_EVENT | self.mBluetooth.CHAR_READ_EVENT, handler=self.CharCallback) # Connection method: Used as callback function to detect a BLE connection. def Connection(self, zResponse): self.mEvents = zResponse.events() if self.mEvents & self.mBluetooth.CLIENT_CONNECTED: print("Client connected") elif self.mEvents & self.mBluetooth.CLIENT_DISCONNECTED: print("Client disconnected") def CreateServChar(self): # Create service and characteristic self.mService = self.mBluetooth.service( uuid=3, isprimary=True) self.mCharacteristic = self.mService.characteristic( uuid=31, properties=self.mBluetooth.PROP_WRITE | self.mBluetooth.PROP_READ, value=6) def CharCallback(self, chr, zResponse): self.mEvents, value = zResponse if self.mEvents & self.mBluetooth.CHAR_READ_EVENT: print("Read from Char = {}".format(value)) if self.mEvents & self.mBluetooth.CHAR_WRITE_EVENT: print("Written to Char = {}".format(value))
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
class sht21: bt = Bluetooth() conn = None def start_sht21(self): self.bt.init() @classmethod def connect_to_sht21(cls): try: cls.conn = sht21.bt.connect(b'\xbc\x6a\x29\xc0\xf0\x69' ) # hard coded ble mac from the device except: print("Connection refused") def extract_value(self): reading = namedtuple('reading', 'temperature humidity') try: x = ubinascii.hexlify( sht21.conn.services()[3].characteristics()[0].read()).decode( ) # read value and convert to hexadecimals and strings #extraction temperature values tem = str( ustruct.unpack("i", ubinascii.unhexlify(x[:4] + '0000'))[0]) tem = tem[:2] + '.' + tem[2:] print("The ambient temperature is: " + tem) # extract humidity values hum = str( ustruct.unpack("i", ubinascii.unhexlify(x[4:] + '0000'))[0]) hum = hum[:2] + '.' + hum[2:] print("The ambient humidity is: " + hum) return reading(tem, hum) except: print("No connection established ...")
def main(): first = True while True: if first == True: om2m.createApplication('http://smart-iot.lan.uow.edu.au:8181/~/in-cse', 'admin:admin', 'LOPY5') om2m.createContainer('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5', 'admin:admin', 'WiFi_Connectivity') om2m.subscribeResource('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/WiFi_Connectivity', 'admin:admin', 'lopy5_wifi_sub', 'http://smart-iot.lan.uow.edu.au:8081/monitorLopy5Wifi') wlan = WLAN() wlan.init(mode=WLAN.STA) wfResults = wlan.scan() wifiCon = getWifiConnectivity(wfResults) print('WiFi Connectivity:') print(wifiCon) print(len(wifiCon['names'])) wifiData = { 'Networks': wifiCon['names'], 'MAC Addresses': wifiCon['macs'], 'Signal Strengths': wifiCon['strengths'] } om2m.createContentInstance('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/WiFi_Connectivity', 'admin:admin', json.dumps(wifiData) ) if first == True: om2m.createContainer('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5', 'admin:admin', 'BT_Connectivity') om2m.subscribeResource('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/BT_Connectivity', 'admin:admin', 'lopy5_bt_sub', 'http://smart-iot.lan.uow.edu.au:8081/monitorLopy5BT') first = False bluetooth = Bluetooth() bluetooth.start_scan(3) while bluetooth.isscanning(): time.sleep(1) btResults = bluetooth.get_advertisements() btCon = getBTConnectivity(btResults) print('BT Connectivity:') print(btCon) btData = { 'MAC Addresses': btCon['macs'], 'Signal Strengths': btCon['strengths'] } om2m.createContentInstance('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/BT_Connectivity', 'admin:admin', json.dumps(btData) ) time.sleep(30)
def scanBluetooth(): bt = Bluetooth() bt.start_scan( -1) # Start scanning indefinitely until stop_scan() is called while True: adv = bt.get_adv() if adv: # try to get the complete name print("BT Name: {}".format( bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL))) # print out mac address of bluetooth device print("Mac addr: {}, {}".format(adv.mac, binascii.hexlify(adv.mac))) else: time.sleep(0.5) time.sleep(3)
def main(): gc.enable() while True: WIFI() #Connect to WiFi set_rtc() #Set RTC time mqtt1() #Connect Heatcheck Client mqtt2() #Conenct BLE Client _thread.start_new_thread(heartbeat, ()) #Start HeartBeat loop print("Scanning... from: " + MAC) #Prints device MAC print(TOPIC) #Prints BLE data Topic global bt bt = Bluetooth() if CONFIG.get( 'btExt') == True: #If wnating to use external BLE antenna Pin('P12', mode=Pin.OUT)(True) bt.init(antenna=Bluetooth.EXT_ANT) print("Using Ext for Bt") bt.start_scan(-1) #Start Scanning for BLE data indefinitely _thread.start_new_thread(scan, ()) #Start BLE decode loop print("Scanning....") running_check() #Start wait loop, checks for incoming messages machine.reset() #Should never get this ppoint
import time from machine import Pin from network import LoRa import socket from network import Bluetooth from network import WLAN import network pycom.heartbeat(False) if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('wake form deepsleep') time.sleep(1) bluetooth = Bluetooth() wlan = network.WLAN(mode=network.WLAN.STA) lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(False) def conn_cb (bt_o): events = bt_o.events() if events & Bluetooth.CLIENT_CONNECTED: print("Client connected") elif events & Bluetooth.CLIENT_DISCONNECTED: print("Client disconnected") bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb)
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:
""" Module de la LoPy effe, elle joue le rôle du serveur bluetooth""" from network import Bluetooth bluetooth = Bluetooth() bluetooth.set_advertisement(name='Effe', service_uuid=b'1234567890123456') def conn_cb(bt_o): events = bt_o.events( ) # this method returns the flags and clears the internal registry if events & Bluetooth.CLIENT_CONNECTED: print("Client connected") elif events & Bluetooth.CLIENT_DISCONNECTED: print("Client disconnected") bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) bluetooth.advertise(True) srv1 = bluetooth.service(uuid=b'1234567890123456', isprimary=True) chr1 = srv1.characteristic(uuid=b'ab34567890123456', value=5) def char1_cb(chr): print("Write request with value = {}".format(chr.value()))
from network import Bluetooth import binascii import time bt = Bluetooth() bt.set_advertisement(name="lopy1", manufacturer_data="lopy_v1") # scan until we can connect to any BLE device around bt.start_scan(-1) while True: adv = bt.get_adv() if adv and bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) == 'lopy2': try: 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: print('Reading chars from service = %x' % service.uuid()) chars = service.characteristics() for char in chars: if (char.properties() & Bluetooth.PROP_READ): print('char {} value = {}'.format( char.uuid(), char.read())) conn.disconnect() break except: print("Error while connecting or reading from the BLE device")
"""Boot file: executed at boot only.""" from machine import UART import machine import os import pycom from network import WLAN from network import Bluetooth # Heartbeat LED pycom.heartbeat(False) # WIFI + WIFI AP at boot print("Boot: disabling WIFI") pycom.wifi_on_boot(False) wlan = WLAN() wlan.deinit() # Bluetooth print("Boot: disabling Bluetooth") bluetooth = Bluetooth() bluetooth.deinit() uart = UART(0, baudrate=115200) os.dupterm(uart) machine.main('main.py')
def close(self): bluetooth = Bluetooth() bluetooth.disconnect_client() bluetooth.deinit() pass
from pysense import Pysense from LIS2HH12 import LIS2HH12 from SI7006A20 import SI7006A20 from LTR329ALS01 import LTR329ALS01 from MPL3115A2 import MPL3115A2,ALTITUDE,PRESSURE from secrets import WIFISSID, WIFIPASS wdt = machine.WDT(timeout=300000) py = Pysense() mp = MPL3115A2(py,mode=ALTITUDE) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals si = SI7006A20(py) lt = LTR329ALS01(py) li = LIS2HH12(py) bt = Bluetooth() bt.set_advertisement(name="pycom") bt.advertise(True) while True: wdt.feed() bt.start_scan(10) while bt.isscanning(): time.sleep_ms(100) advs = bt.get_advertisements() devices = set() devicetypes = dict() for adv in advs: if adv.mac in devices: continue devices.add(adv.mac)
from network import Bluetooth import time bt = Bluetooth() bt.start_scan(-1) while True: adv = bt.get_adv() if adv and bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) == 'LoPy': try: 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: print('Reading chars from service = %x' % service.uuid()) chars = service.characteristics() for char in chars: if (char.properties() & Bluetooth.PROP_READ): print('char {} value = {}'.format(char.uuid(), char.read())) time.sleep(4) conn.disconnect() print("Disconnected from server") #break except: print("Error while connecting or reading from the BLE device") break else: time.sleep(0.050)
from network import Bluetooth import time bt = Bluetooth() bt.start_scan(-1) def char_cb(char): print('char {} value modified = {}'.format(hex(char.uuid()), char.read())) def bt_cb(bt): print("bt disconnected") while True: print("loop") adv = bt.get_adv() if adv and bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) == 'test': try: bt.stop_scan() conn = bt.connect(adv.mac) print("connected to My iPhone") bt.callback(Bluetooth.CLIENT_DISCONNECTED, bt_cb) services = conn.services() for service in services: print('service UUID = {}'.format(service.uuid() if isinstance( service.uuid(), bytes) else hex(service.uuid()))) if service.uuid() == 0x1111: chars = service.characteristics() for char in chars:
#=============================================================================== # This is a simple script that will provide a value to be read over BLE # # For macOS you can use the LightBlue app to observe # # service characteristics are a maximum 2 bytes in size (i.e. 0xFFFF is the max value) #=============================================================================== from network import Bluetooth import pycom import machine #=============================================================================== pycom.heartbeat(False) #=============================================================================== bluetooth = Bluetooth() bluetooth.set_advertisement(name='LoPy',manufacturer_data='Pycom', service_data='Blutooth Low Energy') bluetooth.start_scan(-1) # scan forever pycom.rgbled(0x00007f) # Blue #=============================================================================== init_value = 0x20 char1_read_counter = 0 #=============================================================================== # UUID are READ LSB first (little endian) # i.e. # b'BLUTOOTH_SERVICE' = b'424c55544f4f54485f53455256494345' # will appear as 45434956-5245-535F-4854-4F4F54554C42 b'BLUTOOTH_SERVICE' srv1 = bluetooth.service(uuid=b'BLUTOOTH_SERVICE', isprimary=True) char1 = srv1.characteristic(uuid=b'CHARACTERISTIC!!', value=40) char1.value(init_value) #=============================================================================== def char1_cb_handler(char1):
from network import Bluetooth import time bt = Bluetooth() bt.start_scan(-1) while True: adv = bt.get_adv() if adv # try to get the complete name print(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)) # try to get the manufacturer data (Apple's iBeacon data is sent here) print(binascii.hexlify(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_MANUFACTURER_DATA))) if 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: print('Reading chars from service = %x' % service.uuid()) chars = service.characteristics() for char in chars: if (char.properties() & Bluetooth.PROP_READ): print('char {} value = {}'.format(char.uuid(), char.read())) conn.disconnect() break else:
return round(-1 * temp, 2) def extractHumidity(data): 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)