예제 #1
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()
예제 #2
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
예제 #3
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')
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)
예제 #5
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')
예제 #6
0
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)


#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()
예제 #7
0
 def close(self):
     bluetooth = Bluetooth()
     bluetooth.disconnect_client()
     bluetooth.deinit()
     pass
예제 #8
0
def BLEAndLoRaFun():
    ###### First, initialize as one LoRa node device ######
    # initialize LoRa in LORAWAN mode.
    # Please pick the region that matches where you are using the device:
    # Asia = LoRa.AS923
    # Australia = LoRa.AU915
    # Europe = LoRa.EU868
    # United States = LoRa.US915
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.US915)

    # create an ABP authentication params
    dev_addr = struct.unpack(">l", binascii.unhexlify('26021A14'))[0]
    nwk_swkey = binascii.unhexlify('BB515D851353D2AB5ACCD112F0F2C597')
    app_swkey = binascii.unhexlify('B74092CB7C5A79CAD681C384ABF925D2')

    # remove all the channels
    for channel in range(0, 72):
        lora.remove_channel(channel)

    # set all channels to the same frequency (must be before sending the OTAA join request)
    for channel in range(0, 72):
        lora.add_channel(channel,
                         frequency=config.LORA_FREQUENCY,
                         dr_min=0,
                         dr_max=3)

    # join a network using ABP (Activation By Personalization)
    lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

    # create a LoRa socket
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

    # set the LoRaWAN data rate
    s.setsockopt(socket.SOL_LORA, socket.SO_DR, 3)  # last parameter is 3

    # make the socket non-blocking
    s.setblocking(False)
    '''
	###### Second, set up BLE server service ######
    pycom.heartbeat(False)
    bluetooth = Bluetooth() #create a bluetooth object
    bluetooth.set_advertisement(name='LoPyServer'+str(globalvar.device_id), service_uuid=b'3333333333333333')
    
    #using callback conn_cb to check client's connection
    ##Function:   conn_cb(callback for bluetooth object events checking)
    ##Description:check there is any client connected to the service
    def conn_cb (bt_o):
        events = bt_o.events()#using events to check if there is any client connected to the service
        if  events & Bluetooth.CLIENT_CONNECTED:
            print("Client connected")
            pycom.rgbled(0x007f00) # green
        elif events & Bluetooth.CLIENT_DISCONNECTED:
            bt_o.disconnect_client()
            print("Client disconnected")
            pycom.rgbled(0x7f0000) # red    
            time.sleep(3)       
    bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb)
    bluetooth.advertise(True)
    #set up BLE service
    srv1 = bluetooth.service(uuid=b'3333333333333333', isprimary=True)
    #set up service character
    chr1 = srv1.characteristic(uuid=b'3333333333333333', value=5)
    #char1_read_counter = 0
    def char1_cb_handler(chr):
        #global char1_read_counter
        #char1_read_counter += 1
        global BLEConnectionCounter
        events = chr.events()
        if  events & Bluetooth.CHAR_WRITE_EVENT:
            print("Write request with value = {}".format(chr.value()))
        else:
            #modify here to send its device_id to other clients
            BLEConnectionCounter += 1
            return str(globalvar.device_id)+' '+str(BLEConnectionCounter)
    #using the callback to send the data to other clients
    char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char1_cb_handler)
	'''
    ###### Third, set up BLE client service ######
    bluetooth_client = Bluetooth()
    #bluetooth_client.init(id=0, mode=Bluetooth.BLE, antenna=None)
    bluetooth_client.start_scan(10)
    #server_name1 = bluetooth_client.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)

    counter = 50
    #while True:
    while counter > 0:
        print(counter)
        counter -= 1
        #Gets an named tuple with the advertisement data received during the scanning.
        #The structure is (mac, addr_type, adv_type, rssi, data)
        adv = bluetooth_client.get_adv()
        #servermac = ''#save the serer mac
        #use resolve_adv_data to resolve the 31 bytes of the advertisement message
        #Here is problem: when disconnect from server, then adv will always be null...

        #if get a valid advertisement from one server
        if adv:
            server_name = bluetooth_client.resolve_adv_data(
                adv.data, Bluetooth.ADV_NAME_CMPL)
            #print(server_name)
            if checkValidServer(server_name):
                try:
                    #Opens a BLE connection with the device specified by the mac_addr argument
                    #This function blocks until the connection succeeds or fails.
                    #print(adv.mac)
                    #global servermac#change servermac to global
                    #servermac = adv.mac
                    #counter += 1
                    conn = bluetooth_client.connect(adv.mac)
                    #print('connected?',conn.isconnected())
                    services = conn.services()
                    #print('This is service',services)
                    #print(services)
                    #Yunwei - it seems that only when the type of uuid is bytes then could read the data from server
                    for service in services:
                        time.sleep(0.050)
                        if type(service.uuid()) == bytes:
                            chars = service.characteristics()
                            for char in chars:
                                #check if the character properties is PROP_READ
                                properties = char.properties()
                                print('char properties is ' + str(properties))
                                if (properties & Bluetooth.PROP_READ):
                                    print('char {} value = {}'.format(
                                        char.uuid(), char.read()))
                                    #Use LoRa to send the data out
                                    #s.send(char.read())
                                    time.sleep(2)
                                #10 & Bluetooth.PROP_WRITE
                                #10&Bluetooth.PROP_READ
                                if (properties & Bluetooth.PROP_WRITE):
                                    print('write to server!')
                                    char.write(b'x02')
                                    time.sleep(2)
                    #Yunwei
                    conn.disconnect()
                    #bluetooth_client.deinit()
                    bluetooth_client.stop_scan()
                    time.sleep(3)
                    bluetooth_client.deinit()
                    print('deinit')
                    time.sleep(3)
                    bluetooth_client.init()
                    #if(bluetooth_client.isscanning()):
                    #    bluetooth_client.stop_scan()
                    #bluetooth_client.deinit()
                    bluetooth_client.start_scan(10)
                    print('connected?', conn.isconnected())
                    #break
                    time.sleep(3)
                    gc.collect()
                    #if it's still scan, then need to stop scan first
                    #bluetooth_client.start_scan(-1)
                    '''
                    if(bluetooth_client.isscanning()):
                        bluetooth_client.stop_scan()
                        #then scan again
                        bluetooth_client.start_scan(-1)
                    '''
                except:
                    print(
                        "Error while connecting or reading from the BLE device"
                    )
                    #break
                    time.sleep(1)
                    if (bluetooth_client.isscanning()):
                        bluetooth_client.stop_scan()
                        bluetooth_client.deinit()
                        time.sleep(1)
                        bluetooth_client.deinit()
                        time.sleep(1)
                        #init again
                        bluetooth_client.init(id=0,
                                              mode=Bluetooth.BLE,
                                              antenna=None)
                        bluetooth_client.start_scan(10)
                    else:
                        bluetooth_client.deinit()
                        time.sleep(1)
                        bluetooth_client.init()
                        time.sleep(1)
                        bluetooth_client.start_scan(10)
                    print('Scan again')
        else:
            print('adv is None!')
            time.sleep(3)
            '''
            time.sleep(3)
            #if it's still scan, then need to stop scan first
            if(bluetooth_client.isscanning()):
                bluetooth_client.stop_scan()
                #then scan again
                bluetooth_client.start_scan(-1)
            '''
    #bluetooth_client.stop_scan()
    bluetooth_client.stop_scan()
    bluetooth_client.deinit()
    print('out of loop!')
