Building a BLE Application with ReactJS and BleuIO

In this tutorial, we’ll explore how to create a Bluetooth Low Energy (BLE) application using ReactJS and the BleuIO BLE USB dongle. BleuIO is a versatile BLE device that makes developing BLE applications fast and easy with its user-friendly AT commands.

Introduction

Bluetooth Low Energy (BLE) technology is widely used for short-range communication, particularly in IoT applications. BleuIO, with its easy-to-use AT commands, simplifies the process of integrating BLE functionality into your applications. In this tutorial, we’ll demonstrate how to create a BLE application using ReactJS. Specifically, we will show you how to scan for nearby BLE devices for three seconds and display the results on the screen, highlighting the capabilities of BleuIO.

Prerequisites

Before we start, make sure you have the following:

  • A BleuIO USB dongle
  • A computer with a Chromium-based browser (like Chrome or Edge)
  • Node.js and npm installed
  • Basic knowledge of ReactJS

Setting Up the Project

First, let’s create a new React project. If you haven’t already installed create-react-app, you can do so with the following command:

npx create-react-app ble-react-app
cd ble-react-app
npm start

This will create a new React application and start the development server.

Creating the Serial Port Component

We’ll create a component to handle the serial port communication with the BleuIO dongle. Create a new file called SerialPortComponent.js in the src directory and add the following code:

import React, { useState, useEffect } from 'react';

const SerialPortComponent = () => {
const [port, setPort] = useState(null);
const [output, setOutput] = useState('');
const [reader, setReader] = useState(null);
const [writer, setWriter] = useState(null);

const connectToSerialPort = async () => {
try {
// Request a port and open a connection.
const selectedPort = await navigator.serial.requestPort();
await selectedPort.open({ baudRate: 9600 });
setPort(selectedPort);

const textDecoder = new TextDecoderStream();
const readableStreamClosed = selectedPort.readable.pipeTo(
textDecoder.writable
);
const reader = textDecoder.readable.getReader();
setReader(reader);

const textEncoder = new TextEncoderStream();
const writableStreamClosed = textEncoder.readable.pipeTo(
selectedPort.writable
);
const writer = textEncoder.writable.getWriter();
setWriter(writer);

// Read data from the serial port.
readSerialData(reader);
} catch (error) {
console.error('There was an error opening the serial port:', error);
}
};

const readSerialData = async (reader) => {
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
// Convert the received data to a string and update the state.
setOutput((prevOutput) => prevOutput + value);
}
} catch (error) {
console.error('Error reading from the serial port:', error);
}
};

const writeToSerialPort = async () => {
setOutput('');
try {
if (writer) {
// Send AT+CENTRAL command
await writer.write('AT+CENTRAL\r');
setOutput((prevOutput) => prevOutput + 'AT+CENTRAL\r\n');

// Wait for a short while to ensure the command is processed
await new Promise((resolve) => setTimeout(resolve, 500));

// Send AT+GAPSCAN=3 command
await writer.write('AT+GAPSCAN=3\r');
setOutput((prevOutput) => prevOutput + 'AT+GAPSCAN=3\r\n');

// Wait for scan to complete and read response
await new Promise((resolve) => setTimeout(resolve, 3000));

// Read and process data from the serial port
let scanData = '';
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
scanData += value;
}
setOutput((prevOutput) => prevOutput + scanData);
} else {
console.error('Writer not available');
}
} catch (error) {
console.error('Error writing to the serial port:', error);
}
};

useEffect(() => {
return () => {
// Cleanup function to close port when component unmounts
if (port) {
port.close();
}
if (reader) {
reader.releaseLock();
}
if (writer) {
writer.releaseLock();
}
};
}, [port, reader, writer]);

return (
<div className="mt-5">
<button
className="btn btn-success me-2"
onClick={connectToSerialPort}
disabled={!!port}
>
Connect to BleuIO
</button>
<button
className="btn btn-warning me-2"
onClick={writeToSerialPort}
disabled={!writer}
>
Scan for nearby BLE devices for 3 seconds
</button>

{output && (
<div>
<h3>Response from the BleuIO:</h3> <pre>{output}</pre>
</div>
)}
</div>
);
};

export default SerialPortComponent;

Explanation of the Code

  1. Connecting to the Serial Port: The connectToSerialPort function requests access to the serial port and opens a connection. It initializes the text encoder and decoder streams for reading and writing data.
  2. Reading Serial Data: The readSerialData function reads data from the serial port continuously and updates the output state with the received data.
  3. Writing to the Serial Port: The writeToSerialPort function sends AT commands to the serial port. It first sends the AT+CENTRAL command to put the device in central mode, then sends the AT+GAPSCAN=3 command to scan for nearby BLE devices for 3 seconds. It reads and displays the response from the serial port after the scan completes.
  4. Cleanup: The useEffect hook ensures that the serial port is properly closed and resources are released when the component is unmounted.

Using the Component in Your App

Update your App.js to include the new SerialPortComponent.

// src/App.js
import React from 'react';
import SerialPortComponent from './SerialPortComponent';

function App() {
return (
<div className="App">
<header className="App-header">
<h1>BLE Application with React and BleuIO</h1>
<SerialPortComponent />
</header>
</div>
);
}

export default App;

Running the Application

Make sure your BleuIO USB dongle is connected to your computer. Start your React application:

npm start

Open your browser and navigate to http://localhost:3000. You should see the application with two buttons: “Connect to BleuIO” and “Scan for nearby BLE devices for 3 seconds“.

  • Connect to BleuIO: Click this button to connect to the BleuIO USB dongle. The browser will prompt you to select the serial port.
  • Scan for nearby BLE devices for 3 seconds: After connecting, click this button to send the AT+CENTRAL and AT+GAPSCAN=3 commands to the BleuIO dongle. The output area will display the response from the device.

Output

In this tutorial, we’ve demonstrated a basic usage of BleuIO AT commands by creating a BLE application using ReactJS and the BleuIO USB dongle. By leveraging the Web Serial API and the straightforward AT commands provided by BleuIO, you can quickly develop BLE applications that run on any platform. You can expand on this example to develop your own applications using BleuIO’s comprehensive set of AT commands. Read more about the AT commands in our documentation.

BleuIO simplifies BLE development and, combined with the popularity and versatility of ReactJS, allows developers to create powerful and cross-platform BLE applications with ease. Whether you’re building IoT devices, wearable tech, or any BLE-enabled application, BleuIO is a reliable and efficient choice.

Share this post on :

BleuIO Firmware Update 2.7.2: Enhanced Security and Stability

The BleuIO Bluetooth Low Energy (BLE) USB dongle continues to set the standard for BLE application development with its latest firmware update, version 2.7.2. This update brings significant enhancements, focusing on security features and critical bug fixes, making it an essential upgrade for developers and users of BleuIO.

Key Enhancements in Firmware 2.7.2

Enhanced Security with Authentication and Encryption Permissions

One of the most notable additions in this update is the introduction of Authentication and Encryption Permission support for Custom Service attributes. This feature is a major step forward in ensuring secure BLE communications. The permissions framework allows the server (BleuIO) to determine the client’s access level to characteristic or descriptor values based on the need for an authenticated and/or encrypted connection. This means that sensitive data can now be protected more robustly, ensuring that only authorized clients can read from or write to specific attributes.

Bug Fixes and Stability Improvements

The 2.7.2 firmware update also addresses several bugs that were affecting the reliability and performance of the BleuIO dongle. Here are the key fixes:

  1. AT+GETBOND Command Bug Fixes:
    • Incorrect MAC Addresses: Previously, the AT+GETBOND command occasionally returned incorrect MAC addresses. This issue has now been resolved, ensuring accurate reporting of bonded device addresses.
    • Removal of Address Type: The address type part of the MAC address, which was always returned as PUBLIC_ADDRESS (0) and not stored with the bonding information, has been removed. This simplification helps in reducing confusion and potential errors in handling bonded device information.
  2. AT+GAPSCAN Command Stability:
    • The command AT+GAPSCAN= with an empty argument previously caused the device to reset unexpectedly. This bug has been fixed, ensuring stable and predictable behavior when scanning for devices.
  3. Connection Initiation Fixes:
    • The update resolves issues where attempting to initiate a connection using AT+GAPCONNECT while also advertising led to unpredictable behavior, such as being unable to connect or scan properly. This fix enhances the overall stability and reliability of establishing BLE connections.

For developers and users of the BleuIO dongle, updating to firmware version 2.7.2 is highly recommended. The new security features ensure that your BLE applications can enforce stringent access controls, protecting sensitive data. The bug fixes improve the overall functionality and reliability of the device, reducing the likelihood of encountering errors during development and deployment.

For more detailed information and to download the latest firmware, visit the BleuIO getting started guide.

Share this post on :

Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications Part 3 (secure connection)

Introduction

Building on the steps in our previous post Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications Part 2 where we showed how to use the BleuIO to advertise sensor data, we are now going to put the data in a Custom Service. Additionally, we are going to protect the data by making it only available with a secure connection that can only be established by entering a 6-digit passkey.

This example is going to show you how to start protecting your data as well as how to set up and use a custom service.

Requirements

Running the example

Make sure the BleuIO Dongle is connected to the Feather RP2040 Board. Connect the Feather RP2040 Board to your computer using the USB cable.

Make sure the Feather RP2040 Board is selected as well as the correct COM port in the drop-down menu.

(Optional) Change the passkey used for the secure connection and/or the frequency the sensors are read, in the code

/* Requires 6 digits */
#define SECURE_CONN_PASSKEY "232425"
// How often we read the sensors and update the characteristics (in
seconds)
#define READ_UPDATE_FREQUENCY   5

Click the Upload button.

Done! The dongle should now be advertising the sensor values. (If you just plugged in the Feather it may take about 10 seconds before advertising starts as the BleuIO bootloader opens and closes)

(Optional) Open Serial Monitor. You can open the Serial Monitor from the menu:

Tools>Serial Monitor

You should now see the output from the project.

Getting the data

To get the results you can use any BLE scanner app. Here we use nRF Connect:

Find the device that advertise as BleuIO Arduino Example and connect.

You will be prompted to pair.

And then to enter the passkey.
Enter the passkey/pin (default: 232425) and continue.

Go to the service with the UUID: ee6ec068-7447-4045-9fd0-593f3ba3c2ee Notice that you are now bonded.

The service has 5 characteristics, one for each of the sensor values:

1. Lux
2. Pressure
3. Temperature
4. Humidity
5. Gas resistance

Read and/or enable notification for each characteristic to see the data.
The Characteristic User Description Descriptor of each characteristic can be read to show what value it holds.

Like in the previous example, when we parse the hex into decimal values we get:

Lux: 0x0068 = 104 uW/cm2
Pressure: 0x03F8 = 1016 hPa
Temperature: 0x0017 = 23 Celcius
Humidity: 0x0017 = 23 %Rh
Gas Resistance: 0x0041 = 65 KOhms

If not bonded, the values will always show 00-00.

Share this post on :

Developing BLE Applications with BleuIO and Rust

BleuIO is a versatile Bluetooth Low Energy (BLE) USB dongle designed to simplify the development of BLE applications. With its support for AT commands and seamless integration with Rust programming language, BleuIO offers developers a straightforward and efficient way to create BLE applications. In this tutorial, we will explore how to use BleuIO and Rust to develop BLE applications easily.

About Rust Programming Language:

Rust is a modern, systems programming language that focuses on safety, performance, and concurrency. Developed by Mozilla, Rust has gained popularity for its unique features and advantages, making it an excellent choice for various application domains, including system programming, web development, and embedded systems.

Prerequisites:

Setting Up BleuIO:

  1. Connect BleuIO Dongle:
    • Connect the BleuIO dongle to an available USB port on your computer.
  2. Identify Serial Port:
    • Identify the serial port associated with BleuIO. For example, On macOS and Linux, it may look like /dev/cu.usbmodem4048FDE52DAF1. On windows it looks like COM6

Installing Rust and Cargo:

  • Windows:
    • Download and install the Rust compiler (including Cargo) from the official website: Rustup.
    • Follow the installation instructions provided on the website.
  • Mac/Linux:
    • Open a terminal and run the following command to install Rust and Cargo:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Follow the on-screen instructions to complete the installation.

Creating a Cargo Project:

  • Open Terminal/Command Prompt:
    • Windows: Open Command Prompt or PowerShell.
    • Mac/Linux: Open Terminal.
  • Navigate to Project Directory:
cd /path/to/projects
  • Create a New Cargo Project:
cargo new BleuIO

This will create a new directory named “BleuIO” containing the project files.

  • Navigate into the Project Directory:
cd BleuIO

Writing BLE Application Code:

  • Open src/main.rs in Your Code Editor:
    • Replace the default Rust code with the BLE application code. Make sure to replace the port_name with your connected BleuIO port.
  • Implement BLE Application Logic:
    • Write Rust code to interact with BleuIO using AT commands.
