building bluetooth low energy systems

Learn working with CSRMesh in this guest post by Muhammad Usama bin Aftab, the author of Building Bluetooth Low Energy Systems.

CSRMesh is a mesh protocol developed to run over Bluetooth Low Energy. It extends the traditional Bluetooth Low Energy functionality and enables it to relay messages over longer distances. The protocol creates a mesh from CSR SoC-based (CSR1010 and CSR1011) devices. This solution is very effective for a home automation system, as it is not bound to a transmission range. CSR also markets its development kit, which helps in prototyping. Since it is a BLE-based device, you can connect through your Android, iOS, or desktop device.  Here is the complete list of products offered by CSRMesh:

It is advisable that you buy a CSRMesh development kit that comes with at least three boards to make a full mesh structure. A complete list of devices with their distributors in each continent is available at http://csrcorpkfxpa9lag2.devcloud.acquia-sites.com/products/applications/sales-csr-solutions-provider-web-shops.

Here is a view of a CSRMesh development board:

CSRMesh overview

A CSRMesh development board comes with the following features:

  • CSR1010 IC with EEPROM
  • PCB antenna
  • 1x RGB LED
  • 2x buttons and 1x slide switch
  • Power switch
  • SPI programming connector
  • 2x AA batteries
  • I/O pads
  • Temperature sensor

In 2016, Qualcomm acquired CSR, and it now sells CSR products while preserving the brand name. A list of CSR products can be found on the Qualcomm website, under the Bluetooth Products section (https://www.qualcomm.com/products/bluetooth).

Setting up the CSRMesh development kit

After unpacking your CSRMesh development kit, the next step is to know your board. The CSRMesh development kit comes with a uEnergy SDk to download the CSRMesh Light application on the development board. The CSRMesh development board interface consists of the following:

  • Switch SW1: Power switch.
  • Button SW2: Pressing this button for 2 seconds will remove the board from the mesh network. Such behavior can be turned off by user configuration.
  • Button Sw3 and SW4: Unassigned.
  • RGB LED: It blinks blue until it is not assigned, blinks yellow when association is in progress, blinks red when in fault. The light color can be controlled by the user once the association is made.

A QR code representing a CSRMesh device tag can be found with the development board:

CSR-TAg

You can find the following information on the service tag:

  • Bluetooth Address (BT) and crystal trim values (XTAL TRIM). Set these values in light_csr101x_A05.keyr, provided with the development kit, before programming.
  • SN represents the serial number of the board.
  • The Universally Unique Identifier (UUID) and Authorization Code (AC) are used by control applications during associations.
  • The QR code is another representation of the UUID and AC.

Follow these steps to program service tag information (UUID, AC, and so on) in the non-volatile memory (NVM) of the board:

  1. Open Command Prompt.
  2. Program the UUID and AC value in the EEPROM using the serial interface link. If the base NVM_START_ADDRESS is defined in the .keyr file, use the following command to program the AC and UUID (use Little Endian-hex representation):
<CSR_uEnergy_Tools Path>uEnergyProdTest.exe -k light_csr101x_A05.keyr \
      -m1 0x04 <ENTER_UUID> <ENTER_AC>
  1. If the .keyr file is not included in the command, the device UUID and authorization code can be programmed as follows:
<CSR_uEnergy_Tools Path>uEnergyProdTest.exe -m1 0xF804 <ENTER_UUID> <ENTER_AC>

Here is a view of the non-volatile memory of CSRMesh:

Entity nameType                                         Size of entity (words)NVM offset (words)
Sanity worduint1610
Application NVM versionuint1611
CSRMesh device UUIDuint16 array82
CSRMesh device authorization codeuint16 array410
CSRMesh network keyuint16 array815
CSRMesh device IDuint16125
CSRMesh message sequence numberuint32226
CSRMesh device eTaguint16 array428
CSRMesh association stateBoolean132
Light model group IDsuint16 array433
Power model group IDsuint16 array437
Attention model group IDsuint16 array441
Data model group IDsuint16 array445
Light RGB and power valuesstructure247
Bearer model datastructure350

The Android CSRMesh control application

CSR offers a control application (on Android and iOS) that communicates with BLE mesh devices. The application connects to the mesh device that runs CSR’s custom-defined CSRMesh control profile. The control application can be used to:

  • Set up a mesh network by associating individual mesh devices
  • Configure and cluster the mesh devices in a mesh network
  • Control light by setting colors and brightness levels

Copy the CSRmeshDemo.apk file and install it manually. Make sure to check Unknown sources in the settings of your Android phone.

Step 1 – Connect to the network

Once you start the app after installation, you will get a Connecting… dialog box on your screen:

csrmesh connecting

Step 2 – Set up a mesh network

In order to set up a mesh network, the application needs to generate a passphrase. Follow these steps to generate a passphrase and set up the network:

  1. Go to the Security Settings page, enter a passphrase, and press OK. This is an authorization key for your network and will be used by new devices to connect to your mesh network.
  2. The Security Settings screen will now show the Bluetooth Address (BA) of the connected bridge device.

It is recommended that you use the authorization code for every associating device. However, you can find a checkbox that disables the device authorization feature. This feature should only be used if you are using an older version of the kit and the devices do not support the AC feature.

Step 3 – associate new devices with your network

Choose Device Association from the dropdown. It will open a screen with a list of available devices for association. This list will also show the 128-bit UUID of the devices:

csrmesh available

Long-press on the device you want to associate with the network. A message in the bottom will show a progress bar with the association process. Once it is done processing, it will show a toast message that the device has been added to your network. You can repeat the process with every device you want to connect to your network.

Step 4 – Authorize connected devices

At this point, a QR code will come in handy as it is required to make the associations. At the bottom of the Device Association screen, you can see a QR Code button. Press it and scan the QR code using your device camera.

By this point, you have successfully associated and authorized the devices on your mesh network. The CSRMesh application also provides the functionality to control devices through this app.

Additional step – Controlling light and thermostat

Navigate to the Light Control or Temperature Control screens to get a complete list of control options. You can choose the color using a color wheel and associate that color to an individual light or a group of lights. Similarly, you can control the thermostat by tapping up and down on the screen. This control can be run over an individual device or a group of devices.

Here is a view of the control screens:

csrmesh control app view

Additional step – configuring your devices

Navigate to Configuration from the drop-down menu. By default, the app creates four groups. You can get additional options by long-pressing on any group. Renaming, deleting, device information, firmware information, and request data options will be visible in the pop-up menu.

Additional step – grouping your devices

In the Configuration menu from the dropdown, select the group you want to edit. It will give you all the available devices that you can associate with this group. You can check and uncheck the devices from the group and click on the Apply button at the bottom of the screen.

 

CSRMesh library for Android

This section describes the CSRMesh library for Android so that you can learn to make your own control apps. You will be walked through the functionalities offered by this library and how it can be used in an Android application. You can also refer to the CSRMesh demo source code provided with this chapter.

The CSRMesh library for Android comes with MeshService and Model classes dedicated for different tasks. This MeshService represents an Android service that provides methods to connect to a bridge and its associated devices. It can be considered as the core of the CSRMesh Android API, which is responsible for performing central-peripheral communication. Once you make a connection, the next step is to send control commands to the mesh network. This can be performed using Model classes.

In order to understand the different components of the CSRMesh Android library, refer to this block diagram:

Android CSRMesh Diagram

Getting started with the CSRMesh Android library

The CSRMesh library is not yet available on Gradle, so you cannot add it directly to the build.gradle file in your Android project. You need to add the CSRmeshLibrary.aar file in your project. You also need to add Spongy Castle libraries used for mesh security.

After attaching the library, go to the AndroidManifest.xml class to add a MeshService. This can be achieved by writing this in your Manifest.xml file under the <application> tag:

<service android:name="com.csr.mesh.MeshService" android:enabled="true" android:exported="false">
</service>

Also, provide the BLUETOOTH and BLUETOOTH_ADMIN permissions in your application using the following lines of code:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Using MeshService

Since MeshService is the core class of the CSRMesh Android library, you will need it in your main activity. Create a global variable and bind it inside the onCreate method:

private MeshService mMeshService;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // Make a connection to MeshService to enable us to use its services.
  Intent bindIntent = new Intent(this, MeshService.class);
  bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
}

If you notice, there is an unknown variable in the above code, mServiceConnection. This is an object that will handle the service connection. Declare it using the following code:

private ServiceConnection mServiceConnection = 
    new ServiceConnection() {
      public void onServiceConnected(ComponentName className, IBinder rawBinder) {
         mService = ((MeshService.LocalBinder) rawBinder).getService();
      }
      public void onServiceDisconnected(ComponentName classname) {
        mService = null;
     }
  };

MeshService is now ready, but the CSRMesh stack has not yet been initialized. First, declare a handler that is responsible for receiving messages from CSRMesh (which can later be used in the user interface of the application). In order to do this, set a mMeshHandler in mMeshService:

private final Handler mMeshHandler = new Handler(this);
private boolean connect(){
   mMeshService.setHandler(mMeshHandler);
}

The next step is to start a Bluetooth scan to detect CSRMesh devices in the vicinity. For this, you need to declare a ScanCallBack object, which will be called as the CSRMesh library hears the scan response:

private LeScanCallback mScanCallBack = new LeScanCallback() {
  @Override
  public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
    mMeshService.processMeshAdvert(device, scanRecord, rssi);
  }
};

private boolean connect(){
  mMeshService.setHandler(mMeshHandler);
  mMeshService.setLeScanCallback(mScanCallBack);
}

This mScanCallback function must explicitly call mMeshService.processMeshAdvert() for every advertisement it receives. This will allow the library to consume any CSRMesh advertisement packets. The library is smart enough to automatically enable and disable Bluetooth scanning according to your requirements. But if continuous scanning is required, you can do it by calling this method:

mMeshService.setContinuousLeScanEnabled(true);

By default, BLE notifications are enabled on the bridge, but you can manually enable it by calling this method:

setBridgeNotificationsEnabled(true);

After scanning, you can connect the library to the bridge by calling the following:

mMeshService.connectBridge(bridgeDevice);

The bridgeDevice variable is the BluetoothDevice object that represents a bridge device. Scanning for a bridge device is the same as scanning for BLE devices. Since you want to filter only CSRMesh devices in your scan, you can use the bridge service UUID, 0xFEF1.

Mesh handler

In the previous code, a handler object was associated with mMeshService, which is responsible for receiving responses from CSRMesh. It is better to extend a custom class that inherits the handler class for your custom implementation. The messages received by the handler are defined in the MeshService class. For example, when an association message is caught by the handler, it will have the value of MeshService.MESSAGE_DEVICE_ASSOCIATED. So in order to write a handler for this kind of response, you need to write the following code:

public void handleMessage(Message msg) {
  switch (msg.what) {
   case MeshService.MESSAGE_DEVICE_ASSOCIATED :
     Do something here...
     break;
   }
}

Since these are messages coming back from CSRMesh devices, some data may be associated with them. In order to retrieve this data, you can use the following tags:

case MeshService.MESSAGE_DEVICE_ASSOCIATED: {
  // New device has been associated and is telling us its device id.
  // Request supported models before adding to DeviceStore, and the UI.
  int deviceId = msg.getData().getInt(MeshService.EXTRA_DEVICE_ID);
  int uuidHash = msg.getData().getInt(MeshService.EXTRA_UUIDHASH_31);
  Log.d(TAG, "New device associated with id " + String.format("0x%x", deviceId));
  break;
}

Mesh controlling using Model classes

The application can send control requests using Model classes. The CSRMesh library provides various Model classes, and they can be acquired by calling the appropriate method on the MeshService class. Here is the list of Model classes available in the CSRMesh library:

  • ActuatorModelApi: Send requests to the device that are not awake 100% of the time
  • AttentionModelApi: Tell a device to get user attention
  • BearerModelApi: Enable or disable the relay functionality
  • ConfigModelApi: Acquire device configuration and remove associations
  • DataModelApi: Exchange manufacturer’s data using ACK and UNACK packets
  • LightModelApi: Control and modify lighting information
  • GroupModelApi: Manage a mesh group
  • PowerModelApi: Manipulate or acquire a mesh device’s power state
  • FirmwareModelApi: Perform firmware-related operations
  • PingModelApi: Ping the mesh network just like a network ping
  • SensorModelApi: Control and modify sensor information

You can use these classes in order to perform tasks on mesh devices. For example, if you want to get information about a device, you can use this:

ConfigModelApi.getInfo(mDeviceId, ConfigModelApi.DeviceInfo.VID_PID_VERSION);

Here, mDeviceId is the ID of the device you need to acquire information from. Similarly, if you want to obtain the firmware version of a particular device, you can write this:

FirmwareModelApi.getVersionInfo(mDeviceId);

An example of controlling a mesh device is to set the color of the light. You can call LightModelApi to set RGB colors of the light:

LightModelApi.setRgb(mDeviceId, red, green, blue, (byte)0xFF, 1, false);

The (byte)0xFF variable identifies the light level, 1 identifies the duration, and false describes whether the command is to be acknowledged or not.

You’ve now learned working with CSRMesh. If you enjoyed this tutorial and want to build your on BLE-based projects, you can refer to Building Bluetooth Low Energy Systems by Muhammad Usama bin Aftab. If you’re a developer passionate about learning Bluetooth Low Energy technologies, this book is a must-have in your bookshelf.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here