Access BLE data remotely

Suppose you have some BLE devices at your home and want to control or scan for those devices while at your workplace. In this project, we will discuss how to access BLE data remotely.  

We have already created a script that communicates through BleuIO dongle remotely and gives us the response. You can access the script at 

https://github.com/smart-sensor-devices-ab/bledata_remote_access.git

You are free to clone the script and make changes as you wish. 

In this script, JavaScript is used to connect to the dongle using google chrome’s serial port. There is a simple PHP script that helps pass data through the cloud.

Step 1: Uploading

Upload the API folder in any server that supports PHP. This script reads and writes data to a JSON file upon request.

We have uploaded the file at http://smartsensor.io/api/api.php

You can use this URL if you don’t have a server to upload.

Step 2: Home computer setup

Open the index.js file found in the root folder and update the URL of the API file on both occasions. 

You can leave the url as it is if you want to use file from our server.

Now connect a BleuIO dongle to your home computer and open the index.html file from the root folder.

Click connect and select the COM port where the dongle is connected.

Step 3: Office / Workplace / remote computer setup

Open the index.html file found in the user folder and update the URL of the API file on both occasions.

You can leave the url as it is if you want to use file from our server.

Now open this file in a browser and start writing AT commands.

Currently, You can access the following AT commands 

  • ATI ( Returns firmware version, hardware type and unique organization identifier, device connection status )
  • AT+CENTRAL (Sets the device Bluetooth role to central role.)
  • AT+PERIPHERAL (Sets the device Bluetooth role to the peripheral.)
  • AT+DUAL (Sets the device Bluetooth role to dual role. Which means it has both Central and Peripheral role capabilities.)
  • AT+ADVSTART (Starts advertising)
  • AT+ADVSTOP (Stops advertising. Returns ERROR if not already advertising)
  • AT+GAPSTATUS (Reports the Bluetooth role)
  • AT+GAPSCAN=2 (Starts a Bluetooth device scan with the timer set in seconds. Make sure to set a timer for the scan.)

Once you type one of the above commands, you will start to see the response from the dongle on your browser screen.

I am trying to scan for BLE devices at my home where BleuIO dongle is connected. Here I got a list of devices showing on my browser screen. Make sure the device is on central mode to scan for devices.

You can add more AT commands to the script as required. All you need to do is update the index.js file found in the root folder. 

Find the list of AT commands our from getting started guide at

https://www.bleuio.com/getting_started/docs/commands/
Share this post on :

Build your own firmware for BleuIO – An advertising example

The BleuIO is Bluetooth low energy USB dongle that can be used to create new BLE 5.0 applications in the fastest and easiest way. The BleuIO comes with a bootloader that allows you to update the firmware or flash your own application to the dongle. 

This guide will show you how to get started with making your own firmware for the BleuIO Dongle by importing our advertising example project and running it on the BleuIO dongle.

Introduction

This project has both USB CDC and BLE in Peripheral Mode. This allows you to create your own command interpreter that takes in commands to the Dongle via a serial terminal. You can then use this to execute BLE tasks such as start set advertsing or response data, start and stop advertsing etc.

The project, like the previous, uses FreeRTOS and handles the usb cdc functions in the usb_cdc_task located in the usb_cdc.c:

USB CDC task!

And the ble functions in the ble_peripheral_task located in ble_peripheral_task.c:

The example will start advertsing and is connecteble. It also has the Device Information Service (DIS) with some default values taken from Dialog Semiconductor’s ble_peripheral example. This and the advertising data can be changed in ble_peripheral_task.c:

DIS Service and Advertising Data!

Setup

