BleuIO Firmware Update v2.6.0: Introduces Auto Execution Command

BleuIO, a pioneer in Bluetooth Low Energy (BLE) technology, is thrilled to introduce its latest firmware update, version 2.6.0. This release contains auto execution functionality, which enables users to automate tasks and execute commands effortlessly upon device startup.

Added Features:

Users can now configure up to 10 commands that will execute automatically upon the BleuIO device starting up. This commands are stored in the device’s flash memory, ensures that the commands persist even through power cycles, eliminating the need for manual intervention.

What truly sets this feature apart is its ability to function independently of a host computer. Unlike previous iterations where a host computer was necessary to trigger commands, BleuIO v2.6.0 allows AT COMMANDS execution directly from the device itself. Imagine the possibilities – from initiating beacon advertising to executing custom routines – all with the simple power cycle of the device, no additional hardware required.

The startup execution mechanism further enhances the user experience. Upon startup, BleuIO checks for configured commands in the auto execute (AUTOEXEC) list and proceeds to execute them in the specified order. This streamlined process not only accelerates development but also ensures consistent performance, enabling rapid deployment of BLE applications with minimal effort.

New AT Commands:

The AT+AUTOEXEC command enables users to both set and display commands in the AUTOEXEC list. Setting auto execution commands is as simple as using the syntax AT+AUTOEXEC=<cmd>, providing developers with a straightforward means of configuring device behavior.

Additionally, the AT+CLRAUTOEXEC command facilitates the removal of all commands set in the AUTOEXEC list, allowing for easy modification and refinement of device functionality. This level of flexibility helps developers to iterate quickly, experiment freely, and ultimately create BLE applications.

How to Upgrade:

To take advantage of these enhancements, make sure to update your BleuIO dongle to firmware version 2.6.0. You can find the firmware update and detailed instructions on the official BleuIO website. Click here to know more about firmware updates.

By introducing persistent auto execution commands and enhancing command management capabilities, BleuIO continues to lead the way in innovation, providing developers with the tools they need to create exceptional BLE solutions.

Share this post on :

BleuIO Firmware Update v2.5.0: Enhanced Bonding Persistence

We are thrilled to announce the latest firmware update for BleuIO, version 2.5.0. In this release, we’ve introduced exciting features and commands that significantly enhance the user experience.

Added Features:

Bonding Information Persistence:

The standout feature of this update is the persistence of bonding information across power cycles. Now, when you establish a bond with another device using either the AT+GAPPAIR=BOND command from the dongle or the corresponding command from the paired device, the bond will remain active even after unplugging the BleuIO dongle. This ensures a seamless reconnection experience, saving you time and effort.

To check the bonding status, simply run AT+GETCONN when connected. This command will indicate whether you are bonded or not. To remove bonding information, the AT+GAPUNPAIR command can be used. This command provides the flexibility to either remove all bonded device information or selectively remove the bonding information of a specific device using the AT+GAPUNPAIR=[addrType]MacAddress format.

New AT Command: AT+GETBOND

We have introduced a new AT command – AT+GETBOND. This command allows you to display the MAC addresses of all bonded devices, providing valuable insights into the devices currently paired with your BleuIO dongle. What’s more, you can run this command at any time, even when not connected, giving you the flexibility to manage your bonded devices effortlessly.

Bug Fixes:

Command AT+GETCONN Enhancement:

In this release, we’ve addressed a minor issue related to the AT+GETCONN command. We removed a verbose line that was displayed when the BleuIO dongle was not in verbose mode. This ensures a cleaner and more streamlined experience when using this command.

How to Upgrade:

To take advantage of these enhancements, make sure to update your BleuIO dongle to firmware version 2.5.0. You can find the firmware update and detailed instructions on the official BleuIO website. Click here to know more about firmware updates.

We are committed to continuously improving BleuIO and providing you with the latest features and capabilities.

Share this post on :

Building BLE web application with Python Flask and BleuIO

Bluetooth Low Energy (BLE) is a powerful technology for connecting devices wirelessly, and developing applications for BLE devices can be both exciting and challenging. In this tutorial, we’ll explore how to create a simple BLE device scanner using Python, Flask, and the BleuIO USB dongle. The BleuIO dongle provides a convenient interface through AT commands, allowing developers to easily interact with BLE devices.

Prerequisites

Before we dive into the tutorial, make sure you have the following:

  • BleuIO USB dongle
  • Python installed on your machine
  • Flask installed (pip install flask)

