コード例 #1
0
def demo():
    ble = bluetooth.BLE()
    p = BLEGattServer(ble)
    num_revs = 0

    while True:
        if p.is_connected():
            # Short burst of queued notifications.

            ## CSC Measurement Buffer
            # https://www.bluetooth.com/wp-content/uploads/Sitecore-Media-Library/Gatt/Xml/Characteristics/org.bluetooth.characteristic.csc_measurement.xml
            #
            # Features:
            #   [Flags] 8 bit
            #   [Cumulative Wheel Revolutions] uint32
            #   [Last Wheel Event Time]  uint16
            #   [Cumulative Crank Revolutions] uint16
            #   [Last Crank Event Time] uint16

            num_revs += 1
            contains_data = "{0:08b}".format(2)
            cum_crank_revolutions = "{0:016b}".format(num_revs)
            last_event_time = "{0:016b}".format(
                int(1024 * utime.ticks_us() / (1e6)))
            package = int(
                last_event_time + cum_crank_revolutions + contains_data,
                2).to_bytes(5, 'little')

            p.send(package)
            print('Writing: ', package)
            utime.sleep(1)
コード例 #2
0
    def __init__(self, name="esp32-fmpt", led=None):
        self.timer = Timer(-1)
        self.led = led
        self.irq_busy = False
        self.buzz = NOTIFYER(25, 13)
        self.i = 0
        self._is_connected = False
        self.alert_level = 0
        self._ble = bluetooth.BLE()
        self._ble.active(True)
        self._ble.irq(handler=self._irq)
        ((self._appear, self._manufact, self._model, self._firm),
         (self._alert_handle, )) = self._ble.gatts_register_services(
             (_DEV_INF_SERV_SERVICE, _IMMEDIATE_ALERT_SERVICE))
        self._connections = set()
        self._payload = advertising_payload(
            name=name,
            services=[_IMMEDIATE_ALERT_SERV_UUID],
            appearance=_ADV_APPEARANCE_GENERIC_KEYRING)
        # print(len(self._payload))
        # First 30 seconds (fast connection) Advertising Interval 20 ms to 30 ms
        print('Advertising in fast connection mode for 30 seconds...')
        self._advertise(interval_us=30000)
        self._ble.gatts_write(
            self._appear, struct.pack("h", _ADV_APPEARANCE_GENERIC_KEYRING))
        self._ble.gatts_write(self._manufact,
                              bytes('Espressif Incorporated', 'utf8'))
        self._ble.gatts_write(self._model, bytes(_MODEL_NUMBER, 'utf8'))
        self._ble.gatts_write(self._firm, bytes(_FIRMWARE_REV, 'utf8'))

        # Timeout 30 s
        self.start_adv_fast_timeout()
コード例 #3
0
ファイル: desk.py プロジェクト: DavidVentura/iot_home
 def __init__(self, macaddr):
     ble = bluetooth.BLE()
     self.bt = BLESimpleCentral(ble, self._move_to_target)
     self.bt.connect(1, macaddr)
     self._height_target = None
     while not self.bt.is_connected():
         time.sleep_ms(100)
コード例 #4
0
def demo():
    from main import UartBLE
    from test import cada1SegundoEnviar

    bt = bluetooth.BLE()
    taximetro = UartBLE(bt)
    cada1SegundoEnviar(taximetro=taximetro, texto='texto', led=True)
コード例 #5
0
def ble_connect(device='yolobit'):
    global bt
    bt = BLESimpleCentral(bluetooth.BLE())
    not_found = False

    def on_scan(addr_type, addr, name):
        nonlocal device
        print(device)
        #print("Found peripheral:", name)
        if addr_type is not None and name == device:
            bt.connect()
        else:
            nonlocal not_found
            not_found = True
            print("No peripheral found.")

    bt.scan(callback=on_scan)

    # Wait for connection...
    timeout = 100
    while not bt.is_connected() and timeout > 0:
        time.sleep_ms(100)
        if not_found:
            return False
        timeout -= 1

    if timeout < 0:
        print("Connect failed")
        return False

    print("Connected")
    #bt.on_notify(_ble_on_rx)
    return True
