ble_main.c 19 KB
Newer Older
1 2 3 4 5 6 7
/* card10:
 * Copied from lib/sdk/Libraries/BTLE/stack/ble-profiles/sources/apps/fit/fit_main.c
 *
 * Also have a look at lib/sdk/Applications/EvKitExamples/BLE_fit/fit_main.c which has some changes
 * to this file regarding handling of OOB paring data
 *
 * This file contains some application logic taken from the "fit" example.
8 9 10 11 12
 *
 * Things have been renamed:
 * fit -> ble
 * Fit -> Ble
 * FIT -> BLE
13
 */
schneider's avatar
schneider committed
14 15
/* clang-format off */
/* clang-formet turned off for easier diffing against orginal file */
16
#include <stdio.h>
17 18 19
#include <string.h>
#include "wsf_types.h"
#include "util/bstream.h"
20
#include "fs_util.h"
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include "wsf_msg.h"
#include "wsf_trace.h"
#include "hci_api.h"
#include "dm_api.h"
#include "att_api.h"
#include "smp_api.h"
#include "app_api.h"
#include "app_db.h"
#include "app_ui.h"
#include "app_hw.h"
#include "svc_ch.h"
#include "svc_core.h"
#include "svc_hrs.h"
#include "svc_dis.h"
#include "svc_batt.h"
#include "svc_rscs.h"
#include "bas/bas_api.h"
#include "hrps/hrps_api.h"
#include "rscp/rscp_api.h"

41 42
#include "modules/log.h"

43 44 45 46 47
/**************************************************************************************************
  Macros
**************************************************************************************************/

/*! WSF message event starting value */
48
#define BLE_MSG_START               0xA0
49 50 51 52

/*! WSF message event enumeration */
enum
{
53
  BLE_BATT_TIMER_IND = BLE_MSG_START,                     /*! Battery measurement timer expired */
54 55 56 57 58 59 60 61 62 63 64 65 66
};

/**************************************************************************************************
  Data Types
**************************************************************************************************/

/*! Application message type */
typedef union
{
  wsfMsgHdr_t     hdr;
  dmEvt_t         dm;
  attsCccEvt_t    ccc;
  attEvt_t        att;
67
} bleMsg_t;
68 69 70 71 72 73

/**************************************************************************************************
  Configurable Parameters
**************************************************************************************************/

/*! configurable parameters for advertising */
74
static const appAdvCfg_t bleAdvCfg =
75
{
76
  {0,             0,              0},                  /*! Advertising durations in ms */
77
  {500/0.625,     4000/0.625,     0}                   /*! Advertising intervals in 0.625 ms units */
78 79 80
};

/*! configurable parameters for slave */
81
static const appSlaveCfg_t bleSlaveCfg =
82 83 84 85 86
{
  1,                                      /*! Maximum connections */
};

/*! configurable parameters for security */
87
static const appSecCfg_t bleSecCfg =
88 89 90 91 92 93 94 95 96
{
  DM_AUTH_BOND_FLAG | DM_AUTH_SC_FLAG,    /*! Authentication and bonding flags */
  0,                                      /*! Initiator key distribution flags */
  DM_KEY_DIST_LTK,                        /*! Responder key distribution flags */
  FALSE,                                  /*! TRUE if Out-of-band pairing data is present */
  TRUE                                    /*! TRUE to initiate security upon connection */
};

/*! configurable parameters for connection parameter update */
97
static const appUpdateCfg_t bleUpdateCfg =
98 99 100
{
  6000,                                   /*! Connection idle period in ms before attempting
                                              connection parameter update; set to zero to disable */
101 102
  800/1.25,                               /*! Minimum connection interval in 1.25ms units */
  1000/1.25,                              /*! Maximum connection interval in 1.25ms units */
103
  0,                                      /*! Connection latency */
104
  9000/10,                                /*! Supervision timeout in 10ms units */
105 106 107 108
  5                                       /*! Number of update attempts before giving up */
};