Setting Up the Flask App

Let’s start by examining the Python Flask code provided in app.py. This code defines a Flask web application with two routes: the home route (/) and a route to run the BLE device scan (/run_scan). The app uses the serial library to communicate with the BleuIO dongle over the serial port.

from flask import Flask, render_template, request
import serial
import time

app = Flask(__name__)

def scan_ble_devices():
    connecting_to_dongle = 0
    print("Connecting to dongle...")

    while connecting_to_dongle == 0:
        try:
            console = serial.Serial(
                port='/dev/cu.usbmodem4048FDE52DAF1',
                baudrate=57600,
                parity="N",
                stopbits=1,
                bytesize=8,
                timeout=0
            )
            if console.is_open.__bool__():
                connecting_to_dongle = 1
        except:
            print("Dongle not connected. Please reconnect Dongle.")
            time.sleep(5)

    console.write(str.encode("AT+CENTRAL"))
    console.write('\r'.encode())
    time.sleep(0.1)
    console.write(str.encode("AT+GAPSCAN=2"))
    console.write('\r'.encode())
    time.sleep(3)
    json_responses = []

    while console.inWaiting() > 0:
        line = console.readline().decode().strip()
        print(line)
        if line.startswith('['):
            json_responses.append(line)
    
    console.close()
    return json_responses

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/run_scan', methods=['POST'])
def run_scan():
    if request.method == 'POST':
        json_responses = scan_ble_devices()
        
        return render_template('index.html', json_responses=json_responses)

if __name__ == '__main__':
    app.run(debug=True,port=5001)

HTML Template (index.html)

The HTML template (index.html) defines a simple web page with a button to trigger the BLE device scan. The page displays the results of the scan in an unordered list. Make sure the index.html file should stay inside template folder. so the folder structure should be like this

├── app.py
└── templates
    └── index.html

Code for index.html is provided below


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Flask BLE Device Scanner</title>
    <link
      href="//cdn.muicss.com/mui-0.10.3/css/mui.min.css"
      rel="stylesheet"
      type="text/css"
    />
  </head>
  <body>
    <div class="mui-container">
      <br /><br />
      <div class="mui-panel">
        <img
          src="https://flask.palletsprojects.com/en/3.0.x/_images/flask-horizontal.png"
          alt=""
          height="100"
        />
        &nbsp; &nbsp; &nbsp; &nbsp;
        <img
          src="https://1000logos.net/wp-content/uploads/2020/08/Python-Logo.png"
          alt=""
          height="100"
        />
        <h1>Hello, Python BLE programmer!</h1>
        <p>
          This is a simple web page created with Flask to interact with BLE
          devices nearby.
        </p>

        <form action="/run_scan" method="post">
          <button
            type="submit"
            class="mui-btn mui-btn--primary mui-btn--raised"
          >
            Scan for BLE Devices
          </button>
        </form>
        <br />

        {% if json_responses %}
        <ul class="mui-list--unstyled">
          {% for json_response in json_responses %}
          <li style="margin-bottom: 10px">
            &#10003; {{ json_response | safe }}
          </li>
          {% endfor %}
        </ul>
        {% endif %}
      </div>
    </div>
  </body>
</html>

Explaining the Code

Let’s dive into the connection part of the code and explain how the serial port is specified and why it is essential.

console = serial.Serial(
    port='/dev/cu.usbmodem4048FDE52DAF1',
    baudrate=57600,
    parity="N",
    stopbits=1,
    bytesize=8,
    timeout=0
)

In this code snippet, the serial.Serial function is used to create a serial port object (console) for communication with the BleuIO dongle. Let’s break down the parameters used in this function:

  • port: Specifies the name or address of the port to which the BleuIO dongle is connected. In this case, it is set to '/dev/cu.usbmodem4048FDE52DAF1'.
    On macOS, /dev/cu.* represents serial ports, and by running ls /dev/cu.* in the terminal, you can see a list of connected devices. The specific port for the BleuIO dongle is copied from this list and pasted into the code.

For windows the COM port information can be found here. Here the path for the dongle is COM14

  • baudrate: Sets the baud rate for communication. The BleuIO dongle communicates at a baud rate of 57600, so it is set accordingly.
  • parity: Specifies the parity checking scheme. In this case, it is set to “N” for no parity.
  • stopbits: Defines the number of stop bits. It is set to 1, which is a common configuration.
  • bytesize: Sets the number of data bits. It is set to 8, which is standard for most serial communication.
  • timeout: Sets the timeout for read operations. It is set to 0, meaning no timeout, allowing the code to wait indefinitely for responses from the BleuIO dongle.

