main.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. */
  6. /* Includes */
  7. #include "common.h"
  8. #include "gap.h"
  9. /* Library function declarations */
  10. void ble_store_config_init(void);
  11. /* Private function declarations */
  12. static void on_stack_reset(int reason);
  13. static void on_stack_sync(void);
  14. static void nimble_host_config_init(void);
  15. static void nimble_host_task(void *param);
  16. /* Private functions */
  17. /*
  18. * Stack event callback functions
  19. * - on_stack_reset is called when host resets BLE stack due to errors
  20. * - on_stack_sync is called when host has synced with controller
  21. */
  22. static void on_stack_reset(int reason) {
  23. /* On reset, print reset reason to console */
  24. ESP_LOGI(TAG, "nimble stack reset, reset reason: %d", reason);
  25. }
  26. static void on_stack_sync(void) {
  27. /* On stack sync, do advertising initialization */
  28. adv_init();
  29. }
  30. static void nimble_host_config_init(void) {
  31. /* Set host callbacks */
  32. ble_hs_cfg.reset_cb = on_stack_reset;
  33. ble_hs_cfg.sync_cb = on_stack_sync;
  34. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  35. /* Store host configuration */
  36. ble_store_config_init();
  37. }
  38. static void nimble_host_task(void *param) {
  39. /* Task entry log */
  40. ESP_LOGI(TAG, "nimble host task has been started!");
  41. /* This function won't return until nimble_port_stop() is executed */
  42. nimble_port_run();
  43. /* Clean up at exit */
  44. vTaskDelete(NULL);
  45. }
  46. void app_main(void) {
  47. /* Local variables */
  48. int rc = 0;
  49. esp_err_t ret = ESP_OK;
  50. /* NVS flash initialization */
  51. ret = nvs_flash_init();
  52. if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
  53. ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  54. ESP_ERROR_CHECK(nvs_flash_erase());
  55. ret = nvs_flash_init();
  56. }
  57. if (ret != ESP_OK) {
  58. ESP_LOGE(TAG, "failed to initialize nvs flash, error code: %d ", ret);
  59. return;
  60. }
  61. /* NimBLE host stack initialization */
  62. ret = nimble_port_init();
  63. if (ret != ESP_OK) {
  64. ESP_LOGE(TAG, "failed to initialize nimble stack, error code: %d ",
  65. ret);
  66. return;
  67. }
  68. /* GAP service initialization */
  69. rc = gap_init();
  70. if (rc != 0) {
  71. ESP_LOGE(TAG, "failed to initialize GAP service, error code: %d", rc);
  72. return;
  73. }
  74. /* NimBLE host configuration initialization */
  75. nimble_host_config_init();
  76. /* Start NimBLE host task thread and return */
  77. xTaskCreate(nimble_host_task, "NimBLE Host", 4*1024, NULL, 5, NULL);
  78. return;
  79. }