コード例 #6
0
def start():
    bname = '{}-{}'.format(platform, hexlify(unique_id()).decode())
    ble = bluetooth.BLE()
    uart = BLEUART(ble, name=bname)
    stream = BLEUARTStream(uart)

    os.dupterm(stream)
コード例 #7
0
def main():
    ble = bluetooth.BLE()
    remote = BLEHeadrushRemote(ble)

    previous_pot_value = -1
    button_down = None
    button_hall_sensor = False
    button_hall_sensor_down = False
    button_pot = False
    button_pot_down = False
    while True:
        if remote.is_connected():
            # foot switches
            for command, button in _BUTTON_PIN_MAP.items():
                if not button_down == command and button.value() == 0:
                    button_down = command
                    print("sending '{command}'.".format(command=command))
                    # remote.send(struct.pack("I", command))
                    remote.send(command)
                    blink_led(2)
                    break
                elif button_down == command and button.value() == 1:
                    button_down = None

            # POT
            if _BUTTON_POT.value() == 0 and not button_pot_down:
                button_pot = not button_pot
                button_pot_down = True
            elif _BUTTON_POT.value() == 1 and button_pot_down:
                button_pot_down = False
            if button_pot:
                pot_value = int(_POT.read() / 32)
                if previous_pot_value not in [
                        pot_value - 1, pot_value, pot_value + 1
                ]:
                    # wheels: 61, 62, 63
                    number = 61
                    previous_pot_value = pot_value
                    remote.send("POT|{}|{}".format(number, pot_value))
                if _LED_POT_STATUS.value() == 0:
                    _LED_POT_STATUS.value(1)
            else:
                if _LED_POT_STATUS.value() == 1:
                    _LED_POT_STATUS.value(0)

            # Hall sensor
            if _BUTTON_HALL_SENSOR.value(
            ) == 0 and not button_hall_sensor_down:
                button_hall_sensor = not button_hall_sensor
                button_hall_sensor_down = True
            elif _BUTTON_HALL_SENSOR.value() == 1 and button_hall_sensor_down:
                button_hall_sensor_down = False
            if button_hall_sensor:
                hall_vallue = esp32.hall_sensor()
                print(hall_vallue)
                if _LED_HALL_SENSOR.value() == 0:
                    _LED_HALL_SENSOR.value(1)
            else:
                if _LED_HALL_SENSOR.value() == 1:
                    _LED_HALL_SENSOR.value(0)
コード例 #8
0
    def __init__(self, name, network, state=[], debug=False):
        if debug:
            print('init')
        self._ble = bluetooth.BLE()
        self._ble.active(True)
        self._debug = debug
        self._ble.irq(self._irq)
        self._not_found = False
        self._name = name
        self._network = network
        self._address = network[name]
        self._set_local_network()
        self.state = state

        self._scanning = False
        self._connecting_device = None

        ## Connection to Parent
        ((self._handle_tx,
          self._handle_rx), ) = self._ble.gatts_register_services(
              (_UART_SERVICE, ))
        self._ble.gatts_write(self._handle_rx,
                              bytes(100))  #set max message size to 100 bytes
        self._ble.gatts_set_buffer(self._handle_rx, 100)
        self._ble.gatts_set_buffer(self._handle_tx, 100)
        self._conn_handle_parent = None

        self._response_received = True
        self._write_callback = None
        self._payload = advertising_payload(name=name, services=[_UART_UUID])

        self._reset()
コード例 #9
0
def demo4(): #FUNCIONA OK CON ALIMENTACION EXTERNA DESDE EL RELOJ Y LED A 5V
    from main import UartBLE
    from test import cada1SegundoEnviar

    bt = bluetooth.BLE()
    taximetro = UartBLE(bt)
    cada1SegundoEnviar(taximetro=taximetro,texto='texto',led=True)
