]> granicus.if.org Git - esp-idf/blob - components/protocomm/src/transports/protocomm_ble.c
protocomm_ble : Fixed custom service UUID support
[esp-idf] / components / protocomm / src / transports / protocomm_ble.c
1 // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <sys/param.h>
16 #include <esp_log.h>
17 #include <esp_gatt_common_api.h>
18 #include <esp_gap_bt_api.h>
19
20 #include <protocomm.h>
21 #include <protocomm_ble.h>
22
23 #include "protocomm_priv.h"
24 #include "simple_ble.h"
25
26 #define CHAR_VAL_LEN_MAX         (256 + 1)
27 #define PREPARE_BUF_MAX_SIZE     CHAR_VAL_LEN_MAX
28
29 static const char *TAG = "protocomm_ble";
30
31 /* BLE specific configuration parameters */
32 static const uint16_t primary_service_uuid       = ESP_GATT_UUID_PRI_SERVICE;
33 static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE;
34 static const uint16_t character_user_description = ESP_GATT_UUID_CHAR_DESCRIPTION;
35 static const uint8_t  character_prop_read_write  = ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_WRITE;
36 static const uint8_t  ble_advertisement_flags    = ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT;
37
38 typedef struct {
39     uint8_t type;
40     uint8_t length;
41     uint8_t *data_p;
42 } raw_data_info_t;
43
44 typedef struct {
45     uint8_t                *prepare_buf;
46     int                     prepare_len;
47     uint16_t                handle;
48 } prepare_type_env_t;
49
50 static prepare_type_env_t prepare_write_env;
51
52 typedef struct name_uuid128 {
53     const char *name;
54     uint8_t uuid128[ESP_UUID_LEN_128];
55 } name_uuid128_t;
56
57 typedef struct _protocomm_ble {
58     protocomm_t *pc_ble;
59     name_uuid128_t *g_nu_lookup;
60     ssize_t g_nu_lookup_count;
61     uint16_t gatt_mtu;
62     uint8_t *service_uuid;
63     uint8_t *raw_adv_data_p;
64     uint8_t raw_adv_data_len;
65     uint8_t *raw_scan_rsp_data_p;
66     uint8_t raw_scan_rsp_data_len;
67 } _protocomm_ble_internal_t;
68
69 static _protocomm_ble_internal_t *protoble_internal;
70
71 static esp_ble_adv_params_t adv_params = {
72     .adv_int_min         = 0x100,
73     .adv_int_max         = 0x100,
74     .adv_type            = ADV_TYPE_IND,
75     .own_addr_type       = BLE_ADDR_TYPE_PUBLIC,
76     .channel_map         = ADV_CHNL_ALL,
77     .adv_filter_policy   = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
78 };
79
80 static char* protocomm_ble_device_name = NULL;
81
82 static void hexdump(const char *msg, uint8_t *buf, int len)
83 {
84     ESP_LOGD(TAG, "%s:", msg);
85     ESP_LOG_BUFFER_HEX_LEVEL(TAG, buf, len, ESP_LOG_DEBUG);
86 }
87
88 static const uint16_t *uuid128_to_16(const uint8_t *uuid128)
89 {
90     return (const uint16_t *) &uuid128[12];
91 }
92
93 static const char *handle_to_handler(uint16_t handle)
94 {
95     const uint8_t *uuid128 = simple_ble_get_uuid128(handle);
96     if (!uuid128) {
97         return NULL;
98     }
99     for (int i = 0; i < protoble_internal->g_nu_lookup_count; i++) {
100         if (*uuid128_to_16(protoble_internal->g_nu_lookup[i].uuid128) == *uuid128_to_16(uuid128)) {
101             return protoble_internal->g_nu_lookup[i].name;
102         }
103     }
104     return NULL;
105 }
106
107 static void transport_simple_ble_read(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
108 {
109     static const uint8_t *read_buf = NULL;
110     static uint16_t read_len = 0;
111     esp_gatt_status_t status = ESP_OK;
112
113     ESP_LOGD(TAG, "Inside read w/ session - %d on param %d %d",
114              param->read.conn_id, param->read.handle, read_len);
115     if (!read_len) {
116         ESP_LOGD(TAG, "Reading attr value first time");
117         status = esp_ble_gatts_get_attr_value(param->read.handle, &read_len,  &read_buf);
118     } else {
119         ESP_LOGD(TAG, "Subsequent read request for attr value");
120     }
121
122     esp_gatt_rsp_t gatt_rsp = {0};
123     gatt_rsp.attr_value.len = MIN(read_len, (protoble_internal->gatt_mtu - 1));
124     gatt_rsp.attr_value.handle = param->read.handle;
125     gatt_rsp.attr_value.offset = param->read.offset;
126     gatt_rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
127     if (gatt_rsp.attr_value.len && read_buf) {
128         memcpy(gatt_rsp.attr_value.value,
129                 read_buf + param->read.offset,
130                 gatt_rsp.attr_value.len);
131     }
132     read_len -= gatt_rsp.attr_value.len;
133     esp_err_t err = esp_ble_gatts_send_response(gatts_if, param->read.conn_id,
134                                                 param->read.trans_id, status, &gatt_rsp);
135     if (err != ESP_OK) {
136         ESP_LOGE(TAG, "Send response error in read");
137     }
138 }
139
140 static esp_err_t prepare_write_event_env(esp_gatt_if_t gatts_if,
141                                          esp_ble_gatts_cb_param_t *param)
142 {
143     ESP_LOGD(TAG, "prepare write, handle = %d, value len = %d",
144              param->write.handle, param->write.len);
145     esp_gatt_status_t status = ESP_GATT_OK;
146     if (prepare_write_env.prepare_buf == NULL) {
147         prepare_write_env.prepare_buf = (uint8_t *) malloc(PREPARE_BUF_MAX_SIZE * sizeof(uint8_t));
148         if (prepare_write_env.prepare_buf == NULL) {
149             ESP_LOGE(TAG, "%s , failed tp allocate preparebuf", __func__);
150             status = ESP_GATT_NO_RESOURCES;
151         }
152         /* prepare_write_env.prepare_len = 0; */
153     } else {
154         if (param->write.offset > PREPARE_BUF_MAX_SIZE) {
155             status = ESP_GATT_INVALID_OFFSET;
156         } else if ((param->write.offset + param->write.len) > PREPARE_BUF_MAX_SIZE) {
157             status = ESP_GATT_INVALID_ATTR_LEN;
158         }
159     }
160     memcpy(prepare_write_env.prepare_buf + param->write.offset,
161            param->write.value,
162            param->write.len);
163     prepare_write_env.prepare_len += param->write.len;
164     prepare_write_env.handle = param->write.handle;
165     if (param->write.need_rsp) {
166         esp_gatt_rsp_t gatt_rsp = {0};
167         gatt_rsp.attr_value.len = param->write.len;
168         gatt_rsp.attr_value.handle = param->write.handle;
169         gatt_rsp.attr_value.offset = param->write.offset;
170         gatt_rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
171         if (gatt_rsp.attr_value.len && param->write.value) {
172             memcpy(gatt_rsp.attr_value.value, param->write.value, param->write.len);
173         }
174         esp_err_t response_err = esp_ble_gatts_send_response(gatts_if, param->write.conn_id,
175                 param->write.trans_id, status,
176                 &gatt_rsp);
177         if (response_err != ESP_OK) {
178             ESP_LOGE(TAG, "Send response error in prep write");
179         }
180     }
181     if (status != ESP_GATT_OK) {
182         if (prepare_write_env.prepare_buf) {
183             free(prepare_write_env.prepare_buf);
184             prepare_write_env.prepare_buf = NULL;
185             prepare_write_env.prepare_len = 0;
186         }
187         return ESP_FAIL;
188     }
189     return ESP_OK;
190 }
191
192 static void transport_simple_ble_write(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
193 {
194     uint8_t *outbuf = NULL;
195     ssize_t outlen = 0;
196     esp_err_t ret;
197
198     ESP_LOGD(TAG, "Inside write with session - %d on attr handle - %d \nLen -%d IS Prep - %d",
199              param->write.conn_id, param->write.handle, param->write.len, param->write.is_prep);
200
201     if (param->write.is_prep) {
202         ret = prepare_write_event_env(gatts_if, param);
203         if (ret != ESP_OK) {
204             ESP_LOGE(TAG, "Error appending to prepare buffer");
205         }
206         return;
207     } else {
208         ESP_LOGD(TAG, "is_prep not set");
209     }
210
211     ret = protocomm_req_handle(protoble_internal->pc_ble,
212                                handle_to_handler(param->write.handle),
213                                param->write.conn_id,
214                                param->write.value,
215                                param->write.len,
216                                &outbuf, &outlen);
217     if (ret == ESP_OK) {
218         ret = esp_ble_gatts_set_attr_value(param->write.handle, outlen, outbuf);
219         if (ret != ESP_OK) {
220             ESP_LOGE(TAG, "Failed to set the session attribute value");
221         }
222         ret = esp_ble_gatts_send_response(gatts_if, param->write.conn_id,
223                                           param->write.trans_id, ESP_GATT_OK, NULL);
224         if (ret != ESP_OK) {
225             ESP_LOGE(TAG, "Send response error in write");
226         }
227         hexdump("Response from  write", outbuf, outlen);
228
229     } else {
230         ESP_LOGE(TAG, "Invalid content received, killing connection");
231         esp_ble_gatts_close(gatts_if, param->write.conn_id);
232     }
233     if (outbuf) {
234         free(outbuf);
235     }
236 }
237
238 static void transport_simple_ble_exec_write(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
239 {
240     esp_err_t err;
241     uint8_t *outbuf = NULL;
242     ssize_t outlen = 0;
243     ESP_LOGD(TAG, "Inside exec_write w/ session - %d", param->exec_write.conn_id);
244
245     if ((param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC)
246             &&
247             prepare_write_env.prepare_buf) {
248         err = protocomm_req_handle(protoble_internal->pc_ble,
249                                    handle_to_handler(prepare_write_env.handle),
250                                    param->exec_write.conn_id,
251                                    prepare_write_env.prepare_buf,
252                                    prepare_write_env.prepare_len,
253                                    &outbuf, &outlen);
254
255         if (err != ESP_OK) {
256             ESP_LOGE(TAG, "Invalid content received, killing connection");
257             esp_ble_gatts_close(gatts_if, param->exec_write.conn_id);
258         } else {
259             hexdump("Response from exec write", outbuf, outlen);
260             esp_ble_gatts_set_attr_value(prepare_write_env.handle, outlen, outbuf);
261         }
262     }
263     if (prepare_write_env.prepare_buf) {
264         free(prepare_write_env.prepare_buf);
265         prepare_write_env.prepare_buf = NULL;
266         prepare_write_env.prepare_len = 0;
267     }
268
269     err = esp_ble_gatts_send_response(gatts_if, param->exec_write.conn_id, param->exec_write.trans_id, ESP_GATT_OK, NULL);
270     if (err != ESP_OK) {
271         ESP_LOGE(TAG, "Send response error in exec write");
272     }
273     if (outbuf) {
274         free(outbuf);
275     }
276 }
277
278 static void transport_simple_ble_disconnect(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
279 {
280     esp_err_t ret;
281     ESP_LOGD(TAG, "Inside disconnect w/ session - %d", param->disconnect.conn_id);
282     if (protoble_internal->pc_ble->sec &&
283         protoble_internal->pc_ble->sec->close_transport_session) {
284         ret = protoble_internal->pc_ble->sec->close_transport_session(param->disconnect.conn_id);
285         if (ret != ESP_OK) {
286             ESP_LOGE(TAG, "error closing the session after disconnect");
287         }
288     }
289     protoble_internal->gatt_mtu = ESP_GATT_DEF_BLE_MTU_SIZE;
290 }
291
292 static void transport_simple_ble_connect(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
293 {
294     esp_err_t ret;
295     ESP_LOGD(TAG, "Inside BLE connect w/ conn_id - %d", param->connect.conn_id);
296     if (protoble_internal->pc_ble->sec &&
297         protoble_internal->pc_ble->sec->new_transport_session) {
298         ret = protoble_internal->pc_ble->sec->new_transport_session(param->connect.conn_id);
299         if (ret != ESP_OK) {
300             ESP_LOGE(TAG, "error creating the session");
301         }
302     }
303 }
304
305 static void transport_simple_ble_set_mtu(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
306 {
307     protoble_internal->gatt_mtu = param->mtu.mtu;
308     return;
309 }
310
311 static esp_err_t protocomm_ble_add_endpoint(const char *ep_name,
312                                             protocomm_req_handler_t req_handler,
313                                             void *priv_data)
314 {
315     /* Endpoint UUID already added when protocomm_ble_start() was called */
316     return ESP_OK;
317 }
318
319 static esp_err_t protocomm_ble_remove_endpoint(const char *ep_name)
320 {
321     /* Endpoint UUID will be removed when protocomm_ble_stop() is called  */
322     return ESP_OK;
323 }
324
325 static ssize_t populate_gatt_db(esp_gatts_attr_db_t **gatt_db_generated)
326 {
327     int i;
328     /* Each endpoint requires 3 attributes:
329      * 1) for Characteristic Declaration
330      * 2) for Characteristic Value (for reading and writing to an endpoint)
331      * 3) for Characteristic User Description (endpoint name)
332      *
333      * Therefore, we need esp_gatts_attr_db_t of size 3 * number of endpoints + 1 for service
334      */
335     ssize_t gatt_db_generated_entries = 3 * protoble_internal->g_nu_lookup_count + 1;
336
337     *gatt_db_generated = (esp_gatts_attr_db_t *) malloc(sizeof(esp_gatts_attr_db_t) *
338                                                         (gatt_db_generated_entries));
339     if ((*gatt_db_generated) == NULL) {
340         ESP_LOGE(TAG, "Failed to assign memory to gatt_db");
341         return -1;
342     }
343     /* Declare service */
344     (*gatt_db_generated)[0].attr_control.auto_rsp       = ESP_GATT_RSP_BY_APP;
345
346     (*gatt_db_generated)[0].att_desc.uuid_length        = ESP_UUID_LEN_16;
347     (*gatt_db_generated)[0].att_desc.uuid_p             = (uint8_t *) &primary_service_uuid;
348     (*gatt_db_generated)[0].att_desc.perm               = ESP_GATT_PERM_READ;
349     (*gatt_db_generated)[0].att_desc.max_length         = ESP_UUID_LEN_128;
350     (*gatt_db_generated)[0].att_desc.length             = ESP_UUID_LEN_128;
351     (*gatt_db_generated)[0].att_desc.value              = protoble_internal->service_uuid;
352
353     /* Declare characteristics */
354     for (i = 1 ; i < gatt_db_generated_entries ; i++) {
355         (*gatt_db_generated)[i].attr_control.auto_rsp     = ESP_GATT_RSP_BY_APP;
356
357         if (i % 3 == 1) {
358             /* Characteristic Declaration */
359             (*gatt_db_generated)[i].att_desc.perm         = ESP_GATT_PERM_READ;
360             (*gatt_db_generated)[i].att_desc.uuid_length  = ESP_UUID_LEN_16;
361             (*gatt_db_generated)[i].att_desc.uuid_p       = (uint8_t *) &character_declaration_uuid;
362             (*gatt_db_generated)[i].att_desc.max_length   = sizeof(uint8_t);
363             (*gatt_db_generated)[i].att_desc.length       = sizeof(uint8_t);
364             (*gatt_db_generated)[i].att_desc.value        = (uint8_t *) &character_prop_read_write;
365         } else if (i % 3 == 2) {
366             /* Characteristic Value */
367             (*gatt_db_generated)[i].att_desc.perm         = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
368             (*gatt_db_generated)[i].att_desc.uuid_length  = ESP_UUID_LEN_128;
369             (*gatt_db_generated)[i].att_desc.uuid_p       = protoble_internal->g_nu_lookup[i / 3].uuid128;
370             (*gatt_db_generated)[i].att_desc.max_length   = CHAR_VAL_LEN_MAX;
371             (*gatt_db_generated)[i].att_desc.length       = 0;
372             (*gatt_db_generated)[i].att_desc.value        = NULL;
373         } else {
374             /* Characteristic User Description (for keeping endpoint names) */
375             (*gatt_db_generated)[i].att_desc.perm         = ESP_GATT_PERM_READ;
376             (*gatt_db_generated)[i].att_desc.uuid_length  = ESP_UUID_LEN_16;
377             (*gatt_db_generated)[i].att_desc.uuid_p       = (uint8_t *) &character_user_description;
378             (*gatt_db_generated)[i].att_desc.max_length   = strlen(protoble_internal->g_nu_lookup[i / 3 - 1].name);
379             (*gatt_db_generated)[i].att_desc.length       = (*gatt_db_generated)[i].att_desc.max_length;
380             (*gatt_db_generated)[i].att_desc.value        = (uint8_t *) protoble_internal->g_nu_lookup[i / 3 - 1].name;
381         }
382     }
383     return gatt_db_generated_entries;
384 }
385
386 static void protocomm_ble_cleanup(void)
387 {
388     if (protoble_internal) {
389         if (protoble_internal->g_nu_lookup) {
390             for (unsigned i = 0; i < protoble_internal->g_nu_lookup_count; i++) {
391                 if (protoble_internal->g_nu_lookup[i].name) {
392                     free((void *)protoble_internal->g_nu_lookup[i].name);
393                 }
394             }
395             free(protoble_internal->g_nu_lookup);
396         }
397         free(protoble_internal->raw_adv_data_p);
398         free(protoble_internal->raw_scan_rsp_data_p);
399         free(protoble_internal);
400         protoble_internal = NULL;
401     }
402     if (protocomm_ble_device_name) {
403         free(protocomm_ble_device_name);
404         protocomm_ble_device_name = NULL;
405     }
406 }
407
408 esp_err_t protocomm_ble_start(protocomm_t *pc, const protocomm_ble_config_t *config)
409 {
410     if (!pc || !config || !config->device_name || !config->nu_lookup) {
411         return ESP_ERR_INVALID_ARG;
412     }
413
414     if (protoble_internal) {
415         ESP_LOGE(TAG, "Protocomm BLE already started");
416         return ESP_FAIL;
417     }
418
419     /* Store BLE device name internally */
420     protocomm_ble_device_name = strdup(config->device_name);
421     if (protocomm_ble_device_name == NULL) {
422         ESP_LOGE(TAG, "Error allocating memory for storing BLE device name");
423         protocomm_ble_cleanup();
424         return ESP_ERR_NO_MEM;
425     }
426
427     protoble_internal = (_protocomm_ble_internal_t *) calloc(1, sizeof(_protocomm_ble_internal_t));
428     if (protoble_internal == NULL) {
429         ESP_LOGE(TAG, "Error allocating internal protocomm structure");
430         protocomm_ble_cleanup();
431         return ESP_ERR_NO_MEM;
432     }
433
434     protoble_internal->g_nu_lookup_count = config->nu_lookup_count;
435     protoble_internal->g_nu_lookup = malloc(config->nu_lookup_count * sizeof(name_uuid128_t));
436     if (protoble_internal->g_nu_lookup == NULL) {
437         ESP_LOGE(TAG, "Error allocating internal name UUID table");
438         protocomm_ble_cleanup();
439         return ESP_ERR_NO_MEM;
440     }
441
442     for (unsigned i = 0; i < protoble_internal->g_nu_lookup_count; i++) {
443         memcpy(protoble_internal->g_nu_lookup[i].uuid128, config->service_uuid, ESP_UUID_LEN_128);
444         memcpy((uint8_t *)uuid128_to_16(protoble_internal->g_nu_lookup[i].uuid128),
445                &config->nu_lookup[i].uuid, ESP_UUID_LEN_16);
446
447         protoble_internal->g_nu_lookup[i].name = strdup(config->nu_lookup[i].name);
448         if (protoble_internal->g_nu_lookup[i].name == NULL) {
449             ESP_LOGE(TAG, "Error allocating internal name UUID entry");
450             protocomm_ble_cleanup();
451             return ESP_ERR_NO_MEM;
452         }
453     }
454
455     pc->add_endpoint = protocomm_ble_add_endpoint;
456     pc->remove_endpoint = protocomm_ble_remove_endpoint;
457     protoble_internal->pc_ble = pc;
458     protoble_internal->gatt_mtu = ESP_GATT_DEF_BLE_MTU_SIZE;
459
460     /* The BLE advertisement data (max 31 bytes) consists of:
461      * 1) Flags -
462      *      Size : length (1 byte) + type (1 byte) + value (1 byte) = 3 bytes
463      * 2) Complete 128 bit UUID of the service -
464      *      Size : length (1 byte) + type (1 byte) + value (16 bytes) = 18 bytes
465      *
466      * Remaining 31 - (3 + 18) = 10 bytes could be used for manufacturer data
467      * or something else in the future.
468      */
469     raw_data_info_t adv_data[] = {
470         {   /* Flags */
471             .type   = ESP_BLE_AD_TYPE_FLAG,
472             .length = sizeof(ble_advertisement_flags),
473             .data_p = (uint8_t *) &ble_advertisement_flags
474         },
475         {   /* 128 bit Service UUID */
476             .type   = ESP_BLE_AD_TYPE_128SRV_CMPL,
477             .length = ESP_UUID_LEN_128,
478             .data_p = (uint8_t *) config->service_uuid
479         },
480     };
481
482     /* Get the total raw data length required for above entries */
483     uint8_t adv_data_len = 0;
484     for (uint8_t i = 0; i < (sizeof(adv_data)/sizeof(adv_data[0])); i++) {
485         /* Add extra bytes required per entry, i.e.
486          * length (1 byte) + type (1 byte) = 2 bytes */
487         adv_data_len += adv_data[i].length + 2;
488     }
489     if (adv_data_len > ESP_BLE_ADV_DATA_LEN_MAX) {
490         ESP_LOGE(TAG, "Advertisement data too long = %d bytes", adv_data_len);
491         protocomm_ble_cleanup();
492         return ESP_ERR_NO_MEM;
493     }
494
495     /* Allocate memory for the raw advertisement data */
496     protoble_internal->raw_adv_data_len = adv_data_len;
497     protoble_internal->raw_adv_data_p = malloc(adv_data_len);
498     if (protoble_internal->raw_adv_data_p == NULL) {
499         ESP_LOGE(TAG, "Error allocating memory for raw advertisement data");
500         protocomm_ble_cleanup();
501         return ESP_ERR_NO_MEM;
502     }
503
504     /* Form the raw advertisement data using above entries */
505     for (uint8_t i = 0, len = 0; i < (sizeof(adv_data)/sizeof(adv_data[0])); i++) {
506         protoble_internal->raw_adv_data_p[len++] = adv_data[i].length + 1; // + 1 byte for type
507         protoble_internal->raw_adv_data_p[len++] = adv_data[i].type;
508         memcpy(&protoble_internal->raw_adv_data_p[len],
509                adv_data[i].data_p, adv_data[i].length);
510
511         if (adv_data[i].type == ESP_BLE_AD_TYPE_128SRV_CMPL) {
512             /* Remember where the primary service UUID is kept in the
513              * raw advertisement data, so that it can be used while
514              * populating the GATT database
515              */
516             protoble_internal->service_uuid = &protoble_internal->raw_adv_data_p[len];
517         }
518
519         len += adv_data[i].length;
520     }
521
522     size_t ble_devname_len = strlen(protocomm_ble_device_name);
523     /* The BLE scan response (31 bytes) consists of:
524      * 1) Device name (complete / incomplete) -
525      *      Size : The maximum supported name length
526      *              will be 31 - 2 (length + type) = 29 bytes
527      *
528      * Any remaining space may be used for accommodating
529      * other fields in the future
530      */
531     raw_data_info_t scan_resp_data[] = {
532         {   /* If full device name can fit in the scan response then indicate
533              * that by setting type to "Complete Name", else set it to "Short Name"
534              * so that client can fetch full device name - after connecting - by
535              * reading the device name characteristic under GAP service */
536             .type   = (ble_devname_len > (ESP_BLE_SCAN_RSP_DATA_LEN_MAX - 2) ?
537                        ESP_BLE_AD_TYPE_NAME_SHORT : ESP_BLE_AD_TYPE_NAME_CMPL),
538             .length = MIN(ble_devname_len, (ESP_BLE_SCAN_RSP_DATA_LEN_MAX - 2)),
539             .data_p = (uint8_t *) protocomm_ble_device_name
540         },
541     };
542
543     /* Get the total raw scan response data length required for above entries */
544     uint8_t scan_resp_data_len = 0;
545     for (int i = 0; i < (sizeof(scan_resp_data)/sizeof(scan_resp_data[0])); i++) {
546         /* Add extra bytes required per entry, i.e.
547          * length (1 byte) + type (1 byte) = 2 bytes */
548         scan_resp_data_len += scan_resp_data[i].length + 2;
549     }
550     if (scan_resp_data_len > ESP_BLE_SCAN_RSP_DATA_LEN_MAX) {
551         ESP_LOGE(TAG, "Scan response data too long = %d bytes", scan_resp_data_len);
552         protocomm_ble_cleanup();
553         return ESP_ERR_NO_MEM;
554     }
555
556     /* Allocate memory for the raw scan response data */
557     protoble_internal->raw_scan_rsp_data_len = scan_resp_data_len;
558     protoble_internal->raw_scan_rsp_data_p = malloc(scan_resp_data_len);
559     if (protoble_internal->raw_scan_rsp_data_p == NULL) {
560         ESP_LOGE(TAG, "Error allocating memory for raw response data");
561         protocomm_ble_cleanup();
562         return ESP_ERR_NO_MEM;
563     }
564
565     /* Form the raw scan response data using above entries */
566     for (uint8_t i = 0, len = 0; i < (sizeof(scan_resp_data)/sizeof(scan_resp_data[0])); i++) {
567         protoble_internal->raw_scan_rsp_data_p[len++] = scan_resp_data[i].length + 1; // + 1 byte for type
568         protoble_internal->raw_scan_rsp_data_p[len++] = scan_resp_data[i].type;
569         memcpy(&protoble_internal->raw_scan_rsp_data_p[len],
570                scan_resp_data[i].data_p, scan_resp_data[i].length);
571         len += scan_resp_data[i].length;
572     }
573
574     simple_ble_cfg_t *ble_config = simple_ble_init();
575     if (ble_config == NULL) {
576         ESP_LOGE(TAG, "Ran out of memory for BLE config");
577         protocomm_ble_cleanup();
578         return ESP_ERR_NO_MEM;
579     }
580
581     /* Set function pointers required for simple BLE layer */
582     ble_config->read_fn         = transport_simple_ble_read;
583     ble_config->write_fn        = transport_simple_ble_write;
584     ble_config->exec_write_fn   = transport_simple_ble_exec_write;
585     ble_config->disconnect_fn   = transport_simple_ble_disconnect;
586     ble_config->connect_fn      = transport_simple_ble_connect;
587     ble_config->set_mtu_fn      = transport_simple_ble_set_mtu;
588
589     /* Set parameters required for advertising */
590     ble_config->adv_params      = adv_params;
591
592     ble_config->raw_adv_data_p        = protoble_internal->raw_adv_data_p;
593     ble_config->raw_adv_data_len      = protoble_internal->raw_adv_data_len;
594     ble_config->raw_scan_rsp_data_p   = protoble_internal->raw_scan_rsp_data_p;
595     ble_config->raw_scan_rsp_data_len = protoble_internal->raw_scan_rsp_data_len;
596
597     ble_config->device_name     = protocomm_ble_device_name;
598     ble_config->gatt_db_count   = populate_gatt_db(&ble_config->gatt_db);
599
600     if (ble_config->gatt_db_count == -1) {
601         ESP_LOGE(TAG, "Invalid GATT database count");
602         simple_ble_deinit();
603         protocomm_ble_cleanup();
604         return ESP_ERR_INVALID_STATE;
605     }
606
607     esp_err_t err = simple_ble_start(ble_config);
608     if (err != ESP_OK) {
609         ESP_LOGE(TAG, "simple_ble_start failed w/ error code 0x%x", err);
610         simple_ble_deinit();
611         protocomm_ble_cleanup();
612         return err;
613     }
614
615     prepare_write_env.prepare_buf = NULL;
616     ESP_LOGD(TAG, "Waiting for client to connect ......");
617     return ESP_OK;
618 }
619
620 esp_err_t protocomm_ble_stop(protocomm_t *pc)
621 {
622     if ((pc != NULL) &&
623         (protoble_internal != NULL ) &&
624         (pc == protoble_internal->pc_ble)) {
625         esp_err_t ret = ESP_OK;
626         ret = simple_ble_stop();
627         if (ret) {
628             ESP_LOGE(TAG, "BLE stop failed");
629         }
630         simple_ble_deinit();
631         protocomm_ble_cleanup();
632         return ret;
633     }
634     return ESP_ERR_INVALID_ARG;
635 }