/*! battery measurement configuration */
109
static const basCfg_t bleBasCfg =
110 111 112 113 114 115 116
{
  30,       /*! Battery measurement timer expiration period in seconds */
  1,        /*! Perform battery measurement after this many timer periods */
  100       /*! Send battery level notification to peer when below this level. */
};

/*! SMP security parameter configuration */
117
static const smpCfg_t bleSmpCfg =
118 119
{
  3000,                                   /*! 'Repeated attempts' timeout in msec */
120
  SMP_IO_DISP_YES_NO,                     /*! I/O Capability */
121 122 123
  7,                                      /*! Minimum encryption key length */
  16,                                     /*! Maximum encryption key length */
  3,                                      /*! Attempts to trigger 'repeated attempts' timeout */
124
  DM_AUTH_MITM_FLAG,                      /*! Device authentication requirements */
125 126
};

127 128 129 130 131 132 133 134 135
/* Configuration structure */
static const attCfg_t bleAttCfg =
{
  15,                                  /* ATT server service discovery connection idle timeout in seconds */
  241,                                 /* desired ATT MTU */
  ATT_MAX_TRANS_TIMEOUT,               /* transaction timeout in seconds */
  1                                    /* number of queued prepare writes supported by server */
};

136 137 138 139 140
/**************************************************************************************************
  Advertising Data
**************************************************************************************************/

/*! advertising data, discoverable mode */
141
static const uint8_t bleAdvDataDisc[] =
142 143 144 145 146 147 148 149 150 151 152 153 154
{
  /*! flags */
  2,                                      /*! length */
  DM_ADV_TYPE_FLAGS,                      /*! AD type */
  DM_FLAG_LE_GENERAL_DISC |               /*! flags */
  DM_FLAG_LE_BREDR_NOT_SUP,

  /*! tx power */
  2,                                      /*! length */
  DM_ADV_TYPE_TX_POWER,                   /*! AD type */
  0,                                      /*! tx power */

  /*! service UUID list */
155
  5,                                      /*! length */
156 157 158 159 160 161
  DM_ADV_TYPE_16_UUID,                    /*! AD type */
  UINT16_TO_BYTES(ATT_UUID_DEVICE_INFO_SERVICE),
  UINT16_TO_BYTES(ATT_UUID_BATTERY_SERVICE)
};

/*! scan data, discoverable mode */
162
uint8_t bleScanDataDisc[] =
163 164
{
  /*! device name */
165
  14,                                      /*! length */
166
  DM_ADV_TYPE_LOCAL_NAME,                 /*! AD type */
167
  'c','a','r','d','1','0','-','0','0','0','0','0','0'
168 169 170 171 172 173 174 175 176
};

/**************************************************************************************************
  Client Characteristic Configuration Descriptors
**************************************************************************************************/

/*! enumeration of client characteristic configuration descriptors */
enum
{
177 178 179
  BLE_GATT_SC_CCC_IDX,                    /*! GATT service, service changed characteristic */
  BLE_BATT_LVL_CCC_IDX,                   /*! Battery service, battery level characteristic */
  BLE_NUM_CCC_IDX
180 181 182
};

/*! client characteristic configuration descriptors settings, indexed by above enumeration */
183
static const attsCccSet_t bleCccSet[BLE_NUM_CCC_IDX] =
184 185
{
  /* cccd handle          value range               security level */
186 187
  {GATT_SC_CH_CCC_HDL,    ATT_CLIENT_CFG_INDICATE,  DM_SEC_LEVEL_NONE},   /* BLE_GATT_SC_CCC_IDX */
  {BATT_LVL_CH_CCC_HDL,   ATT_CLIENT_CFG_NOTIFY,    DM_SEC_LEVEL_NONE},   /* BLE_BATT_LVL_CCC_IDX */
188 189 190 191 192 193 194
};

/**************************************************************************************************
  Global Variables
**************************************************************************************************/

/*! WSF handler ID */
195
wsfHandlerId_t bleHandlerId;
196 197


198
static void BleHandler(wsfEventMask_t event, wsfMsgHdr_t *pMsg);
199 200 201 202 203 204 205 206 207
/*************************************************************************************************/
/*!
 *  \brief  Application DM callback.
 *
 *  \param  pDmEvt  DM callback event
 *
 *  \return None.
 */
/*************************************************************************************************/
208
static void bleDmCback(dmEvt_t *pDmEvt)
209 210 211 212 213 214 215 216 217
{
  dmEvt_t *pMsg;
  uint16_t len;

  len = DmSizeOfEvt(pDmEvt);

  if ((pMsg = WsfMsgAlloc(len)) != NULL)
  {
    memcpy(pMsg, pDmEvt, len);
218
    WsfMsgSend(bleHandlerId, pMsg);
219 220 221 222 223 224 225 226 227 228 229 230
  }
}

/*************************************************************************************************/
/*!
 *  \brief  Application ATT callback.
 *
 *  \param  pEvt    ATT callback event
 *
 *  \return None.
 */
/*************************************************************************************************/
231
static void bleAttCback(attEvt_t *pEvt)
232 233 234 235 236 237 238 239
{
  attEvt_t *pMsg;

  if ((pMsg = WsfMsgAlloc(sizeof(attEvt_t) + pEvt->valueLen)) != NULL)
  {
    memcpy(pMsg, pEvt, sizeof(attEvt_t));
    pMsg->pValue = (uint8_t *) (pMsg + 1);
    memcpy(pMsg->pValue, pEvt->pValue, pEvt->valueLen);
240
    WsfMsgSend(bleHandlerId, pMsg);
241 242 243 244 245 246 247 248 249 250 251 252
  }
}

/*************************************************************************************************/
/*!
 *  \brief  Application ATTS client characteristic configuration callback.
 *
 *  \param  pDmEvt  DM callback event
 *
 *  \return None.
 */
/*************************************************************************************************/
253
static void bleCccCback(attsCccEvt_t *pEvt)
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
{
  attsCccEvt_t  *pMsg;
  appDbHdl_t    dbHdl;

  /* if CCC not set from initialization and there's a device record */
  if ((pEvt->handle != ATT_HANDLE_NONE) &&
      ((dbHdl = AppDbGetHdl((dmConnId_t) pEvt->hdr.param)) != APP_DB_HDL_NONE))
  {
    /* store value in device database */
    AppDbSetCccTblValue(dbHdl, pEvt->idx, pEvt->value);
  }

  if ((pMsg = WsfMsgAlloc(sizeof(attsCccEvt_t))) != NULL)
  {
    memcpy(pMsg, pEvt, sizeof(attsCccEvt_t));
269
    WsfMsgSend(bleHandlerId, pMsg);
270 271 272 273 274 275 276 277 278 279 280 281 282 283
  }
}



/*************************************************************************************************/
/*!
 *  \brief  Process CCC state change.
 *
 *  \param  pMsg    Pointer to message.
 *
 *  \return None.
 */
/*************************************************************************************************/
284
static void bleProcCccState(bleMsg_t *pMsg)
285 286 287 288
{
  APP_TRACE_INFO3("ccc state ind value:%d handle:%d idx:%d", pMsg->ccc.value, pMsg->ccc.handle, pMsg->ccc.idx);

  /* handle battery level CCC */
289
  if (pMsg->ccc.idx == BLE_BATT_LVL_CCC_IDX)
290 291 292
  {
    if (pMsg->ccc.value == ATT_CLIENT_CFG_NOTIFY)
    {
293
      BasMeasBattStart((dmConnId_t) pMsg->ccc.hdr.param, BLE_BATT_TIMER_IND, BLE_BATT_LVL_CCC_IDX);
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    }
    else
    {
      BasMeasBattStop((dmConnId_t) pMsg->ccc.hdr.param);
    }
    return;
  }
}