It’s crucial to accurately specify the port to establish a successful connection between the Flask application and the BleuIO dongle. Incorrect port information will result in a failure to establish communication.

  1. Connecting to BleuIO Dongle: The scan_ble_devices function attempts to establish a connection with the BleuIO dongle over the serial port. It retries until the connection is successful.
  2. Sending AT Commands: The function sends specific AT commands to the dongle to set it in central mode (AT+CENTRAL) and initiate a BLE device scan for two seconds (AT+GAPSCAN=2).
  3. Parsing JSON Responses: The function reads and parses the JSON responses received from the dongle. It collects the responses in a list (json_responses).
  4. Flask Routes: The Flask app has two routes – the home route (/) renders the index.html template, and the /run_scan route triggers the BLE device scan and displays the results

To run the script simply run the following code on the terminal.

python app.py

Output

In this tutorial, we’ve explored how to create a simple BLE device scanner using Python, Flask, and the BleuIO USB dongle. The combination of Flask and BleuIO’s AT commands provides a straightforward way for Python developers to interact with BLE devices, making BLE application development more accessible and efficient. You can further extend this project by adding features like connecting to specific BLE devices, reading characteristics, or even controlling devices.
Details of the AT commands available on the BleuIO documentation.

To get started, make sure to have your BleuIO dongle, install Flask, and run the provided Python script. Happy BLE programming!

Share this post on :

Developing BLE Applications : A Tutorial for Linux/MacOS

Bluetooth Low Energy (BLE) technology has become increasingly popular for creating wireless applications with low power consumption. In this tutorial, we’ll explore the process of scanning for nearby BLE devices, connecting to a specific device, and reading characteristics using the BleuIO BLE USB dongle. The tutorial is designed for Linux/MacOS environments.

Introduction to BleuIO

BleuIO is a versatile Bluetooth Low Energy USB dongle that simplifies BLE application development. It supports the AT command set, allowing developers to interact with the dongle using familiar commands. Whether you’re a seasoned BLE developer or just getting started, BleuIO offers a convenient and efficient way to work with BLE applications.

Forget complex libraries and complicated programming. Develop BLE applications effortlessly through simple AT commands.

Setting Up the Development Environment

Before diving into the tutorial, ensure you have the following prerequisites:

  • BleuIO USB Dongle: Connect the BleuIO dongle to your computer.
  • Python: Ensure that Python is installed on your system.

Writing the BLE Application Script

The provided Python script demonstrates the process of connecting to the BleuIO dongle, scanning for nearby BLE devices, and reading characteristics. Let’s break down the key components of the script:

# Importing necessary modules
import serial
import time

# Establishing connection to the BleuIO dongle
connecting_to_dongle = 0
print("Connecting to dongle...")

while connecting_to_dongle == 0:
    try:
        # Configuring the serial connection
        console = serial.Serial(
            port='/dev/cu.usbmodem4048FDE52CF21',
            baudrate=57600,
            parity="N",
            stopbits=1,
            bytesize=8,
            timeout=0
        )
        if console.is_open.__bool__():
            connecting_to_dongle = 1
    except:
        print("Dongle not connected. Please reconnect Dongle.")
        time.sleep(5)

# Sending commands to the BleuIO dongle
console.write(str.encode("AT+CENTRAL"))
console.write('\r'.encode())
time.sleep(0.1)
console.write(str.encode("AT+GAPSCAN=3"))
console.write('\r'.encode())
time.sleep(3.5)
console.write(str.encode("AT+GAPCONNECT=[1]D1:79:29:DB:CB:CC"))
console.write('\r'.encode())
console.write(str.encode("AT+GATTCREAD=0013"))
console.write('\r'.encode())

# Waiting for the dongle to respond
time.sleep(1)
out = ""
while console.inWaiting() > 0:
    out += console.read(console.inWaiting()).decode()
else:
    if not out.isspace():
        print(out + " ")
        out = " "

Explanation:

1. Connecting to BleuIO:

  • Download and install a serial terminal emulator like screen or minicom.
  • Ensure your dongle is connected and note its port (e.g., /dev/cu.usbmodem4048FDE52CF21).
  • Run the script with the correct port and baudrate (57600) in your terminal.
  • The script attempts connection until successful, then sends essential AT commands:
    • AT+CENTRAL: Configures BleuIO as a central device (scanning/connecting).
    • AT+GAPSCAN=3: Starts scanning for BLE devices for 3 seconds.

2. Selecting and Connecting:

  • The scan results will appear in your terminal.
  • Identify the desired device, usually by name or MAC address.
  • Replace D1:79:29:DB:CB:CC in the script with your device’s MAC address.
  • Send AT+GAPCONNECT=[1]D1:79:29:DB:CB:CC to connect to the device (replace the mac address with your desired device if needed).

3. Reading a Characteristic:

  • Every BLE device exposes characteristics containing specific data.
  • Replace 0013 in AT+GATTCREAD with the characteristic’s UUID to read its value.
  • This script reads the characteristic with UUID 0013 and prints its value. Currently its showing the device type.

The outout

The output will be shown on the screen as

Value read: SSD002/2B
Hex: 0x5353443030322F3242
Size: 9

Understanding the Code:

  • The script uses serial library to communicate with BleuIO via AT commands.
  • While loops ensure connection success and read all available data.
  • The script parses output and filters empty space to avoid repetitive printing.

In this tutorial, we’ve covered the basics of working with the BleuIO BLE USB dongle on Linux/MacOS systems. The simplicity of the AT command interface and cross-platform compatibility make BleuIO an excellent choice for BLE application development. Experiment with the provided script, explore additional AT commands from BleuIO, and unlock the full potential of BLE applications with BleuIO. Happy coding!

Share this post on :

Creating a Home Assistant Integration with HibouAir and BleuIO

In this tutorial, we will walk you through the process of creating a Home Assistant integration to read air quality data from a BLE air quality monitor called HibouAir. To accomplish this, we’ll be using BleuIO, a BLE USB dongle, to read data via the serial port. BleuIO comes equipped with a Python library that simplifies the project significantly. This integration provides real-time updates of various air quality parameters, such as pressure, temperature, humidity, VOC, CO2 and Particle Matters.

Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites in place:

  1. HibouAir Air Quality Monitor: Ensure you have a HibouAir air quality monitor. You can obtain it from the official source.
  2. BleuIO BLE USB Dongle: Acquire a BleuIO BLE USB dongle to facilitate communication with the HibouAir monitor.
  3. Host Computer: We’ll use a Windows-based host computer in this example.
  4. Home Assistant: Install Home Assistant and have it up and running. You can run Home Assistant within a virtual machine using VirtualBox, as demonstrated in this tutorial.

Implementation

Let’s start by setting up the Home Assistant integration for HibouAir and BleuIO. You can find the complete code for this project on the following GitHub repository:

GitHub Repository: HibouAir Home Assistant BLE Integration

Follow these steps to implement the integration:

1. Set Up the Custom Component

  • Create a folder named custom_components within your Home Assistant directory.
  • Inside the custom_components directory, create a subfolder named hibouair_ble.
  • Copy all the files from the GitHub repository (__init__.py, const.py, manifest.json, and sensor.py) into the hibouair_ble directory.
  • Open the const.py file and update the HibouAir sensor ID to match your specific device. This ID is used to identify the devices advertised data.

2. Update Configuration

Edit your Home Assistant configuration file (configuration.yaml) to include the newly added HibouAir BLE sensor:

sensor: 
    - platform: hibouair_ble 
      scan_interval: 120

Here’s a brief explanation of this configuration:

  • platform: Specifies the integration to use, which is hibouair_ble in this case.
  • scan_interval: Sets the interval for scanning and updating data. The example uses 120 seconds (2 minutes) for real-time data updates. Adjust this value according to your preference.

3. Restart Home Assistant

After updating the configuration, save the file and restart your Home Assistant instance. This will enable the integration.

4. Monitor Air Quality Data

Once Home Assistant is restarted, you should be able to see entities representing various air quality parameters with the hibouair_ble prefix. These parameters may include pressure, temperature, humidity, VOC, CO2, and more. The air quality data will update every 2 minutes, providing real-time information about your environment.

After setting up the dashboard with the Hibouair_ble entities , the dashboard looks like this

This integration is a simple example, and you can further customize and automate your smart home based on the data collected from the HibouAir monitor. Feel free to adapt the code to your specific requirements and enhance the capabilities of your Home Assistant setup.

