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 :

Testing Bluetooth Low Energy Application with BleuIO and Jest

Bluetooth Low Energy (BLE) has become a popular technology for creating wireless communication between devices with low power consumption. When developing BLE applications, it’s essential to thoroughly test them to ensure they work correctly. This tutorial shows a basic test script that determines the role of a Bluetooth Low Energy (BLE) device and passes the test based on the device role. The test script utilizes the BleuIO Bluetooth Low Energy USB dongle along with a JavaScript Testing Framework. You can modify this script according to your specific needs for testing BLE applications.. We’ll communicate with the dongle using Node SerialPort, write AT commands, and read back responses from the dongle.

Prerequisites

Before we start, make sure you have the following:

  1. BleuIO Bluetooth Low Energy USB dongle.
  2. Node.js and npm installed on your computer.
  3. Basic knowledge of JavaScript and testing concepts.

Setting Up the Environment

First, connect the BleuIO dongle to your computer. To find the path of the dongle, open your terminal and run the following command:

ls /dev/cu.*

Note down the path of the dongle (e.g., /dev/cu.usbmodem4048FDE6EBCB1).

Next, create a new directory for your project and initialize a Node.js project by running:

npm init -y

Now, install the required packages: SerialPort and Jest.

npm install serialport
npm install --save-dev jest

Writing the Role Check Function

Create a new file rolecheck.js and paste the following code:

import { SerialPort } from 'serialport';

const dongleReadWrite = () => {
  return new Promise((resolve) => {
    let readDataArray = [];
    const port = new SerialPort({
      path: '/dev/cu.usbmodem4048FDE6EBCB1', // Replace this with your dongle's path
      baudRate: 115200,
      dataBits: 8,
      parity: 'none',
      stopBits: 1,
    });

    // Function to write data to the dongle
    const writeData = async (cmd) => {
      port.on('open', () => {
        port.write(cmd + '\r\n', (err) => {
          if (err) {
            return console.log('Error writing data: ', err.message);
          }
        });
      });
    };

    // Function to read data from the dongle
    const readData = () => {
      return new Promise(function (resolve, reject) {
        port.on('readable', () => {
          let data = port.read();
          let enc = new TextDecoder();
          let arr = new Uint8Array(data);
          arr = enc.decode(arr);
          let removeRn = arr.replace(/\r?\n|\r/gm, '');
          if (removeRn != null) readDataArray.push(removeRn);
          return resolve(readDataArray);
        });
      });
    };

    // Write the command 'AT+GAPSTATUS' to the dongle
    writeData('AT+GAPSTATUS');

    // Read the response from the dongle after a delay of 1 second
    readData().then((data) => {
      setTimeout(() => {
        port.close();
        return resolve(data);
      }, 1000);
    });
  });
};

// Function to get the role of the dongle
export const getRole = () => {
  return new Promise((resolve) => {
    // Call dongleReadWrite() to fetch data from the dongle
    dongleReadWrite().then((data) => {
      const regex = /(Peripheral|Central)/i;
      // Find the role from the response data using regular expression
      const roleMatch = data.find((element) => regex.test(element));
      // Extract the role ('Peripheral' or 'Central') from the match
      const role = roleMatch ? roleMatch.match(regex)[0] : null;
      // Return the role to the caller
      return resolve(role);
    });
  });
};

The getRole() function connects to the dongle and writes the command AT+GAPSTATUS to find out the role. The response we get is an array, which looks like this
[ ‘AT+GAPSTATUS’, ‘Peripheral roleNot ConnectedNot Advertising’ ]
we extract the role information from it.

Writing the Test Script

Create another file rolecheck.test.js and paste the following code:

import { getRole } from './rolecheck';
import { jest } from '@jest/globals';
jest.useFakeTimers();

test('Get peripheral role', async () => {
  const dataPromise = getRole(); // Start the data fetching process

  jest.advanceTimersByTime(1000); // Advance the timer by 1 second

  // At this point, the timer has advanced by 1 second, but the data is not resolved yet
  // We can check that the dataPromise is still pending
  expect(dataPromise).toBeInstanceOf(Promise);

  jest.advanceTimersByTime(2000); // Advance the timer by another 2 seconds to complete the 3 seconds

  // Now, the data should be resolved, and the test should pass if the role is 'Peripheral'
  expect(dataPromise).resolves.toBe('Peripheral');
});

