xref: /nrf52832-nimble/packages/NimBLE-latest/apps/blecent/src/blecent.c (revision 042d53a763ad75cb1465103098bb88c245d95138)
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #include <assert.h>
21 #include <string.h>
22 
23 #include <rtthread.h>
24 
25 /* BLE */
26 #include "nimble/ble.h"
27 #include "host/ble_hs.h"
28 #include "host/util/util.h"
29 
30 /* HCI transport. */
31 #include "nimble/ble_hci_trans.h"
32 
33 /* Mandatory services. */
34 #include "services/gap/ble_svc_gap.h"
35 #include "services/gatt/ble_svc_gatt.h"
36 
37 /* Application-specified header. */
38 #include "blecent.h"
39 
40 static int blecent_gap_event(struct ble_gap_event *event, void *arg);
41 
42 /**
43  * Application callback.  Called when the read of the ANS Supported New Alert
44  * Category characteristic has completed.
45  */
46 static int
blecent_on_read(uint16_t conn_handle,const struct ble_gatt_error * error,struct ble_gatt_attr * attr,void * arg)47 blecent_on_read(uint16_t conn_handle,
48                 const struct ble_gatt_error *error,
49                 struct ble_gatt_attr *attr,
50                 void *arg)
51 {
52     MODLOG_DFLT(INFO, "Read complete; status=%d conn_handle=%d", error->status,
53                 conn_handle);
54     if (error->status == 0) {
55         MODLOG_DFLT(INFO, " attr_handle=%d value=", attr->handle);
56         print_mbuf(attr->om);
57     }
58     MODLOG_DFLT(INFO, "\n");
59 
60     return 0;
61 }
62 
63 /**
64  * Application callback.  Called when the write to the ANS Alert Notification
65  * Control Point characteristic has completed.
66  */
67 static int
blecent_on_write(uint16_t conn_handle,const struct ble_gatt_error * error,struct ble_gatt_attr * attr,void * arg)68 blecent_on_write(uint16_t conn_handle,
69                  const struct ble_gatt_error *error,
70                  struct ble_gatt_attr *attr,
71                  void *arg)
72 {
73     MODLOG_DFLT(INFO,
74                 "Write complete; status=%d conn_handle=%d attr_handle=%d\n",
75                 error->status, conn_handle, attr->handle);
76 
77     return 0;
78 }
79 
80 /**
81  * Application callback.  Called when the attempt to subscribe to notifications
82  * for the ANS Unread Alert Status characteristic has completed.
83  */
84 static int
blecent_on_subscribe(uint16_t conn_handle,const struct ble_gatt_error * error,struct ble_gatt_attr * attr,void * arg)85 blecent_on_subscribe(uint16_t conn_handle,
86                      const struct ble_gatt_error *error,
87                      struct ble_gatt_attr *attr,
88                      void *arg)
89 {
90     MODLOG_DFLT(INFO, "Subscribe complete; status=%d conn_handle=%d "
91                       "attr_handle=%d\n",
92                 error->status, conn_handle, attr->handle);
93 
94     return 0;
95 }
96 
97 /**
98  * Performs three concurrent GATT operations against the specified peer:
99  * 1. Reads the ANS Supported New Alert Category characteristic.
100  * 2. Writes the ANS Alert Notification Control Point characteristic.
101  * 3. Subscribes to notifications for the ANS Unread Alert Status
102  *    characteristic.
103  *
104  * If the peer does not support a required service, characteristic, or
105  * descriptor, then the peer lied when it claimed support for the alert
106  * notification service!  When this happens, or if a GATT procedure fails,
107  * this function immediately terminates the connection.
108  */
109 static void
blecent_read_write_subscribe(const struct peer * peer)110 blecent_read_write_subscribe(const struct peer *peer)
111 {
112     const struct peer_chr *chr;
113     const struct peer_dsc *dsc;
114     uint8_t value[2];
115     int rc;
116 
117     /* Read the supported-new-alert-category characteristic. */
118     chr = peer_chr_find_uuid(peer,
119                              BLE_UUID16_DECLARE(BLECENT_SVC_ALERT_UUID),
120                              BLE_UUID16_DECLARE(BLECENT_CHR_SUP_NEW_ALERT_CAT_UUID));
121     if (chr == NULL) {
122         MODLOG_DFLT(ERROR, "Error: Peer doesn't support the Supported New "
123                            "Alert Category characteristic\n");
124         goto err;
125     }
126 
127     rc = ble_gattc_read(peer->conn_handle, chr->chr.val_handle,
128                         blecent_on_read, NULL);
129     if (rc != 0) {
130         MODLOG_DFLT(ERROR, "Error: Failed to read characteristic; rc=%d\n",
131                     rc);
132         goto err;
133     }
134 
135     /* Write two bytes (99, 100) to the alert-notification-control-point
136      * characteristic.
137      */
138     chr = peer_chr_find_uuid(peer,
139                              BLE_UUID16_DECLARE(BLECENT_SVC_ALERT_UUID),
140                              BLE_UUID16_DECLARE(BLECENT_CHR_ALERT_NOT_CTRL_PT));
141     if (chr == NULL) {
142         MODLOG_DFLT(ERROR, "Error: Peer doesn't support the Alert "
143                            "Notification Control Point characteristic\n");
144         goto err;
145     }
146 
147     value[0] = 99;
148     value[1] = 100;
149     rc = ble_gattc_write_flat(peer->conn_handle, chr->chr.val_handle,
150                               value, sizeof value, blecent_on_write, NULL);
151     if (rc != 0) {
152         MODLOG_DFLT(ERROR, "Error: Failed to write characteristic; rc=%d\n",
153                     rc);
154     }
155 
156     /* Subscribe to notifications for the Unread Alert Status characteristic.
157      * A central enables notifications by writing two bytes (1, 0) to the
158      * characteristic's client-characteristic-configuration-descriptor (CCCD).
159      */
160     dsc = peer_dsc_find_uuid(peer,
161                              BLE_UUID16_DECLARE(BLECENT_SVC_ALERT_UUID),
162                              BLE_UUID16_DECLARE(BLECENT_CHR_UNR_ALERT_STAT_UUID),
163                              BLE_UUID16_DECLARE(BLE_GATT_DSC_CLT_CFG_UUID16));
164     if (dsc == NULL) {
165         MODLOG_DFLT(ERROR, "Error: Peer lacks a CCCD for the Unread Alert "
166                            "Status characteristic\n");
167         goto err;
168     }
169 
170     value[0] = 1;
171     value[1] = 0;
172     rc = ble_gattc_write_flat(peer->conn_handle, dsc->dsc.handle,
173                               value, sizeof value, blecent_on_subscribe, NULL);
174     if (rc != 0) {
175         MODLOG_DFLT(ERROR, "Error: Failed to subscribe to characteristic; "
176                            "rc=%d\n", rc);
177         goto err;
178     }
179 
180     return;
181 
182 err:
183     /* Terminate the connection. */
184     ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
185 }
186 
187 /**
188  * Called when service discovery of the specified peer has completed.
189  */
190 static void
blecent_on_disc_complete(const struct peer * peer,int status,void * arg)191 blecent_on_disc_complete(const struct peer *peer, int status, void *arg)
192 {
193 
194     if (status != 0) {
195         /* Service discovery failed.  Terminate the connection. */
196         MODLOG_DFLT(ERROR, "Error: Service discovery failed; status=%d "
197                            "conn_handle=%d\n", status, peer->conn_handle);
198         ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
199         return;
200     }
201 
202     /* Service discovery has completed successfully.  Now we have a complete
203      * list of services, characteristics, and descriptors that the peer
204      * supports.
205      */
206     MODLOG_DFLT(INFO, "Service discovery complete; status=%d "
207                        "conn_handle=%d\n", status, peer->conn_handle);
208 
209     /* Now perform three concurrent GATT procedures against the peer: read,
210      * write, and subscribe to notifications.
211      */
212     blecent_read_write_subscribe(peer);
213 }
214 
215 /**
216  * Initiates the GAP general discovery procedure.
217  */
218 static void
blecent_scan(void)219 blecent_scan(void)
220 {
221     uint8_t own_addr_type;
222     struct ble_gap_disc_params disc_params;
223     int rc;
224 
225     /* Figure out address to use while advertising (no privacy for now) */
226     rc = ble_hs_id_infer_auto(0, &own_addr_type);
227     if (rc != 0) {
228         MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
229         return;
230     }
231 
232     /* Tell the controller to filter duplicates; we don't want to process
233      * repeated advertisements from the same device.
234      */
235     disc_params.filter_duplicates = 1;
236 
237     /**
238      * Perform a passive scan.  I.e., don't send follow-up scan requests to
239      * each advertiser.
240      */
241     disc_params.passive = 1;
242 
243     /* Use defaults for the rest of the parameters. */
244     disc_params.itvl = 0;
245     disc_params.window = 0;
246     disc_params.filter_policy = 0;
247     disc_params.limited = 0;
248 
249     rc = ble_gap_disc(own_addr_type, BLE_HS_FOREVER, &disc_params,
250                       blecent_gap_event, NULL);
251     if (rc != 0) {
252         MODLOG_DFLT(ERROR, "Error initiating GAP discovery procedure; rc=%d\n",
253                     rc);
254     }
255 }
256 
257 /**
258  * Indicates whether we should tre to connect to the sender of the specified
259  * advertisement.  The function returns a positive result if the device
260  * advertises connectability and support for the Alert Notification service.
261  */
262 static int
blecent_should_connect(const struct ble_gap_disc_desc * disc)263 blecent_should_connect(const struct ble_gap_disc_desc *disc)
264 {
265     struct ble_hs_adv_fields fields;
266     int rc;
267     int i;
268 
269     /* The device has to be advertising connectability. */
270     if (disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_ADV_IND &&
271         disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) {
272 
273         return 0;
274     }
275 
276     rc = ble_hs_adv_parse_fields(&fields, disc->data, disc->length_data);
277     if (rc != 0) {
278         return rc;
279     }
280 
281     /* The device has to advertise support for the Alert Notification
282      * service (0x1811).
283      */
284     for (i = 0; i < fields.num_uuids16; i++) {
285         if (ble_uuid_u16(&fields.uuids16[i].u) == BLECENT_SVC_ALERT_UUID) {
286             return 1;
287         }
288     }
289 
290     return 0;
291 }
292 
293 /**
294  * Connects to the sender of the specified advertisement of it looks
295  * interesting.  A device is "interesting" if it advertises connectability and
296  * support for the Alert Notification service.
297  */
298 static void
blecent_connect_if_interesting(const struct ble_gap_disc_desc * disc)299 blecent_connect_if_interesting(const struct ble_gap_disc_desc *disc)
300 {
301     int rc;
302 
303     /* Don't do anything if we don't care about this advertiser. */
304     if (!blecent_should_connect(disc)) {
305         return;
306     }
307 
308     /* Scanning must be stopped before a connection can be initiated. */
309     rc = ble_gap_disc_cancel();
310     if (rc != 0) {
311         MODLOG_DFLT(DEBUG, "Failed to cancel scan; rc=%d\n", rc);
312         return;
313     }
314 
315     /* Try to connect the the advertiser.  Allow 30 seconds (30000 ms) for
316      * timeout.
317      */
318     rc = ble_gap_connect(BLE_OWN_ADDR_PUBLIC, &disc->addr, 30000, NULL,
319                          blecent_gap_event, NULL);
320     if (rc != 0) {
321         MODLOG_DFLT(ERROR, "Error: Failed to connect to device; addr_type=%d "
322                            "addr=%s\n",
323                     disc->addr.type, addr_str(disc->addr.val));
324         return;
325     }
326 }
327 
328 /**
329  * The nimble host executes this callback when a GAP event occurs.  The
330  * application associates a GAP event callback with each connection that is
331  * established.  blecent uses the same callback for all connections.
332  *
333  * @param event                 The event being signalled.
334  * @param arg                   Application-specified argument; unused by
335  *                                  blecent.
336  *
337  * @return                      0 if the application successfully handled the
338  *                                  event; nonzero on failure.  The semantics
339  *                                  of the return code is specific to the
340  *                                  particular GAP event being signalled.
341  */
342 static int
blecent_gap_event(struct ble_gap_event * event,void * arg)343 blecent_gap_event(struct ble_gap_event *event, void *arg)
344 {
345     struct ble_gap_conn_desc desc;
346     struct ble_hs_adv_fields fields;
347     int rc;
348 
349     switch (event->type) {
350     case BLE_GAP_EVENT_DISC:
351         rc = ble_hs_adv_parse_fields(&fields, event->disc.data,
352                                      event->disc.length_data);
353         if (rc != 0) {
354             return 0;
355         }
356 
357         /* An advertisment report was received during GAP discovery. */
358         print_adv_fields(&fields);
359 
360         /* Try to connect to the advertiser if it looks interesting. */
361         blecent_connect_if_interesting(&event->disc);
362         return 0;
363 
364     case BLE_GAP_EVENT_CONNECT:
365         /* A new connection was established or a connection attempt failed. */
366         if (event->connect.status == 0) {
367             /* Connection successfully established. */
368             MODLOG_DFLT(INFO, "Connection established ");
369 
370             rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
371             assert(rc == 0);
372             print_conn_desc(&desc);
373             MODLOG_DFLT(INFO, "\n");
374 
375             /* Remember peer. */
376             rc = peer_add(event->connect.conn_handle);
377             if (rc != 0) {
378                 MODLOG_DFLT(ERROR, "Failed to add peer; rc=%d\n", rc);
379                 return 0;
380             }
381 
382             /* Perform service discovery. */
383             rc = peer_disc_all(event->connect.conn_handle,
384                                blecent_on_disc_complete, NULL);
385             if (rc != 0) {
386                 MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc);
387                 return 0;
388             }
389         } else {
390             /* Connection attempt failed; resume scanning. */
391             MODLOG_DFLT(ERROR, "Error: Connection failed; status=%d\n",
392                         event->connect.status);
393             blecent_scan();
394         }
395 
396         return 0;
397 
398     case BLE_GAP_EVENT_DISCONNECT:
399         /* Connection terminated. */
400         MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
401         print_conn_desc(&event->disconnect.conn);
402         MODLOG_DFLT(INFO, "\n");
403 
404         /* Forget about peer. */
405         peer_delete(event->disconnect.conn.conn_handle);
406 
407         /* Resume scanning. */
408         blecent_scan();
409         return 0;
410 
411     case BLE_GAP_EVENT_DISC_COMPLETE:
412         MODLOG_DFLT(INFO, "discovery complete; reason=%d\n",
413                     event->disc_complete.reason);
414         return 0;
415 
416     case BLE_GAP_EVENT_ENC_CHANGE:
417         /* Encryption has been enabled or disabled for this connection. */
418         MODLOG_DFLT(INFO, "encryption change event; status=%d ",
419                     event->enc_change.status);
420         rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
421         assert(rc == 0);
422         print_conn_desc(&desc);
423         return 0;
424 
425     case BLE_GAP_EVENT_NOTIFY_RX:
426         /* Peer sent us a notification or indication. */
427         MODLOG_DFLT(INFO, "received %s; conn_handle=%d attr_handle=%d "
428                           "attr_len=%d\n",
429                     event->notify_rx.indication ?
430                         "indication" :
431                         "notification",
432                     event->notify_rx.conn_handle,
433                     event->notify_rx.attr_handle,
434                     OS_MBUF_PKTLEN(event->notify_rx.om));
435 
436         /* Attribute data is contained in event->notify_rx.attr_data. */
437         return 0;
438 
439     case BLE_GAP_EVENT_MTU:
440         MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
441                     event->mtu.conn_handle,
442                     event->mtu.channel_id,
443                     event->mtu.value);
444         return 0;
445 
446     case BLE_GAP_EVENT_REPEAT_PAIRING:
447         /* We already have a bond with the peer, but it is attempting to
448          * establish a new secure link.  This app sacrifices security for
449          * convenience: just throw away the old bond and accept the new link.
450          */
451 
452         /* Delete the old bond. */
453         rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
454         assert(rc == 0);
455         ble_store_util_delete_peer(&desc.peer_id_addr);
456 
457         /* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
458          * continue with the pairing operation.
459          */
460         return BLE_GAP_REPEAT_PAIRING_RETRY;
461 
462     default:
463         return 0;
464     }
465 }
466 
467 static void
blecent_on_reset(int reason)468 blecent_on_reset(int reason)
469 {
470     MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
471 }
472 
473 static void
blecent_on_sync(void)474 blecent_on_sync(void)
475 {
476     int rc;
477 
478     /* Make sure we have proper identity address set (public preferred) */
479     rc = ble_hs_util_ensure_addr(0);
480     assert(rc == 0);
481 
482     /* Begin scanning for a peripheral to connect to. */
483     blecent_scan();
484 }
485 
486 extern int nimble_ble_enable(void);
487 /**
488  * main
489  *
490  * All application logic and NimBLE host work is performed in default task.
491  *
492  * @return int NOTE: this function should never return!
493  */
blecent_entry(void)494 int blecent_entry(void)
495 {
496     int rc;
497 
498     /* Configure the host. */
499     ble_hs_cfg.reset_cb = blecent_on_reset;
500     ble_hs_cfg.sync_cb = blecent_on_sync;
501     ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
502 
503     /* Initialize data structures to track connected peers. */
504     rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64);
505     assert(rc == 0);
506 
507     /* Set the default device name. */
508     rc = ble_svc_gap_device_name_set("nimble-blecent");
509     assert(rc == 0);
510 
511     /* startup bluetooth host stack*/
512     ble_hs_thread_startup();
513 
514     return 0;
515 }
516 
517 MSH_CMD_EXPORT_ALIAS(blecent_entry, blecent, "bluetooth centrol role sample");
518