With the combination of HibouAir and BleuIO, you can effortlessly create a home automation system that ensures your environment remains healthy and comfortable.

Share this post on :

BleuIO Releases Python Library v1.3.1 to support BleuIO firmware v2.4.0

BleuIO, has recently unveiled its latest offering: Python Library v1.3.1. This release brings a range of improvements and features, including support for the SUOTA (Software Updates Over The Air) commands introduced in BleuIO firmware version 2.4.0. Additionally, it addresses a bug that affected MacOS users, making the library more robust and user-friendly.

Support for SUOTA Commands:

One of the standout features of BleuIO’s Python Library v1.3.1 is its support for SUOTA commands. SUOTA, which stands for Software Updates Over The Air, is a critical feature for any BLE device. It allows users to update firmware wirelessly, eliminating the need for physical connections or manual updates. With this library update, developers working with BleuIO now have a powerful tool at their disposal to streamline firmware updates for their BLE devices. Whether it’s fixing bugs or adding new features, the ability to update firmware over the air provides flexibility and convenience, ultimately enhancing the user experience.

Bug Fix for MacOS Users:

The new Python library also includes a significant bug fix for MacOS users. Previously, there was an issue where serial responses were sometimes returned in two parts instead of one when using the library on MacOS. This inconsistency could lead to compatibility problems and hinder the development process. BleuIO has promptly addressed this issue, ensuring that the library can now handle serial responses that come in multiple parts. This improvement guarantees a smoother experience for MacOS users and eliminates a common frustration during development.

The Python Library v1.3.1 by BleuIO is readily available for developers on the Python Package Index (PyPI). You can access and download the library from the following link: BleuIO Python Library on PyPI. This convenient accessibility ensures that developers can easily integrate the library into their projects and start benefiting from the new features and bug fixes immediately.

Share this post on :

BleuIO Takes Firmware Updates to the Next Level with SUOTA Integration

In today’s fast-paced world of technology, keeping devices up-to-date with the latest firmware is crucial for ensuring optimal performance, security, and functionality. To meet this demand, BLE (Bluetooth Low Energy) devices have become increasingly popular in various applications, from fitness trackers to smart home gadgets. One critical aspect of maintaining these devices is the ability to perform firmware updates seamlessly. BleuIO, a cutting-edge Bluetooth Low Energy USB dongle, has stepped up to the plate by offering support for SUOTA (Software Updates Over The Air), revolutionizing the way we update our Bluetooth-enabled devices.

Firmware updates are like lifelines for electronic devices. They bring enhancements, bug fixes, improved security, and often introduce new features to your gadgets. Without regular updates, devices can become vulnerable to security threats, suffer from performance issues, and lag behind in terms of functionality.

BleuIO is a highly versatile Bluetooth module that provides a wide range of capabilities, from supporting various Bluetooth profiles to enabling seamless communication between devices. One of the standout features of BleuIO is its support for SUOTA, which allows for effortless and efficient firmware updates. To avail this feature, ensure you update your BleuIO dongle to firmware version 2.4.0.

SUOTA, or Software Updates Over The Air, is a game-changer in the world of firmware updates. Unlike traditional methods that require a physical connection or specialized tools, SUOTA leverages Bluetooth technology to transmit firmware updates wirelessly. BleuIO’s integration of SUOTA support makes it a standout choice for developers and manufacturers looking to streamline firmware updates for their Bluetooth-enabled devices.

In a world where technology evolves rapidly, the ability to keep devices up-to-date is paramount. BleuIO’s support for SUOTA represents a significant leap forward in the realm of firmware updates. It offers convenience, cost-efficiency, speed, and security, all while enhancing the overall user experience. Whether you’re a developer or an end-user, BleuIO’s SUOTA support is a step in the right direction towards a smarter, more connected future.

Share this post on :

BlueIO Firmware Update v2.3.1: Enhanced Features and Critical Bug Fixes

BlueIO, a prominent player in the Bluetooth industry, has recently unveiled its firmware version v2.3.1. This update comes packed with exciting additions and crucial bug fixes, promising a more seamless and efficient Bluetooth experience.

Enhanced Features:

AT+SCANFILTER Upgrade: One of the standout features of the v2.3.1 firmware update is the enhancement made to the AT+SCANFILTER functionality. Previously, this feature only filtered based on UUID, but now, it has been extended to include “Service Data – 128-bit UUID” and “Service Data – 16-bit UUID” packets. This means that when filtering devices, you can now fine-tune your criteria even further, ensuring that only the most relevant devices are detected. This added flexibility is a significant boon for developers and users alike, enabling a more tailored Bluetooth experience.

