Skip to content

Preface ​

  • Bluetooth communication programming is very close to the physical layer, the closer to the physical world, the further away from those perfect abstract programming concepts. Handling these Bluetooth instructions is indeed very tedious, and the so-called SesameSDK is exactly a good implementation of these complex operations, and it is encapsulated into an open source library for easy use.
  • This whole set of Bluetooth protocols is the crystallization of hard work and wisdom of the third-generation engineers of CANDY HOUSE for more than ten years (2014〜2016, 2017〜2019, 2020〜), its open source does not mean "cheap and no good goods", on the contrary, we hope This work that we think is near perfect can be used as a set of "living" Bluetooth protocols to carry forward the central ideas in the world.
  • Bluetooth operation involves two main parts: Bluetooth Broadcasting and Bluetooth Data Transfer, which will be introduced in detail.

Bluetooth Broadcasting (BLE Advertising) ​

BLEadvertisingSesameOS3

  • The longest length of Bluetooth LE 4.0 advertising is 31 bytes.
  • Yellow background or yellow background indicates the protocol defined by CANDY HOUSE.
  • The rest of the white background is a mandatory declaration required by the Bluetooth SIG specification.

Official IDs of Bluetooth SIG ​

DecimalHex
BLE Service UUID648970xFD81
Company ID13700x055A

Product Model ​

  • The 8th and 9th bytes in the Bluetooth broadcast express the model
8th 9th BytesModel
0Sesame 3
1WiFi Module 2
2Sesame Bot 1
3Sesame Bike 1
4Sesame 4
5Sesame 5
6Sesame Bike 2
7Sesame 5 Pro
8Open Sensor
9Sesame Touch 1 Pro
10Sesame Touch 1
11Ble Connector
13Hub 3
14Sesame Remote
15Remote Nano
16Sesame 5 US
17Sesame Bot 2
18F2
19F1
20Bluetooth Optical Relay

Device Status ​

  • The 10th byte in the Bluetooth broadcast is split into 8 bits, each bit expressing various device status
8 bits of the 10th byteDevice Status
01
1st bitUnregisteredRegistered
2nd bit
3rd bit
4th bit
5th bit
6th bit
7th bit
8th bit

Compliance with  Accessory Design Guidelines for Apple Devices ​

Encourage to use nRF Connect app to get familiar with Sesame BLE adv ​

nrfConnect_Demo_SesameOS3_adv.svg


Bluetooth Data Transmission (BLE Data Transmission) ​

BLEcommunication4Layers.jpg

  • Inspired by the TCP/IP Model, we divide Bluetooth communication into 4 layers.
  • The plain text of any format information is encrypted and cut and then transmitted through Bluetooth GATT . The 4 states are called Application Layer , Security Layer , Transport Layer , GATT Bearer Layer .
  • This way of cutting information can transmit arbitrarily formatted information of infinite length.

Transmission Protocol Request, Response and Publish ​

Sesame

  • Inspired by RESTful API to add, delete, inquire, and change the database POST method, we encapsulated 1 command method based on BLE write without response:
    ・Request
  • Inspired by RESTful API async/sync, we packaged 2 receiving callback methods based onBLE notify:
    ・Response
    ・Publish
  • The Response method has no relationship to BLE write without response of the same name, and this causes confusion we are very sorry.
  • Every Request will receive a Response immediately. The information needs execution time to know the execution result with Publish feedback.

Only use 2 BLE Characteristics to receive and transmit Bluetooth information ​

  • When receiving and transmitting Bluetooth information through Request, Response, Publish method, only 2 BLE Characteristics of the Sesame BLE Service (0xFD81) will be used.
  • The Characteristics of UUID 16860002-a5ae-9856-b6d3-dbb4c676993e is used to write BLE commands without response.
  • The Characteristics of UUID 16860003-a5ae-9856-b6d3-dbb4c676993e is used to receive BLE Notify

nrfConnect_Demo_Sesame_BLE_Characteristics.svg

Application Layer Business Content ​

1. Sesame "Register" Activity Diagram ​

Sesame

2. Sesame "Register" Sequence Diagram ​

Sesame

3. Sesame "Login" Sequence Diagram ​

Sesame

4. Sesame "Send Command" Sequence Diagram ​

Sesame

5. State Machine of Mobile Sesame SDK Encapsulation ​

Sesame

6. Sesame Timing Chart ​

Sequence_diagram

Two ways of communication between mobile phone's Bluetooth and Sesame ​

  • The first is Publish, Sesame actively sends messages to the phone.
  • The second is Request, the phone asks Sesame to work, and Sesame replies to Response

1. Publish【Sesame->Phone】 ​