コード例 #10
0
    def __init__(self, device_name="Generic HID Device"):
        self._ble = bluetooth.BLE()
        self.adv = None
        self.device_state = DEVICE_STOPPED
        self.conn_handle = None
        self.state_change_callback = None

        print("Server created")

        self.device_name = device_name
        self.service_uuids = [UUID(0x180A),
                              UUID(0x180F),
                              UUID(0x1812)]  # Service UUIDs: DIS, BAS, HIDS
        self.device_appearance = 960  # Generic HID Appearance
        self.battery_level = 100

        self.DIS = (  # Device Information Service description
            UUID(0x180A),  # Device Information
            (
                (UUID(0x2A50), F_READ),  # PnP ID
            ),
        )
        self.BAS = (  # Battery Service description
            UUID(0x180F),  # Device Information
            (
                (UUID(0x2A19), F_READ_NOTIFY),  # Battery level
            ),
        )

        self.services = [self.DIS,
                         self.BAS]  # List of service descriptions, append HIDS

        self.HID_INPUT_REPORT = None
コード例 #11
0
def demo2(): #FUNCIONA OK CON USB PERO NO CON ALIMENTACION EXTERNA
    from main import UartBLE
    from test import cada1SegundoEnviar

    bt = bluetooth.BLE()
    taximetro = UartBLE(bt)
    cada1SegundoEnviar(taximetro,'texto')
コード例 #12
0
def main():
    ble = bluetooth.BLE()
    servant = BLEHeadrushServant(ble)

    def on_scan(addr_type, addr, name):
        if addr_type is not None:
            print("Remote found:", addr_type, addr, name)
            servant.connect()
        else:
            print("Remote not found.")

    # Wait for connection...
    while not servant.is_connected():
        print("scanning for remote...")
        servant.scan(callback=on_scan)
        sleep_ms(2500)

    blink_led(1, 4)
    print("Connected")

    # Explicitly issue reads, using "print" as the callback.
    # while servant.is_connected():
    #     servant.read(callback=command_received_fallback)
    #     time.sleep_ms(2000)

    # Alternative to the above, just show the most recently notified value.
    # while servant.is_connected():
    #     # command_received_fallback(servant.value())
    #     sleep_ms(100)

    print("Disconnected")
コード例 #13
0
 def __init__(self, ble, name="esp32-voltmeter"):
     self.ads_dev = MY_ADS(ADS1115, i2c)
     self.init_ads()
     self.ads_timer = Timer(-1)
     self.irq_busy = False
     self.min_volt = None
     self.typ_volt = None
     self.max_volt = None
     self.ads_dev.ads.conversion_start(7, channel1=self.ads_dev.channel)
     self.i = 0
     self._ble = bluetooth.BLE()
     self._ble.active(True)
     self._ble.irq(handler=self._irq)
     ((self._appear, self._manufact, self._model, self._firm), (self._volt_h,)) = self._ble.gatts_register_services(
         (_DEV_INF_SERV_SERVICE, _ADS_SERV_SERVICE))
     self._connections = set()
     self._payload = advertising_payload(
         name=name, services=[
             _ENV_SERV_UUID], appearance=_ADV_APPEARANCE_HID_DIGITAL_PEN
     )
     self._advertise(interval_us=30000)
     self._ble.gatts_write(self._appear, struct.pack(
         "h", _ADV_APPEARANCE_HID_DIGITAL_PEN))
     self._ble.gatts_write(self._manufact, bytes('Espressif Incorporated',
                                                 'utf8'))
     self._ble.gatts_write(self._model, bytes(_MODEL_NUMBER, 'utf8'))
     self._ble.gatts_write(self._firm, bytes(_FIRMWARE_REV, 'utf8'))
     volt_sample = (self.ads_dev.ads.raw_to_v(
         self.ads_dev.ads.alert_read()))
     volt_bin = int(volt_sample / (2**(-6)))
     self._ble.gatts_write(self._volt_h, struct.pack(
         "H", volt_bin))
