Maker Pro
Custom

Multiple Connections in Bluetooth LE Central Device

March 02, 2022 by Sheikh Shuhad
Share
banner

This article will explain how to use BleuIO’s multi-connection features, connect to multiple BLE devices and transfer data between them.

Hardware

Bluetooth low energy technology offers a suitable way of connecting smart devices. The term IoT or Internet of Things brings new technologies to transform and make the world in the era of connectivity. The IoT says that everything is connected, and Bluetooth has made it much easier to work. One central device can initiate and maintain connections with multiple Bluetooth Low Energy peripherals devices.

The BleuIO is a Bluetooth low energy solution that can create new BLE 5.0 applications fastest and easiest way. Using this BleuIO’s multi-connection feature, we can easily connect to multiple BLE devices and transfer data between them.

This article will explain how to use BleuIO’s multi-connection features, connect to multiple BLE devices and transfer data between them. We will use three BleuIO dongles for this project: one central and two peripheral. The central dongle will connect to peripheral and send data simultaneously.

We will create a simple python script that will help us do the task.

Step 1:

Let’s create a python file called py_serial_transfer.py and copy the following code.

Source code is also available at GitHub

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

import serial
import time
import string
import random

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

connecting_to_dongle = True
trying_to_connect = False
trying_to_connect2 = False

def id_generator(size=10, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

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"
connected2 = "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 1...")
        if not dongle_output2.isspace():
            if dongle_output2.decode().__contains__("\r\nCONNECTED."):
                connected = "1"
                print("Connected to 1st device!")                
                time.sleep(5)
            if dongle_output2.decode().__contains__("\r\nDISCONNECTED."):
                connected = "0"
                print("Disconnected!")
                trying_to_connect = False
            dongle_output2 = " "
    while connected2 == "0":
        time.sleep(0.5)
        if not trying_to_connect2:
            console.write(str.encode("AT+GAPCONNECT="))
            console.write(str.encode(target_dongle_mac_address2))
            console.write("\r".encode())
            trying_to_connect2 = True
        dongle_output2 = console.read(console.in_waiting)
        time.sleep(2)
        print("Trying to connect to Peripheral 2...")
        if not dongle_output2.isspace():
            if dongle_output2.decode().__contains__("\r\nCONNECTED."):
                connected2 = "1"
                print("Connected to 2nd device!")                
                time.sleep(5)
            if dongle_output2.decode().__contains__("\r\nDISCONNECTED."):
                connected2 = "0"
                print("Disconnected!")
                trying_to_connect2 = False
            dongle_output2 = " "
    while connected == "1" and connected2 =="1":        
        dongle_output3 = console.read(console.in_waiting)
        delay=10
        close_time=time.time()+delay
        i=0
        while True:
            myConIndex =  ('0000' if i%2 == 0 else '0001')
            console.write(str.encode("AT+TARGETCONN="))
            console.write(str.encode(myConIndex))
            console.write("\r".encode())
            console.write(str.encode("AT+SPSSEND="))
            console.write(str.encode(id_generator()+'-'+myConIndex))
            console.write("\r".encode())
            time.sleep(0.2)
            i+=1
            if time.time()>close_time:
                break
        console.write(str.encode("AT+SPSSEND=[DONE]\r"))
        time.sleep(0.2)
        print("Sending complete!\r\n")
        print("Exiting script...")
        exit()

This script will be used for the central BleuIO dongle. We need to find the port number of each dongle and the peripheral mac address.

Step 2:

Connect three BleuIO dongles on your PC. You can do the process on three different PC or Raspberry Pi.

I have connected both the central and the peripheral to one PC for this project.

After connecting the dongles, open device manager (windows) to find ports of each dongle.

ble-port.jpg

On my PC, I have the BleuIO dongles connected on ports 7, 8 and 18.

Let’s make COM7 the central, COM8 and COM18 as peripheral.

Now open the scripts and set the ports number on line 12.

We also need to know the peripheral dongles mac address.

To do that, we can simply advertise the dongle using AT+ADVSTART command.

ble-advertising-1024x435.jpg

Do the same process for the other peripheral dongle.

Now both the peripheral dongle is advertising. We can do a gap scan from central to find their mac address.

Now look for the dongle called BleuIO.

ble-scan-device.jpg

Update the script with the peripheral mac address (line 6, 9)

Step 3 :

Now lets run the script.

Go to the script folder and type python py_serial_transfer.py

It will connect to both the peripheral dongles and send data randomly.

You will see the responses on the web terminal screen.

Please follow the video to get better understanding.

Related Content

Comments


You May Also Like