Critical Bug Fixes:

SPS Message Recognition: Before the v2.3.1 update, some users may have encountered a frustrating issue where the dongle failed to recognize SPS (Serial Port Service) messages correctly. This problem stemmed from the system incorrectly handling messages due to a different handle, resulting in an improper display format that did not align with previous firmware versions. However, with the diligent efforts of the BlueIO team, this bug has been decisively squashed. Now, SPS messages are correctly recognized and displayed in a consistent manner, eliminating the confusion and inconvenience experienced by users.

AT+GETCONN Bonded Device Display: Another critical bug addressed in this firmware update relates to the AT+GETCONN command. Previously, when users attempted to reconnect with previously bonded or paired devices, these devices would not show up as bonded or paired during the reconnection process. This inconsistency could lead to unnecessary complications and frustration for users. Thankfully, BlueIO has rectified this issue in v2.3.1. Now, when you reconnect with your trusted devices, they will correctly appear as bonded or paired, streamlining the reconnection process and ensuring a smoother user experience.

Be sure to update your BlueIO firmware to v2.3.1 to take full advantage of these improvements and enjoy a more hassle-free Bluetooth experience.
Details of the update can be found at

https://www.bleuio.com/getting_started/docs/firmware/

Share this post on :

Connecting and Reading BLE Device Characteristics using BleuIO and JavaScript

Bluetooth Low Energy (BLE) technology has revolutionized the way we interact with devices wirelessly, enabling a wide range of applications such as fitness trackers, smartwatches, and IoT devices. To demonstrate the seamless process of connecting to a BLE device and reading its characteristics, this tutorial will guide you through the steps of using the BleuIO JavaScript library. BleuIO simplifies the process of communicating with BLE devices and extracting valuable information from them.

Prerequisites

Before diving into the tutorial, make sure you have the following prerequisites:

  1. Basic understanding of JavaScript.
  2. Node.js installed on your system.
  3. BleuIO Bluetooth Low Energy USB dongle.
  4. Air quality monitoring BLE device HibouAir (for demonstration purposes).

Step 1: Set Up the Project

  • Create a new directory for your project and navigate to it using the terminal.
  • Install BleuIO javascript library using
    npm i bleuio
  • Create an index.html page that contains buttons to connect to the dongle, connecting and reading characteristics value. We will also have a js script linked at the bottom of the page. Here is the full page content
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Connect and Service data from BLE devices</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9"
      crossorigin="anonymous"
    />
    <style>
      #terminal {
        background-color: black;
        color: white;
        font-size: medium;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        padding: 20px;
        margin: 20px 0;
      }
    </style>
  </head>
  <body>
    <div class="container my-3">
      <img src="https://www.bleuio.com/images/logo.png" alt="" />
      <h1 class="my-4">Example script to connect and read Characteristics</h1>

      <button class="btn btn-warning" id="connect">Connect</button>
      <button class="btn btn-primary" id="info">Connection Information</button>
      <button class="btn btn-success" id="ReadService">
        Connect & Read Service Data
      </button>

      <h3><div id="readResponse"></div></h3>
      <div id="terminal"></div>
    </div>
    <script type="module" src="./script.js"></script>
  </body>
</html>
  • Create a js page that contains the logic for connecting to dongle and then connect to Air quality monitoring BLE device HibouAir. After connecting to the device we try to read device manufacturing company name by reading characteristics.
    following is the script file.
import * as my_dongle from 'bleuio';
document.getElementById('connect').addEventListener('click', function () {
  my_dongle.at_connect();
});
document.getElementById('info').addEventListener('click', function () {
  my_dongle.ati().then((x) => {
    document.getElementById('terminal').innerHTML += x.join('<br>');
  });
});

let deviceToConnect = '[1]D1:53:C9:A9:8C:D2';
document.getElementById('ReadService').addEventListener('click', function () {
  my_dongle.at_dual().then(() => {
    my_dongle.at_gapconnect(deviceToConnect).then((x) => {
      setTimeout(() => {
        document.getElementById('terminal').innerHTML += x.join('<br>');
        my_dongle.at_gattcread('0011').then((x) => {
          document.getElementById('terminal').innerHTML += x.join('<br>');
          document.getElementById('readResponse').innerHTML = x[x.length - 1];
          my_dongle.at_gapdisconnectall();
        });
      }, 500);
    });
  });
});