コード例 #14
0
    def __init__(self, name=b'mpy_centeral'):

        self.ble = bluetooth.BLE()
        self.ble.active(True)
        self.ble.config(gap_name=name)
        print("BLE: activated!")
        self.ble.irq(self._irq)
        self._debug = False
        self._reset()
コード例 #15
0
def demo():
    import time

    ble = bluetooth.BLE()
    uart = BLEUART(ble)

    def on_rx():
        print("rx: ", uart.read().decode().strip())

    uart.irq(handler=on_rx)
コード例 #16
0
def demo():
    ble = bluetooth.BLE()
    temp = BLESocialDistance(ble)

    print("Start")
    while True:
        print("Scanning")
        ble.gap_scan(2000, 30000, 30000)
        print("End Scanning")
        time.sleep_ms(1000)
コード例 #17
0
def demo1():
    bt = bluetooth.BLE()
    taximetro = UartBLE(bt)
    i = 0
    while True:
        taximetro.enviar_dato(dato='hola{}'.format(i),notify=True)
        i+=1
        if (i > 50):
            i = 0
        time.sleep(1)
コード例 #18
0
def main():
    def onchange(state):
        data = bytes([state])
        bk.write(data)

    ble = bluetooth.BLE()
    bk = BLEKey(ble)
    key = Key(PIN_DAH, PIN_DIT)
    key.irq(handler=onchange)
    while True:
        key.callback()
コード例 #19
0
ファイル: SPIKEbleUART.py プロジェクト: ste7anste7an/ble
def demo():
    print("starting BLE")
    ble = bluetooth.BLE()
    central = BLESimpleCentral(ble)

    not_found = False

    def on_scan(addr_type, addr, name):
        if addr_type is not None:
            print("Found peripheral:", addr_type, addr, name)
            central.connect()
        else:
            nonlocal not_found
            not_found = True
            print("No peripheral found.")

    print("start scanning")
    central.scan(callback=on_scan)

    # Wait for connection...
    while not central.is_connected():
        time.sleep_ms(100)
        if not_found:
            return

    print("Connected")

    def on_rx(v):
        print("RX", v)

    central.on_notify(on_rx)

    with_response = False
    # while central._acc_handle == None:
    #    time.sleep_ms(100)
    try:
        pass
        #central.enable_notify()
        #central.read(on_rx)
    except:
        print("TX failed")
    print(central._buta_handle, central._butb_handle, central._rx_handle)
    i = 0
    time.sleep_ms(1000)
    while central.is_connected():
        try:
            v = str(i) + "fromSPIKE"
            print("TX", v)
            central.write(v, with_response)
        except:
            print("TX failed")
        i += 1
        time.sleep_ms(400 if with_response else 20)
    print("Disconnected")
コード例 #20
0
 def __init__(self, rx_cb, central_name="mpy-uart"):
     self._ble = bluetooth.BLE()
     self._ble.active(True)
     self._ble.irq(self._irq)
     ((self._handle_tx, self._handle_rx),) = self._ble.gatts_register_services((_UART_SERVICE,))
     self._connections = set()
     self._rx_cb = rx_cb
     self._payload = advertising_payload(name=central_name, services=[_ADV_APPEARANCE_GENERIC_COMPUTER])
     # Optionally add services=[_UART_UUID], but this is likely to make the payload too large.
     # self._payload = advertising_payload(name=central_name, services=[_UART_UUID])
     self._advertise()
コード例 #21
0
def demo():
    ble = bluetooth.BLE()
    temp = BLETemperature(ble)

    t = 25
    i = 0

    while True:
        pot_value = pot.read()
        # Write every second, notify every 10 seconds.
        i = (i + 1) % 10
        temp.set_temperature(pot_value, notify=i == 0)
        time.sleep_ms(1000)