When NotifyEnable = True is enabled, Sesame actively pushes subscription messages to the phone, such as the 81_Mechanical Status in the [「Response Command Comparison Table」](#Response Command Comparison Table).

Byte Index012 ~ N
Datatypecmd_codepayload
DescriptionPush TypeCommand NumberData sent to the phone
c

typedef struct {
    uint8_t type;               /// Push type: publish
    uint8_t item_code;          /// Command item_code
    union ss5_payload payload;  /// Data sent to the mobile phone
} ss5_publish;

2. Request【Phone->Sesame】 ​

  • Request is when the phone asks Sesame to do something, Sesame responds to the receiving status, such as the 82_Lock in the [「request command comparison table」](#Request command comparison table)
  • To avoid confusion, a queue is needed to ensure order, support synchronous serial transmission, and BLE, when acting as a lower computer, reads and writes one feature value Characteristics each. The reading and writing operation method is the content of the send protocol
Byte index01 ~ N
Dataitem_codepayload
DescriptionCommand numberData sent to Sesame
c

typedef struct {
    uint8_t item_code;              /// Command (see details in item_code)
    union ss5_payload payload;      /// Data sent to Sesame5 
} ss5_request;
c
typedef enum {
    ITEM_CODE_NONE = 0,
    ITEM_CODE_REGISTRATION = 1,
    ITEM_CODE_LOGIN = 2,
    ...
} item_code_e;

2.1. Response command data format ​

Byte index0123 ~ N
Datatypeitem_coderespayload
DescriptionPush typeCommand numberCommand processing statusData sent to mobile phone
c

typedef struct {
    uint8_t type;                   /// Push type: Response
    uint8_t item_code;              /// Command (item_code)
    uint8_t res;                    /// Command processing status (always reply with success)
    union ss5_payload payload;      /// Data sent to the mobile phone
} ss5_response;

Processing Status ​

c
typedef enum {
    CMD_RESULT_SUCCESS = 0,         /// Sesame5 will respond success directly upon receiving a command from the phone
    CMD_RESULT_INVALID_ACTION = 9,  /// Registering command when already registered
} cmd_result_e;

2.2 Push Type ​

When the tag is 0x07, it is a normal response response, 0x08 is a push publish

c
typedef enum {
    OP_CODE_RESPONSE = 0x07,
    OP_CODE_PUBLISH = 0x08,
} op_code_e;

Request command comparison table ​

Byte index01 ~ NN+
Dataitem_codepayloadothers
說明指令編號送給 Sesame 的資料其它資料
注册11-64【publicKeyA】65-68【timestamp】
登入21-4【ccmkeyA】
历史41【is peek】ispeek=true 不删除
版本5none
更新时间81-4【timestamp】
自动上锁111-2【秒数】
角度校正17none
機械設定801-5【autolock+开关锁角度】
機械狀態81noneNo Response
關鎖821-7【历史标签】
開鎖831-7【历史标签】
開門90none
關門91none
自動上鎖92none
重置104none
添加芝麻「touch」1011-16【Device Name】17-32【secretKey】
删除芝麻「touch」1031-16【Device Name】
更新卡片「touch」1070【Card ID Len】1-id_len【CardID】CardIDLen+1【CardNameLen】etc
删除卡片「touch」1081-16【Card ID】
获取卡片「touch」113none
卡片模式114none
指纹更新1150【FingerIDLen】1-Len【FingerID】】
指纹删除1161【FingerID】
指纹获取117none
指纹模式121none
指纹模式设置122none
密码更新1230【PwIDlen】1-pwLen【Password】】
密码删除124none
密码获取125none
获取密码模式129none
密码模式设置1300 验证 1 新增

Response command comparison table ​

Byte index0123 ~ NN+N++
Datatypeitem_coderespayloadpayloadpayload
說明推送類型指令編號命令處裡狀態送給手機的資料 1送給手機的資料 2送給手機的資料 3
初始化81400-3【random code】none
注册7100-6【mechStatus】7-12【mechSetting】】13~76【publicKeyS】】
登入7200-3【timestamp】
历史7400-3【id】】4【type】5-8【timestamp】
版本7500-11【version】
機械設定88000-1【lock】2-3【unlock】】4-5【autolock_second】
機械狀態88100-3【random code】
推送芝麻钥匙810200-21【ssm0-name】22【ssm0-status】23-44【ssm1_name】etc
获取芝麻钥匙710900-3【CardID】
获取指纹711700-3【FingerID】
指纹模式获取812100-3【random code】
Byte index01 ~ NN+
Dataitem_codepayloadother data
DescriptionCommand numberData sent to SesameOther data
Register11-64【publicKeyA】65-68【timestamp】
...
Byte index0123 ~ NN+N++
Datatypeitem_coderespayloadpayloadpayload
DescriptionPush typeCommand numberCommand processing statusData 1 sent to the phoneData 2 sent to the phoneData 3 sent to the phone
Initialization81400-3【random code】none
...

Security Layer ​

The Security Layer is the encryption transmission protocol implemented by the data transparent transmission between the mobile phone Bluetooth and Sesame5.

1. 4-byte Random code ​

After the mobile phone Bluetooth searches for the Sesame device and connects to open the notify with a feature value of 0xFD81, the Sesame device actively publish sends a 4-byte Random Code/Session Token.(see 14_Initialization)

2. Device Secret ​

During registration, both the APP and Sesame5 will generate a public key and private key through secp256r1 and exchange to generate a Device secret.

  • publicKey : 64 Bytes
  • privateKey : 32 Bytes
  • secret : 32 Bytes

Steps : ​

    1. sesame5 uses secp256r1 to generate publicKeyS and privateKeyS
    1. APP uses secp256r1 to generate publicKeyA and privateKeyA
    1. Both parties exchange publicKey
    1. sesame5 uses privateKeyS and publicKeyA to generate secret S
    1. APP uses privateKeyA and publicKeyS to generate secret A
    1. secret S and secret A are equal
    1. Both parties use the first 16 bytes of the secret asDevice secret.

Token Use ​

    1. Log in authentication (see : 2_Login)
    1. During data transmission, aes_ccm is used to encrypt data, using Token as the key used during encryption.

Generation Method ​

Using the AES_CMAC algorithm, the 4Bytes Random code is signed with the Device secret to generate the Token. device_secret: 16 Bytes random_code: 4 Bytes Token: 16 Bytes

c

AES_CMAC(key:device_secret, input:random_code, input_size:4, output:Token);

3. Data Encryption and Decryption ​

Encryption Parameter: Initialization Vector (CCM_IV) ​

    1. count : 8 bytes, initialized to 0 at startup, count increases by one for each encryption
    1. nouse : 1 byte, default value is 0
    1. random_code : 4 bytes, updated random_code after connecting to the device
c

typedef struct {
    int64_t count;///8 byte
    uint8_t nouse;///1 byte = 0
    uint8_t random_code[4];///4 byte
} CCM_IV;

aes_ccm parameters ​

Input:

    1. key : Encryption key, used for AES-CCM operation
    1. iv : Initialization vector (CCM_IV)
    1. iv length : AES-CCM uses a 13-byte (104-bit) IV
    1. add : Additional authentication data
    1. add length : length of additional authentication data
    1. input : The input data to be encrypted
    1. input length : Length of data to be encrypted
    1. tag length : Length of buffer and tag used to store authentication tag (MAC)

Output:

    1. tag : ccm_tag
    1. output : ccm_ecrrypt_data, data after encryption

C language Encryption Example ​

c
aes_ccm_encrypt_and_tag(
                        key:ccm_key,
                        iv:CCM_IV,
                        iv_length:13,
                        add:0x00,
                        add_length:1,
                        input:p_data,
                        add_length:length,
                        output:ccm_ecrrypt_data,
                        tag:ccm_tag,
                        tag_length:4
                        );
CCM_IV.count ++;

AES is a symmetric encryption algorithm, the method name is aes_ccm_auth_decrypt, and the parameters correspond to encryption

C language Decryption Example ​

c
aes_ccm_auth_decrypt(
                    key:ccm_key,
                    iv:CCM_IV,
                    iv_length:13,
                    add:0x00,
                    add_length:1,
                    input:ccm_ecrrypt_data,
                    add_length:length,
                    output:ans_data,
                    tag:ccm_tag, tag_length:4
                    );
CCM_IV.count ++;

Note

The count in the CCM_IV used for data encryption and decryption records the number of encryption times. If the counts at the encryption and decryption ends do not match, it will cause decryption failure.

Segment Layer ​

The Segment Layer has two tasks.

    1. When Sesame5 communicates with the mobile phone, the maximum packet size is limited to 20Bytes. If you want to send long messages, you need to split the data and reassemble it at the receiving end.
    1. Mark whether the transmitted data is encrypted, and there are three types of plaintext ciphertext packet methods with different lengths.

1. Mark Reference Table ​

Segment Layer marks whether this packet has been cut or encrypted in the packet header. The receiving end can handle it according to the mark and restore the packet to the original data. The following is a Segment Layer mark reference table.

Segment Layer mark has 8bits, of which bit 7 ~ 1 indicates whether it is the end packet and whether the data is encrypted, and bit 0 indicates whether this packet is the starting packet of a data.

bit 7 ~ 1endbitstart
b0000000no end0not start
b0000000no end1start
b0000001plaintext end0not start
b0000001plaintext end1start
b0000010encryption end0not start
b0000010encryption end1start

Mark in hexadecimal ​

0 This packet is neither a start packet nor an end packet

1 This packet is a start packet but not an end packet

2 This packet is not a start packet but an end packet, and the assembled data is plaintext

3 This packet is both a start and end packet, and the data is plaintext. The data is not cut and does not need to be recombined

4 This packet is not a start packet but an end packet, and the assembled data is ciphertext

5 This packet is both a start and end packet, and the data is ciphertext. The data is not cut and does not need to be recombined

Markstartend
0x00not startno end
0x01startno end
0x02not startplaintext end
0x03startplaintext end
0x04not startencryption end
0x05startencryption end

Example ​

Assuming a packet can hold 4bytes of data, it needs to be split if it exceeds 4bytes (actually 20bytes).

2. Three kinds of plaintext ciphertext packet methods with different lengths ​

2.1 Short plaintext packet ​

Data: A A B B

Sent:

1. Received data: A A B B
2. Data: A A B B
3. Add packet header: 3 A A B B

Received:

4. Received: 3 A A B B
5. Remove the packet header to restore data: A A B B

2.2 Medium plaintext packet ​

Data: A A A A B B B B

Sent:

1. Received data: A A A A B B B B
2. Split data: A A A A
3. Add packet header: 1 A A A A
6. Split data: B B B B
7. Add packet header: 2 B B B B

Received:

4. Received: 1 A A A A
5. Determine that the data has not been sent completely, waiting for the next packet
8. Received: 2 B B B B
9. Data reception is complete, assemble packets
10. Remove packet header to restore data: A A A A B B B B

2.3 Long plaintext packet ​

Data: A A A A B B B B C C C C

Sent:

1. Received data: A A A A B B B B C C C C
2. Split data: A A A A
3. Add packet header: 1 A A A A
6. Split data: B B B B
7. Add packet header: 0 B B B B
10. Split data: C C C C
11. Add packet header: 2 C C C C

Received:

4. Received: 1 A A A A
5. Determine that the data has not been sent completely, wait for the next packet
8. Received: 0 B B B B
9. Determine that the data has not been sent completely, wait for the next packet
12. Received: 2 C C C C
13. Data reception is complete, assemble packets
14. Remove packet header to restore data: A A A A B B B B C C C C

2.4 Short ciphertext packet ​

Data: A A B B

Data after encryption: X X Y Y

Sent:

1. Received data: A A B B
2. Data after encryption: X X Y Y
3. Add packet header: 5 X X Y Y

Received:

4. Received: 5 X X Y Y
5. Remove packet header to restore data: X X Y Y
6. Decryption: A A B B

2.5 Medium ciphertext packet ​

Data: A A A A B B B B

Data after encryption: X X X X Y Y Y Y

Send:

1. Received data: A A A A B B B B
2. Data after encryption: X X X X Y Y Y Y
3. Split data: X X X X
4. Add packet header: 1 X X X X
7. Split data: Y Y Y Y
8. Add packet header: 4 Y Y Y Y

Received:

5. Received: 1 X X X X
6. Determine that the data has not been sent completely, wait for the next packet
9. Received: 4 Y Y Y Y
10. Data reception is complete, assemble packets
11. Remove packet header to restore data: X X X X Y Y Y Y
12. Decryption: A A A A B B B B

2.6 Long ciphertext packet ​

Data: A A A A B B B B C C C C

Data after encryption: X X X X Y Y Y Y Z Z Z Z

Sent:

1. Received data: A A A A B B B B C C C C
2. Data after encryption: X X X X Y Y Y Y Z Z Z Z
3. Split data: X X X X
4. Add packet header: 1 X X X X
7. Split data: Y Y Y Y
8. Add packet header: 0 Y Y Y Y
11. Split data: Z Z Z Z
12. Add packet header: 4 Z Z Z Z

Received:

5. Received: 1 X X X X
6. Determine that the data has not been sent completely, wait for the next packet
9. Received: 0 Y Y Y Y
10. Determine that the data has not been sent completely, wait for the next packet
13. Received: 4 Z Z Z Z
14. Data reception is complete, assemble packets
15. Remove packet header to restore data: X X X X Y Y Y Y Z Z Z Z
16. Decryption: A A A A B B B B C C C C

Note

After the data is encrypted with AES_CCM, in addition to the ciphertext, it will also generate a 4Bytes ccm_tag for decryption. The ciphertext and ccm_tag need to be transmitted to the receiving end together, so the data will increase by 4Bytes after encryption. See security_Layer description for details.