예제 #1
0
    def begin(self, name):
        self._ble = Bluetooth()

        # Some apps require the service uuid to be part of the advertising packet for the device to show up
        # as Uart capable, like the Bluefruit Connect app
        self._ble.set_advertisement(
            name=name,
            service_uuid=unhex('6E400001-B5A3-F393-E0A9-E50E24DCCA9E'))
        #self._ble.set_advertisement(name=name)

        self._ble.callback(trigger=Bluetooth.CLIENT_CONNECTED
                           | Bluetooth.CLIENT_DISCONNECTED,
                           handler=self.conn_callback)
        self._ble.advertise(True)

        nus = self._ble.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,
            properties=Bluetooth.PROP_WRITE_NR,
            value='')

        self.tx = nus.characteristic(
            uuid=unhex('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'),
            #properties=Bluetooth.PROP_READ | Bluetooth.PROP_NOTIFY,
            properties=Bluetooth.PROP_NOTIFY,
            value='')

        self.tx.callback(trigger=Bluetooth.CHAR_SUBSCRIBE_EVENT,
                         handler=self.tx_subsc_callback)
        self.rx.callback(trigger=Bluetooth.CHAR_WRITE_EVENT,
                         handler=self.rx_callback)
예제 #2
0
    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
예제 #3
0
    def run(self):
        bluetooth = Bluetooth()
        bluetooth.set_advertisement(name='LoPy',
                                    service_uuid=b'1234567890123456')

        bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED
                           | Bluetooth.CLIENT_DISCONNECTED,
                           handler=self.conn_cb)
        bluetooth.advertise(True)

        #Create a new service on the internal GATT server. Returns a object of type BluetoothServerService.
        srv1 = bluetooth.service(
            uuid=self.uuid2bytes('00001819-0000-1000-8000-00805f9b34fb'),
            isprimary=True)

        #Creates a new characteristic on the service. Returns an object of the class GATTSCharacteristic
        self.char1 = srv1.characteristic(
            uuid=self.uuid2bytes('00002a67-0000-1000-8000-00805f9b34fb'),
            properties=Bluetooth.PROP_BROADCAST | Bluetooth.PROP_INDICATE,
            value=1)

        #Creates a callback that will be executed when any of the triggers occurs
        char1_cb = self.char1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT
                                       | Bluetooth.CHAR_READ_EVENT,
                                       handler=self.char1_cb_handler)
예제 #4
0
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
예제 #5
0
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 start(self):
        """ """

        print('Starting Bluetooth')
        self.bt = Bluetooth()

        # Default
        #self.bt.init(id=0, mode=Bluetooth.BLE, antenna=Bluetooth.INT_ANT, modem_sleep=True)
        #self.bt.init(id=0, antenna=Bluetooth.INT_ANT, modem_sleep=False)
        self.bt.init(modem_sleep=False)

        return

        print('Entering main loop')
        while True:
            print('--- loop ---')

            adv = self.bt.get_adv()
            print('adv:', adv)

            # Give the system some breath.
            print('machine.idle()')
            machine.idle()

            utime.sleep(10.0)
            continue
예제 #7
0
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
예제 #8
0
def init(callback):
    bt = Bluetooth()
    bt.set_advertisement(name='LoPy', service_uuid=b'1234567890123456')
    bt.callback(trigger=Bluetooth.CLIENT_CONNECTED
                | Bluetooth.CLIENT_DISCONNECTED,
                handler=callback)
    bt.advertise(True)
예제 #9
0
파일: main.py 프로젝트: jf87/PlantPy
def setup_ble():
    bt = Bluetooth()
    if C.BLE_ENABLED:
        bt.set_advertisement(name="LoPy")
        bt.advertise(True)
    else:
        bt.deinit()
예제 #10
0
def gatt_connect():
    global ble
    ble = Bluetooth()
    ble.set_advertisement(name='SiPy')
    ble.callback(trigger=Bluetooth.CLIENT_CONNECTED
                 | Bluetooth.CLIENT_DISCONNECTED,
                 handler=con_cb)
    ble.advertise(True)
예제 #11
0
 def __init__(self):
     #Body.SwarmBody.__init__(self)
     #Network.SwarmNetwork.__init__(self)
     self.bluetooth = Bluetooth()
     self.Collision_Timer = 0
     self.Tile_Transmit_Timer = 2
     self.bl_threshold = -35
     self.RepulsionTime = 2000
     pass
예제 #12
0
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
예제 #13
0
 def __init__(self):
     self._bt = Bluetooth()
     self._bt.callback(trigger=Bluetooth.CLIENT_CONNECTED,
                       handler=self.onClientConnect,
                       arg=self)
     self._bt.callback(trigger=Bluetooth.CLIENT_DISCONNECTED,
                       handler=self.onClientConnect,
                       arg=self)
     self._services = {}
예제 #14
0
 def __init__(self, buffer_size):
     """Store buffer in given storage."""
     self.beaconlist = []
     self.beacontime = []
     self.beaconrssi = []
     self.beaconevents = []
     self.beaconcount = []
     self.timelastdata = time.time()
     self.eventBuffer = RingBuffer(buffer_size)
     self.bluetooth = Bluetooth()