コード例 #22
0
    def __init__(self, device_name="Generic HID Device"):
        self._ble = bluetooth.BLE()
        self.adv = None
        self.device_state = HumanInterfaceDevice.DEVICE_STOPPED
        self.conn_handle = None
        self.state_change_callback = None

        print("Server created")

        self.device_name = device_name
        self.service_uuids = [UUID(0x180A),
                              UUID(0x180F),
                              UUID(0x1812)]  # Service UUIDs: DIS, BAS, HIDS
        self.device_appearance = 960  # Generic HID Appearance
        self.battery_level = 100

        self.model_number = "1"
        self.serial_number = "1"
        self.firmware_revision = "1"
        self.hardware_revision = "1"
        self.software_revision = "1"
        self.manufacture_name = "Homebrew"
        self.pnp_manufacturer_source = 0x01  # Bluetooth uuid list
        self.pnp_manufacturer_uuid = 0xFE61  # 0xFEB2 for Microsoft, 0xFE61 for Logitech, 0xFD65 for Razer
        self.pnp_product_id = 0x01  # ID 1
        self.pnp_product_version = 0x0123  # Version 1.2.3

        self.DIS = (  # Device Information Service description
            UUID(0x180A),  # Device Information
            (
                (UUID(0x2A24), F_READ),  # Model number string
                (UUID(0x2A25), F_READ),  # Serial number string
                (UUID(0x2A26), F_READ),  # Firmware revision string
                (UUID(0x2A27), F_READ),  # Hardware revision string
                (UUID(0x2A28), F_READ),  # Software revision string
                (UUID(0x2A29), F_READ),  # Manufacturer name string
                (UUID(0x2A50), F_READ),  # PnP ID
            ),
        )
        self.BAS = (  # Battery Service description
            UUID(0x180F),  # Device Information
            (
                (UUID(0x2A19), F_READ_NOTIFY),  # Battery level
            ),
        )

        self.services = [self.DIS,
                         self.BAS]  # List of service descriptions, append HIDS

        self.HID_INPUT_REPORT = None
コード例 #23
0
def demo():
    ble = bluetooth.BLE()
    temp = BLETemperature(ble)

    t = 25
    i = 0

    while True:
        # Write every second, notify every 10 seconds.
        i = (i + 1) % 10
        temp.set_temperature(t, notify=i == 0)
        # Random walk the temperature.
        t += random.uniform(-0.5, 0.5)
        time.sleep_ms(1000)
コード例 #24
0
ファイル: ble.py プロジェクト: kamilgwozdziowski/mylux-esp32
 def __init__(self, name, config):
     self._config = config
     self._ble = bluetooth.BLE()
     self._ble.active(True)
     self._ble.irq(handler=self._irq)
     services = self.constructUUIDList()
     ((self._variables), ) = self._ble.gatts_register_services(services)
     self._connections = set()
     self._handler = None
     #...
     # Optionally add services=[_UART_UUID], but this is likely to make the payload too large.
     self._payload = advertising_payload(
         name=name, appearance=_ADV_APPEARANCE_GENERIC_COMPUTER)
     self._advertise()
コード例 #25
0
ファイル: micro.py プロジェクト: ste7anste7an/ble
def demo():
    ble = bluetooth.BLE()
    central = BLESimpleCentral(ble)

    not_found = False

    def on_scan(addr_type, addr, name):
        if addr_type is not None:
            print("Found peripheral:", addr_type, addr, name)
            central.connect()
        else:
            nonlocal not_found
            not_found = True
            print("No peripheral found.")

    central.scan(callback=on_scan)

    # Wait for connection...
    while not central.is_connected():
        time.sleep_ms(100)
        if not_found:
            return

    print("Connected")

    def on_rx(v):
        if len(v) == 6:
            ax, ay, az = struct.unpack("3h", v)
        print("RX", ax, ay, az)

    central.on_notify(on_rx)

    with_response = False
    while central._acc_handle == None:
        time.sleep_ms(100)
    try:
        pass
        central.enable_notify()
        #central.read()
    except:
        print("TX failed")

    i = 0
    while central.is_connected():
        i += 1
        #central.read()
        time.sleep_ms(400 if with_response else 30)

    print("Disconnected")
