wiki:wireless/bleproject

BLE Demonstration

This page documents a demonstration in which two Gateworks SBCs were used with a GW16126/GW16132 BLE radio which communicated using the BLE & GATT. The packets were then pushed to an Azure Database which was then shown using a web app.

System Diagram

Bluetooth 5 and BLE

About Bluetooth 5

Bluetooth 5 offers considerable improvements to its data bandwidth and operational range compared to its predecessors. For high data bandwidth applications, bluetooth v4.2 was capable of up to 1Mbps whereas v5 doubles this speed at a maximum rate of 2Mbps. At reduced bandwidth, Bluetooth LE Coded PHY, a new PHY mode offered by Bluetooth 5, provides an operational range of around 800ft. This is a roughly four times range increase from v4.2. Additional benefits of Bluetooth 5, in some cases, will reduce power consumption compared to its predecessors.

To read more about Bluetooth 5, view the following link:
https://www.bluetooth.com/blog/exploring-bluetooth-5-going-the-distance/

To look further in depth at how Bluetooth 5 accomplishes these improvements, look at the following link:
https://e2e.ti.com/blogs_/b/process/archive/2017/01/30/how-does-bluetooth-5-increase-the-achievable-range-of-a-bluetooth-low-energy-connection

The Bluetooth Core Spec

Bluetooth developers may want to familiarize themselves with the Bluetooth Core Spec, which can be viewed here: https://www.bluetooth.com/specifications/bluetooth-core-specification /

This spec details every operation available to Bluetooth developers.

Some important sections for Bluetooth development using Gateworks boards include the following:

  • Vol 4, Part E: Host Controller Interface (HCI) Functional Spec (p.1794) - Describes the command interface to a Bluetooth Controller
  • 5.4.1: HCI Command Packet Descriptions (p.1890) – Command descriptions and packet formats to send to the controller
  • 7.7: HCI Events (p.2289) – List of events triggered by the controller
  • 7.8: LE Controller Commands (p.2473) – Commands for configuring and modifying LE connections
  • Vol 1, Part F: Controller Error Codes – Details the error codes provided by the controller (p.361)

Bluez

Bluez is the primary Bluetooth library for developing Bluetooth applications in C on Linux. It provides several command line tools as well as function calls for setting up and managing Bluetooth connections.

Installation

On Ubuntu, the Bluez library can be installed with:

apt-get install bluez

To use the Bluez developer library, compile your code with -lbluetooth, which can be installed on ubuntu with:

apt-get install libbluetooth-dev

Installing Bluez from Source

Installing Bluez from source provides access to example code and some developer tools.

Install the necessary dependencies:

sudo apt-get install libglib2.0-dev libdbus-1-dev libudev-dev
libical-dev libreadline-dev 

Download and install:

wget https://www.kernel.org/pub/linux/bluetooth/bluez-5.53.tar.xz
tar xvf bluez-5.53.tar.xz
cd bluez-5.53
./configure --prefix=/usr --mandir=/usr/share/man --sysconfdir=/etc
--localstatedir=/var --disable-systemd --enable-experimental
--enable-maintainer-mode
make
sudo make install
sudo cp attrib/gatttool /usr/bin

Bluez CLI Tools

Here are a few of the provided command line tools:

  • bluetoothctl: The best introduction to Bluez. It provides a relatively easy to use CLI for running scans and pairing devices. It is not as great for running custom applications or commands.
  • btmgmgt: Used for Bluez management
  • hciconfig: Sends configuration commands to the Bluetooth controller
  • hcitool: Configures Bluetooth connections and allows sending special or custom commands to the Bluetooth controller

Sending HCI Commands with Bluez

Bluez allows users to send custom HCI packets to the Bluetooth controller using hcitool. Available commands and more information about HCI can be found in the Bluetooth Core Spec. The commands can be sent with hcitool in the following format:

hcitool cmd <OGF> <OCF> <Param1> <Param2> <Param…>
  1. OGF = OpCode Group Field (6 bits): Specific to a command's group
  2. OCF = OpCode Command Field (10 bits): Specifies the command within its grouping
  3. Parameters = Specific the command as defined in the Bluetooth Core Spec

Additional Bluez Links

Bluetooth C Programming Quickstart: http://docs.cubieboard.org/tutorials/common/development/bluez_programming

Navigating the Bluez Source Code: https://gbrault.github.io/gattclient/hci__lib_8h.html

Connecting GW16126 With Devices Using Bluez

Initial Setup

Follow the setup instructions for the GW16126 u-blox BLE module to setup the module as an available Bluetooth

Interface. This can be found at: expansion/gw16126

Bluez Configuration

Before continuing, you may want to edit your /etc/bluetooth/main.conf file to the desired values. It is recommended that you set the DiscoverableTimeout and PairableTimeout to 0 to disable them for testing purposes.

Setting Up a Connection

