1 /** 2 * Arduino Wrapper for BTstack 3 */ 4 5 #include <Arduino.h> 6 #include <SPI.h> 7 8 #ifdef __AVR__ 9 #include <avr/wdt.h> 10 #endif 11 12 #if __arm__ 13 #include <Reset.h> // also provides NVIC_SystemReset 14 #endif 15 16 #include "BTstack.h" 17 18 #include "btstack_memory.h" 19 #include "hal_tick.h" 20 #include "hal_cpu.h" 21 #include "hci_cmds.h" 22 #include "utils.h" 23 #include "run_loop.h" 24 #include "sdp_util.h" 25 26 #include "bt_control_em9301.h" 27 #include "hci.h" 28 #include "hci_dump.h" 29 #include "l2cap.h" 30 #include "ad_parser.h" 31 #include "att.h" 32 #include "att_server.h" 33 #include "att_db_util.h" 34 #include "le_device_db.h" 35 #include "sm.h" 36 #include "gap_le.h" 37 #include "debug.h" 38 39 // Pin 13 has an LED connected on most Arduino boards. 40 #define PIN_LED 13 41 42 // prototypes 43 extern "C" void embedded_execute_once(void); 44 extern "C" void hal_uart_dma_process(void); 45 46 enum { 47 SET_ADVERTISEMENT_PARAMS = 1 << 0, 48 SET_ADVERTISEMENT_DATA = 1 << 1, 49 SET_ADVERTISEMENT_ENABLED = 1 << 2, 50 }; 51 52 typedef enum gattAction { 53 gattActionWrite, 54 gattActionSubscribe, 55 gattActionUnsubscribe, 56 gattActionServiceQuery, 57 gattActionCharacteristicQuery, 58 gattActionRead, 59 } gattAction_t; 60 61 static gattAction_t gattAction; 62 63 // btstack state 64 static int btstack_state; 65 66 static const uint8_t iBeaconAdvertisement01[] = { 0x02, 0x01 }; 67 static const uint8_t iBeaconAdvertisement38[] = { 0x1a, 0xff, 0x4c, 0x00, 0x02, 0x15 }; 68 static uint8_t adv_data[31]; 69 static uint16_t adv_data_len = 0; 70 static uint16_t gatt_client_id; 71 static int gatt_is_characteristics_query; 72 73 static uint16_t le_peripheral_todos = 0; 74 static bool have_custom_addr; 75 static bd_addr_t public_bd_addr; 76 77 static timer_source_t connection_timer; 78 79 static void (*bleAdvertismentCallback)(BLEAdvertisement * bleAdvertisement) = NULL; 80 static void (*bleDeviceConnectedCallback)(BLEStatus status, BLEDevice * device)= NULL; 81 static void (*bleDeviceDisconnectedCallback)(BLEDevice * device) = NULL; 82 static void (*gattServiceDiscoveredCallback)(BLEStatus status, BLEDevice * device, BLEService * bleService) = NULL; 83 static void (*gattCharacteristicDiscoveredCallback)(BLEStatus status, BLEDevice * device, BLECharacteristic * characteristic) = NULL; 84 static void (*gattCharacteristicNotificationCallback)(BLEDevice * device, uint16_t value_handle, uint8_t* value, uint16_t length) = NULL; 85 static void (*gattCharacteristicIndicationCallback)(BLEDevice * device, uint16_t value_handle, uint8_t* value, uint16_t length) = NULL; 86 static void (*gattCharacteristicReadCallback)(BLEStatus status, BLEDevice * device, uint8_t * value, uint16_t length) = NULL; 87 static void (*gattCharacteristicWrittenCallback)(BLEStatus status, BLEDevice * device) = NULL; 88 static void (*gattCharacteristicSubscribedCallback)(BLEStatus status, BLEDevice * device) = NULL; 89 static void (*gattCharacteristicUnsubscribedCallback)(BLEStatus status, BLEDevice * device) = NULL; 90 91 92 // retarget printf to Serial 93 #ifdef ENERGIA 94 extern "C" int putchar(int c) { 95 Serial.write((uint8_t)c); 96 return c; 97 } 98 #else 99 #ifdef __AVR__ 100 static FILE uartout = {0} ; 101 static int uart_putchar (char c, FILE *stream) { 102 Serial.write(c); 103 return 0; 104 } 105 #endif 106 // added for Arduino Zero. Arduino Due already has tis own _write(..) implementation 107 // in /Users/mringwal/Library/Arduino15/packages/arduino/hardware/sam/1.6.4/cores/arduino/syscalls_sam3.c 108 #if defined(__SAMD21G18A__) 109 // #ifdef __arm__ 110 extern "C" int _write(int file, char *ptr, int len){ 111 int i; 112 for (i = 0; i < len; i++) { 113 if (ptr[i] == '\n') { 114 Serial.write((uint8_t)'\r'); 115 } 116 Serial.write((uint8_t)ptr[i]); 117 } 118 return i; 119 } 120 #endif 121 #endif 122 123 // HAL CPU Implementation 124 extern "C" void hal_cpu_disable_irqs(void){ } 125 extern "C" void hal_cpu_enable_irqs(void) { } 126 extern "C" void hal_cpu_enable_irqs_and_sleep(void) { } 127 128 // 129 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 130 131 bd_addr_t addr; 132 uint16_t handle; 133 134 switch (packet_type) { 135 136 case HCI_EVENT_PACKET: 137 switch (packet[0]) { 138 139 case BTSTACK_EVENT_STATE: 140 btstack_state = packet[2]; 141 // bt stack activated, get started 142 if (packet[2] == HCI_STATE_WORKING) { 143 le_peripheral_todos |= SET_ADVERTISEMENT_PARAMS 144 | SET_ADVERTISEMENT_DATA 145 | SET_ADVERTISEMENT_ENABLED; 146 } 147 break; 148 149 case HCI_EVENT_DISCONNECTION_COMPLETE: 150 if (bleDeviceDisconnectedCallback) { 151 handle = READ_BT_16(packet, 3); 152 BLEDevice device(handle); 153 (*bleDeviceDisconnectedCallback)(&device); 154 } 155 le_peripheral_todos |= SET_ADVERTISEMENT_ENABLED; 156 break; 157 158 case GAP_LE_ADVERTISING_REPORT: { 159 if (bleAdvertismentCallback) { 160 BLEAdvertisement advertisement(packet); 161 (*bleAdvertismentCallback)(&advertisement); 162 } 163 break; 164 } 165 166 case HCI_EVENT_COMMAND_COMPLETE: 167 if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) { 168 bt_flip_addr(addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]); 169 printf("Local Address: %s\n", bd_addr_to_str(addr)); 170 break; 171 } 172 break; 173 174 case HCI_EVENT_LE_META: 175 switch (packet[2]) { 176 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 177 handle = READ_BT_16(packet, 4); 178 printf("Connection complete, handle 0x%04x\n", handle); 179 run_loop_remove_timer(&connection_timer); 180 if (!bleDeviceConnectedCallback) break; 181 if (packet[3]){ 182 (*bleDeviceConnectedCallback)(BLE_STATUS_CONNECTION_ERROR, NULL); 183 } else { 184 BLEDevice device(handle); 185 (*bleDeviceConnectedCallback)(BLE_STATUS_OK, &device); 186 } 187 break; 188 default: 189 break; 190 } 191 break; 192 } 193 } 194 // if (client_packet_handler){ 195 // (*client_packet_handler)(packet_type, channel, packet, size); 196 // } 197 } 198 199 static void extract_service(le_service_t * service, uint8_t * packet){ 200 service->start_group_handle = READ_BT_16(packet, 4); 201 service->end_group_handle = READ_BT_16(packet, 6); 202 service->uuid16 = 0; 203 swap128(&packet[8], service->uuid128); 204 if (sdp_has_blueooth_base_uuid(service->uuid128)){ 205 service->uuid16 = READ_NET_32(service->uuid128, 0); 206 } 207 } 208 209 static void extract_characteristic(le_characteristic_t * characteristic, uint8_t * packet){ 210 characteristic->start_handle = READ_BT_16(packet, 4); 211 characteristic->value_handle = READ_BT_16(packet, 6); 212 characteristic->end_handle = READ_BT_16(packet, 8); 213 characteristic->properties = READ_BT_16(packet, 10); 214 characteristic->uuid16 = 0; 215 swap128(&packet[12], characteristic->uuid128); 216 if (sdp_has_blueooth_base_uuid(characteristic->uuid128)){ 217 characteristic->uuid16 = READ_NET_32(characteristic->uuid128, 0); 218 } 219 } 220 221 static void gatt_client_callback(uint8_t packet_type, uint8_t * packet, uint16_t size){ 222 223 // if (hci) event is not 4-byte aligned, event->handle causes crash 224 // workaround: check event type, assuming GATT event types are contagious 225 if (packet[0] < GATT_QUERY_COMPLETE) return; 226 if (packet[0] > GATT_MTU) return; 227 228 uint16_t con_handle = READ_BT_16(packet, 2); 229 uint8_t status; 230 uint8_t * value; 231 uint16_t value_handle; 232 uint16_t value_length; 233 234 BLEDevice device(con_handle); 235 switch(packet[0]){ 236 case GATT_SERVICE_QUERY_RESULT: 237 if (gattServiceDiscoveredCallback) { 238 le_service_t service; 239 extract_service(&service, packet); 240 BLEService bleService(service); 241 (*gattServiceDiscoveredCallback)(BLE_STATUS_OK, &device, &bleService); 242 } 243 break; 244 case GATT_CHARACTERISTIC_QUERY_RESULT: 245 if (gattCharacteristicDiscoveredCallback){ 246 le_characteristic_t characteristic; 247 extract_characteristic(&characteristic, packet); 248 BLECharacteristic bleCharacteristic(characteristic); 249 (*gattCharacteristicDiscoveredCallback)(BLE_STATUS_OK, &device, &bleCharacteristic); 250 } 251 break; 252 case GATT_QUERY_COMPLETE: 253 status = READ_BT_16(packet, 4); 254 switch (gattAction){ 255 case gattActionWrite: 256 if (gattCharacteristicWrittenCallback) gattCharacteristicWrittenCallback(status ? BLE_STATUS_OTHER_ERROR : BLE_STATUS_OK, &device); 257 break; 258 case gattActionSubscribe: 259 if (gattCharacteristicSubscribedCallback) gattCharacteristicSubscribedCallback(status ? BLE_STATUS_OTHER_ERROR : BLE_STATUS_OK, &device); 260 break; 261 case gattActionUnsubscribe: 262 if (gattCharacteristicUnsubscribedCallback) gattCharacteristicUnsubscribedCallback(status ? BLE_STATUS_OTHER_ERROR : BLE_STATUS_OK, &device); 263 break; 264 case gattActionServiceQuery: 265 if (gattServiceDiscoveredCallback) gattServiceDiscoveredCallback(BLE_STATUS_DONE, &device, NULL); 266 break; 267 case gattActionCharacteristicQuery: 268 if (gattCharacteristicDiscoveredCallback) gattCharacteristicDiscoveredCallback(BLE_STATUS_DONE, &device, NULL); 269 break; 270 default: 271 break; 272 }; 273 break; 274 case GATT_NOTIFICATION: 275 if (gattCharacteristicNotificationCallback) { 276 value_handle = READ_BT_16(packet, 4); 277 value_length = READ_BT_16(packet, 6); 278 value = &packet[8]; 279 (*gattCharacteristicNotificationCallback)(&device, value_handle, value, value_length); 280 } 281 break; 282 case GATT_INDICATION: 283 if (gattCharacteristicIndicationCallback) { 284 value_handle = READ_BT_16(packet, 4); 285 value_length = READ_BT_16(packet, 6); 286 value = &packet[8]; 287 (*gattCharacteristicIndicationCallback)(&device, value_handle, value, value_length); 288 } 289 break; 290 case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT: 291 if (gattCharacteristicReadCallback) { 292 value_handle = READ_BT_16(packet, 4); 293 value_length = READ_BT_16(packet, 6); 294 value = &packet[8]; 295 (*gattCharacteristicReadCallback)(BLE_STATUS_OK, &device, value, value_length); 296 } 297 break; 298 default: 299 break; 300 } 301 } 302 303 static void connection_timeout_handler(timer_source_t * timer){ 304 // log_info("Cancel outgoing connection"); 305 le_central_connect_cancel(); 306 if (!bleDeviceConnectedCallback) return; 307 (*bleDeviceConnectedCallback)(BLE_STATUS_CONNECTION_TIMEOUT, NULL); // page timeout 0x04 308 } 309 310 // 311 312 static int nibble_for_char(const char c){ 313 if ('0' <= c && c <= '9') return c - '0'; 314 if ('a' <= c && c <= 'f') return c - 'a' + 10; 315 if ('A' <= c && c <= 'F') return c - 'A' + 10; 316 return 0; 317 } 318 319 /// UUID class 320 UUID::UUID(void){ 321 memset(uuid, 0, 16); 322 } 323 324 UUID::UUID(const uint8_t uuid[16]){ 325 memcpy(this->uuid, uuid, 16); 326 } 327 328 UUID::UUID(const char * uuidStr){ 329 memset(uuid, 0, 16); 330 int len = strlen(uuidStr); 331 if (len <= 4){ 332 // Handle 4 Bytes HEX 333 uint16_t uuid16; 334 int result = sscanf( (char *) uuidStr, "%x", &uuid16); 335 if (result == 1){ 336 sdp_normalize_uuid(uuid, uuid16); 337 } 338 return; 339 } 340 341 // quick UUID parser, ignoring dashes 342 int i = 0; 343 int data = 0; 344 int have_nibble = 0; 345 while(*uuidStr && i < 16){ 346 const char c = *uuidStr++; 347 if (c == '-') continue; 348 data = data << 4 | nibble_for_char(c); 349 if (!have_nibble) { 350 have_nibble = 1; 351 continue; 352 } 353 uuid[i++] = data; 354 data = 0; 355 have_nibble = 0; 356 } 357 } 358 359 const uint8_t * UUID::getUuid(void) const { 360 return uuid; 361 } 362 363 static char uuid16_buffer[5]; 364 const char * UUID::getUuidString() const { 365 // TODO: fix sdp_has_blueooth_base_uuid call to use const 366 if (sdp_has_blueooth_base_uuid((uint8_t*)uuid)){ 367 sprintf(uuid16_buffer, "%04x", (uint16_t) READ_NET_32(uuid, 0)); 368 return uuid16_buffer; 369 } else { 370 // TODO: fix uuid128_to_str 371 return uuid128_to_str((uint8_t*)uuid); 372 } 373 } 374 375 const char * UUID::getUuid128String() const { 376 return uuid128_to_str((uint8_t*)uuid); 377 } 378 379 bool UUID::matches(UUID *other) const { 380 return memcmp(this->uuid, other->uuid, 16) == 0; 381 } 382 383 384 // BD_ADDR class 385 BD_ADDR::BD_ADDR(void){ 386 } 387 388 BD_ADDR::BD_ADDR(const char * address_string, BD_ADDR_TYPE address_type ) : address_type(address_type) { 389 // TODO: implement 390 // log_error("BD_ADDR::BD_ADDR(const char *, BD_ADDR_TYPE) not implemented yet!"); 391 } 392 393 BD_ADDR::BD_ADDR(const uint8_t address[6], BD_ADDR_TYPE address_type) : address_type(address_type){ 394 memcpy(this->address, address, 6); 395 } 396 397 const uint8_t * BD_ADDR::getAddress(void){ 398 return address; 399 } 400 401 const char * BD_ADDR::getAddressString(void){ 402 return bd_addr_to_str(address); 403 } 404 405 BD_ADDR_TYPE BD_ADDR::getAddressType(void){ 406 return address_type; 407 } 408 409 410 BLEAdvertisement::BLEAdvertisement(uint8_t * event_packet) : 411 advertising_event_type(event_packet[2]), 412 rssi(event_packet[10]), 413 data_length(event_packet[11]) 414 { 415 bd_addr_t addr; 416 bt_flip_addr(addr, &event_packet[4]); 417 bd_addr = BD_ADDR(addr, (BD_ADDR_TYPE)event_packet[3]); 418 memcpy(data, &event_packet[12], LE_ADVERTISING_DATA_SIZE); 419 } 420 421 const uint8_t * BLEAdvertisement::getAdvData(void){ 422 return data; 423 } 424 425 BD_ADDR * BLEAdvertisement::getBdAddr(void){ 426 return &bd_addr; 427 } 428 429 int BLEAdvertisement::getRssi(void){ 430 return rssi > 127 ? rssi - 256 : rssi; 431 } 432 433 434 bool BLEAdvertisement::containsService(UUID * service){ 435 return ad_data_contains_uuid128(data_length, data, (uint8_t*) service->getUuid()); 436 } 437 438 bool BLEAdvertisement::nameHasPrefix(const char * name_prefix){ 439 ad_context_t context; 440 int name_prefix_len = strlen(name_prefix); 441 for (ad_iterator_init(&context, data_length, data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){ 442 uint8_t data_type = ad_iterator_get_data_type(&context); 443 uint8_t data_len = ad_iterator_get_data_len(&context); 444 uint8_t * data = ad_iterator_get_data(&context); 445 int compare_len = name_prefix_len; 446 switch(data_type){ 447 case 8: // shortented local name 448 case 9: // complete local name 449 if (compare_len > data_len) compare_len = data_len; 450 if (strncmp(name_prefix, (const char*) data, compare_len) == 0) return true; 451 break; 452 default: 453 break; 454 } 455 } 456 return false; 457 }; 458 459 bool BLEAdvertisement::isIBeacon(void){ 460 return ((memcmp(iBeaconAdvertisement01, data, sizeof(iBeaconAdvertisement01)) == 0) 461 && (memcmp(iBeaconAdvertisement38, &data[3], sizeof(iBeaconAdvertisement38)) == 0)); 462 } 463 464 const UUID * BLEAdvertisement::getIBeaconUUID(void){ 465 return new UUID(&data[9]); 466 }; 467 uint16_t BLEAdvertisement::getIBeaconMajorID(void){ 468 return READ_NET_16(data, 25); 469 }; 470 uint16_t BLEAdvertisement::getIBecaonMinorID(void){ 471 return READ_NET_16(data, 27); 472 }; 473 uint8_t BLEAdvertisement::getiBeaconMeasuredPower(void){ 474 return data[29]; 475 } 476 477 478 BLECharacteristic::BLECharacteristic(void){ 479 } 480 481 BLECharacteristic::BLECharacteristic(le_characteristic_t characteristic) 482 : characteristic(characteristic), uuid(characteristic.uuid128) { 483 } 484 485 const UUID * BLECharacteristic::getUUID(void){ 486 return &uuid; 487 } 488 489 bool BLECharacteristic::matches(UUID * uuid){ 490 return this->uuid.matches(uuid); 491 } 492 493 bool BLECharacteristic::isValueHandle(uint16_t value_handle){ 494 return characteristic.value_handle == value_handle; 495 } 496 497 const le_characteristic_t * BLECharacteristic::getCharacteristic(void){ 498 return &characteristic; 499 } 500 501 502 BLEService::BLEService(void){ 503 } 504 505 BLEService::BLEService(le_service_t service) 506 : service(service), uuid(service.uuid128){ 507 } 508 509 const UUID * BLEService::getUUID(void){ 510 return &uuid; 511 } 512 513 bool BLEService::matches(UUID * uuid){ 514 return this->uuid.matches(uuid); 515 } 516 517 const le_service_t * BLEService::getService(void){ 518 return &service; 519 } 520 521 // discovery of services and characteristics 522 BLEDevice::BLEDevice(void){ 523 } 524 BLEDevice::BLEDevice(uint16_t handle) 525 : handle(handle){ 526 } 527 uint16_t BLEDevice::getHandle(void){ 528 return handle; 529 } 530 int BLEDevice::discoverGATTServices(void){ 531 return BTstack.discoverGATTServices(this); 532 } 533 int BLEDevice::discoverCharacteristicsForService(BLEService * service){ 534 return BTstack.discoverCharacteristicsForService(this, service); 535 } 536 int BLEDevice::readCharacteristic(BLECharacteristic * characteristic){ 537 return BTstack.readCharacteristic(this, characteristic); 538 } 539 int BLEDevice::writeCharacteristic(BLECharacteristic * characteristic, uint8_t * data, uint16_t size){ 540 return BTstack.writeCharacteristic(this, characteristic, data, size); 541 } 542 int BLEDevice::writeCharacteristicWithoutResponse(BLECharacteristic * characteristic, uint8_t * data, uint16_t size){ 543 return BTstack.writeCharacteristicWithoutResponse(this, characteristic, data, size); 544 } 545 int BLEDevice::subscribeForNotifications(BLECharacteristic * characteristic){ 546 return BTstack.subscribeForNotifications(this, characteristic); 547 } 548 int BLEDevice::unsubscribeFromNotifications(BLECharacteristic * characteristic){ 549 return BTstack.unsubscribeFromNotifications(this, characteristic); 550 } 551 int BLEDevice::subscribeForIndications(BLECharacteristic * characteristic){ 552 return BTstack.subscribeForIndications(this, characteristic); 553 } 554 int BLEDevice::unsubscribeFromIndications(BLECharacteristic * characteristic){ 555 return BTstack.unsubscribeFromIndications(this, characteristic); 556 } 557 558 559 560 static uint16_t (*gattReadCallback)(uint16_t characteristic_id, uint8_t * buffer, uint16_t buffer_size); 561 static int (*gattWriteCallback)(uint16_t characteristic_id, uint8_t *buffer, uint16_t buffer_size); 562 563 // ATT Client Read Callback for Dynamic Data 564 // - if buffer == NULL, don't copy data, just return size of value 565 // - if buffer != NULL, copy data and return number bytes copied 566 // @param offset defines start of attribute value 567 static uint16_t att_read_callback(uint16_t con_handle, uint16_t att_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){ 568 if (gattReadCallback){ 569 return gattReadCallback(att_handle, buffer, buffer_size); 570 } 571 return 0; 572 } 573 /* LISTING_END */ 574 575 576 /* 577 * @section ATT Write 578 * 579 * @text The only valid ATT write in this example is to the Client Characteristic Configuration, which configures notification 580 * and indication. If the ATT handle matches the client configuration handle, the new configuration value is stored and used 581 * in the heartbeat handler to decide if a new value should be sent. See Listing attWrite. 582 */ 583 584 /* LISTING_START(attWrite): ATT Write */ 585 static int att_write_callback(uint16_t con_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){ 586 if (gattWriteCallback){ 587 gattWriteCallback(att_handle, buffer, buffer_size); 588 } 589 return 0; 590 } 591 592 593 594 BTstackManager::BTstackManager(void){ 595 // client_packet_handler = NULL; 596 have_custom_addr = false; 597 // reset handler 598 bleAdvertismentCallback = NULL; 599 bleDeviceConnectedCallback = NULL; 600 bleDeviceDisconnectedCallback = NULL; 601 gattServiceDiscoveredCallback = NULL; 602 gattCharacteristicDiscoveredCallback = NULL; 603 gattCharacteristicNotificationCallback = NULL; 604 605 att_db_util_init(); 606 607 // disable LOG_INFO messages 608 hci_dump_enable_log_level(LOG_LEVEL_INFO, 0); 609 610 #ifdef __AVR__ 611 // configure stdout to go via Serial 612 fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); 613 stdout = &uartout; 614 #endif 615 } 616 617 void BTstackManager::setBLEAdvertisementCallback(void (*callback)(BLEAdvertisement * bleAdvertisement)){ 618 bleAdvertismentCallback = callback; 619 } 620 void BTstackManager::setBLEDeviceConnectedCallback(void (*callback)(BLEStatus status, BLEDevice * device)){ 621 bleDeviceConnectedCallback = callback; 622 } 623 void BTstackManager::setBLEDeviceDisconnectedCallback(void (*callback)(BLEDevice * device)){ 624 bleDeviceDisconnectedCallback = callback; 625 } 626 void BTstackManager::setGATTServiceDiscoveredCallback(void (*callback)(BLEStatus status, BLEDevice * device, BLEService * bleService)){ 627 gattServiceDiscoveredCallback = callback; 628 } 629 void BTstackManager::setGATTCharacteristicDiscoveredCallback(void (*callback)(BLEStatus status, BLEDevice * device, BLECharacteristic * characteristic)){ 630 gattCharacteristicDiscoveredCallback = callback; 631 } 632 void BTstackManager::setGATTCharacteristicNotificationCallback(void (*callback)(BLEDevice * device, uint16_t value_handle, uint8_t* value, uint16_t length)){ 633 gattCharacteristicNotificationCallback = callback; 634 } 635 void BTstackManager::setGATTCharacteristicIndicationCallback(void (*callback)(BLEDevice * device, uint16_t value_handle, uint8_t* value, uint16_t length)){ 636 gattCharacteristicIndicationCallback = callback; 637 } 638 void BTstackManager::setGATTCharacteristicReadCallback(void (*callback)(BLEStatus status, BLEDevice * device, uint8_t * value, uint16_t length)){ 639 gattCharacteristicReadCallback = callback; 640 } 641 void BTstackManager::setGATTCharacteristicWrittenCallback(void (*callback)(BLEStatus status, BLEDevice * device)){ 642 gattCharacteristicWrittenCallback = callback; 643 } 644 void BTstackManager::setGATTCharacteristicSubscribedCallback(void (*callback)(BLEStatus status, BLEDevice * device)){ 645 gattCharacteristicSubscribedCallback = callback; 646 } 647 void BTstackManager::setGATTCharacteristicUnsubscribedCallback(void (*callback)(BLEStatus status, BLEDevice * device)){ 648 gattCharacteristicUnsubscribedCallback = callback; 649 } 650 651 int BTstackManager::discoverGATTServices(BLEDevice * device){ 652 gattAction = gattActionServiceQuery; 653 return gatt_client_discover_primary_services(gatt_client_id, device->getHandle()); 654 } 655 int BTstackManager::discoverCharacteristicsForService(BLEDevice * device, BLEService * service){ 656 gattAction = gattActionCharacteristicQuery; 657 return gatt_client_discover_characteristics_for_service(gatt_client_id, device->getHandle(), (le_service_t*) service->getService()); 658 } 659 int BTstackManager::readCharacteristic(BLEDevice * device, BLECharacteristic * characteristic){ 660 return gatt_client_read_value_of_characteristic(gatt_client_id, device->getHandle(), (le_characteristic_t*) characteristic->getCharacteristic()); 661 } 662 int BTstackManager::writeCharacteristic(BLEDevice * device, BLECharacteristic * characteristic, uint8_t * data, uint16_t size){ 663 gattAction = gattActionWrite; 664 return gatt_client_write_value_of_characteristic(gatt_client_id, device->getHandle(), characteristic->getCharacteristic()->value_handle, 665 size, data); 666 } 667 int BTstackManager::writeCharacteristicWithoutResponse(BLEDevice * device, BLECharacteristic * characteristic, uint8_t * data, uint16_t size){ 668 return gatt_client_write_value_of_characteristic_without_response(gatt_client_id, device->getHandle(), characteristic->getCharacteristic()->value_handle, 669 size, data); 670 } 671 int BTstackManager::subscribeForNotifications(BLEDevice * device, BLECharacteristic * characteristic){ 672 gattAction = gattActionSubscribe; 673 return gatt_client_write_client_characteristic_configuration(gatt_client_id, device->getHandle(), (le_characteristic_t*) characteristic->getCharacteristic(), 674 GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION); 675 } 676 int BTstackManager::subscribeForIndications(BLEDevice * device, BLECharacteristic * characteristic){ 677 gattAction = gattActionSubscribe; 678 return gatt_client_write_client_characteristic_configuration(gatt_client_id, device->getHandle(), (le_characteristic_t*) characteristic->getCharacteristic(), 679 GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION); 680 } 681 int BTstackManager::unsubscribeFromNotifications(BLEDevice * device, BLECharacteristic * characteristic){ 682 gattAction = gattActionUnsubscribe; 683 return gatt_client_write_client_characteristic_configuration(gatt_client_id, device->getHandle(), (le_characteristic_t*) characteristic->getCharacteristic(), 684 GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NONE); 685 } 686 int BTstackManager::unsubscribeFromIndications(BLEDevice * device, BLECharacteristic * characteristic){ 687 gattAction = gattActionUnsubscribe; 688 return gatt_client_write_client_characteristic_configuration(gatt_client_id, device->getHandle(), (le_characteristic_t*) characteristic->getCharacteristic(), 689 GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NONE); 690 } 691 void BTstackManager::bleConnect(BLEAdvertisement * advertisement, int timeout_ms){ 692 bleConnect(advertisement->getBdAddr(), timeout_ms); 693 } 694 void BTstackManager::bleConnect(BD_ADDR * address, int timeout_ms){ 695 bleConnect(address->getAddressType(), address->getAddress(), timeout_ms); 696 } 697 void BTstackManager::bleConnect(BD_ADDR_TYPE address_type, const char * address, int timeout_ms){ 698 // TOOD: implement 699 // log_error("BTstackManager::bleConnect(BD_ADDR_TYPE address_type, const char * address, int timeout_ms) not implemented"); 700 } 701 void BTstackManager::bleConnect(BD_ADDR_TYPE address_type, const uint8_t address[6], int timeout_ms){ 702 le_central_connect((uint8_t*)address, (bd_addr_type_t) address_type); 703 if (!timeout_ms) return; 704 run_loop_set_timer(&connection_timer, timeout_ms); 705 run_loop_set_timer_handler(&connection_timer, connection_timeout_handler); 706 run_loop_add_timer(&connection_timer); 707 } 708 709 void BTstackManager::bleDisconnect(BLEDevice * device){ 710 run_loop_remove_timer(&connection_timer); 711 gap_disconnect(device->getHandle()); 712 } 713 714 void BTstackManager::setPublicBdAddr(bd_addr_t addr){ 715 have_custom_addr = true; 716 memcpy(public_bd_addr, addr ,6); 717 } 718 719 // static hci_uart_config_t config; 720 721 722 void bluetooth_hardware_error(){ 723 printf("Bluetooth Hardware Error event. Restarting...\n\n\n"); 724 #ifdef __AVR__ 725 wdt_enable(WDTO_15MS); 726 // wait for watchdog to trigger 727 #endif 728 729 #ifdef __arm__ 730 NVIC_SystemReset(); 731 #endif 732 while(1); 733 } 734 735 void BTstackManager::setup(void){ 736 737 #ifdef PIN_LED 738 pinMode(PIN_LED, OUTPUT); 739 #endif 740 741 printf("BTstackManager::setup()\n"); 742 743 btstack_memory_init(); 744 run_loop_init(RUN_LOOP_EMBEDDED); 745 746 hci_transport_t * transport = hci_transport_h4_dma_instance(); 747 bt_control_t * control = bt_control_em9301_instance(); 748 hci_init(transport, NULL, control, NULL); 749 750 if (have_custom_addr){ 751 hci_set_bd_addr(public_bd_addr); 752 } 753 754 hci_set_hardware_error_callback(&bluetooth_hardware_error); 755 756 l2cap_init(); 757 758 // setup central device db 759 le_device_db_init(); 760 761 sm_init(); 762 763 att_server_init(att_db_util_get_address(),att_read_callback, att_write_callback); 764 att_server_register_packet_handler(packet_handler); 765 766 gatt_client_init(); 767 gatt_client_id = gatt_client_register_packet_handler(gatt_client_callback); 768 769 // setup advertisements params 770 uint16_t adv_int_min = 0x0030; 771 uint16_t adv_int_max = 0x0030; 772 uint8_t adv_type = 0; 773 bd_addr_t null_addr; 774 memset(null_addr, 0, 6); 775 gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00); 776 777 // setup advertisements data 778 int pos = 0; 779 const uint8_t flags[] = { 0x02, 0x01, 0x02 }; 780 memcpy(&adv_data[pos], flags, sizeof(flags)); 781 pos += sizeof(flags); 782 char * name = "BTstack LE Shield"; 783 adv_data[pos++] = strlen(name) + 1; 784 adv_data[pos++] = 0x09; 785 memcpy(&adv_data[pos], name, strlen(name)); 786 pos += strlen(name); 787 adv_data_len = pos; 788 gap_advertisements_set_data(adv_data_len, adv_data); 789 790 // turn on! 791 btstack_state = 0; 792 hci_power_control(HCI_POWER_ON); 793 794 // poll until working 795 while (btstack_state != HCI_STATE_WORKING){ 796 loop(); 797 } 798 printf("--> READY <--\n"); 799 } 800 801 void BTstackManager::enablePacketLogger(void){ 802 hci_dump_open(NULL, HCI_DUMP_STDOUT); 803 } 804 void BTstackManager::enableDebugLogger(){ 805 // enable LOG_INFO messages 806 hci_dump_enable_log_level(LOG_LEVEL_INFO, 1); 807 } 808 809 810 void BTstackManager::loop(void){ 811 // process data from/to Bluetooth module 812 hal_uart_dma_process(); 813 // BTstack Run Loop 814 embedded_execute_once(); 815 } 816 817 void BTstackManager::bleStartScanning(void){ 818 printf("Start scanning\n"); 819 le_central_start_scan(); 820 } 821 void BTstackManager::bleStopScanning(void){ 822 le_central_stop_scan(); 823 } 824 825 void BTstackManager::setGATTCharacteristicRead(uint16_t (*cb)(uint16_t characteristic_id, uint8_t * buffer, uint16_t buffer_size)){ 826 gattReadCallback = cb; 827 } 828 void BTstackManager::setGATTCharacteristicWrite(int (*cb)(uint16_t characteristic_id, uint8_t *buffer, uint16_t buffer_size)){ 829 gattWriteCallback = cb; 830 } 831 void BTstackManager::addGATTService(UUID * uuid){ 832 att_db_util_add_service_uuid128((uint8_t*)uuid->getUuid()); 833 } 834 uint16_t BTstackManager::addGATTCharacteristic(UUID * uuid, uint16_t flags, const char * text){ 835 return att_db_util_add_characteristic_uuid128((uint8_t*)uuid->getUuid(), flags, (uint8_t*)text, strlen(text)); 836 } 837 uint16_t BTstackManager::addGATTCharacteristic(UUID * uuid, uint16_t flags, uint8_t * data, uint16_t data_len){ 838 return att_db_util_add_characteristic_uuid128((uint8_t*)uuid->getUuid(), flags, data, data_len); 839 } 840 uint16_t BTstackManager::addGATTCharacteristicDynamic(UUID * uuid, uint16_t flags, uint16_t characteristic_id){ 841 return att_db_util_add_characteristic_uuid128((uint8_t*)uuid->getUuid(), flags | ATT_PROPERTY_DYNAMIC, NULL, 0); 842 } 843 void BTstackManager::setAdvData(uint16_t adv_data_len, const uint8_t * adv_data){ 844 gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data); 845 } 846 void BTstackManager::startAdvertising(){ 847 gap_advertisements_enable(1); 848 } 849 void BTstackManager::stopAdvertising(){ 850 gap_advertisements_enable(0); 851 } 852 void BTstackManager::iBeaconConfigure(UUID * uuid, uint16_t major_id, uint16_t minor_id, uint8_t measured_power){ 853 memcpy(adv_data, iBeaconAdvertisement01, sizeof(iBeaconAdvertisement01)); 854 adv_data[2] = 0x06; 855 memcpy(&adv_data[3], iBeaconAdvertisement38, sizeof(iBeaconAdvertisement38)); 856 memcpy(&adv_data[9], uuid->getUuid(), 16); 857 net_store_16(adv_data, 25, major_id); 858 net_store_16(adv_data, 27, minor_id); 859 adv_data[29] = measured_power; 860 adv_data_len = 30; 861 gap_advertisements_set_data(adv_data_len, adv_data); 862 } 863 // 02 01 06 1A FF 4C 00 02 15 -- F8 97 17 7B AE E8 47 67 8E CC CC 69 4F D5 FC EE -- 12 67 00 02 00 00 864 // 02 01 06 1a ff 4c 00 02 15 -- FB 0B 57 A2 82 28 44 CD 91 3A 94 A1 22 BA 12 06 -- 00 01 00 02 D1 00 865 866 867 BTstackManager BTstack; 868 869