コード例 #26
0
 def __new__(cls):
     if BleHandler.__instance is None:
         print("[AdvH] Create BLE object, and advertise node...")
         BleHandler.__instance = super().__new__(cls)
         BleHandler.__instance._ble = bluetooth.BLE()
         # Activate bluetooth
         BleHandler.__instance._ble.active(True)
         # Bluetooth irq callback handling
         BleHandler.__instance._ble.irq(cls._irq)
         ((BleHandler.__instance._handle_tx, BleHandler.__instance._handle_rx),) = BleHandler.__instance._ble.gatts_register_services((_UART_SERVICE,))
         # Create connection set
         BleHandler.__instance._connections = set()
         BleHandler.__instance._payload = None
         BleHandler.__instance.local_devs_data = {}
     return BleHandler.__instance
コード例 #27
0
ファイル: BLE.py プロジェクト: VladVons/mpy-vRelay
    def __init__(self, aPayload: bytes):
        self._conns = set()
        self._ble = bluetooth.BLE()
        self._ble.active(True)
        self._ble.irq(self._IRQ)
        (
            (self._hr, ),
            (
                self._tx,
                self._rx,
            ),
        ) = self._ble.gatts_register_services(_SERVICES)

        self._payload = aPayload
        self._Advertise()
コード例 #28
0
  def _start_ble(cls):
    cls._ble = None
    cls._ble = bluetooth.BLE()
    cls._ble.active(True)
    cls._ble.config(rxbuf=_BMS_MTU)
    cls._ble.irq(cls._irq)

    #cls._ble.config(mtu=_BMS_MTU)
    ((cls._shell_command_handle, cls._log_handle, cls._keyboard_handle), ) = cls._ble.gatts_register_services((_HUGO_SERVICE,))
    cls._connections = set()
    cls._payload = cls.advertising_payload(
        name="HuGo", services=[_HUGO_SERVICE], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER
    )

    cls._advertise()
コード例 #29
0
def main():
    ble = bluetooth.BLE()
    remote = BLEHeadrushRemote(ble)
    remote.on_write(lambda message: print(message))

    button_pressed = None
    while True:
        if remote.is_connected():
            for name, button in BUTTON_PIN_MAP.items():
                if not button_pressed == name and button.value() == 0:
                    button_pressed = name
                    print("sending '{name}'.".format(name=name))
                    remote.send(name)
                elif button_pressed == name and button.value() == 1:
                    button_pressed = None
コード例 #30
0
def demo():
    ble = bluetooth.BLE()
    central = BLESimpleCentral(ble)

    not_found = False

    def on_scan(addr_type, addr, name):
        if addr_type is not None:
            print(' ======================================================= ')
            print(" = Found peripheral : ", addr_type, addr, name)
            print(' ======================================================= ')
            central.connect()
        else:
            nonlocal not_found
            not_found = True
            print("No peripheral found.")

    central.scan(callback=on_scan)

    # Wait for connection...
    while not central.is_connected():
        #print('Trying to connect ....')
        time.sleep_ms(100)
        if not_found:
            print('Not found')
            return

    print("Connected")

    def on_rx(v):
        print("RX", v)

    central.on_notify(on_rx)

    with_response = False

    i = 0
    while central.is_connected():
        try:
            v = str(i) + "_"
            print("TX", v)
            central.write(v, with_response)
        except:
            print(".....TX failed")
        i += 1
        time.sleep_ms(400 if with_response else 30)

    print("Disconnected")