Using bluetoothctl

  1. Start bluetoothctl
    1. If your controller is set up properly, the first thing to display should be the MAC address of your Bluetooth controller. Bluetoothctl will then provide a prompt [bluetooth]#
  2. Run show This should list the configuration information for your Bluetooth controller.
  3. Run devices This provides the user with a list of available devices. If you have not scanned yet, this list may be empty except for your own Bluetooth controller.
  4. To enable the controller and prepare for pairing with a device, run the following:
    [bluetooth]# power on
    Changing power on succeeded
    [bluetooth]# agent on
    Agent is already registered
    [bluetooth]# discoverable on
    Changing discoverable on succeeded
    [bluetooth]# pairable on
    Changing pairable on succeeded
    
  5. To search for available Bluetooth devices, enable scanning with scan on This will begin listing all devices transmitting within range. Turn this off anytime with scan off
  6. Once you find the device in the scanning list, trust the MAC address and then connect:
    [bluetooth]# trust XX:XX:XX:XX:XX:XX
    Changing XX:XX:XX:XX:XX:XX trust succeeded
    [bluetooth]# connect XX:XX:XX:XX:XX:XX
    Attempting to connect to XX:XX:XX:XX:XX:XX
    
  7. If the connection is successful, run info XX:XX:XX:XX:XX:XX to see information about the device you are connected to.
  8. quit

Tip: Known MAC addresses can be tab completed in Bluetoothctl. Note: To automate bluetoothctl commands try using bluetoothctl -–command

Using hcitool

  1. Run the init scripts to setup the HCI interface (if you have not already)
  2. Scan for the desired MAC address hcitool -i hci0 lescan | grep <desired MAC>
  3. MAC in format XX:XX:XX:XX:XX:XX
  4. Start the connection hcitool -i hci0 lecc --random <desired MAC>

Using LE Coded PHY

  1. Run init scripts to setup your HCI UART connection (if you have not already)
  2. Inactive Connection:
    1. Set the default PHY on each board to Coded PHY hcitool cmd 0x08 31 00 04 04
    2. See Setting Up a Connection
  3. Active Connection:
    1. Get the connection handle hcitool -i hci0 leinfo --random <Connected MAC>
    2. Change the connection PHY type hcitool cmd 0x08 32 <connection handle> 00 04 04
  4. Connection Handle: 2 bytes in range 0x0000 to 0x0EFF

Useful Commands:

  • LE Set Default PHY (BCS p.2571): Sets the default PHY for either Tx or Rx on the Bluetooth controller.
  • OGF = 0x08
  • OCF = 0x0031
  • All PHYs (1 byte)
  • B0: 0 to set a Tx Preference
  • B1: 0 to set a Rx Preference
  • TX PHYs (1 byte)
  • B0: 1Mbbs Tx PHY
  • B1: 2Mbps Tx PHY
  • B2: Coded Tx PHY
  • RX PHYs (1 byte)
  • B0: 1Mbps Rx PHY
  • B1: 2Mbps Rx PHY
  • B2: Coded Rx PHY
  • LE Set PHY (BCS p.2573): Sets the default PHY for an active connection for either Tx or Rx on the Bluetooth controller.
  • OGF = 0x08
  • OCF = 0x0032
  • Connection Handle (12 bits)
  • All PHYs (1 byte)
  • TX PHYs (1 byte)
  • RX PHYs (1 byte)
  • Response Values: These commands respond with a Command Complete Event (BCS p.2308) which provides two possible values
    • 0x00 = Success
    • Other = Controller Error Code (BCS p.361)

Troubleshooting

  • Run btmon in the background to monitor HCI communications with the Bluetooth controller. Rerun the commands and view the output. btmon &

Setting up a GATT Client/Server

This section talks about setting up a generic Bluetooth GATT client/server model in which a client can connect to a Bluetooth server and relay information to it.

What is GATT?

GATT defines a method of communication among BLE devices using services and characteristics.

For more information on GATT see: https://learn.adafruit.com/introduction-to-bluetooth-low-energy/gatt

GATT Client/Server Example

An example GATT Client and Server is provided in the Bluez source code, see Installing Bluez from Source to get the source code.

Before starting the server, run the following:

sudo btmgmt -i hci0 power off
sudo btmgmt -i hci0 le on
sudo btmgmt -i hci0 connectable on
sudo btmgmt -i hci0 name "some friendly name"
sudo btmgmt -i hci0 advertising on
sudo btmgmt -i hci0 power on

In your Bluez source directory, make the executable and start the server with the following command:

tools/btgatt-server -i hci0 -s low -t random -r -v

Start the client with the following command:

tools/btgatt-client -i hci0 -s low -t random -v -d <Server MAC>

Note: Before starting the client in a Linux environment, you may need to run a scan with hcitool to configure the controller correctly. hcitool lescan

The source code can also be viewed here:

Creating and Connecting to an Azure MySQL Database