In the test script, we import the getRole() function from rolecheck.js. We use Jest’s fake timers to control the asynchronous flow and mimic the behavior of asynchronous code.

The test checks whether the role obtained from the getRole() function is 'Peripheral'. If it is, the test passes; otherwise, it fails.

Running the Test

To execute the test, run the following command in the terminal:

npm test

Jest will run the test, and you should see the test results on your terminal.

The response will look like this

Conclusion

In this tutorial, we explored how to communicate with the BleuIO dongle, write AT commands, and read back responses using a JavaScript Testing Framework (Jest). With the right testing approach, you can ensure the stability and correctness of your BLE application before deploying it to production. Happy testing!

Share this post on :

BlueIO Firmware Update v2.3.0: Empowering Custom Service Management

BlueIO, a leading provider of Bluetooth Low Energy (BLE) solutions, has recently announced the release of its latest firmware version, v2.3.0. This firmware update brings a host of new features and improvements, enabling developers to create better and more customizable applications. With a focus on flexibility and enhanced functionality, BlueIO’s new firmware empowers developers to tailor their applications to meet specific requirements while offering seamless integration with other devices.

One of the key highlights of the BlueIO v2.3.0 firmware is the ability to create a custom service. This feature provides developers with unprecedented control over their applications, allowing them to define characteristics that handle data in a way that aligns with their unique needs. The custom service can be identified by other devices using a custom UUID, ensuring seamless communication and interoperability.

Custom Service Features:

BlueIO’s custom service offers several powerful features that enable developers to build highly specialized applications:

  1. Custom UUID for the Service: Developers can set a custom UUID for the custom service, ensuring its unique identification and compatibility with other devices.
  2. Multiple Characteristics: Up to five characteristics can be added to the custom service, offering increased versatility and flexibility.
  3. Custom UUID for Each Characteristic: Developers can assign custom UUIDs to individual characteristics within the service, enabling precise identification and interaction.
  4. Read/Write Properties: Each characteristic can be configured with read/write properties, allowing bidirectional data transfer between devices.
  5. Write Without Response: Developers can choose to configure specific characteristics with the write without response property, optimizing data transfer efficiency.
  6. Notify or Indicate: Characteristics can be configured to notify or indicate changes, enabling real-time updates to connected devices.
  7. Descriptor Support: Developers can add descriptors to each characteristic, providing additional information and fine-grained control.
  8. Value Manipulation: The firmware update allows developers to change and update the values of characteristics and descriptors, supporting both ASCII and byte data formats.
  9. Peer Notifications: When updating the characteristic value, BlueIO can automatically notify all connected devices that have subscribed to any characteristic with either Notify or Indication properties.

New Commands:

The BlueIO v2.3.0 firmware introduces a set of new commands that facilitate easy setup and control of the custom service:

  1. AT+CUSTOMSERVICE: This command allows developers to configure and query the settings for the custom service.
  2. AT+CUSTOMSERVICESTART: Enables the start of the custom service, initiating its functionality.
  3. AT+CUSTOMSERVICESTOP: Stops the custom service while retaining the user-defined settings.
  4. AT+CUSTOMSERVICERESET: Disables the custom service and clears all user settings associated with it.

The release of BlueIO’s v2.3.0 firmware marks a significant milestone in meeting the demands of developers seeking advanced BLE solutions. The BlueIO team remains committed to enhancing their offerings and will continue to provide updates and new features to support developers in their application development journey.

Share this post on :

Utilizing BleuIO as a BLE Simulator for Testing, Debugging, and Creating BLE Applications