예제 #9
0
from machine import UART
import machine
import os
from network import Bluetooth

uart = UART(0, baudrate=115200)
os.dupterm(uart)

# Turn off Bluetooth
bt = Bluetooth()
bt.deinit()

machine.main('main.py')
def BLEClient():
    #Description: check if the BLE server is set up by another LoPy
    #Note: for convention reason, the LoPy server name will be "LoPyServer"+device_id
    def checkValidServer(server_name):
        if (server_name == None): return False
        else:
            #check if server_name contains "LoPyServer"
            if (re.match('LoPyServer*', server_name)):
                return True
            else:
                return False

    global rec_msg
    ###### Third, set up BLE client service ######
    bluetooth_client = Bluetooth()
    bluetooth_client.start_scan(10)
    #server_name1 = bluetooth_client.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)

    counter = 50
    #while True:
    while counter > 0:

        #Gets an named tuple with the advertisement data received during the scanning.
        #The structure is (mac, addr_type, adv_type, rssi, data)
        adv = bluetooth_client.get_adv()
        #servermac = ''#save the serer mac
        #use resolve_adv_data to resolve the 31 bytes of the advertisement message
        #Here is problem: when disconnect from server, then adv will always be null...

        #if get a valid advertisement from one server
        if adv:
            server_name = bluetooth_client.resolve_adv_data(
                adv.data, Bluetooth.ADV_NAME_CMPL)
            #print(server_name)
            if checkValidServer(server_name):
                try:
                    #Opens a BLE connection with the device specified by the mac_addr argument
                    #This function blocks until the connection succeeds or fails.
                    #print(adv.mac)
                    #global servermac#change servermac to global
                    #servermac = adv.mac
                    #counter += 1
                    conn = bluetooth_client.connect(adv.mac)
                    #print('connected?',conn.isconnected())
                    services = conn.services()
                    #print('This is service',services)
                    #print(services)
                    #Yunwei - it seems that only when the type of uuid is bytes then could read the data from server
                    for service in services:
                        time.sleep(0.050)
                        if type(service.uuid()) == bytes:
                            chars = service.characteristics()
                            for char in chars:
                                #check if the character properties is PROP_READ
                                if (char.properties() & Bluetooth.PROP_READ):
                                    print('char {} value = {}'.format(
                                        char.uuid(), char.read()))
                                    #create lora msg
                                    rec_msg = str(char.read())
                                    counter -= 1
                                    #Use LoRa to send the data out
                                    #s.send(char.read())
                                    time.sleep(5)
                    #Yunwei
                    conn.disconnect()
                    print('connected?', conn.isconnected())
                    #break
                    time.sleep(3)
                    gc.collect()
                    bluetooth_client.start_scan(10)
                except:
                    print(
                        "Error while connecting or reading from the BLE device"
                    )
                    #break
                    time.sleep(1)
                    if (bluetooth_client.isscanning()):
                        bluetooth_client.stop_scan()
                        bluetooth_client.deinit()
                        time.sleep(1)
                        bluetooth_client.init()
                        time.sleep(1)
                        #init again
                        #bluetooth_client.init(id=0, mode=Bluetooth.BLE, antenna=None)
                        bluetooth_client.start_scan(10)
                    else:
                        bluetooth_client.deinit()
                        time.sleep(1)
                        bluetooth_client.init()
                        time.sleep(1)
                        bluetooth_client.start_scan(10)
    bluetooth_client.stop_scan()
    bluetooth_client.deinit()
