Skip to content

Commit

Permalink
ble module intro
Browse files Browse the repository at this point in the history
  • Loading branch information
ImplFerris committed Feb 15, 2025
1 parent 453e8ac commit e7cb191
Show file tree
Hide file tree
Showing 11 changed files with 162 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,9 @@
- [Pin layout](./joystick/pin-layout.md)
- [Circuit](./joystick/circuit.md)
- [Print ADC Values](./joystick/print-adc-values.md)
- [Bluetooth](./bluettoh/index.md)
- [Bluetooth](./bluetooth/index.md)
- [BLE](./bluetooth/ble/index.md)
- [GAP](./bluetooth/ble/gap.md)
- [GATT](./bluetooth/ble/gatt.md)
- [Code](./bluetooth/ble/code.md)
- [Projects](./projects.md)
1 change: 1 addition & 0 deletions src/bluetooth/ble/code.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Code
78 changes: 78 additions & 0 deletions src/bluetooth/ble/gap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Generic Access Profile (GAP)

GAP (Generic Access Profile) is a set of rules that control how Bluetooth Low Energy (BLE) devices discover, connect, and communicate with each other.

## BLE Communication Types

BLE supports two main ways to communicate: **connected communication** and **broadcast communication**.

**Connected Communication :** Two devices form a direct connection, allowing them to send and receive data both ways. For example, a smartwatch connects to a phone and continuously shares data like heart rate, notifications, and step count.

**Broadcast Communication:** A device sends data to all nearby devices without making a direct connection. For example, a Bluetooth beacon in a store broadcasts promotional messages to all phones in range.


## Device Roles

Imagine these roles like in real-world human communication. Just as people interact in different ways depending on their roles in a conversation, Bluetooth Low Energy (BLE) devices have specific roles.

**📢 Broadcaster (connection-less)**: Sends out information (advertisements) but cannot be connected to.
For example, a beacon in a shopping mall continuously sends discount offers to nearby smartphones. The phones can receive the offers but cannot connect to the beacon.

**📡 Observer (connection-less)**: Listens for Bluetooth advertisements but cannot connect to other devices.
For example, a smartphone app scans for beacons to detect nearby stores but does not connect to them.

**📱 Central (connection-oriented)**: This device searches for other devices, connects to them, or reads their advertisement data. It usually has more processing power and resources. It can handle multiple connections at the same time.

For example, a smartphone connects to a smartwatch, a fitness tracker, and wireless earbuds simultaneously.

**⌚ Peripheral (connection-oriented)**: This device broadcasts advertisements and accepts connection requests from central devices.
For example, a fitness tracker advertises itself so a smartphone can find and connect to it for syncing health data.

<img style="display: block; margin: auto;" alt="Central And Peripherals" src="../images/ble-central-peripheral.jpg"/>


## BLE Peripheral Discovery Modes & Advertisement Flags

A BLE peripheral can be in different discovery modes, affecting how it is detected by central devices. These modes are set using advertisement flags in the advertising packet.



### Discovery Modes

1. **Non-Discoverable**
- Default mode when no advertising is active or when a connection is established.
- Cannot be discovered or connected to.

2. **Limited-Discoverable**
- Discoverable **for a limited time** to save power.
- If no connection is made, the device goes idle.

3. **General-Discoverable**
- Advertises **indefinitely** until a connection is established.

### Advertisement Flags

These flags indicate the discovery mode and BLE support level. They are combined using bitwise OR (`|`):

| Bit | Flag (in [`bleps`](https://github.com/bjoernQ/bleps) crate) | Description |
|------|--------------------------------|------------------------------------------------|
| 0 | `AD_FLAG_LE_LIMITED_DISCOVERABLE` | Limited discoverable mode (temporary advertising). |
| 1 | `LE_GENERAL_DISCOVERABLE` | General discoverable mode (advertises indefinitely). |
| 2 | `BR_EDR_NOT_SUPPORTED` | Set when the device **does not support** (or dont want to) Bluetooth Classic (BR/EDR). |
| 3 | `SIMUL_LE_BR_CONTROLLER` | Set if the device can use both Bluetooth Low Energy (LE) and Classic Bluetooth at the same time (Controller level).|
| 4 | `SIMUL_LE_BR_HOST` | Set if the device can run both Bluetooth Low Energy (LE) and Classic Bluetooth at the same time (Host level). |
| 5-7 | Reserved | Not used. |

Example Usage

```rust
ble.cmd_set_le_advertising_data(
create_advertising_data(&[
// Flags
AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED)
// Other advertisement data
]).unwrap()
).await
```

This configures the peripheral to advertise indefinitely (LE_GENERAL_DISCOVERABLE) while indicating that it does not support Bluetooth Classic (BR_EDR_NOT_SUPPORTED).
54 changes: 54 additions & 0 deletions src/bluetooth/ble/gatt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Attribute Protocol (ATT) and Generic Attribute Profile (GATT)

In the previous chapter, we learned that the GAP layer helps Bluetooth LE devices find each other through advertising. After they connect, they need a way to send and receive data. This is where the ATT and GATT layers come in; they define how data is structured and transmitted between devices.

## Client-Server Model

There are two roles in GATT: Server and Client. The server holds data as attributes, and the client accesses this data. Typically, a peripheral device (like a sensor) acts as the server, and a central device (such as a smartphone) functions as the client.

<div class="alert-box alert-box-info">
<span class="icon"><i class="fa fa-info"></i></span>
<div class="alert-content">
<b class="alert-title">Central-Peripheral vs Server-Client</b>
<p>The client and server roles in GATT are independent of the peripheral and central roles in the Generic Access Profile (GAP). This means a central device can be either a client or a server, and the same applies to a peripheral device.
</p>
</div>
</div>

For example, in a smartphone and fitness tracker scenario, the fitness tracker (peripheral) typically acts as a GATT server, storing sensor data like heart rate or step count, while the smartphone (central) acts as a GATT client, reading this data to display it in an app. However, if the smartphone needs to send configuration settings to the tracker (e.g., adjusting display brightness or setting an alarm), it temporarily becomes the server, and the fitness tracker acts as the client to receive these settings.

## Attribute Protocol (ATT) - The Foundation

ATT defines how data is stored as attributes; attributes are the base foundation and building blocks. Each attribute has a unique handle, type(a 16-bit identifier or 128-bit UUID), permissions (e.g., readable, writable), and data(the actual value). The client can read, write, or subscribe to data.


## Generic Attribute Profile (GATT) - Organizing the Data
GATT builds on ATT by adding structure and meaning to the data. It defines how data is grouped and accessed.

GATT organizes attributes into:

- Characteristic: a single piece of data that a device can share. Other devices can read, write, or receive updates from it. For example, a Heart Rate Measurement characteristic holds the current heart rate and can send updates when it changes.

- Service: a collection of related characteristics grouped together. For example, the Heart Rate Service includes characteristics for heart rate measurement and the sensor's location on the body.

- Profiles: A collection of related services (e.g., Heart Rate Service, Device Information Service).

The following picture illustrates the profile, services and characteristics for the Heart Rate Sensor
<img style="display: block; margin: auto;" alt="GAT" src="../images/ble-gatt.png"/>

### UUID
Let's revisit the UUID part in the attribute. Each service and characteristic should have a unique ID value. The UUID could be either a standard Bluetooth-SIG defined UUID (16-bit) or a custom UUID (128-bit).

You can get the predefined UUID list from here: [https://www.bluetooth.com/specifications/assigned-numbers/](https://www.bluetooth.com/specifications/assigned-numbers/)

Pre-defined UUID for Heart Rate Service:
<img style="display: block; margin: auto;" alt="GAT" src="../images/heart-rate-service.png"/>

Pre-defined UUID for Heart Rate Monitor characteristic:
<img style="display: block; margin: auto;" alt="GAT" src="../images/heart-rate-monitor-characteristics.png"/>

**Custom UUID**:
In our examples, we will use custom UUIDs instead of predefined ones. However, if you're implementing a common service like a heart rate sensor, it's best to use the predefined UUIDs listed in the official documentation.

To generate a custom UUID, you can visit the [UUID Generator](https://www.uuidgenerator.net/) and create unique UUIDs for your services and characteristics.

24 changes: 24 additions & 0 deletions src/bluetooth/ble/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# BLE

To work with Bluetooth Low Energy, we need to understand several key concepts. I'll keep it simple and cover just enough to get you started without overwhelming you with too many details. So, buckle up, and let's jump in.



## BLE Stack
The image below illustrates the Bluetooth Low Energy (BLE) protocol stack. The BLE stack is the foundation of communication between BLE devices. We won't go into the Controller (lower layers) in detail, as it's not essential for our purpose. However, understanding key concepts in the Host part, such as GAP and GATT, is important.

<img style="display: block; margin: auto;" alt="Bluetooth LE protocol stack" src="../images/ble-stack.jpg"/>

### GAP => How devices connect and communicate

GAP (Generic Access Profile) defines how BLE devices advertise, connect, and establish communication. It covers device roles (e.g., central, peripheral), connection parameters, and security modes. GAP is responsible for how devices find each other and initiate communication.

### GATT => How devices exchange and structure data

GATT (Generic Attribute Profile) defines how BLE devices exchange data. It organizes data in a hierarchy of services and characteristics, allowing clients (e.g., a smartphone app) to read, write, and subscribe to updates from a BLE peripheral (e.g., a sensor).


## References
If you want deeper understanding, you can refer the following resources
- [Download The Bluetooth Low Energy Primer](https://www.bluetooth.com/bluetooth-resources/the-bluetooth-low-energy-primer/)
- [Bluetooth Low Energy Fundamentals](https://academy.nordicsemi.com/courses/bluetooth-low-energy-fundamentals/)
Binary file added src/bluetooth/images/ble-central-peripheral.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/bluetooth/images/ble-gatt.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/bluetooth/images/ble-stack.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/bluetooth/images/heart-rate-service.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes.

0 comments on commit e7cb191

Please sign in to comment.