In the realm of Bluetooth Low Energy (BLE) development, having a reliable tool for testing, debugging, and creating BLE applications is crucial. BLE simulators serve as virtual environments that mimic real-world BLE devices, enabling developers to streamline the development process. BleuIO, a Bluetooth Low Energy USB dongle, offers a versatile and user-friendly solution for harnessing the power of BLE simulation. In this article, we will explore the significance of BLE simulators, discuss why they are needed, and delve into the various ways BleuIO can assist developers in building robust BLE applications.

Why Do We Need a BLE Simulator?
Testing and debugging BLE applications can be a complex and time-consuming process. Deploying real BLE devices for every development iteration is not only impractical but also resource-intensive. BLE simulators provide an efficient way to replicate various scenarios, allowing developers to validate their applications without relying on physical hardware. By emulating multiple BLE devices and their interactions, developers can thoroughly assess the reliability, compatibility, and functionality of their applications in a controlled environment. This not only reduces costs but also accelerates the development cycle.

How BleuIO Can Be Helpful
BleuIO offers a range of features and functionalities that make it an invaluable tool for BLE application development:

  • BLE Simulation Capabilities: BleuIO acts as a powerful BLE simulator, allowing developers to create and control multiple virtual BLE devices within a single environment. This flexibility enables comprehensive testing of various use cases, such as connecting to multiple peripherals, exploring different communication scenarios, and validating application behavior under different signal strengths and environmental conditions.
  • User-Friendly : BleuIO helps to simplify the process of setting up and managing simulated BLE devices. Developers can easily configure device attributes, services, characteristics, and descriptors, all through AT commands. These commands provide developers with a means to interact with the device programmatically. This ease of use significantly reduces the learning curve and enhances productivity.
  • Real-Time Data Monitoring: With BleuIO, developers can monitor real-time data exchanged between virtual BLE devices and their applications. This feature is particularly useful for debugging purposes, as it allows developers to inspect data packets, analyze communication output, and identify potential issues or inconsistencies. By closely monitoring data flow, developers can refine their applications for optimal performance.
  • Cross-Platform Compatibility: BleuIO supports various operating systems, making it compatible with a wide range of development environments. Whether you are working on Windows, macOS, or Linux, BleuIO seamlessly integrates into your preferred development workflow, ensuring versatility and accessibility.

Basic Functions of BleuIO

BleuIO offers several fundamental functions that aid in BLE application development:

Device Configuration: Developers can easily configure the properties and behavior of virtual BLE devices using BleuIO. This includes setting device names, MAC addresses, advertising intervals, supported services, and characteristics. This flexibility enables developers to simulate diverse scenarios and test application behavior under different configurations.

Advertising and Scanning BleuIO enables the simulation of advertising and scanning functionalities, allowing developers to emulate device discovery and connection processes. This feature is crucial for testing application behavior when interacting with various devices and ensuring seamless connectivity.

GATT Server and Client: BleuIO supports both GATT server and client roles, enabling developers to simulate and test both peripheral and central devices. This versatility allows for comprehensive testing of the application’s functionality in different roles and scenarios.

BleuIO can be served as a powerful BLE simulator that streamlines the testing, debugging, and creation of Bluetooth Low Energy applications. By providing an intuitive AT commands, comprehensive simulation capabilities, real-time data monitoring, and cross-platform compatibility, BleuIO empowers developers to build robust and reliable BLE applications efficiently. With its flexibility and ease of use, BleuIO significantly reduces development time, accelerates the testing process, and enhances the overall quality of Bluetooth Low Energy applications.

Share this post on :

BleuIO Firmware update v2.2.2: Enhanced MTU Control and Advanced Scan Filtering

The BleuIO team is excited to announce the release of their latest firmware version, v2.2.2, packed with new features and improvements for Bluetooth Low Energy (BLE) developers. This firmware update aims to provide an enhanced development experience and empower developers with more control over their BLE applications.

What’s new in this firmware :

One of the notable additions in this release is the inclusion of a new command that allows developers to set or query the maximum MTU (Maximum Transmission Unit) size used in MTU negotiation upon connecting to a device. This feature provides flexibility in adjusting the MTU size, enabling better optimization and efficiency in data transmission between devices.