예제 #11
0
import cayenneLPP  #Low power packet forwarding
import time
import gc
import math
import binascii
import struct

#Enable garbage collection:
gc.enable()
gc.collect()

#Close Unnecessary functions:
ds = DeepSleep()
#ds.enable_auto_poweroff() #enable auto power off
bt = Bluetooth()
bt.deinit()  #close bluetooth
wlan = network.WLAN()
wlan.deinit()  #close WLAN

py = Pytrack()
acc = LIS2HH12()
l76 = L76GNSS(py, timeout=10)

pycom.heartbeat(False)

#Lora settings:
lora = LoRa(mode=LoRa.LORAWAN,
            region=LoRa.US915,
            adr=False,
            device_class=LoRa.CLASS_A,
            tx_power=20)
예제 #12
0
from network import Bluetooth
bluetooth = Bluetooth()
bluetooth.deinit()  #not using Bluetooth, so disable to save energy
예제 #13
0
import pycom
import machine
from machine import Pin

pycom.heartbeat(False)

from network import WLAN
from network import Bluetooth
import os

pycom.wifi_on_boot(False)
wlan = WLAN()  # Instantiates WLAN
wlan.deinit()  # Turns off wifi
bluetooth = Bluetooth()  # Instantiates Bluetooth
bluetooth.deinit()  # Turns off Bluetooth

counter = pycom.nvs_get('count')  # Get ID value from memory

if type(counter) != int:  # If the value is not in memory
    pycom.nvs_set('count', 0)  # ID = 0
예제 #14
0
class BLEUart:
    def __init__(self):
        self.status = {'connected': False}

        self.rx_data = []

    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)

    def end(self):
        self.status['connected'] = False
        self.rx_data = []
        self._ble.disconnect_client()
        self._ble.deinit()

    def conn_callback(self, bt):
        events = bt.events()
        if events & Bluetooth.CLIENT_CONNECTED:
            print("Client connected")
            self.status['connected'] = True
        elif events & Bluetooth.CLIENT_DISCONNECTED:
            print("Client disconnected")
            self.status['connected'] = False
            self.rx_data = []

    def rx_callback(self, chr, msg):
        data = chr.value()
        #print('BLE data received')
        strdata = str(data, 'utf-8')
        #print('> ', strdata)
        self.rx_data.append(strdata)

    def tx_subsc_callback(self, chr, msg):
        print("Client subscribed", chr.value())

    def write(self, msg):
        if self.status['connected'] == True:
            while len(msg):
                data = msg[:20]
                msg = msg[20:]
                print('BLE data send:')
                print('<', data)
                self.tx.value(data)

            self.tx.value('\r\n')

    def available_data(self):
        return (True if (len(self.rx_data) > 0) else False)

    def get_data(self):
        if self.available_data():
            data = self.rx_data[0]
            del self.rx_data[0]
            return data
        else:
            return 0
예제 #15
0
# switch off pycom funtions on boot, add more after testing
pycom.wifi_on_boot(False)
pycom.heartbeat_on_boot(False)
pycom.pybytes_on_boot(False)
pycom.wdt_on_boot(False)

print("Reset Cause: ", machine.reset_cause())

# external RTC with i2c address 104

# initialize RTC
rtc = RTC()

# Disable Blueooth Radio
ble = Bluetooth()
ble.deinit()

# Initialize wifi
connectwifi = ConnectWIFI()

# wakeup reason and logic ?


def ext_rtc_sync():
    print("Syncing RTC .....")
    rtc_sync()
    try:
        print("Updating External RTC ...")
        ds3231.save_time()
        print("External RTC updated")
    except: