Exemple #1
0
    def __init__(self):
        """
        Create instance of _PoweredUPHandler
        """
        # constants
        self.__IRQ_SCAN_RESULT = const(1 << 4)
        self.__IRQ_SCAN_COMPLETE = const(1 << 5)
        self.__IRQ_PERIPHERAL_CONNECT = const(1 << 6)
        self.__IRQ_PERIPHERAL_DISCONNECT = const(1 << 7)
        self.__IRQ_GATTC_SERVICE_RESULT = const(1 << 8)
        self.__IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9)
        self.__IRQ_GATTC_READ_RESULT = const(1 << 11)
        self.__IRQ_GATTC_NOTIFY = const(1 << 13)

        self.__LEGO_SERVICE_UUID = ubluetooth.UUID(
            "00001623-1212-EFDE-1623-785FEABCD123")
        self.__LEGO_SERVICE_CHAR = ubluetooth.UUID(
            "00001624-1212-EFDE-1623-785FEABCD123")

        # class specific
        self.__ble = ubluetooth.BLE()
        self.__ble.active(True)
        self.__ble.irq(handler=self.__irq)
        self.__decoder = _Decoder()
        self.__reset()
        self.debug = False

        # callbacks
        self.__scan_callback = None
        self.__read_callback = None
        self.__notify_callback = None
        self.__connected_callback = None
        self.__disconnected_callback = None
Exemple #2
0
    def __init__(self):
        # constants
        self.__IRQ_SCAN_RESULT = const(1 << 4)
        self.__IRQ_SCAN_COMPLETE = const(1 << 5)
        self.__IRQ_PERIPHERAL_CONNECT = const(1 << 6)
        self.__IRQ_PERIPHERAL_DISCONNECT = const(1 << 7)
        self.__IRQ_GATTC_SERVICE_RESULT = const(1 << 8)
        self.__IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9)
        self.__IRQ_GATTC_DESCRIPTOR_RESULT = const(1 << 10)
        self.__IRQ_GATTC_READ_RESULT = const(1 << 11)
        self.__IRQ_GATTC_NOTIFY = const(1 << 13)

        # used to enable notifications
        self.__NOTIFY_ENABLE = const(1)

        # enter device specific service and characteristic UUIDs (from nRF Connect app)
        # the service and characteristic UUIDs below are for the HM-10 BluetoothLE module
        self.__PERIPHERAL_SERVICE_UUID = ubluetooth.UUID(0xFFE0)
        self.__PERIPHERAL_SERVICE_CHAR = ubluetooth.UUID(0xFFE1)
        # enter peripheral device ID here
        self.__DEVICE_ID = b'\x00\x00\x00\x00\x00\x00'

        # class specific
        self.__ble = ubluetooth.BLE()
        self.__ble.active(True)
        self.__ble.irq(handler=self.__irq)
        self.__decoder = Decoder()
        self.__reset()
Exemple #3
0
 def __init__(self, whitelist=None, blacklist=[]):
     self._ble = ubluetooth.BLE()
     self._ble.active(True)
     self._ble.irq(self.irq_handler)
     self._tags = []  # store for processed tags reset each scan
     self._addrs = []  # store for received addresses reset each scan
     self._callback_handler = None
     self._whitelist = whitelist
     self._blacklist = blacklist
Exemple #4
0
def demo_auto():
    ble = ubluetooth.BLE()
    mf = MiFlora(ble)
    print("demo_auto()")

    while True:
        
        for addr in miflora_sensors:
            mf.search_addr    = addr
            mf.search_service = _GENERIC_ACCESS_SERVICE_UUID

            if SCAN_DEVICES:
                print("Searching for device with MAC address {}...".format(binascii.hexlify(addr)))
                
                mf.scan(callback=mf.scan_done)
            else:
                print("Trying to connect to device with MAC address {}...".format(binascii.hexlify(addr)))
                
                rc = mf.gap_connect(ADDR_TYPE_PUBLIC, addr)
                print("gap_connect() = ", rc)
                
            ########################################
            # Time to perform other tasks...
            ########################################
            
            # The time required depends on the number of visible devices and
            # the selected service discovery/characteristics discovery options.
            if mf.wait_for(S_READ_SENSOR_DONE, 20000):
                if SCAN_DEVICES:
                    print("Sensor '{}' found.".format(mf.name))
                    print("RSSI: {}dbB".format(mf.rssi))
                print("Battery Level: {}%".format(mf.battery))
                print("Version: {}".format(mf.version))
                print("Temperature: {}°C Light: {}lx Moisture: {}% Conductivity: {}µS/cm".format(
                    mf.temp, mf.light, mf.moist, mf.cond)
                )
            else:
                print("Reading sensor data failed (timeout)!")

            mf.disconnect()
            
            if mf.wait_for_connection(False, 10000):
                print("Disconnected")
            else:
                print("Disconnect failed (timeout)!")
                mf._reset()

        print("Sleeping {} seconds...".format(_T_CYCLE))
        time.sleep(_T_CYCLE)
Exemple #5
0
def bleinit(state=True):
    global BLEDev
    try:
        if BLEDev is None:
            BLEDev = ubluetooth.BLE()
    except:
        return False
    try:
        if state:
            if BLEDev.active() == False:
                BLEDev.active(True)
        else:
            if BLEDev.active():
                BLEDev.active(False)
    except:
        pass
Exemple #6
0
    def __init__(self, name):
        # Stores connection status
        self._status = False
    
        self.name = name
        self.ble = ubluetooth.BLE()
        self.ble.active(True)

        self.led = Pin(2, Pin.OUT)
        self.timer1 = Timer(0)
        self.timer2 = Timer(1)
        
        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()
    def __init__(self):
        # constants
        self.__IRQ_SCAN_RESULT = const(1 << 4)
        self.__IRQ_SCAN_COMPLETE = const(1 << 5)
        self.__IRQ_PERIPHERAL_CONNECT = const(1 << 6)
        self.__IRQ_PERIPHERAL_DISCONNECT = const(1 << 7)
        self.__IRQ_GATTC_SERVICE_RESULT = const(1 << 8)
        self.__IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9)
        self.__IRQ_GATTC_READ_RESULT = const(1 << 11)
        self.__IRQ_GATTC_NOTIFY = const(1 << 13)

        self.__LEGO_SERVICE_UUID = ubluetooth.UUID("00001623-1212-EFDE-1623-785FEABCD123")
        self.__LEGO_SERVICE_CHAR = ubluetooth.UUID("00001624-1212-EFDE-1623-785FEABCD123")

        # class specific
        self.__ble = ubluetooth.BLE()
        self.__ble.active(True)
        self.__ble.irq(handler=self.__irq)
        self.__decoder = Decoder()
        self.__reset()
Exemple #8
0
def demo():
	from machine import Pin

	def rx_callback(data):
		print("rx received: {}".format(data))

		led.value(1 if data == b'on' else 0)
		uart.send("on" if led.value() else "off")

	def button_callback(pin):
		led.value(not led.value())
		uart.send("on" if led.value() else "off")

	ble = bt.BLE()
	uart = BLEUART(ble, rx_callback)

	led = Pin(2, Pin.OUT, value=0)
	button = Pin(0, Pin.IN, Pin.PULL_UP)

	button.irq(button_callback, Pin.IRQ_RISING)
Exemple #9
0
    def __init__(self, name):
        self.name = name
        self.ble = ubluetooth.BLE()
        self.ble.active(True)

        pin_OUT = Pin(LOADCELL_DOUT_PIN, Pin.IN, pull=Pin.PULL_DOWN)
        pin_SCK = Pin(LOADCELL_SCK_PIN, Pin.OUT)
        self.hx711 = HX711(pin_SCK, pin_OUT)
        self.hx711.set_scale(config[SCALE])
        self.hx711.set_offset(config[OFFSET])

        self.timer3 = Timer(2)

        # Modificamos el advertiser cada cierto tiempo
        self.timer3.init(
            period=config[INTERVAL_MS],
            mode=Timer.PERIODIC,
            callback=lambda _: self.advertiser(),
        )

        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()
