Beispiel #1
0
class bluetooth:
    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 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)
Beispiel #2
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)
Beispiel #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)
Beispiel #4
0
def setup_ble():
    bt = Bluetooth()
    if C.BLE_ENABLED:
        bt.set_advertisement(name="LoPy")
        bt.advertise(True)
    else:
        bt.deinit()
Beispiel #5
0
class ble:
    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
        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):
        if (accelerate != None):
            self.character_acc_x.value(accelerate[0])
            self.character_acc_y.value(accelerate[1])
            self.character_acc_z.value(accelerate[2])
Beispiel #6
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)
Beispiel #7
0
class PyBluetooth:
    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 = {}

    def __del__(self):
        self._bt.disconnect_client()

    def addService(self, uuid, characteristicNumber=0, isPrimary=False):
        self._services[uuid] = self._bt.service(self.formatUUID(uuid),
                                                nbr_chars=characteristicNumber,
                                                isprimary=True)
        return self._services[uuid]

    def getService(self, uuid):
        return self._services[uuid]

    def setAdvertisement(self,
                         name,
                         manufacturerData=None,
                         serviceData=None,
                         serviceUUID=None):
        self._name = name
        if serviceUUID != None:
            serviceUUID = self.formatUUID(serviceUUID)
        self._bt.set_advertisement(name=name,
                                   manufacturer_data=manufacturerData,
                                   service_data=serviceData,
                                   service_uuid=serviceUUID)

    def startAdvertisement(self):
        self._bt.advertise(True)

    def stopAdvertisement(self):
        self._bt.advertise(False)

    def formatUUID(self, uuid):
        uuid = uuid.encode().replace(b'-', b'')
        tmp = binascii.unhexlify(uuid)
        return bytes(reversed(tmp))

    def onClientConnect(self):
        events = self._bt.events()
        print("[" + self._name + "]: Client connected")
        pycom.heartbeat(False)
        pycom.rgbled(0x110011)

    def onClientDisconnect(self):
        print("[" + self._name + "]: Client disconnected")
        pycom.heartbeat(True)
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)
Beispiel #9
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)
class BLEGATTS:
    def __init__(self):
        self.bt_inst = None
        self.advert_name = None
        self.connect_callback = None
        self.is_connected = False
        self.services = { }

    def _connection_handler(self, bt):
        events = bt.events()
        if events & Bluetooth.CLIENT_CONNECTED:
            self.is_connected = True
            if self.connect_callback: 
                self.connect_callback(self.is_connected)
        elif events & Bluetooth.CLIENT_DISCONNECTED:
            self.is_connected = False
            if self.connect_callback: 
                self.connect_callback(self.is_connected)

    def init(self, advert_name, connect_callback = None):
        self.bt_inst = Bluetooth(id=0,antenna=Bluetooth.INT_ANT)
        self.advert_name = advert_name
        self.connect_callback = connect_callback
        self.bt_inst.set_advertisement(name=self.advert_name, manufacturer_data=None, service_data=None, service_uuid=None)
        self.bt_inst.callback(trigger=Bluetooth.CLIENT_CONNECTED|Bluetooth.CLIENT_DISCONNECTED, handler=self._connection_handler)

    def advertise(self, toggle=True):
        self.bt_inst.advertise(toggle)

    def disconnect(self):
        if self.is_connected:
            self.bt_inst.disconnect_client()

    def deinit(self):
        #TODO: stop services
        self.disconnect()
        self.bt_inst.deinit()

    def addService(self, service_name, uuid):
        self.services[service_name] = BLEGATTSService(self.bt_inst, uuid)
        return self.services[service_name]

    def getService(self, service_name):
        return service_name in self.services and self.services[service_name] or None

    def setCharValue(self, svc_name, char_name, value):
        if self.is_connected and svc_name in self.services and char_name in self.services[svc_name].characteristics:
            #print ('%s:%s=%s' % (svc_name,char_name,str(value)))
            self.services[svc_name].characteristics[char_name].setValue(value)
Beispiel #11
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
Beispiel #12
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)
Beispiel #13
0
    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
Beispiel #14
0
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))
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)
Beispiel #16
0
    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)