use std::io::{self, Write};
use std::thread::sleep;
use std::time::Duration;
use serialport;

fn main() -> io::Result<()> {
    // Open the serial port
    let port_name = "/dev/cu.usbmodem4048FDE52DAF1";
    let mut port = serialport::new(port_name, 9600)
        .timeout(Duration::from_secs(5)) // Adjust timeout value here (5 seconds in this example)
        .open()
        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

    // Write "AT+CENTRAL" to set the BleuIO dongle to centrla role
    let data_central = b"AT+CENTRAL\r\n";
    port.write_all(data_central).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

    // Wait for 500 milliseconds
    sleep(Duration::from_millis(5));

    // Write "AT+GAPSCAN=3" to scan for nearby BLE devices for 3 seconds
    let data_gapscan = b"AT+GAPSCAN=3\r\n";
    port.write_all(data_gapscan).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

    // Read response from the BleuIO dongle until no more data is available
    let mut response = String::new();
    loop {
        let mut buffer: [u8; 128] = [0; 128];
        let bytes_read = port.read(&mut buffer).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

        // Check if no more data is available
        if bytes_read == 0 {
            break;
        }

        // Convert bytes to string and append to the response
        let chunk = String::from_utf8_lossy(&buffer[..bytes_read]);
        response.push_str(&chunk);

        // Print the current chunk of response
        print!("{}", chunk);
    }

    // Drop the port to close it
    drop(port);

    Ok(())
}

Building and Running the Project:

  • Build the Project:
cargo build
  • Run the Project:
cargo run

Output

In this tutorial, we’ve demonstrated how to develop a simple BLE applications using BleuIO and Rust that puts the BleuIO in central role and scans for nearby BLE devices for 3 seconds. Finally shows the list on the screen. By using BleuIO’s support for AT commands and Rust’s simplicity, developers can create BLE applications effortlessly. Start exploring the possibilities with BleuIO and Rust today!

Share this post on :

BleuIO JavaScript Library Update (v1.1.2): Supports BleuIO Firmware v2.7.1

BleuIO JavaScript library received a significant update to version 1.1.2, allows compatibility with BleuIO firmware v2.7.1. This update introduces several new commands, expanding the capabilities of BleuIO and helps developers to innovate further.

Here’s a breakdown of the key additions in version 1.1.2:

  1. at_customservice(): This function allows developers to set or query Custom Services, with the ability to add up to 5 Characteristics. Custom Services play a vital role in tailoring BLE applications to specific use cases, and this addition enhances flexibility in service customization.
  2. at_customservicestart() and at_customservicestop(): These functions enable the starting and stopping of Custom Services based on the settings configured using at_customservice(). This dynamic control over service activation facilitates seamless integration and management of BLE functionalities.
  3. at_customservicereset(): In scenarios where resetting Custom Service settings becomes necessary, this function comes to the rescue. It halts the Custom Service and resets configurations set by at_customservice(), ensuring a clean slate for subsequent operations.
  4. at_suotastart() and at_suotastop(): The addition of these functions facilitates over-the-air firmware updates (SUOTA) by enabling or disabling the SUOTA Service and associated advertising. This capability simplifies the process of updating BLE devices remotely, enhancing maintenance and scalability.
  5. at_autoexec() and at_clrautoexec(): These functions provide control over automatic execution of commands upon BleuIO startup. Developers can set or clear up to 10 commands, optimizing device initialization and enhancing user experience.
  6. at_connparam(): This function simplifies the management of connection parameters, allowing developers to set or display preferred values. Real-time updates during connection enable fine-tuning of parameters for optimal performance.

How to use: Updating to BleuIO JavaScript library 1.1.2 is a straightforward process. Use the following commands to use the lates BleuIO JavaScript library npm i bleuio

Documentation and Further Details: Comprehensive details, usage examples, and guidelines to use the new functionalities introduced in version 1.1.2 of the BleuIO JavaScript library is available at the official NPM page https://www.npmjs.com/package/bleuio

Share this post on :

Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications Part 2

Introduction

After following the steps in our previous post Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications and trying out the Adafruit TinyUSB Library Example serial_host_bridge it is now time for a more practical example. This example is going to show you how to connect real sensors to the Feather, read the values and have it command the BleuIO to advertise them.

Basically you could say that you are going to create a autonomous BLE beacon that advertise the current temperature, humidity etc.

For this example we are using a Gas sensor BME680 and a OPT3002 Light-to-Digital Sensor.