Additionally, the BleuIO firmware v2.2.2 introduces a powerful filtering mechanism for scan results. A new command has been added to apply filters on the outcomes from AT+FINDSCANDATA and AT+GAPSCAN commands. This feature allows filtering based on three different parameters: Local Name, Service UUID, and Manufacturer Specific ID.

It enables the flexibility to activate one filter, two filters in combination, or all three filters simultaneously. Results will only be displayed if the selected filter value is present in the advertising or scan response data. For example, a filter can be set to exclusively show data packets from devices with the Local Name “BleuIO” (either Complete or Shortened) by executing the command AT+SCANFILTER=NAME=BleuIO.

By leveraging these filtering capabilities, developers can easily focus on specific devices or data packets that meet their criteria, streamlining the development and testing process.

To explore the full range of features and improvements introduced in BleuIO firmware v2.2.2, developers are encouraged to visit the official BleuIO documentation at https://www.bleuio.com/getting_started/docs/firmware/. The comprehensive documentation provides detailed information on firmware updates and guides on how to leverage these new features effectively.

The BleuIO team is committed to continuously enhancing the BLE development experience and providing tools needed to build robust and innovative applications. With each firmware release, BleuIO demonstrates its dedication to empowering developers and enabling seamless Bluetooth Low Energy development.

Stay tuned for future updates from the BleuIO team, as they continue to introduce new features and improvements to meet the evolving needs of the BLE developer community.

Share this post on :

BleuIO Node.js Library available on NPM

BleuIO, a leading provider of Bluetooth Low Energy (BLE) solutions, has recently released a new Node.js library for developers. This library is available on NPM, making it easy for developers to access and use it for their projects. With this library, developers can create BLE applications quickly and easily.

The BleuIO Node.js library provides a simple and straightforward way for developers to communicate with BLE devices. It supports a range of BLE protocols. This library is designed to work seamlessly with Node.js, making it easy to integrate into existing projects.

One of the primary advantages of using the BleuIO Node.js library is its ease of use. Developers do not need to have extensive knowledge of Bluetooth technology to use this library. The library provides a high-level API that simplifies the communication process, allowing developers to focus on their application’s functionality rather than the underlying BLE protocols.

Another advantage of the BleuIO Node.js library is its flexibility. The library can be used to create a range of BLE applications, from simple IoT devices to complex mobile applications. This flexibility is made possible by the library’s support for a range of BLE devices and protocols.

The BleuIO Node.js library is also highly customizable. Developers can configure the library to meet their specific requirements, such as setting up a custom scan interval or configuring the advertising payload. This flexibility allows developers to create applications that are tailored to their specific needs.

To use the BleuIO Node.js library, developers must have a BleuIO device or module. BleuIO devices are small, low-cost modules that can be integrated into a range of applications, from simple IoT devices to complex mobile applications. These devices provide a reliable and secure way to communicate with BLE devices.

Installation and how to use this library can be found on BleuIO’s getting started guide.

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

Share this post on :

Create a real-time desktop CO2 widget using Javascript and Bluetooth

Creating a small real-time desktop CO2 widget using JavaScript and Bluetooth is a fun and engaging project that can help you understand how to work with Bluetooth communication and sensor data processing.

In this project we will use BleuIO to communicate with air quality monitoring sensor to read CO2 data. BleuIO is a bluetooth low energy usb dongle that helps to create BLE application easily. The AT command available on this device makes the development faster and easier.

There are many air quality sensor available but one popular choice is the HibouAir.

We will use electron js and node serial to connect with BleuIO. After that we will use AT commands to scan for nearby Bluetooth device that is advertising with a given board ID which is the air quality monitoring sensor.

Requirments :

  1. BleuIO
  2. HibouAir – air quality monitoring sensor

Note: both BleuIO and HibouAir are available at digikey.

Here are the steps you can follow to create your own widget:

Hardware setup :

Connect BleuIO to the computer and wait for the device to recognize it. This usually takes 10 seconds. Connect the air quality monitoring sensor HibouAir to a power cable. Make sure the device is within 50 meters.

Write the code :

Clone this repository from Github using