As you can notice on the script we have a variable called device to connect. This is the mac address of the HibouAir BLE device that we are trying to connect. You can replace this mac address to your own device. After the connection we print out the response in a terminal.
on the terminal we can see available service and characteristics. In this script we are trying to read device manufacturer name which is stored at 0011 handle. Therefore we pass the value as at_gattcread function. You can read more about the AT commands at BleuIO getting started guide.

To run this script, we need a web bundler like parcel js.

Run the script with

npx parcel index.html

Example output


In this tutorial, we’ve successfully demonstrated how to connect to a BLE device using the BleuIO dongle and JavaScript. By leveraging the BleuIO’s Javascript library, we streamlined the process of establishing a connection, reading device characteristics, and displaying the information on a web page. BLE technology has vast potential for various applications, and BleuIO makes it easier than ever to interact with BLE devices programmatically. With this tutorial as a foundation, you can explore further and develop your own BLE-powered projects with confidence.

Share this post on :

BleuIO Python Library Upgraded to support firmware v2.3.0: Simplifying Custom Service Management

BleuIO, a leading provider of Bluetooth Low Energy (BLE) solutions, has recently released an exciting new Python library update that supports its latest firmware version 2.3.0. This Python library is a powerful tool that allows developers to manage BLE custom services effortlessly. In this article, we will explore the key features of BleuIO’s Python library, its benefits, and how it simplifies the process of creating custom BLE services.

BleuIO’s Python Library Update

BleuIO’s Python library is a comprehensive set of tools and functions that interface with the BleuIO Bluetooth Low Energy USB dongle. The latest update, which supports firmware version 2.3.0, introduces enhanced capabilities for managing custom BLE services, making it easier for developers to create and deploy custom services for their applications.

The Python library comes with a range of convenient AT commands that can be used to control various aspects of the BleuIO dongle, including scanning, advertising, connecting, and, most importantly, setting up custom services. With just a few lines of Python code, developers can now configure their own custom BLE services, tailoring them to meet the specific requirements of their projects.

Benefits of the Python Library for Custom Services

The new Python library from BleuIO offers several benefits that simplify the process of working with custom BLE services:

  1. Ease of Use: The library abstracts the complexities of interacting with the BLE dongle through simple and easy-to-understand Python functions. This allows even those new to BLE development to get started quickly.
  2. Time Efficiency: By providing high-level functions for custom service setup, the library saves developers valuable time. No need to write low-level code for every aspect of the BLE service creation; instead, developers can focus on implementing the unique features of their applications.
  3. Flexible Customization: With the library, developers have complete control over the configuration of custom services. They can define custom UUIDs, set permissions, properties, and values for each characteristic, tailoring the service to their specific use case.
  4. Real-time Updates: The example script demonstrates how to continuously update the values of characteristics and notify/indicate subscribers. This feature is invaluable for applications that require real-time data exchange.

Creating a Custom Service with BleuIO’s Python Library

Let’s take a look at a sample Python script that showcases how to create a custom BLE service using BleuIO’s Python library:

# (C) 2023 Smart Sensor Devices AB

import time
from datetime import datetime

from bleuio_lib.bleuio_funcs import BleuIO

# This example will show how to setup your own service
# Press Ctrl-C to exit the script.


# Scan result Callback function
def my_scan_callback(scan_input):
    print("\n\nmy_scan_callback: " + str(scan_input))


# Event Callback function
def my_evt_callback(scan_input):
    print("\n\nmy_evt_callback: " + str(scan_input))


# Start BleuIO
my_dongle = BleuIO()
# Register callback functions for scan results and events
my_dongle.register_evt_cb(my_evt_callback)
my_dongle.register_scan_cb(my_scan_callback)

# Run ATI Command
resp = my_dongle.ati()
print(resp.Cmd)
print(resp.Ack["errMsg"])
print(resp.Rsp)

print("My Role: " + my_dongle.status.role)
print("Is Adv: " + str(my_dongle.status.isAdvertising))
print("Is Connected: " + str(my_dongle.status.isConnected))

# Set role to dual if it isn't set already
if not my_dongle.status.role == my_dongle.gaproles.DUAL:
    resp = my_dongle.at_dual()
    print(resp.Cmd)
    print(resp.Ack)