Beispiel #17
0
class BLE():
# This class initializes the BLE mode in the fipy and also checks
# if the BLE mode param is on or not

    def __init__(self, name, uuid):
        self.ble = Bluetooth()
        self.ble.set_advertisement(name=name, service_uuid=uuid)
        self.setup()

    def connect_cb(self, bt_o):
        # callback for connection
        print('enter connect_cb\n')
        events = bt_o.events()
        if events & Bluetooth.CLIENT_CONNECTED:
            print("Client connected")
        elif events & Bluetooth.CLIENT_DISCONNECTED:
            print("Client disconnected")
        self.string = ""

    def setup(self):
        # sets up all the services and characteristics
        print("Enter Setup\n")
        self.ble.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=self.connect_cb)
        self.ble.advertise(True)
        # main service switches
        config_service = self.ble.service(uuid=0xfff0, isprimary=True, nbr_chars=1)
        # main service
        self.message = config_service.characteristic(uuid=0xfff0, value=0)
        # nvram declarations
        self.string = ""
        pycom.nvs_set('id', 0)
        pycom.nvs_set('mode', 0)
        pycom.nvs_set('wifi', 0)
        pycom.nvs_set('mqtt', 0)
        pycom.nvs_set('lora', 0)
        pycom.nvs_set('ssid', 0)
        pycom.nvs_set('pass', 0)
        pycom.nvs_set('server', 0)
        pycom.nvs_set('port', 0)
        pycom.nvs_set('appSkey', 0)
        pycom.nvs_set('nwkSkey', 0)
        pycom.nvs_set('temp_sensor', 0)
        pycom.nvs_set('temp_f', 0)
        pycom.nvs_set('accl_sensor', 0)
        pycom.nvs_set('accl_f', 0)
        pycom.nvs_set('alt_sensor', 0)
        pycom.nvs_set('alt_f', 0)
        pycom.nvs_set('light_sensor', 0)
        pycom.nvs_set('light_f', 0)
        # callbacks to deploy_handler which will use the switch_dict to switch between chars
        msg_cb = self.message.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=self.msg_handler)
        # restart details callback)
        print("waiting for callback")

    def msg_handler(self,chr):
        print("Entered msg_handler\n")
        # handles write and read requests from the client
        print(chr.value())
        events = chr.events()
        if events & Bluetooth.CHAR_WRITE_EVENT:
            msg = chr.value().decode('utf-8')
            self.string += msg
            print("string is" + self.string)
            if msg[len(msg)-2:] == '>e':
                self.list = []
                self.list = self.string[:len(self.string)-2].split(";")
                msg_list = msg[1:len(msg)-2].split(";")
                print(self.list)
                self.execute(self.list)
                return # device should reset after this

        elif events & Bluetooth.CHAR_READ_EVENT:
            NvsStore('deveui', binascii.hexlify(LoRa().mac()).decode('utf-8'))
            return binascii.hexlify(LoRa().mac()).decode('utf-8')

    def execute(self, msg_list):
        for x in range(len(msg_list)):
            if msg_list[x] == '':
                msg_list[x] = '0'
        print(msg_list)
        print("count" + str(len(msg_list)))
        if len(msg_list) == 15:
                NvsStore('id', msg_list[0])
                if msg_list[2] == "1":
                    NvsStore('wifi', msg_list[2])
                    NvsStore('ssid', msg_list[5])
                    NvsStore('pass', msg_list[6])
                else:
                    pycom.nvs_set('wifi', 0)

                if msg_list[3] == "1":
                    NvsStore('mqtt', msg_list[3])
                    NvsStore('server', msg_list[7])
                    NvsStore('port', msg_list[8])
                else:
                    pycom.nvs_set('mqtt', 0)

                if msg_list[4] == "1":
                    NvsStore('lora', msg_list[4])
                    NvsStore('appskey', msg_list[9])
                    NvsStore('nwkskey', msg_list[10])
                else:
                    pycom.nvs_set('mqtt', 0)

                if msg_list[11] != 0:
                    NvsStore('temp_sensor', '1')
                    NvsStore('temp_f', msg_list[11])
                else:
                    pycom.nvs_set('temp_sensor', 0)

                if msg_list[12] != 0:
                    NvsStore('alt_sensor', '1')
                    NvsStore('alt_f', msg_list[12])
                else:
                    pycom.nvs_set('alt_sensor', 0)

                if msg_list[13] != 0:
                    NvsStore('accl_sensor', '1')
                    NvsStore('accl_f', msg_list[13])
                else:
                    pycom.nvs_set('accl_sensor', 0)

                if msg_list[14] != 0:
                    NvsStore('light_sensor', '1')
                    NvsStore('light_f', msg_list[14])
                else:
                    pycom.nvs_set('light_sensor', 0)

                if int(msg_list[2]) + int(msg_list[4]) == 0:
                    print("YAS")
                    NvsStore('mode', 0)

                NvsStore('mode', msg_list[1])
                pycom.rgbled(0xffffff)
                time.sleep(2)
                pycom.rgbled(0x000000)
                print("ENTERING DEPLOY MODE IN 5 seconds")
                time.sleep(5)
                machine.reset()
        else:
            print("INCORRECT DATA STREAM")
            self.string = ""