/*************************************************************************************************/
/*!
 *  \brief  Perform UI actions on connection close.
 *
 *  \param  pMsg    Pointer to message.
 *
 *  \return None.
 */
/*************************************************************************************************/
312
static void bleClose(bleMsg_t *pMsg)
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
{
  /* stop battery measurement */
  BasMeasBattStop((dmConnId_t) pMsg->hdr.param);
}

/*************************************************************************************************/
/*!
 *  \brief  Set up advertising and other procedures that need to be performed after
 *          device reset.
 *
 *  \param  pMsg    Pointer to message.
 *
 *  \return None.
 */
/*************************************************************************************************/
328
static void bleSetup(bleMsg_t *pMsg)
329
{
330
  char buf[32];
331
  char a, b, c, d, e, f, K;
332 333 334

  if (fs_read_text_file("mac.txt", buf, sizeof(buf)))
  {
335
    if (sscanf(buf, "%c%c:%c%c:%c%c:%c%c:%c%c:%c%c", &K,&K,&K,&K,&K,&K, &a, &b, &c, &d, &e, &f) == 12)
336 337 338 339 340 341 342 343 344 345
    {
      bleScanDataDisc[9]  = a;
      bleScanDataDisc[10] = b;
      bleScanDataDisc[11] = c;
      bleScanDataDisc[12] = d;
      bleScanDataDisc[13] = e;
      bleScanDataDisc[14] = f;
    }
  }
  
346
  /* set advertising and scan response data for discoverable mode */
347 348
  AppAdvSetData(APP_ADV_DATA_DISCOVERABLE, sizeof(bleAdvDataDisc), (uint8_t *) bleAdvDataDisc);
  AppAdvSetData(APP_SCAN_DATA_DISCOVERABLE, sizeof(bleScanDataDisc), (uint8_t *) bleScanDataDisc);
349 350 351 352 353

  /* set advertising and scan response data for connectable mode */
  AppAdvSetData(APP_ADV_DATA_CONNECTABLE, 0, NULL);
  AppAdvSetData(APP_SCAN_DATA_CONNECTABLE, 0, NULL);

354 355
#if 0
  /* TODO: card10: until we have an BLE dialog, be discoverable and bondable always */
356 357
  /* start advertising; automatically set connectable/discoverable mode and bondable mode */
  AppAdvStart(APP_MODE_AUTO_INIT);
358 359 360 361 362
#else
  /* enter discoverable and bondable mode mode by default */
  AppSetBondable(TRUE);
  AppAdvStart(APP_MODE_DISCOVERABLE);
#endif
363 364 365 366 367 368 369 370 371 372 373 374
}


/*************************************************************************************************/
/*!
 *  \brief  Process messages from the event handler.
 *
 *  \param  pMsg    Pointer to message.
 *
 *  \return None.
 */