Download the example project HERE (bleuio_advertising_example.zip or you can clone it from Github at https://github.com/smart-sensor-devices-ab/bleuio_ble_advertising_example.git

Follow the guide for Build Your Own Firmware to import and build the project.

Running the Application

  • When running the example it will, just like the previous example, open a com port that will echo what every you type into the terminal. It will also start advertising with the name “BleuIO Example”.
  • You can scan for it using another dongle with the BleuIO firmware or download a BLE scanning App like ‘BLE Scanner’ or ‘LightBlue”.BLE Scanner!
Share this post on :

Build your own firmware for BleuIO

Introduction

The BleuIO is Bluetooth low energy USB dongle that can be used to create new BLE 5.0 applications in the fastest and easiest way. The BleuIO comes with a bootloader that allows you to update the firmware or flash your own application to the dongle. 

This guide will show you how to get started with making your own firmware for the BleuIO Dongle by importing our example project and running it on the BleuIO dongle.

The project itself is a modified version of Dialog Semiconductor’s ‘usb_cdc’ example project made to work on the BleuIO Dongle.

The ‘usb_cdc’ example will echo anything typed in the terminal back.

Setup

Importing project

  • Open Smart Snippet Studio and when prompted, select the SDK you just downloaded: 

    Selecting SDK in Smart Snippet Studio!
  • Now click the IDE: 

    Open IDE in Smart Snippet Studio!
  • Right-Click in the Project Explorer window and select import: 

    Import project  in Smart Snippet Studio!
  • Select ‘Projects from Folder or Archive’ under the ‘General’ tab: 

    Import Projects from Folder!
  • Click the ‘Directory…’ button and find the ‘bleuio_own_application_example’ project folder inside your SDK folder: 

    Select bleuio_own_application_example!
  • Finally, click ‘Finish’. You have now imported the project!

Building project and creating an image file

  • To create an image file that you can use to flash to the BleuIO Dongle via the bootloader, you must first build the project to create a bin file. To do that, click the ‘Hammer’ icon in the toolbar. Be sure to build the project for DA14683. Build Project!
  • Dialog Semiconductor has a file called mkimage.exe included in the SDK for generating image files. It can be run using the mkimage.bat file located at [SDK_Root]\utilities\scripts\suota\v11. It needs to point to the bin file you want to generate an image file from.
  • You can open up the command prompt in the same folder and run mkimage.bat like this:
mkimage.bat ..\..\..\..\bleuio_own_application_example\DA14683-00-Release_QSPI\bleuio_own_application_example.bin
Copy

You should now have an image file inside your build folder DA14683-00-Release_QSPI named bleuioown_application_example.1.0.0.1.img that can be flashed to the BleuIO Dongle using the ‘_host_usb_updater.exe‘ (More info about updating the firmware: [Firmware Update](../firmware#How to update your firmware)).

Running the Application

  • After you flashed the firmware to a BleuIO Dongle, open up a Serial Communication program (like TeraTerm, Putty or CoolTerm etc.), just like you would with the BleuIO Firmware. When first started you should be greeted by this: 

    Running Example!
  • If you type any text, the application will now echo what you type in the terminal.
Share this post on :

A faster way to new Bluetooth® applications

Swedish IoT company Smart Sensor Devices AB believes developing new Bluetooth applications should be as easy as using them. That’s why they created the BleuIO Bluetooth Low Energy USB dongle – a smart, highly integrated device that lets developers create new BLE 5.0 applications with minimal effort.

Founded in 2016, Smart Sensor Devices provides products and data services for indoor and outdoor applications, mainly in the business-to-business (B2B) sector. This offering is built around its own Internet of Things (IoT) sensor platform, using connectivity based on industry standards such as Bluetooth, Wi-Fi and LTE-M/NB-IoT.

“Our full stack approach gives our customers a complete plug-and-play solution so they can easily start collecting and analyzing sensor data. Thanks to this ease of use, we have been able to establish ourselves as an IoT connected sensor supplier worldwide during the last year,” says CEO Axel Hammar.

Plug-and-play applications

That commitment to ease of use is perfectly demonstrated in the company’s BleuIO Bluetooth Low Energy USB dongle. It offers a quick and easy way to create new BLE 5.0 applications with minimal development effort.

Targeting both B2B and B2C markets, the BleuIO dongle can be used to create peripherals, central applications or both. It offers the latest in Bluetooth security, and is suitable for secured identity and payment applications. With integrated Flash memory and a bootloader, it supports in-field firmware and application upgrades – while custom settings can be stored in Flash or one-time programmable (OTP) memory for greater integrity.

An easy-to-use solution

At the heart of the BleuIO dongle is Dialog’s SmartBond DA14683 high-security, single-chip Bluetooth solution. This combines an ARM microcontroller and Bluetooth 5.0 radio in one energy efficient chip.

“We created a quick, innovative and user-friendly Bluetooth USB dongle based on Dialog’s DA14683 Bluetooth chip and AT commands example. The DA14683 provided a real advantage in power consumption and bill of materials component count while also delivering excellent performance,” Hammar explains.

The use of Smart Sensor Devices’ version of the Dialog AT commands, greatly simplifies development for BleuIO customers. They can develop complete Bluetooth applications without writing a single line of code. Developers can also take advantage of Smart Sensor Devices’ own Python / JavaScript libraries.

Growing market success

This ease of use has already generated market interest in the BleuIO dongle, leading to its use in a range of applications. For example, Swedish air conditioning expert InventiAir is using the dongle in its InventiAir Digital program to digitalize its products and services for even greater energy savings. Within this program, the dongle allows data to be exchanged between ventilation systems and an app on the user’s portable device to control ventilation across multiple units.

Elsewhere, Ipoxo is using the BleuIO dongle as hardware platform for its Phrase Lock USB key password manager. By adding its own software application on top of the dongle’s hardware, Ipoxo has created a brand new product that its own customers can further customize to deliver secure login keys that protect data, people’s identities and IT systems.

Building on such early successes, Smart Sensor Devices is now ready to scale up business in selected sales regions and transition to a stable higher level of business.

“Dialog have always given us outstanding support from all parts of their organization, bringing innovative solutions to our market challenges that help our business move forward and grow. Our company wouldn’t be in as strong a position today without Dialog’s support,” Hammar adds.

BleuIO:
BleuIO is Bluetooth low energy (BLE) USB dongle that can be used to create new BLE 5.0 applications in the fastest and easiest way.
Just use the AT Commands available on the device or use our Python/Javascript libraries for faster development.


InventiAir:

InventiAir´s unique, well-proven ventilation technology and solutions offer a range of benefits.
Our system provides better air circulation, cleaner air and an ideal indoor climate.
At the same time, it´s possible to reduce the power consumption of your property’s ventilation system, increasing efficiency and lowering costs.

iPoxo IT GmbH:
IPoxo provides Phrase-Lock USB-Keys which enables entering passwords into your computer with the mobile phone with strong security.
Integrate Phrase-Lock USB-Keys into your own app following our API. To make integration easier for you, we provide libraries for iOS and Android.

Share this post on :

Update BlueIO firmware using RaspberryPi

The BleuIO comes with a bootloader to allow you to update the firmware or flash your own application to the dongle. To flash the dongle, you will need an image file containing the new firmware or your own application and a host USB loader application.

You can download the latest firmware, and host USB loader from our getting started guide.

This article will explain how to update a BleuIO dongle using a RaspberryPi.

Connect the BleuIO dongle to your Linux / RaspberryPi.

Dongle

To identify which device name the dongle is connected to, you will need to run ls /dev on the terminal.
You might need to do it twice, once before you connect the dongle and once after, to be able to identify which one is the device name.

The following screenshot shows devices list before and after connecting the dongle.

The BleuIO includes a bootloader that allows you to update the firmware easily. When starting up, the dongle will open up a COM port for the bootloader for 10 seconds to allow you to update the firmware (or flash your own application). Afterwards, it will close that port and open a new port for the BleuIO application. 

Now that you know the device name, you can run the following command to update the dongle. 

sudo ./host_usb_updater /dev/ttyACM0 ./example_firmware.img -verbose 

The /dev/ttyACM0 means USB-CDC driver of Linux.

NOTE: The device name may vary and may not be the same as in the picture above.

After running this command successfully, you will see Result: Pass on your terminal.  

Share this post on :

Location analysis using Bluetooth Low Energy

Distance to a Bluetooth device can be measured using RSSI value. The following script will help you locate nearby unique BLE devices within a selected range.

This script scans for nearby unique Bluetooth devices within the given range using a well-known RSSI to distance formula. 

Requirments

Instructions

git clone https://github.com/smart-sensor-devices-ab/device_within_range.git

Go inside the folder type in terminal

parcel index.html

The script will scan for five seconds for nearby devices within range. You can update the value based on your requirements.

You can also run this script from online at

https://smart-sensor-devices-ab.github.io/device_within_range/dist/index.html

**Make sure your BleuIO dongle is connected

Read more about how to calculate the distanceHow to Calculate Distance from the RSSI value of the BLE Beacon

Share this post on :

UC awards Smart Sensor Devices the Nordic Growth Company award

Smart Sensor Devices was awarded the Nordic Growth Company award from UC for success in the financial year 2019/2020. The company is doing steady and robust development and growth. The award was given for efforts during the previous financial year. The company sees a continued positive development and sales have increased compared with the previous financial year.

“The development is very positive with steady growth during the current financial year. Demand for our products and services has increased in the recent period for all our offerings,
We are very gratefully for all our new customers” says Axel Hammar, Founder & CEO of Smart Sensor Devices.

Share this post on :

Get Bluetooth Device Distance in meter Using Javascript

Bluetooth ranging technology is very popular. There are many localization systems that exist based on beacons. Beacon technology usually estimates the distance between devices using the received signal strength (RSSI). 

Bluetooth can be an excellent way to narrow down a search area at close distances when tracking something. This feature can be used in several fields. such as Secure Locks for Buildings and Automotive, Asset localization & tracking, Indoor navigation etc

GPS tracking isn’t excellent at giving accurate measurements of the close distance, especially in the indoor environment. On the other hand, Bluetooth is excellent in short ranges because the waves can go through walls. This might fill the gap that GPS tracking has when tracking devices in indoor spaces.

However, most calculations of the distance between two Bluetooth devices are estimates. It’s hard to determine the exact distance between two Bluetooth devices because many factors affect the calculations. Despite the challenges, there are methods to determine the distance between two Bluetooth devices with an accuracy of at least 60-80%.

The ranging method is simple to implement, and it has the formula to calculate the distance between two Bluetooth devices. As the name suggests, both devices need to be within Bluetooth range to estimate the distance. 

This article will share a simple script written in JavaScript to determine nearby Bluetooth devices and their distance in meters.

This script scans for nearby Bluetooth devices and gets an approximation of the distance by using the well-known RSSI to distance formula.

Read more about how to calculate the distance

How to Calculate Distance from the RSSI value of the BLE Beacon

Requirments

Instructions

git clone https://github.com/smart-sensor-devices-ab/ble_distance_measure.git

The script will an index.html and script.js file. Index.html is just has a connect and scan for device button. upon connecting we will be able to scan for nearby devices and. Once the scanning is completed we will be able to see a list of devices and their distance from my computer.

Here is the index.html file

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Get Device Distance Using BleuIO</title>
  </head>
  <body>
    <div class="container"> <br>
    <a href="https://www.bleuio.com/"> <img src="https://www.bleuio.com/images/logo.png" alt="BleuIO get device distance"></a>
    <h1>Get Device Distance Using BleuIO</h1>
<br>
    <button id="connect" class="btn btn-success">Connect</button>
<button id="scan" class="btn btn-warning">Scan Devices</button> &nbsp; &nbsp;  <span id="scanning" class="d-none"> scanning ...</span>  <br><br><br>
<div id="deviceList"></div>
</div>
<br><br>
<script src="./script.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>


  </body>
</html>

The script.js file uses bleuio javascript library to connect and scan for BLE devices. Once we get the device list, we try to sort it out by RSSI value and convert RSSI value to distance. Finally we print the result into a table.

Here is the script.js file

import * as my_dongle from 'bleuio'
document.getElementById('connect').addEventListener('click', function(){
  my_dongle.at_connect()
})

/*
Functions to converts rssi to distance 
read more at 
https://iotandelectronics.wordpress.com/2016/10/07/how-to-calculate-distance-from-the-rssi-value-of-the-ble-beacon/
*/
const getDistance =(rssi=>{
  let n=2
  let mp=-69
  return 10 ** ((mp - (rssi))/(10 * n))
})
document.getElementById('scan').addEventListener('click', function(){
  var element = document.getElementById("scanning");
  element.classList.remove("d-none");
  my_dongle.at_central().then((data)=>{    
    my_dongle.at_gapscan(4,false).then((dev)=>{
      //convert array string to array of object with key value
      const formated = dev.map((item) => {
        const [ id, dev,devid,none,rssi,rssival,devname ] = item.split(' ');
        return { id, dev,devid,none,rssi,rssival,devname};
      });
      //array list unique
      let uniqueArr= formated.filter(y=>y.devname!=undefined)
      //sort based on rssi value
      uniqueArr.sort((a, b) => a.rssival > b.rssival && 1 || -1)
      
      let withDistance= uniqueArr.map(r=>{
        r.distance=getDistance(r.rssival).toFixed(2)+' meter'
        return r 
      })
      //generate output
      let mytable = `<h2>Device List</h2>
      <table class='table table-striped table-bordered'>
      <tr>
      <th>Device</th>
      <th>RSSI</th>
      <th>Distance</th>
      </tr>`;
      withDistance.map(j=>{
        mytable += "<tr><td>" +j.devid+" - "+ j.devname + "</td><td>"+ j.rssival+"</td><td>"+j.distance+"</td></tr>";
      })
      mytable += "</table>";
      document.getElementById("deviceList").innerHTML = mytable;
      element.classList.add("d-none");
    })
  })
})

To run this script , we can use a web bundler called parcel. https://parceljs.org/

lets go inside the folder and in terminal type.

parcel index.html

The script will scan for five seconds for nearby devices. You can update the value based on your requirements.

You can also run this script from online at
https://smart-sensor-devices-ab.github.io/ble_distance_measure/dist/

**Make sure your BleuIO dongle is connected

Output

Share this post on :

Transfer files wirelessly over the Bluetooth Low Energy protocol Using Python

This tutorial will show how to transfer files wirelessly over the Bluetooth Low Energy protocol. We will use two BleuIO dongles for this project—one for sending and another one for receiving. The sender dongle will be in central mode, while the receiver dongle will be in peripheral mode. 

We have already created two python scripts for sending and receiving. You can get the source code from 

https://github.com/smart-sensor-devices-ab/bleuio_file_transfer_example

You can try this project on two different computers.

A video tutorial will show you how to do it on one computer and send files between two BleuIO dongles.

Requirements :

Steps:

  • First, connect two BleuIO dongles to your computer. 
  • Note down the COM port for each dongle. You can find the port using device manager.
  • Try to find receiver dongle MAC id. To do that, start advertising your receiver dongle and note down the MAC id.  Follow the video if you need more details on how to do it.
  • Open file_recieve.py and file_transfer.py files. Update COM port and MAC id where necessary.

Here is the file_recieve.py

import serial
import time

your_com_port = "COM6"  # Change this to the com port your dongle is connected to.
file_name = "result.png"  # Change this to match the file type you are recieving

connecting_to_dongle = True
trying_to_connect = False

print("Connecting to dongle...")
# Trying to connect to dongle until connected. Make sure the port and baudrate is the same as your dongle.
# You can check in the device manager to see what port then right-click and choose properties then the Port Settings
# tab to see the other settings
while connecting_to_dongle:
    try:
        console = serial.Serial(
            port=your_com_port,
            baudrate=57600,
            parity="N",
            stopbits=1,
            bytesize=8,
            timeout=0,
        )
        if console.is_open.__bool__():
            connecting_to_dongle = False
    except:
        print("Dongle not connected. Please reconnect Dongle.")
        time.sleep(5)

print("Connected to Dongle.")

file_data = ""
file_transfer_done = False
connected = "0"
line = ""
while 1 and console.is_open.__bool__() or not file_transfer_done:
    console.write(str.encode("AT+DUAL"))
    console.write("\r".encode())
    print("Putting dongle in Dual role.")
    time.sleep(0.1)
    console.write(str.encode("AT+ADVSTART"))
    console.write("\r".encode())
    time.sleep(0.1)
    print("Starting advertising and awaiting connection from other dongle...")
    while connected == "0":
        dongle_output2 = console.read(console.in_waiting)
        time.sleep(2)
        if not dongle_output2.isspace():
            if dongle_output2.decode().__contains__("\r\nCONNECTED."):
                connected = "1"
                print("Connected!")
            if dongle_output2.decode().__contains__("\r\nDISCONNECTED."):
                connected = "0"
                print("Disconnected!")
            dongle_output2 = " "
    while connected == "1" or not file_transfer_done:
        time.sleep(0.2)
        dongle_output3 = console.read(console.in_waiting)
        if not dongle_output3.isspace():
            if dongle_output3.__contains__(str.encode("\r\nDISCONNECTED.")):
                print("Disconnected!")
                connected = "0"
            elif dongle_output3.__contains__(str.encode("[DONE]")):
                file_transfer_done = True
                print("File transfer complete!\r\n")
                fo = open(file_name, "wb")
                hex = bytes.fromhex(file_data)
                fo.write(hex)
                fo.close()
                print("Exiting script...")
                exit()
            elif dongle_output3.__contains__(str.encode("[Received]:")):
                line = dongle_output3.decode()
                line = line.replace("\r", "")
                line = line.replace("\n", "")
                line = line.replace("[Received]:", "")
                line = line.replace(" ", "")
                file_data += line
                print(line)
            dongle_output3 = ""
        msg = ""

  • Set the file type that you are expecting to receive. For example, if you are expecting a jpg file, change file_name on file_recieve.py to result.jpg, and for a text file, you can rename it to result.txt

Here is the file_transfer.py

import serial
import time

target_dongle_mac_address = (
    "[0]40:48:FD:E5:2D:AF"  # Change this to the peripheral's mac address.
)
your_com_port = "COM25"  # Change this to the com port your dongle is connected to.

connecting_to_dongle = True
trying_to_connect = False
file_name = "test.txt"

print("Connecting to dongle...")
# Trying to connect to dongle until connected. Make sure the port and baudrate is the same as your dongle.
# You can check in the device manager to see what port then right-click and choose properties then the Port Settings
# tab to see the other settings
while connecting_to_dongle:
    try:
        console = serial.Serial(
            port=your_com_port,
            baudrate=57600,
            parity="N",
            stopbits=1,
            bytesize=8,
            timeout=0,
        )
        if console.is_open.__bool__():
            connecting_to_dongle = False
    except:
        print("Dongle not connected. Please reconnect Dongle.")
        time.sleep(5)

print("Connected to Dongle.")

connected = "0"
while 1 and console.is_open.__bool__():
    console.write(str.encode("AT+DUAL"))
    console.write("\r".encode())
    time.sleep(0.1)
    print("Putting dongle in Dual role and trying to connect to other dongle.")
    while connected == "0":
        time.sleep(0.5)
        if not trying_to_connect:
            console.write(str.encode("AT+GAPCONNECT="))
            console.write(str.encode(target_dongle_mac_address))
            console.write("\r".encode())
            trying_to_connect = True
        dongle_output2 = console.read(console.in_waiting)
        time.sleep(2)
        print("Trying to connect to Peripheral...")
        if not dongle_output2.isspace():
            if dongle_output2.decode().__contains__("\r\nCONNECTED."):
                connected = "1"
                print("Connected!")
                time.sleep(10)
            if dongle_output2.decode().__contains__("\r\nDISCONNECTED."):
                connected = "0"
                print("Disconnected!")
                trying_to_connect = False
            dongle_output2 = " "
    while connected == "1":
        dongle_output3 = console.read(console.in_waiting)
        want_to_exit = input(
            "Press Enter to start sending file or 'exit' to quit script.\n\r>> "
        )
        want_to_exit = want_to_exit.upper()
        if "EXIT" in want_to_exit:
            print("Exiting script...")
            exit()
        hex_to_send = ""
        fo2 = open(file_name, "rb")
        print("Sending file. Please wait...")
        while (byte := fo2.read(1)) :
            hex_to_send += byte.hex().upper()
            if len(hex_to_send) >= 200:
                # my_dongle.at_spssend(hex_to_send)
                console.write(str.encode("AT+SPSSEND=" + hex_to_send + "\r"))
                time.sleep(0.2)
                hex_to_send = ""
        if len(hex_to_send) != 0:
            # my_dongle.at_spssend(hex_to_send)
            console.write(str.encode("AT+SPSSEND=" + hex_to_send + "\r"))
            time.sleep(0.2)
        fo2.close()
        console.write(str.encode("AT+SPSSEND=[DONE]\r"))
        print("File transfer complete!\r\n")
        print("Exiting script...")
        exit()
  • Keep the file in the same directory with file_transfer.py and change the file name accordingly.
  • Now run the script file_recieve.py using a terminal. It will start advertising and will be ready to receive.
  • Now run the file_transfer.py script. 
  • Once both the dongles are connected, you will be asked to send the file from the file transfer script. 
  • The receiver dongle will give you a confirmation once received, and you will find the file stored in the same folder with the receiver script.
  • Finally, you can check if you received the file correctly by running a checksum. 

Please follow the video if you have difficulty in understanding. 

Share this post on :

Create a Bluetooth Low Energy repeater using Raspberry pi

Bluetooth low energy technology offers a suitable way of connecting smart devices.
However, despite the convenience, you can bear witness that the range offered can be a little limiting. Sometimes the connection tends to drop or lag when you move a little further away from the device. Fortunately, it’s easy to overcome this range limitation with the Bluetooth repeater.

This article will explain how to create a BLE Repeater using BLE USB dongle called BleuIO and python.

The BleuIO is Bluetooth low energy solution that can be used to create new BLE 5.0 applications in the fastest and easiest way. Using this dongle’s multi-connection feature, we will make a simple repeater where one dongle scans nearby devices data and sends it to the repeater. At the same time, the repeater passes the data to the receiver dongle. And that’s how a repeater will help us overcome the range limitation.

For this project, sender dongle will scan for air quality data from HibouAir device and pass the advertised data along with timestamp to the repeater. The repeater dongle will be connected to a Raspberry pi which will forward data to the receiver dongle.

We have already created a sample script in python, which will help us to do the task.

Requirements :

  1. 3 pcs BleuIO Dongle.
  2. HibouAir or any BLE device
  3. Python 2.7 or Python 3.4 and newer
  4. pyserial 3.5

Task:

Step 1: 

Let’s start by cloning the repository from https://github.com/smart-sensor-devices-ab/bleuio_repeater_example

Once you cloned the script, you will find three different python script called

  • repeater_example_reciever_dongle.py
  • repeater_example_repeter_dongle.py
  • repeater_example_sender_dongle.py

We need to update the ports on those scripts manually.

repeater_example_reciever_dongle.py

import time
from bleuio_lib.bleuio_funcs import BleuIo


reciever_dongle_port = "COM74"  # Change this to your dongle's COM port
mac_addr_to_repeater = (
    "[0]40:48:FD:E5:2D:74"  # Change this to your repeater dongle's mac address
)

buffer = ""
connected = False
connecting = ""

reciever_dongle = BleuIo(port=reciever_dongle_port)
reciever_dongle.start_daemon()

print("Dongle found.")


def save_msg(buffer):
    """
    Parses incomming data string for just the data and prints it out.
    """
    result = buffer
    result_array1 = result.split("\r\n")
    result_array = result_array1[2].split(" ")
    msg_to_save = str(result_array[0])
    print("Recieved = " + msg_to_save)


try:
    reciever_dongle.at_dual()

    ready = input(
        "Press enter to connect to the repeater dongle. (This should be connected first)."
    )
    print("Connecting...")
    reciever_dongle.at_gapconnect(mac_addr_to_repeater)
    time.sleep(5)
    while not connected:
        connected_status = reciever_dongle.ati()
        if "\r\nConnected" in connected_status[0]:
            connected = True
            break
        if "\r\nNot Connected" in connected_status[0]:
            reciever_dongle.at_gapconnect(mac_addr_to_repeater)
            time.sleep(5)
        print("Trying to connect...")
        time.sleep(2)

    print("Connected.")
    print("Waiting to recieve...")

    while 1:
        buffer = reciever_dongle.rx_buffer.decode("utf-8", "ignore")
        if "\r\nhandle_evt_gattc_notification:" in buffer:
            save_msg(buffer)
        time.sleep(0.5)
except KeyboardInterrupt:
    reciever_dongle.at_cancel_connect()
    reciever_dongle.at_gapdisconnect()
    reciever_dongle.at_advstop()
    print("Shutting down script.")

repeater_example_repeter_dongle.py

import time
from bleuio_lib.bleuio_funcs import BleuIo

repeter_dongle_port = "COM38"  # Change this to your dongle's COM port

repeter_dongle = BleuIo(port=repeter_dongle_port)
repeter_dongle.start_daemon()

buffer = ""
num_of_connected_devices = 0
connection_list = []

print("Dongle found.")

repeter_dongle.at_dual()
repeter_dongle.at_advstart()
repeter_dongle.rx_state = "rx_waiting"
print("Waiting for other dongles to connect...")


def send_msg(buffer):
    """
    Parses incomming data string for just the data and sends it forward via the Serial Port Service.
    """
    try:
        result = buffer
        msg_to_send = ""
        result_array1 = result.split("\r\n")
        for line in result_array1:
            if "[Received]:" in line:
                msg_to_send = line.split(" ")
                msg_to_send = msg_to_send[1]
                break
        print("Forwarding data to reciever:")
        print(msg_to_send)
        if not msg_to_send == "":
            repeter_dongle.at_spssend(msg_to_send)
            repeter_dongle.rx_state = "rx_waiting"
    except:
        print(" ")


try:
    while 1:
        buffer = repeter_dongle.rx_buffer.decode("utf-8", "ignore")
        if "\r\nCONNECTED." in buffer:
            num_of_connected_devices = num_of_connected_devices + 1
            print("A Dongle has connected!")
            repeter_dongle.at_advstart()
            repeter_dongle.rx_state = "rx_waiting"
        if "DISCONNECTED." in buffer:
            num_of_connected_devices = num_of_connected_devices - 1
            connection_list = []
            print("No Dongles connected.")
        if num_of_connected_devices > 1:
            if "\r\n[Received]:" in buffer:
                # print(buffer)
                send_msg(buffer)
        buffer = ""
        time.sleep(0.1)
except KeyboardInterrupt:
    repeter_dongle.at_advstop()
    repeter_dongle.at_gapdisconnect()
    print("Shutting down script.")

repeater_example_sender_dongle.py

import time
from bleuio_lib.bleuio_funcs import BleuIo
import random

sender_dongle_port = "COM73"  # Change this to your dongle's COM port
mac_addr_to_repeater = (
    "[0]40:48:FD:E5:2D:74"  # Change this to your repeater dongle's mac address
)

sender_dongle = BleuIo(port=sender_dongle_port)
sender_dongle.start_daemon()

connected = False
data = ""
buffer = ""


def scan_and_get_results():
    """
    Starts a BLE scan for three seconds, looking for results including the 'FF' flag in the advertising data.
    Then it saves the results in a list and returns one of the results as a string.
    :return: string
    """
    print("Scanning...")
    return_data = ""
    result_list = []
    time.sleep(0.5)
    try:
        scanning = sender_dongle.at_findscandata("FF")
        if "SCANNING" in scanning[0]:
            time.sleep(4)
            sender_dongle.stop_scan()
            time.sleep(0.5)
            result_list = sender_dongle.rx_scanning_results
            if not result_list == []:
                if len(result_list) > 3:
                    lines = result_list[2].split("\r\n")
                    if not lines[1] == "":
                        data_array = lines[1].split(" ")
                        lenght = len(data_array)
                        if lenght == 5:
                            data = data_array[4]
                            return_data = data
            else:
                sender_dongle.stop_scan()
                result_list = []
                sender_dongle.rx_state = "rx_waiting"
                return_data = ""
    except:
        sender_dongle.stop_scan()
        result_list = []
        sender_dongle.rx_state = "rx_waiting"
        return_data = ""
    return return_data


print("Dongle found.")

try:
    sender_dongle.at_dual()
    ready = input(
        "Press enter to connect to the repeater dongle. (This should be connected last)."
    )
    print("Connecting...")
    sender_dongle.at_gapconnect(mac_addr_to_repeater)
    time.sleep(5)
    while not connected:
        connected_status = sender_dongle.ati()
        if "\r\nConnected" in connected_status[0]:
            connected = True
            break
        if "\r\nNot Connected" in connected_status[0]:
            sender_dongle.at_gapconnect(mac_addr_to_repeater)
            time.sleep(5)
        print("Trying to connect...")
        time.sleep(2)

    print("Connected.")
    print("Getting services...")
    get_services = sender_dongle.at_get_services()
    sender_dongle.rx_state = "rx_waiting"
    time.sleep(2)
    ready = input("Press enter to start sending data to the repeater dongle.")

    while 1:
        data = scan_and_get_results()
        time.sleep(1)
        if not data == "":
            sent = sender_dongle.at_spssend(data)
            time.sleep(0.1)
            if len(sent) == 1:
                if "[Sent]" in sent[0]:
                    print("Data = (" + data + ") sent.")
                    time.sleep(1)
            data = ""
        time.sleep(1)
        sender_dongle.rx_state = "rx_waiting"
except KeyboardInterrupt:
    sender_dongle.at_gapdisconnect()
    print("Shutting down script.")

Step 2:
Connect two dongles on your PC. You can do the process on three different PC or Raspberry Pi.
For this project, I have connected both the sender and receiver dongles to one PC.
After connecting the dongles, open device manager (windows) to find ports of each dongle.

On my PC, I have two dongles connected on port 5 and 6.
Let’s make COM 5 as the sender, COM 6 as a receiver.
Now open the scripts and set the ports number accordingly.


We also need to know repeater dongles ID. To do that, we can simply advertise the dongle on Raspberry pi using AT+ADVSTART command .Then do a gapscan using AT+GAPSCAN from sender dongle and look for a dongle called BleuIO


Once we have repeater dongles id, we can put it on our scripts.

Step 3 :

Now lets run the script. 

First move to the script directory on Raspberry pi and using command prompt type sudo python3 repeater_example_repeter_dongle.py to run repeater script.

Similarly, run receiver and sender scripts accordingly on PC.

As the name suggests, the repeater will repeat its content. On the terminal, we will see the message sent to the repeater from the sender, and the repeater forwards the data to the receiver dongle. 

Follow this video for a better understanding.

Share this post on :