Beispiel #18
0
#===============================================================================
# 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):
Beispiel #19
0
from network import Bluetooth

import machine
import socket
import pycom
import binascii
import network
from network import WLAN
from machine import RTC

bluetooth = Bluetooth()
bluetooth.set_advertisement(name="lopy2", manufacturer_data="lopy_v2")
bluetooth.start_scan(
    -1)  #Change to 10 to have it searching for 10 sec instead if forever
#bluetooth.stop_scan()
adv = None
bluetooth.advertise(True)
while True:
    adv = bluetooth.get_adv()
    if adv and bluetooth.resolve_adv_data(adv.data,
                                          Bluetooth.ADV_NAME_CMPL) == 'lopy1':

        try:
            bluetooth.connect(adv.mac)

            print(
                bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_APPEARANCE))
            print("Connected to device with addr = {}".format(
                binascii.hexlify(adv.mac)))

            #bluetooth.connect(adv.mac)
Beispiel #20
0
    elif events & Bluetooth.CHAR_READ_EVENT:
        if True:
            #if char1_read_counter < 3:
            print('Read request on char 2')
        else:
            return 'ABC DEF'


#
# mkfifo ~/myfifo
# while sleep 1; do socat /dev/ttyACM1,b115200,echo=0,raw ~/myfifo; done &
# minicom -o -D ~/myfifo

bluetooth = Bluetooth()
bluetooth.set_advertisement(
    name='gpy4gcam',
    service_uuid=uuid2bytes('d9293538-3087-11ea-aec2-2e728ce88125'))
bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED
                   | Bluetooth.CLIENT_DISCONNECTED,
                   handler=conn_cb)
bluetooth.advertise(True)
# srv1 = bluetooth.service(uuid=uuid2bytes('d9293538-3087-11ea-aec2-2e728ce88125'), isprimary=True, nbr_chars=2)
srv1 = bluetooth.service(uuid=0xAA1, isprimary=True, nbr_chars=2)
cv = '2020-01-01 00:00:00'
chr1 = srv1.characteristic(uuid=0xaaa1, value=cv)
chr2 = srv1.characteristic(uuid=0xaaa2, value=9)
char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT
                         | Bluetooth.CHAR_READ_EVENT,
                         handler=char1_cb_handler)
char2_cb = chr2.callback(trigger=Bluetooth.CHAR_WRITE_EVENT
                         | Bluetooth.CHAR_READ_EVENT,
Beispiel #21
0
related to a vehicle

- 1. Shows the status of car doors
- 2. It receives the bluetooth cmds to open/close all doors
- 3. It receives the bluetooth cmds to open/close back door throw proximity sensor

"""

# Broadcasting BLE and stablish connection
from network import Bluetooth
import time
import machine

bluetooth = Bluetooth()
bluetooth.set_advertisement(name='PyWagenHub',
                            manufacturer_data='manufacturer data',
                            service_uuid=b'1234567890123456')

service = bluetooth.service(b'1234567890123457',
                            isprimary=True,
                            nbr_chars=1,
                            start=True)


def conn_cb(bt_o):
    events = bt_o.events(
    )  # This method returns the flags and clears the internal registry
    print(events)
    if events & Bluetooth.CLIENT_CONNECTED:
        print("Client connected")
    elif events & Bluetooth.CLIENT_DISCONNECTED:
Beispiel #22
0
    global char1_read_counter
    char1_read_counter += 1

    events = chr.events()
    if events & Bluetooth.CHAR_WRITE_EVENT:
        print("Write request with value = {}".format(chr.value()))
    else:
        if True:
            #if char1_read_counter < 3:
            print('Read request on char 1')
        else:
            return 'ABC DEF'


bluetooth = Bluetooth()
bluetooth.set_advertisement(name='gpy4gcam', service_uuid=1)
bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED
                   | Bluetooth.CLIENT_DISCONNECTED,
                   handler=conn_cb)
bluetooth.advertise(True)

srv1 = bluetooth.service(uuid=1, isprimary=True, start=False)
cv = '2020-01-01 00:00:00'
chr1 = srv1.characteristic(uuid=2, value=cv)
char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT
                         | Bluetooth.CHAR_READ_EVENT,
                         handler=char1_cb_handler)
srv1.start()


def chr1_update(Now):
Beispiel #23
0
                  end='')

    # If an OEM controller is found start by reading the heater data.
    if OEM_CONTROLLER_CONNECTED:
        start_state = get_heater_data
    else:
        start_state = send_controller_data

    print("Start State:{}                 ".format(start_state))

    main_protocol_thread = _thread.start_new_thread(protocol_state_machine,
                                                    (start_state, 1))

    bluetooth = Bluetooth()
    service_uuid = util.uuid2bytes('00002A6E00001000800000805F9B34FB')
    bluetooth.set_advertisement(name='Comfort', service_uuid=service_uuid)

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

    bluetooth.advertise(True)

    srv1 = bluetooth.service(uuid=service_uuid, isprimary=True, nbr_chars=2)

    heater_ch = srv1.characteristic(
        uuid=util.uuid2bytes('00001AEF00001000800000805F9B34FB'),
        properties=Bluetooth.PROP_NOTIFY,
        value=0)

    controller_ch = srv1.characteristic(
                                      "big")  # get the value from the payload
        setServoPwn(currentAngle)  # set the servo to the right position
        chr1.value(
            currentAngle)  # update the value that is displayed over Bluetooth
        print("Set new angle: ", currentAngle)


# Function to caculate the pwm value for the angle given.
def setServoPwn(angle):
    servo.duty_cycle(
        ((angle / 180) * 0.05) +
        0.05)  # calculate the right value for PWM based on the angle given


bluetooth = Bluetooth()  # Get a bluetooth instance
bluetooth.set_advertisement(name='FyPi')  # Set the name
bluetooth.callback(
    trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED,
    handler=conn_cb)  # set up the callbacks for connect and disconnect events
bluetooth.advertise(True)  # advertise the device

print("Started BLE")

srv1 = bluetooth.service(
    uuid=0x1815, isprimary=True
)  # set up the service to display the current angle of the servo
chr1 = srv1.characteristic(
    uuid=0x2763,
    value=currentAngle)  # set up the characteristic to get the server angle
char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT,
                         handler=char1_cb_handler
Beispiel #25
0
""" 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()))