# Disconnect if we're connected
if my_dongle.status.isConnected:
    resp = my_dongle.at_gapdisconnectall()
    print(resp.Cmd)
    print(resp.Ack)

# Stop Advertising if we're advertising
if my_dongle.status.isAdvertising:
    resp = my_dongle.at_advstop()
    print(resp.Cmd)
    print(resp.Ack)

# Stop custom service just in case it had been started previously
resp = my_dongle.at_customservice_stop()
print(resp.Cmd)
print(resp.Ack)

# Service

# Set service UUID
resp = my_dongle.at_customservice(
    0, my_dongle.UUID, "ee6ec068-7447-4045-9fd0-593f3ba3c2ee"
)
print(resp.Cmd)
print(resp.Ack)

# Characteristic 1

# Set characteristic 1 UUID
resp = my_dongle.at_customservice(
    2, my_dongle.UUID, "018f55d9-d747-4c4e-a87b-e9b074ffd2b6"
)
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 1 value length
resp = my_dongle.at_customservice(1, my_dongle.CHAR_LENGTH, "100")
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 1 value
# Here we set it to the current time in hours, minutes and seconds format.
cbTime = datetime.now()
char1_data = cbTime.strftime("%H:%M:%S")
resp = my_dongle.at_customservice(1, my_dongle.CHAR_VALUE, char1_data)
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 1 permissions
resp = my_dongle.at_customservice(1, my_dongle.CHAR_PERMISSION, "R")
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 1 properties
# We set it to Read and Notify
resp = my_dongle.at_customservice(1, my_dongle.CHAR_PROPERTY, "NR")
print(resp.Cmd)
print(resp.Ack)

# Characteristic 2

# Set characteristic 2 UUID
resp = my_dongle.at_customservice(
    2, my_dongle.UUID, "a693ba2c-f0df-40cb-aea7-8ae47281d997"
)
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 2 value length
resp = my_dongle.at_customservice(2, my_dongle.CHAR_LENGTH, "100")
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 2 value
# Here we set it to the current time in month, days and years format.
cbTime = datetime.now()
char2_data = cbTime.strftime("%m/%d/%Y")
resp = my_dongle.at_customservice(2, my_dongle.CHAR_VALUE, char2_data)
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 2 permissions
resp = my_dongle.at_customservice(2, my_dongle.CHAR_PERMISSION, "R")
print(resp.Cmd)
print(resp.Ack)

# Set characteristic 2 properties
# We set it to Read and Indicate
resp = my_dongle.at_customservice(2, my_dongle.CHAR_PROPERTY, "IR")
print(resp.Cmd)
print(resp.Ack)

# Here we check that the service data we set has gone in
resp = my_dongle.at_customservice()
print(resp.Cmd)
print(resp.Ack)
print(resp.Rsp)
print(resp.End)

# Here we start the custom service so next time we advertise and someone connects they will see the new service
resp = my_dongle.at_customservice_start()
print(resp.Ack)

# Here we start advertising so other devices can detect us and connect
resp = my_dongle.at_advstart()
print(resp.Ack)

# Going in a never ending loop that will just update the values of Characteristic 1 and 2 every second.
# If anyone is subscribed we will notify/indicate them.
while True:
    cbTime = datetime.now()
    notiCharTime = cbTime.strftime("%H:%M:%S")
    resp = my_dongle.at_customservice(1, my_dongle.CHAR_VALUE, notiCharTime)
    print(resp.Cmd)
    print(resp.Ack)

    indiCharTime = cbTime.strftime("%m/%d/%Y")
    resp = my_dongle.at_customservice(2, my_dongle.CHAR_VALUE, indiCharTime)
    print(resp.Cmd)
    print(resp.Ack)
    time.sleep(1)

The example script demonstrates the process of setting up a custom service with two characteristics. Characteristic 1 holds the current time in hours, minutes, and seconds format, while Characteristic 2 contains the date in month, day, and year format. The script registers callbacks for scan results and events, sets up the service UUID, characteristic UUIDs, permissions, properties, and starts advertising the custom service.

With BleuIO’s Python library and the user-friendly AT commands, BLE application development becomes accessible to a wider audience, fostering a new era of creative and groundbreaking IoT solutions. Developers can explore the BleuIO Python library further by visiting the official PyPI page (https://pypi.org/project/bleuio/) and start harnessing the power of BLE for their projects.

Share this post on :