Setup Azure MySQL Database Server

Follow the most recent instructions to create a MySQL database with Azure using the web portal (Azure account necessary): https://docs.microsoft.com/en-us/azure/mysql/quickstart-create-mysql-server-database-using-azure-portal

Connecting to the database server

The database server can be accessed from any computer with internet connection and a verified IP address. Verified IP addresses can be added to the server under the 'Connection Security' option: https://docs.microsoft.com/en-us/azure/sql-database/sql-database-firewall-configure

To connect the the server using a Gateworks SBC and Ubuntu Linux, run the following command to install MySQL support:

apt-get install mysql-server

Run the following command to login to the MySQL database server, replacing the server name and username to match the database server created using Azure:

mysql --host mydemoserver.mysql.database.azure.com --user myadmin@mydemoserver -p

This will prompt for a password and then start a MySQL command shell.

Once connected, use MySQL commands to create and select a database, add tables, and insert data. Example queries can be found here: https://dev.mysql.com/doc/refman/8.0/en/creating-database.html

Connecting to the database using Python on SBC with Ubuntu

Python programs can also connect and query the database.

Run the commands below to install python and set up the pymysql library:

apt-get install python3
pip install pymysql

Code from the example shown below can be run in a Python shell or script:

#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("mydemoserver.mysql.database.azure.com",
"myadmin@mydemoserver","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()

More resources for using the pymysql library are given here: https://www.tutorialspoint.com/python3/python_database_access.htm

Connecting to the database using C API:

To write programs using C which access the MySQL database, install the following packages:

apt-get install build-essential mysql-server libmysqlclient-dev

Create a C file with the following code example, replacing the database information to match the MySQL server created using Azure:

#include "mysqldb.h"
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
int main() {
MYSQL *conn = NULL;
MYSQL_RES *res = NULL;
MYSQL_ROW row;
char *srv = “mydemoserver.mysql.database.azure.com”;
char *usr = “myadmin@mydemoserver”;
char *psswrd = “test123”;
char *db = “TESTBD”;
/* Connect to database */
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, srv,
usr, psswrd, db, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return NULL;
}
/* send SQL query */
if (mysql_query(conn, "SHOW TABLES;")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}

Compile using the program using:

gcc {filename.c} -o {executable} `mysql_config --cflags --libs`

Alternatively, run the command below and copy and append the output after the executable.

mysql_config --cflags --libs

Client/Server Gateway Github

https://github.com/rstatz/ble_gateway

Web App

The web app for this project shows data from a Microsoft Azure MySQL database. It is an ASP.NET application that runs on your browser of choice.

Download Visual Studio and MySQL:

To work with this project you will need Visual Studio and and MySQL extension for Visual Studio so the web app can interface with the database.

Download Visual Studio
Visual Studio Download

Download MySQL for Visual Studio Extension
MySQL Extension

If you have a Mac, download MySQL
MySQL Download

Connect to Github in Visual Studio

To access the project's web app code, clone it from Github. Visual Studio connects with Github which allows for easy version control.

Connect to the Github repository for the project
Web App Repository

Windows:

  1. Fork the project into your own account.
  2. Open Visual Studio.
  3. Click Continue without Code.
  4. From Team Explorer, click the Manage Connections button.
  5. Under GitHub, click Connect. Complete the process to sign in to your GitHub account.
  6. Click Clone.
  7. Select the project cloned earlier and click Clone.

Mac:

  1. Fork the project into your own account
  2. Open Visual Studio
  3. Click Continue without Code
  4. In the Menu bar, select Version Control > Checkout:
  5. Go to Connect to Repository tab
  6. On the GitHub page of the remote repository, press the Clone or Download button and copy the URL provided
  7. Replace all the text in the URL entry field in the Connect to Repository tab. This will populate most other fields in this tab for you.
  8. Enter the directory that you want to clone the repo into and press Checkout.

Connect to the Database:

Once the project is running on visual studio connect to your database, using the MySQL extension. This will allow the web app to display the information in your database. Connecting to the database through Server Explorer allows MySQL to establish a connection to the MySQL database, and the Web.Config file establishes the Azure connection.

  1. Server Explorer
  2. Add connection (This info comes from the database page on Azure.)
    1. Server Name
    2. Username
    3. Password
    4. Database
  3. Change the connection string in Web.Config to the connection string for your database. The connection string is on the Azure page, under connection strings. Use the Web App connection string.
    1. Fill in the database and password in the connection string with the database name and password for your database.

Running the code:

Run the code by clicking the play button at the top. You can set up the application to run on a specific browser through Visual Studio. The Web App will run for as long as the page is open, and should update with information from the system in real-time.

Credit

Credit to the team at Cal Poly who created this demo as a capstone project

Last modified 4 years ago Last modified on 07/09/2020 10:19:47 PM

Attachments (1)

Download all attachments as: .zip

Note: See TracWiki for help on using the wiki.