Requirements

Arduino Libraries

The libraries can easily be installed through the Arduino IDE:

  • Open Library Manager by clicking the Library Manager icon to the left or go through menu: Sketch>Include Libraries>Manage Libraries…
  • Search for Adafruit_BME680, and install the Adafruit_BME680 Library
  • Search for ClosedCube OPT3002, and install the ClosedCube OPT3002 library

Connecting I2C sensors

  • Connect four wires (at a minimum) for each I2C device.
  • Power the device with 3.3V, then a ground wire.
  • And a SCL clock wire, and and a SDA data wire.

Running the example

  • Make sure the BleuIO Dongle is connected to the Feather RP2040 Board.
  • Connect the Feather RP2040 Board to your computer using the USB cable.
  • Make sure the Feather RP2040 Board is selected aswell as the correct COM port in the dropdown menu.
  • (Optional) Change the frequency the sensors are read and advertising data updated, in the code
// How often we read the sensors and update the advertings message
(in seconds)
#define READ_UPDATE_FREQUENCY   5
  • Click the Upload button.

Done! The dongle should now be advertising the sensor values. (If you just plugged in the Feather it may take about 10 seconds before advertising starts as the BleuIO bootloader opens and closes)

  • (Optional) Open Serial Monitor. You can open the Serial Monitor from the menu: Tools>Serial Monitor

You should now see the output from the project.

Scanning the results

To see the results you can use any BLE scanner app.

Here we use nRF Connect:

The data in the red box is our sensor values:

0x006203EB001700170041

When we parse the hex into decimal values we get:

Light: 0x0062 = 98 uW/cm2
Pressure: 0x03EB = 1003 hPa
Temperature: 0x0017 = 23 Celcius
Humidity: 0x0017 = 23 %Rh
Gas Resistance: 0x0041 = 65 KOhms

Share this post on :

BleuIO Python Library Update (v1.4.0): Supports BleuIO Firmware v2.7.1

BleuIO Python library received a significant update to version 1.4.0, allows compatibility with BleuIO firmware v2.7.1. This update introduces several new commands, expanding the capabilities of BleuIO and helps developers to innovate further.

Enhanced Functionality: The latest BleuIO Python library update includes latest commands, aligning with the advancements in firmware v2.7.1. Let’s have a look into the key additions:

  1. at_autoexec(): This command corresponds to AT+AUTOEXEC in the BleuIO firmware. It enables developers to configure automatic execution of specific actions upon device boot-up. Whether it’s initializing connections or setting parameters, at_autoexec() enables the initialization process, enhancing the efficiency of BLE applications.
  2. at_clrautoexec(): This command corresponds to AT+CLRAUTOEXEC. It helps developers to clear the configured automatic execution settings on the BleuIO device. This function provides flexibility in modifying device behavior dynamically, ensuring seamless adaptability to changing project requirements.
  3. at_connparam(): BLE connection parameters play a pivotal role in defining the characteristics of data transmission between devices. The addition of at_connparam() facilitates precise control over connection parameters, helps developers to optimize communication efficiency based on specific use cases.
  4. at_getbond(): Security is paramount in BLE applications, especially concerning device bonding. The introduction of at_getbond() allows developers to retrieve bonding information from the BleuIO device, enabling seamless integration of security features and enhancing overall data integrity.

How to update: Updating to BleuIO Python library 1.4.0 is a straightforward process. Developers can leverage the command python -m pip install --upgrade bleuio to ensure they have access to the latest functionalities and optimizations.

Documentation and Further Details: Comprehensive details, usage examples, and guidelines to use the new functionalities introduced in version 1.4.0 of the BleuIO Python library is available at the official PyPI page https://pypi.org/project/bleuio/.

Share this post on :

Reading data from BLE device using Python, Microsoft Excel and BleuIO

In today’s data-driven world, extracting meaningful insights from raw data is crucial for informed decision-making. Microsoft Excel stands as an amazing tool for data analysis, offering powerful features for visualization, manipulation, and interpretation. However, accessing and processing data from external sources, such as BLE devices, can often be challenging and time-consuming.

BleuIO revolutionizes BLE application development with its intuitive AT command interface, eliminating the need for complex coding. With BleuIO, developers can communicate effortlessly with BLE devices, retrieve data, and execute commands with ease. Whether you’re a seasoned developer or just starting out, BleuIO streamlines the development process, allowing you to focus on innovation rather than technical complications. In this tutorial we will see how to read data from an air quality monitoring BLE device and get it on Microsoft excel sheet for further analysis.