Exemple #10
0
 def __init__(self, debug=False):
     self._ble = ubluetooth.BLE()
     self._ble.active(True)
     self._ble.irq(self._irq)
     self._reset()
     self.debug = debug
Exemple #11
0
        ble.gap_advertise(None)
        print('[bluetooth] device connected')
    elif event == _IRQ_CENTRAL_DISCONNECT:
        # A central has disconnected from this peripheral.
        conn_handle, addr_type, addr = data
        connections.remove(conn_handle)
        ble.gap_advertise(500000)
        print('[bluetooth] device disconnected')
    else:
        print('[bluetooth] received event {}'.format(event))


# entrypoint
i2c = I2C(0)
imu = MPU6050(i2c)
ble = bluetooth.BLE()
ble.active(True)
ble.irq(bt_irq)
ble.config(gap_name='Bosu')

# configure the services that will be advertised
ACCEL_UUID = bluetooth.UUID('7ED5A5BC-8013-4753-B199-0A364D52E5DE')
ACCEL_CHAR = (
    bluetooth.UUID('F477FD95-41F0-4C73-9093-5DA7DC624DF0'),
    bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
)
ACCEL_SERVICE = (
    ACCEL_UUID,
    (ACCEL_CHAR, ),
)
SERVICES = (ACCEL_SERVICE, )
Exemple #12
0
import ntptime
import time
from micropython import const
import ubluetooth
import gc
import _thread
#import umqtt
import robust2 as umqtt
from collections import OrderedDict

gc.enable()

#-###
#-###
#-### activate ble
ble = ubluetooth.BLE()
if ble.active() == False:
    ble.active(True)

#-###
#-###
#-### create timers
timer_scan = machine.Timer(0)
timer_work = machine.Timer(1)
timer_clean = machine.Timer(2)

#-###
#-###
#-### conenct to network
station = network.WLAN(network.STA_IF)
station.active(True)
import ubluetooth

bt = ubluetooth.BLE()
bt.active(True)
print(bt.config('mac'))
print(bt.config('addr_mode'))
#bt.gap_advertise(10000, adv_data='payload')
Exemple #14
0
 def __init__(self):
     self._ble = ubluetooth.BLE()
     self._ble.active(True)
     self._ble.irq(handler=self._irq)
     self._decoder = Decoder()
     self._reset()
Exemple #15
0
def handle_blescan(httpResponse):
    global bleok
    ws.navMenuIndex = 7
    ws.TXBuffer = ""
    httpResponse.WriteResponseOk(headers=({
        'Cache-Control': 'no-cache'
    }),
                                 contentType='text/html',
                                 contentCharset='UTF-8',
                                 content="")
    ws.sendHeadandTail("TmplStd", ws._HEAD)
    if bleok:
        try:
            BLEHelper.BLEStatus.reportscan(1)
            scanner = BTLE.Scanner(ubluetooth.BLE())
            devices = scanner.scan(15, passive=False)
            BLEHelper.BLEStatus.reportscan(0)
        except Exception as e:
            ws.TXBuffer += "BLE scanning failed "
            ws.TXBuffer += str(e)
            bleok = False
    else:
        ws.TXBuffer += "BLE not supported"
    if bleok:
        ws.TXBuffer += "<table class='multirow'><TR><TH>Address<TH>Address type<TH>RSSI<TH>Connectable<TH>Name<TH>Appearance</TH><TH>Actions</TH></TR>"
        cc = 0
        for dev in devices:
            cc += 1
            ws.TXBuffer += "<TR><TD><div id='mac" + str(
                cc) + "_1' name='mac" + str(cc) + "_1'>" + str(
                    dev.addr) + "</div><TD>" + str(
                        dev.addrType) + "<TD>" + str(
                            dev.rssi) + " dBm<TD>" + str(dev.connectable)
            dname = ""
            shortdname = ""
            appear = ""
            for (adtype, desc, value) in dev.getScanData():
                #        print(adtype,desc,value)#debug
                try:
                    if desc.lower() == "complete local name":
                        dname = str(value)
                except:
                    pass
                try:
                    if desc.lower() == "shortened local name":
                        shortdname = str(value)
                except:
                    pass
                try:
                    if desc.lower() == "appearance":
                        appear = str(value)
                except:
                    pass
            if dname.strip() == "":
                dname = shortdname
            ws.TXBuffer += "<TD>" + str(dname) + "<TD>" + str(appear) + "<TD>"
            ws.TXBuffer += "</TR>"
            httpResponse._write(ws.TXBuffer, strEncoding='UTF-8')
            ws.TXBuffer = ""
        ws.TXBuffer += "</table>"
    ws.sendHeadandTail("TmplStd", ws._TAIL)
    httpResponse._write(ws.TXBuffer, strEncoding='UTF-8')
    ws.TXBuffer = ""