/*************************************************************************************************/
375
static void bleProcMsg(bleMsg_t *pMsg)
376 377
{
  uint8_t uiEvent = APP_UI_NONE;
378
  hciLeConnCmplEvt_t *connOpen;
379 380 381

  switch(pMsg->hdr.event)
  {
382
    case BLE_BATT_TIMER_IND:
383 384 385 386 387 388 389 390
      BasProcMsg(&pMsg->hdr);
      break;

    case ATTS_HANDLE_VALUE_CNF:
      BasProcMsg(&pMsg->hdr);
      break;

    case ATTS_CCC_STATE_IND:
391
      bleProcCccState(pMsg);
392 393 394 395
      break;

    case DM_RESET_CMPL_IND:
      DmSecGenerateEccKeyReq();
396
      bleSetup(pMsg);
397 398 399 400
      uiEvent = APP_UI_RESET_CMPL;
      break;

    case DM_ADV_START_IND:
401
      LOG_INFO("ble", "Advertisement started");
402 403 404 405
      uiEvent = APP_UI_ADV_START;
      break;

    case DM_ADV_STOP_IND:
406
      LOG_INFO("ble", "Advertisement stopped");
407 408 409 410
      uiEvent = APP_UI_ADV_STOP;
      break;

    case DM_CONN_OPEN_IND:
411 412 413 414 415
      connOpen = &pMsg->dm.connOpen;
      LOG_INFO("ble", "connection from %02X:%02X:%02X:%02X:%02X:%02X opened",
               connOpen->peerAddr[0], connOpen->peerAddr[1],
               connOpen->peerAddr[2], connOpen->peerAddr[3],
               connOpen->peerAddr[4], connOpen->peerAddr[5]);
416 417 418 419 420
      BasProcMsg(&pMsg->hdr);
      uiEvent = APP_UI_CONN_OPEN;
      break;

    case DM_CONN_CLOSE_IND:
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
      switch (pMsg->dm.connClose.reason)
      {
        case HCI_ERR_CONN_TIMEOUT:
          LOG_INFO("ble", "Connection closed (0x%02X), Connection timeout",
                   pMsg->dm.connClose.reason);
          break;
        case HCI_ERR_LOCAL_TERMINATED:
          LOG_INFO("ble", "Connection closed (0x%02X), Connection terminated by local host",
                   pMsg->dm.connClose.reason);
          break;
        case HCI_ERR_REMOTE_TERMINATED:
          LOG_INFO("ble", "Connection closed (0x%02X), Remote user terminated connection",
                   pMsg->dm.connClose.reason);
          break;
        case HCI_ERR_CONN_FAIL:
          LOG_INFO("ble", "Connection closed (0x%02X), Connection failed to be established",
                   pMsg->dm.connClose.reason);
          break;
        case HCI_ERR_MIC_FAILURE:
          LOG_INFO("ble", "Connection closed (0x%02X), Connection terminated due to MIC failure",
                   pMsg->dm.connClose.reason);
          break;
        default:
          LOG_INFO("ble", "Connection closed (0x%02X)",
                   pMsg->dm.connClose.reason);
          break;
      }
448
      bleClose(pMsg);
449 450 451 452
      uiEvent = APP_UI_CONN_CLOSE;
      break;

    case DM_SEC_PAIR_CMPL_IND:
453 454
      LOG_INFO("ble", "Secure pairing successful, auth: 0x%02X",
               pMsg->dm.pairCmpl.auth);
455 456 457 458
      uiEvent = APP_UI_SEC_PAIR_CMPL;
      break;

    case DM_SEC_PAIR_FAIL_IND:
459 460 461 462 463 464 465 466 467 468 469 470 471 472
      switch (pMsg->hdr.status) {
        case SMP_ERR_TIMEOUT:
          LOG_INFO("ble", "Secure pairing failed (0x%02X), Transaction timeout",
                   pMsg->hdr.status);
          break;
        case SMP_ERR_ATTEMPTS:
          LOG_INFO("ble", "Secure pairing failed (0x%02X), Repeated attempts",
                   pMsg->hdr.status);
          break;
        default:
          LOG_INFO("ble", "Secure pairing failed (0x%02X)",
                   pMsg->hdr.status);
          break;
      }
473 474 475 476
      uiEvent = APP_UI_SEC_PAIR_FAIL;
      break;

    case DM_SEC_ENCRYPT_IND:
477
      LOG_INFO("ble", "Encrypted handshake successful");
478 479 480 481
      uiEvent = APP_UI_SEC_ENCRYPT;
      break;

    case DM_SEC_ENCRYPT_FAIL_IND:
482
      LOG_INFO("ble", "Encrypted handshake failed");
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
      uiEvent = APP_UI_SEC_ENCRYPT_FAIL;
      break;

    case DM_SEC_AUTH_REQ_IND:
      AppHandlePasskey(&pMsg->dm.authReq);
      break;

    case DM_SEC_ECC_KEY_IND:
      DmSecSetEccKey(&pMsg->dm.eccMsg.data.key);
      break;

    case DM_SEC_COMPARE_IND:
      AppHandleNumericComparison(&pMsg->dm.cnfInd);
      break;

    case DM_HW_ERROR_IND:
499
      LOG_ERR("ble", "HW Error");
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
      uiEvent = APP_UI_HW_ERROR;
      break;

    default:
      break;
  }

  if (uiEvent != APP_UI_NONE)
  {
    AppUiAction(uiEvent);
  }
}