What is BleuIO?

BleuIO is a versatile BLE 5.0 USB dongle designed to simplify the development of BLE applications. With its AT command interface, developers can easily communicate with BLE devices without the need for complex coding. Whether you’re a beginner or an experienced developer, BleuIO makes BLE application development faster and more accessible.

Setting Up the Environment

Before we dive into the code, let’s set up our development environment. You’ll need:

Communicating with BleuIO

To communicate with BleuIO, we’ll use Python and its serial library. First, ensure that you have the pyserial library installed. Then, connect BleuIO to your computer and identify the serial port it’s connected to. Next, we’ll send AT commands to BleuIO and retrieve the responses.

Here is the complete python code

import serial
import re
import json

# Define the serial port and baudrate
serial_port = "COM8"
baudrate = 57600


def read_response(ser):
    """
    Read response from serial port until a newline character is encountered.
    """
    response = b""
    while True:
        char = ser.read(1)
        if char == b"":
            break  # No more data to read
        response += char
        if char == b"\n\n":
            break  # Reached end of response
    return response.decode()


def hex_to_decimal(hex_str):
    """
    Convert hexadecimal string to decimal integer.
    """
    return round(int(hex_str, 16) / 10.0, 1)


def find_pattern(response):
    """
    Find and extract patterns matching the specified format.
    """
    pattern = r"\{T:\"(\w+)\",H:\"(\w+)\",PM1:\"(\w+)\"PM2\.5:\"(\w+)\"PM10:\"(\w+)\",IAQ:\"(\w+)\",PPM:\"(\w+)\"\}"
    matches = re.findall(pattern, response)
    return [
        {
            "T": hex_to_decimal(m[0]),
            "H": hex_to_decimal(m[1]),
            "PM1": hex_to_decimal(m[2]),
            "PM2.5": hex_to_decimal(m[3]),
            "PM10": hex_to_decimal(m[4]),
            # "IAQ": hex_to_decimal(m[5]),
            # "PPM": hex_to_decimal(m[6]),
        }
        for m in matches
    ]


def main():
    # Connect to the serial port
    ser = serial.Serial(serial_port, baudrate, timeout=1)

    # List to store responses
    responses = []

    # Send the command 'AT+CENTRAL' to the device
    ser.write(b"AT+CENTRAL\r")
    response = read_response(ser)

    # Connect to the device
    ser.write(b"AT+GAPCONNECT=[1]D1:53:C9:A9:8C:D2\r")
    response = read_response(ser)

    # Set notification
    ser.write(b"AT+SETNOTI=0021\r")
    response = read_response(ser)

    # Get all data
    ser.write(b"AT+GATTCWRITEWR=0021 GET DATA=ALL\r")
    while True:
        response = read_response(ser)
        responses.append(response.strip())
        if "DATA:END" in response:
            break  # End of response

    # Find and collect patterns matching the specified format
    collected_patterns = []
    for r in responses:
        pattern_matches = find_pattern(r)
        if pattern_matches:
            collected_patterns.extend(pattern_matches)

    # Convert to JSON
    json_data = json.dumps(collected_patterns, indent=2)
    print(json_data)

    # Close the serial port
    ser.close()


if __name__ == "__main__":
    main()

In this code we have

  • Establishes a connection to the serial port, sends commands to the BLE device, and retrieves responses of 7 days air quality data history stored in the device.
  • Parses the responses to extract relevant patterns using regular expressions.
  • Converts the extracted patterns into JSON format for easy handling and printing.
  • Finally, closes the serial port.

Integrating with Excel

Now, let’s integrate BleuIO with Excel to visualize and analyze the air quality data. By executing a Python script within Excel’s VBA environment, we can populate the data directly into Excel for further analysis.

Here is the complete code