예제 #15
0
 def __init__(self, name, serviceUUID):
     self._bt = Bluetooth()
     self.setAdvertisement(name=name, serviceUUID=serviceUUID)
     self._bt.callback(trigger=Bluetooth.CLIENT_CONNECTED,
                       handler=self.onClientConnect,
                       arg=self)
     self._bt.callback(trigger=Bluetooth.CLIENT_DISCONNECTED,
                       handler=self.onClientConnect,
                       arg=self)
     self._services = {}
예제 #16
0
    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()
예제 #17
0
 def start(self):
     self.ble = Bluetooth()
     self.conn = self.ble.connect(self.address)
     while not self.conn.isconnected():
         sleep_ms(100)
     sleep_ms(2000)
     self.svcs = self.conn.services()
     self.chars = self.svcs[2].characteristics()
     self.devicename = self.svcs[1].characteristics()[0].read().decode(
         'utf-8')
예제 #18
0
 def power_off_bluetooth(self):
     """
     We don't use Bluetooth yet.
     """
     log.info('Turning off Bluetooth')
     try:
         from network import Bluetooth
         bluetooth = Bluetooth()
         bluetooth.deinit()
     except:
         log.exception('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)
예제 #20
0
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)
예제 #21
0
    def restart(self):
        print("BLE disconnnect client")
        bluetooth = Bluetooth()
        bluetooth.disconnect_client()
        time.sleep(2)
        self.status['connected'] = False
        if self.on_disconnect:
            self.on_disconnect()

        # bluetooth.deinit()
        # time.sleep(1)
        # self._init()
        pass
예제 #22
0
 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)
예제 #23
0
    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')
예제 #24
0
def bluetooth_scanner():
    global ble_thread
    try:
        while True:
            try:
                tools.debug('BLE - Starting BLE scanner, RSSI: ' + str(int(globalVars.RSSI_NEAR_THRESHOLD,16) - 256) + " - RTC: " + str(int(utime.time())) + " - REFRESH: " + str(globalVars.MAX_REFRESH_TIME) + " - SCAN: " + str(int(globalVars.BLE_SCAN_PERIOD)) + " - SLEEP: " + str(int(globalVars.STANDBY_PERIOD)) + " - DEBUG: " + str(globalVars.debug_cc) ,'v')
                ble_thread = True
                bluetooth = Bluetooth()
                bluetooth.tx_power(Bluetooth.TX_PWR_SCAN, Bluetooth.TX_PWR_P9)
                bluetooth.start_scan(int(globalVars.BLE_SCAN_PERIOD))
                while bluetooth.isscanning():
                    adv = bluetooth.get_adv()
                    if adv:
                        if 'WILOC_01' in str(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)):
                            data_raw = str(ubinascii.hexlify(adv.data).decode('utf-8'))
                            if globalVars.MAC_TYPE == "LORA":
                                mac_proc = data_raw[34:50] # LoRa MAC
                            elif globalVars.MAC_TYPE == "BLE":
                                mac_proc = str(ubinascii.hexlify(adv.mac).decode('utf-8')) # MAC BLE
                            tools.debug('Name: '+ str(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)) +' MAC: '+ str(mac_proc)+ ' RSSI: ' + str(adv.rssi) + ' DT: '+ str(int(utime.time())) +' RAW: ' + data_raw,'vvv')
                            if mac_proc not in globalVars.mac_scanned:
                                tools.debug('Step 1 - New device detected: ' + str(mac_proc),'vv')
                                globalVars.mac_scanned.append(mac_proc)
                            if adv.rssi >= (int(globalVars.RSSI_NEAR_THRESHOLD,16) - 256):  
                                wilocMain.checkListType(str(mac_proc), globalVars.ALARM_LIST_TYPE)
                            globalVars.scanned_frames.append(Device(addr=mac_proc,rssi=adv.rssi, raw=data_raw))
                        elif 'WIL_C01' in str(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)):
                            data_raw = str(ubinascii.hexlify(adv.data).decode('utf-8'))
                            mac_proc = str(ubinascii.hexlify(adv.mac).decode('utf-8')) # MAC BLE
                            #tools.debug('BLE Name: '+ str(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)) +' - BLE MAC: '+ str(mac_proc)+ ' - RSSI: ' + str(adv.rssi) + ' - DT: '+ str(int(utime.time())) +' - RAW: ' + data_raw,'vvv')
                            if mac_proc not in globalVars.mac_scanned:
                                tools.debug('Step 1 - BLE New device detected: ' + str(mac_proc),'vv')
                                globalVars.mac_scanned.append(mac_proc)
                            if adv.rssi >= (int(globalVars.RSSI_NEAR_THRESHOLD,16) - 256):  
                                wilocMain.checkListType(str(mac_proc), globalVars.ALARM_LIST_TYPE)
                            globalVars.scanned_frames.append(Device(addr=mac_proc,rssi=adv.rssi, raw=data_raw))

                tools.debug('BLE - Stopping BLE scanner ' + str(int(utime.time())),'v')
                tools.sleepWiloc(int(globalVars.STANDBY_PERIOD))
            except BaseException as ee1:
                checkError("Error scanning Bluetooth",ee1)
                tools.sleepWiloc(int(globalVars.STANDBY_PERIOD))
    except BaseException as e:
        checkError("Error thread Bluetooth", e)
        ble_thread = False
    finally:
        ble_thread = False
        _thread.start_new_thread(bluetooth_scanner,())
예제 #25
0
 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
예제 #26
0
    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
예제 #27
0
    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)
예제 #28
0
    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()
예제 #29
0
    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 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)