/*************************************************************************************************/
/*!
 *  \brief  Application handler init function called during system initialization.
 *
 *  \param  handlerID  WSF handler ID.
 *
 *  \return None.
 */
/*************************************************************************************************/
522
static void BleHandlerInit(void)
523
{
524
  APP_TRACE_INFO0("BleHandlerInit");
525 526

  /* store handler ID */
527
  bleHandlerId =WsfOsSetNextHandler(BleHandler);
528 529

  /* Set configuration pointers */
530 531 532 533
  pAppAdvCfg = (appAdvCfg_t *) &bleAdvCfg;
  pAppSlaveCfg = (appSlaveCfg_t *) &bleSlaveCfg;
  pAppSecCfg = (appSecCfg_t *) &bleSecCfg;
  pAppUpdateCfg = (appUpdateCfg_t *) &bleUpdateCfg;
534 535 536 537 538

  /* Initialize application framework */
  AppSlaveInit();

  /* Set stack configuration pointers */
539
  pSmpCfg = (smpCfg_t *) &bleSmpCfg;
540
  pAttCfg = (attCfg_t *) &bleAttCfg;
541 542

  /* initialize battery service server */
543
  BasInit(bleHandlerId, (basCfg_t *) &bleBasCfg);
544 545 546 547 548 549 550 551 552 553 554 555
}

/*************************************************************************************************/
/*!
 *  \brief  WSF event handler for application.
 *
 *  \param  event   WSF event mask.
 *  \param  pMsg    WSF message.
 *
 *  \return None.
 */
/*************************************************************************************************/
556
static void BleHandler(wsfEventMask_t event, wsfMsgHdr_t *pMsg)
557 558 559
{
  if (pMsg != NULL)
  {
560
    APP_TRACE_INFO1("Ble got evt %d", pMsg->event);
561 562 563 564 565 566 567 568 569 570 571

    if (pMsg->event >= DM_CBACK_START && pMsg->event <= DM_CBACK_END)
    {
      /* process advertising and connection-related messages */
      AppSlaveProcDmMsg((dmEvt_t *) pMsg);

      /* process security-related messages */
      AppSlaveSecProcDmMsg((dmEvt_t *) pMsg);
    }

    /* perform profile and user interface-related operations */
572
    bleProcMsg((bleMsg_t *) pMsg);
573 574 575 576 577 578 579 580 581 582
  }
}

/*************************************************************************************************/
/*!
 *  \brief  Start the application.
 *
 *  \return None.
 */
/*************************************************************************************************/
583
void BleStart(void)
584
{
schneider's avatar
schneider committed
585

586
  BleHandlerInit();
schneider's avatar
schneider committed
587

588
  /* Register for stack callbacks */
589 590 591
  DmRegister(bleDmCback);
  DmConnRegister(DM_CLIENT_ID_APP, bleDmCback);
  AttRegister(bleAttCback);
592
  AttConnRegister(AppServerConnCback);
593
  AttsCccRegister(BLE_NUM_CCC_IDX, (attsCccSet_t *) bleCccSet, bleCccCback);
594 595 596

  /* Initialize attribute server database */
  SvcCoreAddGroup();
597
  SvcDisAddGroup(); // Device Information Service
598 599 600 601 602 603
  SvcBattCbackRegister(BasReadCback, NULL);
  SvcBattAddGroup();

  /* Reset the device */
  DmDevReset();
}
schneider's avatar
schneider committed
604
/* clang-format on */