Sub SerialCommunication()
    Dim response As String
    Dim pythonScriptPath As String
    Dim wsh As Object, exec As Object, output As String
    Dim jsonData As Object
    Dim obj As Object
    Dim i As Integer, j As Integer
    
    ' Set the path to the Python script
    pythonScriptPath = "C:\Users\PC\Desktop\excel bleuio\serial_communication.py" ' Update with the correct path
    
    ' Create Windows Script Host object
    Set wsh = CreateObject("WScript.Shell")
    
    ' Execute the Python script and capture its output
    Set exec = wsh.exec("python """ & pythonScriptPath & """")
    
    ' Read the output of the script
    output = exec.StdOut.ReadAll
    
    ' Parse JSON data
    Set jsonData = JsonConverter.ParseJson(output)
    
    ' Write headers in the first row
    i = 1 ' Starting row
    j = 1 ' Starting column
    For Each key In jsonData(1).Keys
        Sheet1.Cells(i, j).value = key
        j = j + 1
    Next key
    
    ' Write data into separate columns
    i = i + 1 ' Move to the next row
    For Each obj In jsonData
        j = 1 ' Starting column
        For Each key In obj.Keys
            Sheet1.Cells(i, j).value = obj(key)
            j = j + 1
        Next key
        i = i + 1 ' Move to the next row
    Next obj
End Sub

In this code we have,

  • Called the python script.
  • The response we got from python script we then passed it using JsonConverter.
  • Finally we loop through the object and presented it on the Excel sheet on their respective cells.


Set up JsonConverter

If you get error like JsonConverter object is not recognized, follow the steps:

  1. Download JSONConverter.bas: You can download the JSONConverter.bas file from various sources online. Here is a good github link to download from.
    https://github.com/VBA-tools/VBA-JSON
    It’s a common utility module for VBA that provides JSON parsing capability.
  2. Import JSONConverter.bas into your project: Open your Excel workbook, then go to the Visual Basic Editor (Alt + F11). From the menu, select File > Import File and choose the JSONConverter.bas file you downloaded. This will add the JSONConverter module to your project.
  3. Ensure Microsoft Scripting Runtime Reference: Go to Tools > References in the VBA editor and ensure that “Microsoft Scripting Runtime” is checked. This is needed for dictionary objects used in JSON parsing.

Run the script

  1. Insert a Button:
    • Go to the “Developer” tab in Excel. If you don’t see the “Developer” tab, you may need to enable it in Excel options.
    • Click on the “Insert” drop-down menu in the “Controls” group.
    • Choose the “Button” (Form Control) option.
    • Click and drag to draw the button on your worksheet.
  2. Assign the Macro:
    • Right-click on the button you just inserted and select “Assign Macro”.
    • In the “Assign Macro” dialog box, you should see a list of available macros. Since you just created a new macro, it should be listed. In this case, it should be “SerialCommunication”.
    • Select the “SerialCommunication” macro and click “OK”.
  3. Edit the Macro (if needed):
    • If you want to edit the macro, you can click on the “Edit” button in the “Assign Macro” dialog box. This will open the VBA editor where you can make changes to the macro.
  4. Test the Button:
    • Click on the button you inserted in your worksheet. This should trigger the “SerialCommunication” macro, which will execute the VBA code to communicate with the serial port and display the response in Excel.
  5. Ensure Correct Port and Settings:
    • Before testing, ensure that the COM port (COM8) and other settings in the VBA code match your requirements and device specifications.

Output

Use Cases: Transforming Data into Actionable Insights

  1. Indoor Air Quality Monitoring: Deploy BLE-enabled sensors in indoor environments to monitor air quality parameters such as temperature, humidity, and particulate matter. Excel’s data analysis capabilities enable users to identify trends, anomalies, and potential air quality issues, facilitating proactive measures for improving indoor air quality.
  2. Environmental Studies and Research: Conduct environmental studies and research projects using BleuIO to collect air quality data in various outdoor settings. Excel serves as a powerful tool for data aggregation, statistical analysis, and visualization, enabling researchers to gain valuable insights into environmental patterns and trends.
  3. Health and Safety Compliance: Ensure compliance with health and safety regulations by monitoring air quality in workplaces, public spaces, and industrial facilities. BleuIO, coupled with Excel, enables continuous monitoring of air quality parameters, facilitating compliance reporting and risk assessment processes.

By leveraging BleuIO’s seamless BLE communication capabilities and Excel’s robust data analysis features, developers and analysts can unlock the full potential of BLE application development and data analysis. Whether you’re monitoring air quality in indoor environments, conducting environmental research, or ensuring regulatory compliance, BleuIO and Excel provide a powerful combination for transforming raw data into actionable insights.

Share this post on :

BleuIO Firmware Update 2.7.0 Featuring Dynamic Connection Parameter Adjustment

BleuIO, the versatile Bluetooth Low Energy (BLE) USB dongle renowned for simplifying BLE application development, has released a new firmware upgrade to version 2.7.0. This latest update brings forth new features and commands, further enables developers to create innovative BLE applications with ease.

Added Features:

  • Dynamic Connection Parameter Adjustment: One of the standout additions in firmware 2.7.0 is the ability to change connection parameters on the fly, even while maintaining a connection. This feature not only facilitates fine-tuning of BLE connections but also provides flexibility in adapting to varying network conditions. Additionally, developers can modify default connection parameters for improved efficiency when utilizing the AT+GAPCONNECT command with just the MAC address as an argument.

New Commands:

  • AT+CONNPARAM: This command emerges as a powerful tool for setting or displaying preferred connection parameters. When executed while connected, it enables seamless updating of connection parameters on the current target connection, streamlining the optimization process for BLE applications.

With these enhancements, BleuIO offers rapid BLE development solution. Whether you’re a seasoned developer or pro in BLE applications development, firmware 2.7.0 unlocks new possibilities and simplifies the path to crafting cutting-edge solutions.

How to Upgrade:

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

Share this post on :

Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications

In the realm of IoT projects, finding a reliable and efficient host hardware solution is important. The Adafruit Feather RP2040 is an excellent solution for that. It comes equipped with a comprehensive ecosystem, including an IDE and libraries tailored for your new projects. With this setup, you get to keep the main USB port for uploading, debugging, and data communication, while at the same time sending and receiving data to just-about-any USB device, like the BleuIO. 

https://learn.adafruit.com/adafruit-feather-rp2040-with-usb-type-a-host

In this first blog with the Adafruit Feather board, we are going to show how you can setup the USB stack and communicate with BleuIO using the Adafruit Feather RP2040 board. Later in next project we will show how to read a Temperature and Humidity sensor and display the data help of the Bluetooth Low Energy (BLE) interface. 

Requirements

Setting Up the Development Environment

Arduino IDE Download 

This section covers getting your Arduino IDE set up to include your board. 

  • Download and install it to your computer.
  • Once installed, open the Arduino IDE. In the Arduino IDE, and navigate to the Preferences window. 
  • Copy the following URL and Add the URL to the the Additional Boards Manager URLs field 
  • https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json 

Selecting the Appropriate Board Configuration

Add Board Support Package 

  • In the Arduino IDE, click on Tools > Board > Boards Manager. If you have previously selected a board, the Board menu item may have a board name after it. 
  • In the Boards Manager, search for RP2040. Scroll down to the Raspberry Pi Pico/RP2040 by Earle F Philhower, III entry. Click Install to install it. 

Choose Your Board 

  • In the Tools > Boards menu, you should now see Raspberry Pi RP2040 Boards (possibly followed by a version number). 
  • Navigate to the Raspberry Pi RP2040 Boards menu and choose Adafruit Feather RP2040 USB Host

Now you’re ready to begin using Arduino with your RP2040 board! The main use case for this Feather is to act as a USB host.  

Library Installation

Install Adafruit_TinyUSB Library 

To use your Feather as a USB host, you’ll need to install the Adafruit TinyUSB library. It can be installed using the Library Manager in the Arduino IDE. 

Click the Manage Libraries > menu item, search for Adafruit TinyUSB, and select the Adafruit TinyUSBLibrary 

 
Install Pico PIO USB Library 

Additionally, you’ll need to install the Pico PIO USB library.

Click the Manage Libraries > menu item again, search for PIO USB, and select the Pico PIO USB library.

Configuration and Deployment

Board Upload Settings 

  • In the Tools menu, select Adafruit Feather RP2040 USB Host under Board.
  • For CPU Speed, you’ll need to select 120 MHz or240 MHz.
  • Finally, under USB Stack, select Adafruit TinyUSB.  

Serial Host Bridge Example 

  • Load the example code onto your Feather after following the library installation instructions on the Arduino Library Install page
  • Navigate to the Adafruit TinyUSB Library Examples and select DualRole – CDC – serial_host_bridge 

Now you can control the BleuIO USB Dongle via the Adafruit Feather board. 

With these steps completed, you’re now ready to start integrating BleuIO with your Adafruit Feather RP2040 board. This setup lays the foundation for exciting IoT projects, and we’ll explore more functionalities in future tutorials where we will show how to make the BleuIO USB Dongle advertise data from a Temperature and Humidity sensor. 

Stay tuned for further guides on applying BleuIO and Adafruit Feather RP2040 for your projects!

Share this post on :