Beispiel #26
0
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)
        print("MAC: "+str(ubinascii.hexlify(adv.mac)))
Beispiel #27
0
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")
Beispiel #28
0
from machine import Pin
import pycom
import time
from network import Bluetooth

bluetooth = Bluetooth()
bluetooth.set_advertisement(name='FiPy', service_uuid=0xffffff01234)

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)

bluetooth.advertise(True)

srv1 = bluetooth.service(uuid=0xfff0, isprimary=True)

chr1 = srv1.characteristic(uuid=0x1000, value="ssid")

def char1_cb_handler(chr):

    events = chr.events()
    if  events & Bluetooth.CHAR_WRITE_EVENT:
        chr1.value(chr.value())
        print("Write request with value = {}".format(chr.value()))
    else:
        return chr1.value()
Beispiel #29
0
bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb)


#BLE

bluetooth.deinit()
wlan.deinit()
lora.power_mode(LoRa.SLEEP)

bluetooth = Bluetooth()
pycom.heartbeat(False)
pycom.rgbled(0x000077)

print('sending BT')
bluetooth.set_advertisement(name='LoPy', service_uuid=b'1234567890abcdef')
bluetooth.advertise(True)

time.sleep(8)

#micro
bluetooth.deinit()
wlan.deinit()
lora.power_mode(LoRa.SLEEP)

pycom.rgbled(0x000000)
h = 0
for i in range (300000):
    h = h+1;

#WIFI
Beispiel #30
0
        # print('.', end='')


def char21_cb_handler(chr, data):
    print("char2_cb_handler")
    # The value is not used in this callback as the WRITE events are not processed.
    events, value = data
    if events & Bluetooth.CHAR_READ_EVENT:
        print('Read request on char 2')


print("init")
bt = Bluetooth()
bt.set_advertisement(
    name='Pycom BT test server5',
    service_uuid=666,
    manufacturer_data=b'deadbeef',
    service_data=b'cafebabe'
)  # bytes([0xC0, 0x01, 0xD0, 0x0D, 0xC0, 0x01, 0xD0, 0x0D, 0xC0, 0x01, 0xD0, 0x0D, 0xC0, 0x01, 0xD0, 0x0D, ])) # b'1234567890123456')
bt.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED,
            handler=conn_cb)

print("service 1")
srv1 = bt.service(
    isprimary=True, uuid=1
)  # bytes([0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, ]))
chr11 = srv1.characteristic(uuid=11, value=87)
chr11.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT,
               handler=char11_cb_handler)
chr12 = srv1.characteristic(uuid=12, value=99)
# chr13 = srv1.characteristic(uuid=13, value=33)