Exemple #16
0
def demo_man():
    ble = ubluetooth.BLE()
    mf = MiFlora(ble)
    print("demo_man()")
    
    while True:
        for addr in miflora_sensors:
            mf.search_addr    = addr
            mf.search_service = _GENERIC_ACCESS_SERVICE_UUID

            if SCAN_DEVICES:
                print("Searching for device with MAC address {}...".format(binascii.hexlify(addr)))
                
                mf.scan(callback=mf.scan_done)
                
                if mf.wait_for(S_SCAN_DONE, 2500):
                    print("Scan done.")
                else:
                    print("Scan timeout!")
                    continue
                    
                if mf.addr_found == False:
                    print("Sensor not found!")
                    continue
                
                print("Sensor '{}' found.".format(mf.name))
                print("RSSI: {}dbB".format(mf.rssi))
        
            print("Trying to connect to device with MAC address {}...".format(binascii.hexlify(addr)))
            rc = mf.gap_connect(ADDR_TYPE_PUBLIC, addr)
            print("gap_connect() = ", rc)
            
            if mf.wait_for_connection(True, 3000):
                print("Connected")
            else:
                print("Connection failed!")
                continue
            
            if DISCOVER_SERVICES:
                mf.discover_services()
                
                if mf.wait_for(S_SERVICE_DONE, 2500):
                    print(mf.services)
                else:
                    print("discover_services failed!")
                
            if DISCOVER_CHARACTERISTICS:
                mf.discover_characteristics(1, 9)
                
                if mf.wait_for(S_CHARACTERISTIC_DONE, 2500):
                    print(mf.characteristics)
                else:
                    print("discover_characteristics failed!")
            
            mf.read_firmware(callback=mf.read_firmware_done)
        
            if mf.wait_for(S_READ_FIRMWARE_DONE, 2000):
                print("Battery Level: {}%".format(mf.battery))
                print("Version: {}".format(mf.version))
        
                mf.mode_change(mf.mode_change_done)
        
                if not mf.wait_for(S_MODE_CHANGE_DONE, 2000):
                    print("Mode change failed!")
                    break;
            
                mf.read_sensor(callback=mf.read_sensor_done)
                
                if mf.wait_for(S_READ_SENSOR_DONE, 2000):
                     print("Temperature: {}°C Light: {}lx Moisture: {}% Conductivity: {}µS/cm".format(
                        mf.temp, mf.light, mf.moist, mf.cond)
                    )
                else:
                    print("Reading sensor data failed!")
            else:
                print("Reading sensor firmware version and battery status failed!")

            mf.disconnect()
            
            if mf.wait_for_connection(False, 10000):
                print("Disconnected")
            else:
                print("Disconnect failed!")
                mf._reset()

        print("Sleeping {} seconds...".format(_T_CYCLE))
        time.sleep(_T_CYCLE)