git clone https://github.com/smart-sensor-devices-ab/bluetooth-co2-desktop-widget.git

After that go inside the directory and write

npm install 

on terminal. This will install necessary libraries.

Inside this folder we will find three .js files and one html file. The index.html file is the frontend where we will see the real-time CO2 values.

The main.js file initialize the application and creates an window of 200px X 200px

render.js is the file which has all the logic go connect to BleuIO via serial port , gets real-time air quality data, decode it and finally print it on the screen.

Code explanation :

On render.js file, at first we make a list of devices connected to serial port. Then we filter out only the BleuIO devices by filtering with vendorID which is 2dcf. After that we pick the first item of the list.

Once we know the path of the BleuIO device , we connect to it.

ports = ports.filter((x) => x.vendorId == "2dcf");
      if (ports && ports.length > 0) {
        port = new SerialPort({
          path: ports[0].path,
          baudRate: 57600,
        });
}

Now that we are connected to the BleuIO dongle, we can write AT commands to it and get the response.

At first we write AT+DUAL to the dongle to put the dongle in dual role. So that we can scan for nearby devices and advertised data.

to put the dongle in dual role we write

port.write(Buffer.from("AT+DUAL\r"), function (err) {
          if (err) {
            document.getElementById("error").textContent =
              "Error writing at dual";
          } else {
            console.log('dongle in dual role')
}

In this project I am trying to get air quality data from a HibouAir device which has a board ID of 45840D. Therefore I look for advertised data that has this specific boardID. If i write AT+FINDSCANDATA=4584OD, BleuIO will filter out only advertise data from this board ID.

After writing this , we get a response from the dongle. To read the response from serial port we use

 port.on("readable", () => {
          let data = port.read();
console.log(data)
})

We can push the response in an array and later decide what to do with it.

When we do a AT+FINDSCANDATA=45840D

the response from the dongle looks something like this

Then we take the last response by using

resp = readDataArray[readDataArray.length - 2];

After that , get the advertised data from the string by

resp.split(" ").pop();

Now we have the advertised data in a variable. We can easily get the CO2 value from this string by selecting the position. The documentation from HibouAirs says , the CO2 value is right at the end of the string. In that case the value is 023A which is 570 is decimal.

We can print this value in our screen.

We can create a function that do the scanning every 20 seconds to get latest values.

Here is the complete code to render.js file

// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const { SerialPort } = require("serialport");
var port;
var readDataArray = [];
async function listSerialPorts() {
  await SerialPort.list().then((ports, err) => {
    if (err) {
      document.getElementById("error").textContent = err.message;
      return;
    } else {
      document.getElementById("error").textContent = "";
    }
    console.log("ports", ports);

    if (ports.length === 0) {
      document.getElementById("error").textContent = "No ports discovered";
    } else {
      ports = ports.filter((x) => x.vendorId == "2dcf");
      if (ports && ports.length > 0) {
        port = new SerialPort({
          path: ports[0].path,
          baudRate: 57600,
        });
        port.write(Buffer.from("AT+DUAL\r"), function (err) {
          if (err) {
            document.getElementById("error").textContent =
              "Error writing at dual";
          } else {
            const myWriteFunc = () => {
              port.write(Buffer.from("AT+FINDSCANDATA=5B0705=3\r")),
                function (err) {
                  if (err) {
                    document.getElementById("error").textContent =
                      "Error writing findscandata";
                  } else {
                    console.log("here");
                  }
                };
            };
            myWriteFunc();
            setInterval(() => {
              myWriteFunc();
            }, 20000);
          }
        });
        // Read serial port data
        port.on("readable", () => {
          let data = port.read();
          let enc = new TextDecoder();
          let arr = new Uint8Array(data);
          let removeRn = enc.decode(arr).replace(/\r?\n|\r/gm, "");
          if (removeRn != null) readDataArray.push(removeRn);
          if (removeRn == "SCAN COMPLETE") {
            console.log(readDataArray);
            let resp = readDataArray[readDataArray.length - 2];

            let advData = resp.split(" ").pop();
            let pos = advData.indexOf("5B0705");
            console.log("advData", advData);
            console.log("c", advData.substr(pos + 46, 4));
            let co2 = parseInt("0x" + advData.substr(pos + 46, 4));
            console.log(co2);
            document.getElementById("co2Val").innerHTML = co2;
          }
        });
      } else {
        document.getElementById("error").innerHTML =
          "No device found. Please connect a BleuIO ongle to your computer and try again.";
      }
    }
  });
}

function listPorts() {
  listSerialPorts();
  setTimeout(listPorts, 20000);
}

// Set a timeout that will check for new serialPorts every 2 seconds.
// This timeout reschedules itself.
//setTimeout(listPorts, 2000);

listSerialPorts();

To build this app we need a library called electron-builder. To install this library we write on terminal
npm i electron-builder

Once the library is build , we need to update our package json file and add build option or mac.

"build": {
    "appId": "com.co2.widget",
    "productName": "co2-widget",
    "mac": {
      "category": "airquality.app.widget"
    }
  }

We can update our script on package json like this

"scripts": {
    "start": "electron .",
    "pack": "electron-builder --dir",
    "dist": "electron-builder"
  },

Once we are done, build the app with

npm run build

We will see a dmg file in our dist folder. Once we run the app, the widget will look like this.

The value will update every 20 seconds.

Creating a small desktop CO2 widget using JavaScript and BlueIO is a great way to learn about these technologies and create a useful tool for monitoring indoor air quality.

Share this post on :

BleuIO Python library v1.2.0 includes verbose mode with easier event handling features

BleuIO Python library is updated and supports firmware version 2.2.1 .This update utilizes the new Verbose mode of the dongle and make it a lot simpler to work with Bluetooth Low Energy with Python.
Now the AT commands returns an object with 4 members

  • Command
  • Acknowledge
  • Response
  • End

Each contains a JSON object, except Response. The Response contains a list of JSON objects since a command can have several responses.

This new update of the library makes it easier to get the relevant information without building your own parser.
Status variables : Helpful status variables has been added which helps to keep track of the dongle status ; whether it is scanning, advertising or connected along with the dongle role.
Callback function : A callback function should be registered for both scan results and events. The callback functions will run every time a new event or scan result is detected.

Using the library

List of AT commands are available at https://www.bleuio.com/getting_started/docs/commands/

and how to access these AT commands using python library can be found at
https://pypi.org/project/bleuio/

Before starting to install our library, make sure you have the latest python installed on your system.

If you have never installed a library from PyPI, you must install the pip tool enabling you to download and install a PyPI package. There are several methods that are described on this page.

Now Install the library by running

pip install bleuio

pip automatically downloads and installs the most recent library on your system in the correct directory. To check that the installation went well, you can launch a Python interpreter and run the following lines:

from bleuio_lib.bleuio_funcs import BleuIO
my_dongle = BleuIO()
print(my_dongle.ati().Rsp)

Good luck on creating amazing Bluetooth Low Energy application using BleuIO and Python.

Share this post on :

BleuIO’s new firmware version 2.2.1 increased MTU size to 512 bytes

What is the maximum transmission unit (MTU)?

In networking, maximum transmission unit (MTU) is a measurement representing the largest data packet that a network-connected device will accept.

BleuIO’s new firmware version 2.2.1 increased MTU size from 247 bytes to 512 bytes, which allows more data to fit into fewer packets. This generally results in a faster and more efficient transmission of data.

A new AT command AT+GETMAC is also added to the latest firmware. This will return the MAC address of the BleuIO dongle.

Added features:

  • Increased MTU to 512 bytes.
  • Added an MTU event that shows the negotiated MTU when connected or when changed: (MTU CHANGED: xxx) (using verbose mode: {779:”0000″,”evt”:{“action”:”mtu changed”,”mtu”:xxx}})
  • Added new AT command: AT+GETMAC for getting bleuio mac address.

Bugfixes

  • Fixed format errors of some messages when using verbose mode that doesn’t comform to JSON.

To find out more about the updates of the dongles new firmware 2.2.1, please visit our Getting Started Guide.

Share this post on :