diff --git a/applications/bt/bt_debug_app/bt_debug_app.c b/applications/bt/bt_debug_app/bt_debug_app.c index 1511e84f..90333107 100755 --- a/applications/bt/bt_debug_app/bt_debug_app.c +++ b/applications/bt/bt_debug_app/bt_debug_app.c @@ -1,4 +1,5 @@ #include "bt_debug_app.h" +#include enum BtDebugSubmenuIndex { BtDebugSubmenuIndexCarrierTest, @@ -25,6 +26,10 @@ uint32_t bt_debug_start_view(void* context) { BtDebugApp* bt_debug_app_alloc() { BtDebugApp* app = furi_alloc(sizeof(BtDebugApp)); + + // Load settings + bt_settings_load(&app->settings); + // Gui app->gui = furi_record_open("gui"); @@ -88,7 +93,15 @@ void bt_debug_app_free(BtDebugApp* app) { int32_t bt_debug_app(void* p) { BtDebugApp* app = bt_debug_app_alloc(); + // Stop advertising + furi_hal_bt_stop_advertising(); + view_dispatcher_run(app->view_dispatcher); + + // Restart advertising + if(app->settings.enabled) { + furi_hal_bt_start_advertising(); + } bt_debug_app_free(app); return 0; } diff --git a/applications/bt/bt_service/bt.c b/applications/bt/bt_service/bt.c index 09094d17..672919fa 100755 --- a/applications/bt/bt_service/bt.c +++ b/applications/bt/bt_service/bt.c @@ -3,13 +3,6 @@ #define BT_SERVICE_TAG "BT" -// static void bt_update_statusbar(void* arg) { -// furi_assert(arg); -// Bt* bt = arg; -// BtMessage m = {.type = BtMessageTypeUpdateStatusbar}; -// furi_check(osMessageQueuePut(bt->message_queue, &m, 0, osWaitForever) == osOK); -// } - static void bt_draw_statusbar_callback(Canvas* canvas, void* context) { canvas_draw_icon(canvas, 0, 0, &I_Bluetooth_5x8); } @@ -42,10 +35,6 @@ Bt* bt_alloc() { // Alloc queue bt->message_queue = osMessageQueueNew(8, sizeof(BtMessage), NULL); - // doesn't make sense if we waiting for transition on service start - // bt->update_status_timer = osTimerNew(bt_update_statusbar, osTimerPeriodic, bt, NULL); - // osTimerStart(bt->update_status_timer, 4000); - // Setup statusbar view port bt->statusbar_view_port = bt_statusbar_view_port_alloc(); // Gui @@ -67,15 +56,18 @@ int32_t bt_srv() { FURI_LOG_E(BT_SERVICE_TAG, "Core2 startup failed"); } else { view_port_enabled_set(bt->statusbar_view_port, true); - if(bt->bt_settings.enabled) { - bool bt_app_started = furi_hal_bt_start_app(); - if(!bt_app_started) { - FURI_LOG_E(BT_SERVICE_TAG, "BT App start failed"); - } else { - FURI_LOG_I(BT_SERVICE_TAG, "BT App started"); + if(furi_hal_bt_init_app()) { + FURI_LOG_I(BT_SERVICE_TAG, "BLE stack started"); + if(bt->bt_settings.enabled) { + furi_hal_bt_start_advertising(); + FURI_LOG_I(BT_SERVICE_TAG, "Start advertising"); } + } else { + FURI_LOG_E(BT_SERVICE_TAG, "BT App start failed"); } } + // Update statusbar + view_port_enabled_set(bt->statusbar_view_port, furi_hal_bt_is_alive()); BtMessage message; while(1) { diff --git a/applications/bt/bt_service/bt.h b/applications/bt/bt_service/bt.h index 0bde59b8..ccf5e501 100644 --- a/applications/bt/bt_service/bt.h +++ b/applications/bt/bt_service/bt.h @@ -9,6 +9,8 @@ extern "C" { typedef struct Bt Bt; +void bt_update_statusbar(Bt* bt); + void bt_update_battery_level(Bt* bt, uint8_t battery_level); bool bt_pin_code_show(Bt* bt, uint32_t pin_code); diff --git a/applications/bt/bt_service/bt_api.c b/applications/bt/bt_service/bt_api.c index a12ac268..db709871 100755 --- a/applications/bt/bt_service/bt_api.c +++ b/applications/bt/bt_service/bt_api.c @@ -1,6 +1,12 @@ #include "bt.h" #include "bt_i.h" +void bt_update_statusbar(Bt* bt) { + furi_assert(bt); + BtMessage message = {.type = BtMessageTypeUpdateStatusbar}; + furi_check(osMessageQueuePut(bt->message_queue, &message, 0, osWaitForever) == osOK); +} + void bt_update_battery_level(Bt* bt, uint8_t battery_level) { furi_assert(bt); BtMessage message = { diff --git a/applications/bt/bt_service/bt_i.h b/applications/bt/bt_service/bt_i.h index fbc0f378..fa78811a 100644 --- a/applications/bt/bt_service/bt_i.h +++ b/applications/bt/bt_service/bt_i.h @@ -32,7 +32,6 @@ typedef struct { struct Bt { BtSettings bt_settings; osMessageQueueId_t message_queue; - osTimerId_t update_status_timer; Gui* gui; ViewPort* statusbar_view_port; DialogsApp* dialogs; diff --git a/applications/bt/bt_settings_app/bt_settings_app.c b/applications/bt/bt_settings_app/bt_settings_app.c index 6eaf3761..f3e60937 100755 --- a/applications/bt/bt_settings_app/bt_settings_app.c +++ b/applications/bt/bt_settings_app/bt_settings_app.c @@ -31,12 +31,11 @@ BtSettingsApp* bt_settings_app_alloc() { view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - app->submenu = submenu_alloc(); + app->var_item_list = variable_item_list_alloc(); view_dispatcher_add_view( - app->view_dispatcher, BtSettingsAppViewSubmenu, submenu_get_view(app->submenu)); - app->dialog_ex = dialog_ex_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, BtSettingsAppViewDialogEx, dialog_ex_get_view(app->dialog_ex)); + app->view_dispatcher, + BtSettingsAppViewVarItemList, + variable_item_list_get_view(app->var_item_list)); scene_manager_next_scene(app->scene_manager, BtSettingsAppSceneStart); return app; @@ -44,12 +43,9 @@ BtSettingsApp* bt_settings_app_alloc() { void bt_settings_app_free(BtSettingsApp* app) { furi_assert(app); - // Submenu - view_dispatcher_remove_view(app->view_dispatcher, BtSettingsAppViewSubmenu); - submenu_free(app->submenu); - // Dialog - view_dispatcher_remove_view(app->view_dispatcher, BtSettingsAppViewDialogEx); - dialog_ex_free(app->dialog_ex); + // Variable item list + view_dispatcher_remove_view(app->view_dispatcher, BtSettingsAppViewVarItemList); + variable_item_list_free(app->var_item_list); // View dispatcher view_dispatcher_free(app->view_dispatcher); scene_manager_free(app->scene_manager); diff --git a/applications/bt/bt_settings_app/bt_settings_app.h b/applications/bt/bt_settings_app/bt_settings_app.h old mode 100644 new mode 100755 index cfbea1d0..0cb2b0be --- a/applications/bt/bt_settings_app/bt_settings_app.h +++ b/applications/bt/bt_settings_app/bt_settings_app.h @@ -6,8 +6,7 @@ #include #include -#include -#include +#include #include "../bt_settings.h" #include "scenes/bt_settings_scene.h" @@ -17,11 +16,7 @@ typedef struct { Gui* gui; SceneManager* scene_manager; ViewDispatcher* view_dispatcher; - Submenu* submenu; - DialogEx* dialog_ex; + VariableItemList* var_item_list; } BtSettingsApp; -typedef enum { - BtSettingsAppViewSubmenu, - BtSettingsAppViewDialogEx, -} BtSettingsAppView; +typedef enum { BtSettingsAppViewVarItemList } BtSettingsAppView; diff --git a/applications/bt/bt_settings_app/scenes/bt_settings_scene_config.h b/applications/bt/bt_settings_app/scenes/bt_settings_scene_config.h index e7d19b1a..6aa23850 100644 --- a/applications/bt/bt_settings_app/scenes/bt_settings_scene_config.h +++ b/applications/bt/bt_settings_app/scenes/bt_settings_scene_config.h @@ -1,2 +1 @@ ADD_SCENE(bt_settings, start, Start) -ADD_SCENE(bt_settings, disable_dialog, DisableDialog) diff --git a/applications/bt/bt_settings_app/scenes/bt_settings_scene_disable_dialog.c b/applications/bt/bt_settings_app/scenes/bt_settings_scene_disable_dialog.c deleted file mode 100755 index ac2d5f44..00000000 --- a/applications/bt/bt_settings_app/scenes/bt_settings_scene_disable_dialog.c +++ /dev/null @@ -1,44 +0,0 @@ -#include "../bt_settings_app.h" -#include -#include - -static void bt_setting_disable_dialog_callback(DialogExResult result, void* context) { - BtSettingsApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, result); -} - -void bt_settings_scene_disable_dialog_on_enter(void* context) { - BtSettingsApp* app = context; - DialogEx* dialog_ex = app->dialog_ex; - dialog_ex_set_text( - dialog_ex, "Reboot device\nto disable Bluetooth", 64, 32, AlignCenter, AlignCenter); - dialog_ex_set_left_button_text(dialog_ex, "Back"); - dialog_ex_set_right_button_text(dialog_ex, "Reboot"); - dialog_ex_set_result_callback(dialog_ex, bt_setting_disable_dialog_callback); - dialog_ex_set_context(dialog_ex, app); - - view_dispatcher_switch_to_view(app->view_dispatcher, BtSettingsAppViewDialogEx); -} - -bool bt_settings_scene_disable_dialog_on_event(void* context, SceneManagerEvent event) { - BtSettingsApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == DialogExResultLeft) { - scene_manager_previous_scene(app->scene_manager); - consumed = true; - } else if(event.event == DialogExResultRight) { - app->settings.enabled = false; - bt_settings_save(&app->settings); - furi_hal_boot_set_mode(FuriHalBootModeNormal); - furi_hal_power_reset(); - } - } - return consumed; -} - -void bt_settings_scene_disable_dialog_on_exit(void* context) { - BtSettingsApp* app = context; - dialog_ex_clean(app->dialog_ex); -} diff --git a/applications/bt/bt_settings_app/scenes/bt_settings_scene_start.c b/applications/bt/bt_settings_app/scenes/bt_settings_scene_start.c index faf1d3a1..6e021148 100755 --- a/applications/bt/bt_settings_app/scenes/bt_settings_scene_start.c +++ b/applications/bt/bt_settings_app/scenes/bt_settings_scene_start.c @@ -1,28 +1,45 @@ #include "../bt_settings_app.h" #include "furi-hal-bt.h" -enum BtSettingsAppStartSubmenuIndex { - BtSettingsAppStartSubmenuIndexEnable, +enum BtSetting { + BtSettingOff, + BtSettingOn, + BtSettingNum, }; -static void bt_settings_scene_start_submenu_callback(void* context, uint32_t index) { - BtSettingsApp* app = context; +const char* const bt_settings_text[BtSettingNum] = { + "Off", + "On", +}; + +static void bt_settings_scene_start_var_list_change_callback(VariableItem* item) { + BtSettingsApp* app = variable_item_get_context(item); + uint8_t index = variable_item_get_current_value_index(item); + + variable_item_set_current_value_text(item, bt_settings_text[index]); view_dispatcher_send_custom_event(app->view_dispatcher, index); } void bt_settings_scene_start_on_enter(void* context) { BtSettingsApp* app = context; - Submenu* submenu = app->submenu; + VariableItemList* var_item_list = app->var_item_list; - const char* submenu_label = app->settings.enabled ? "Disable" : "Enable"; - submenu_add_item( - submenu, - submenu_label, - BtSettingsAppStartSubmenuIndexEnable, - bt_settings_scene_start_submenu_callback, + VariableItem* item; + item = variable_item_list_add( + var_item_list, + "Bluetooth", + BtSettingNum, + bt_settings_scene_start_var_list_change_callback, app); + if(app->settings.enabled) { + variable_item_set_current_value_index(item, BtSettingOn); + variable_item_set_current_value_text(item, bt_settings_text[BtSettingOn]); + } else { + variable_item_set_current_value_index(item, BtSettingOff); + variable_item_set_current_value_text(item, bt_settings_text[BtSettingOff]); + } - view_dispatcher_switch_to_view(app->view_dispatcher, BtSettingsAppViewSubmenu); + view_dispatcher_switch_to_view(app->view_dispatcher, BtSettingsAppViewVarItemList); } bool bt_settings_scene_start_on_event(void* context, SceneManagerEvent event) { @@ -30,27 +47,19 @@ bool bt_settings_scene_start_on_event(void* context, SceneManagerEvent event) { bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { - if(event.event == BtSettingsAppStartSubmenuIndexEnable) { - if(!app->settings.enabled) { - app->settings.enabled = true; - furi_hal_bt_start_app(); - submenu_clean(app->submenu); - submenu_add_item( - app->submenu, - "Disable", - BtSettingsAppStartSubmenuIndexEnable, - bt_settings_scene_start_submenu_callback, - app); - } else { - scene_manager_next_scene(app->scene_manager, BtSettingsAppSceneDisableDialog); - } - consumed = true; + if(event.event == BtSettingOn) { + furi_hal_bt_start_advertising(); + app->settings.enabled = true; + } else if(event.event == BtSettingOff) { + app->settings.enabled = false; + furi_hal_bt_stop_advertising(); } + consumed = true; } return consumed; } void bt_settings_scene_start_on_exit(void* context) { BtSettingsApp* app = context; - submenu_clean(app->submenu); + variable_item_list_clean(app->var_item_list); } diff --git a/firmware/targets/f6/ble-glue/app_ble.c b/firmware/targets/f6/ble-glue/app_ble.c deleted file mode 100644 index 652c29ef..00000000 --- a/firmware/targets/f6/ble-glue/app_ble.c +++ /dev/null @@ -1,140 +0,0 @@ -#include "main.h" - -#include "app_entry.h" -#include "app_common.h" -#include "dbg_trace.h" -#include "ble.h" -#include "tl.h" -#include "app_ble.h" -#include "shci.h" -#include "cmsis_os.h" - -#include - -PLACE_IN_SECTION("MB_MEM1") ALIGN(4) static TL_CmdPacket_t BleCmdBuffer; - -// PLACE_IN_SECTION("TAG_OTA_END") const uint32_t MagicKeywordValue = 0x94448A29 ; -// PLACE_IN_SECTION("TAG_OTA_START") const uint32_t MagicKeywordAddress = (uint32_t)&MagicKeywordValue; - -osMutexId_t MtxHciId; -osSemaphoreId_t SemHciId; -osThreadId_t HciUserEvtProcessId; - -const osThreadAttr_t HciUserEvtProcess_attr = { - .name = CFG_HCI_USER_EVT_PROCESS_NAME, - .attr_bits = CFG_HCI_USER_EVT_PROCESS_ATTR_BITS, - .cb_mem = CFG_HCI_USER_EVT_PROCESS_CB_MEM, - .cb_size = CFG_HCI_USER_EVT_PROCESS_CB_SIZE, - .stack_mem = CFG_HCI_USER_EVT_PROCESS_STACK_MEM, - .priority = CFG_HCI_USER_EVT_PROCESS_PRIORITY, - .stack_size = CFG_HCI_USER_EVT_PROCESS_STACK_SIZE -}; - -/* Private function prototypes -----------------------------------------------*/ -static void HciUserEvtProcess(void *argument); -static void BLE_UserEvtRx( void * pPayload ); -static void BLE_StatusNot( HCI_TL_CmdStatus_t status ); -static void Ble_Tl_Init( void ); - -bool APP_BLE_Init() { - SHCI_C2_Ble_Init_Cmd_Packet_t ble_init_cmd_packet = { - {{0,0,0}}, /**< Header unused */ - {0, /** pBleBufferAddress not used */ - 0, /** BleBufferSize not used */ - CFG_BLE_NUM_GATT_ATTRIBUTES, - CFG_BLE_NUM_GATT_SERVICES, - CFG_BLE_ATT_VALUE_ARRAY_SIZE, - CFG_BLE_NUM_LINK, - CFG_BLE_DATA_LENGTH_EXTENSION, - CFG_BLE_PREPARE_WRITE_LIST_SIZE, - CFG_BLE_MBLOCK_COUNT, - CFG_BLE_MAX_ATT_MTU, - CFG_BLE_SLAVE_SCA, - CFG_BLE_MASTER_SCA, - CFG_BLE_LSE_SOURCE, - CFG_BLE_MAX_CONN_EVENT_LENGTH, - CFG_BLE_HSE_STARTUP_TIME, - CFG_BLE_VITERBI_MODE, - CFG_BLE_LL_ONLY, - 0} - }; - - // Initialize Ble Transport Layer - Ble_Tl_Init( ); - // Register the hci transport layer to handle BLE User Asynchronous Events - HciUserEvtProcessId = osThreadNew(HciUserEvtProcess, NULL, &HciUserEvtProcess_attr); - // Starts the BLE Stack on CPU2 - return (SHCI_C2_BLE_Init( &ble_init_cmd_packet ) == SHCI_Success); -} - -static void Ble_Tl_Init( void ) { - HCI_TL_HciInitConf_t Hci_Tl_Init_Conf; - - MtxHciId = osMutexNew( NULL ); - SemHciId = osSemaphoreNew( 1, 0, NULL ); /*< Create the semaphore and make it busy at initialization */ - - Hci_Tl_Init_Conf.p_cmdbuffer = (uint8_t*)&BleCmdBuffer; - Hci_Tl_Init_Conf.StatusNotCallBack = BLE_StatusNot; - hci_init(BLE_UserEvtRx, (void*) &Hci_Tl_Init_Conf); -} - -static void HciUserEvtProcess(void *argument) { - UNUSED(argument); - - for(;;) - { - osThreadFlagsWait( 1, osFlagsWaitAny, osWaitForever); - hci_user_evt_proc( ); - } -} - -/************************************************************* - * - * WRAP FUNCTIONS - * - *************************************************************/ -void hci_notify_asynch_evt(void* pdata) { - UNUSED(pdata); - osThreadFlagsSet( HciUserEvtProcessId, 1 ); -} - -void hci_cmd_resp_release(uint32_t flag) { - UNUSED(flag); - osSemaphoreRelease( SemHciId ); -} - -void hci_cmd_resp_wait(uint32_t timeout) { - UNUSED(timeout); - osSemaphoreAcquire( SemHciId, osWaitForever ); -} - -static void BLE_UserEvtRx( void * pPayload ) { - SVCCTL_UserEvtFlowStatus_t svctl_return_status; - tHCI_UserEvtRxParam *pParam; - - pParam = (tHCI_UserEvtRxParam *)pPayload; - - svctl_return_status = SVCCTL_UserEvtRx((void *)&(pParam->pckt->evtserial)); - if (svctl_return_status != SVCCTL_UserEvtFlowDisable) { - pParam->status = HCI_TL_UserEventFlow_Enable; - } else { - pParam->status = HCI_TL_UserEventFlow_Disable; - } -} - -static void BLE_StatusNot( HCI_TL_CmdStatus_t status ) { - switch (status) { - case HCI_TL_CmdBusy: - osMutexAcquire( MtxHciId, osWaitForever ); - break; - case HCI_TL_CmdAvailable: - osMutexRelease( MtxHciId ); - break; - default: - break; - } -} - -void SVCCTL_ResumeUserEventFlow( void ) { - hci_resume_flow(); -} diff --git a/firmware/targets/f6/ble-glue/app_conf.h b/firmware/targets/f6/ble-glue/app_conf.h index 381d5ae7..bfd6f9dd 100644 --- a/firmware/targets/f6/ble-glue/app_conf.h +++ b/firmware/targets/f6/ble-glue/app_conf.h @@ -427,9 +427,6 @@ typedef enum #define DBG_TRACE_MSG_QUEUE_SIZE 4096 #define MAX_DBG_TRACE_MSG_SIZE 1024 -#define CFG_LED_SUPPORTED 0 -#define CFG_BUTTON_SUPPORTED 0 - /****************************************************************************** * FreeRTOS ******************************************************************************/ @@ -441,34 +438,5 @@ typedef enum #define CFG_SHCI_USER_EVT_PROCESS_PRIORITY osPriorityNone #define CFG_SHCI_USER_EVT_PROCESS_STACK_SIZE (128 * 7) -#define CFG_HCI_USER_EVT_PROCESS_NAME "ble_hci_evt" -#define CFG_HCI_USER_EVT_PROCESS_ATTR_BITS (0) -#define CFG_HCI_USER_EVT_PROCESS_CB_MEM (0) -#define CFG_HCI_USER_EVT_PROCESS_CB_SIZE (0) -#define CFG_HCI_USER_EVT_PROCESS_STACK_MEM (0) -#define CFG_HCI_USER_EVT_PROCESS_PRIORITY osPriorityNone -#define CFG_HCI_USER_EVT_PROCESS_STACK_SIZE (128 * 8) - -#define CFG_ADV_UPDATE_PROCESS_NAME "ble_adv_upd" -#define CFG_ADV_UPDATE_PROCESS_ATTR_BITS (0) -#define CFG_ADV_UPDATE_PROCESS_CB_MEM (0) -#define CFG_ADV_UPDATE_PROCESS_CB_SIZE (0) -#define CFG_ADV_UPDATE_PROCESS_STACK_MEM (0) -#define CFG_ADV_UPDATE_PROCESS_PRIORITY osPriorityNone -#define CFG_ADV_UPDATE_PROCESS_STACK_SIZE (128 * 6) - -#define CFG_HRS_PROCESS_NAME "hrs" -#define CFG_HRS_PROCESS_ATTR_BITS (0) -#define CFG_HRS_PROCESS_CB_MEM (0) -#define CFG_HRS_PROCESS_CB_SIZE (0) -#define CFG_HRS_PROCESS_STACK_MEM (0) -#define CFG_HRS_PROCESS_PRIORITY osPriorityNone -#define CFG_HRS_PROCESS_STACK_SIZE (128 * 8) - -typedef enum { - CFG_LPM_APP, - CFG_LPM_APP_BLE, -} CFG_LPM_Id_t; - #define CFG_OTP_BASE_ADDRESS OTP_AREA_BASE #define CFG_OTP_END_ADRESS OTP_AREA_END_ADDR diff --git a/firmware/targets/f6/ble-glue/app_entry.c b/firmware/targets/f6/ble-glue/app_entry.c index 431fed6a..a970da32 100644 --- a/firmware/targets/f6/ble-glue/app_entry.c +++ b/firmware/targets/f6/ble-glue/app_entry.c @@ -1,7 +1,7 @@ #include "app_common.h" #include "main.h" #include "app_entry.h" -#include "app_ble.h" +#include "ble_app.h" #include "ble.h" #include "tl.h" #include "cmsis_os.h" @@ -47,8 +47,6 @@ void APPE_Init() { ble_glue_status = BleGlueStatusStartup; SystemPower_Config(); /**< Configure the system Power Mode */ - HW_TS_Init(hw_ts_InitMode_Full, &hrtc); /**< Initialize the TimerServer */ - // APPD_Init(); furi_hal_power_insomnia_enter(); @@ -137,7 +135,7 @@ static void APPE_SysUserEvtRx( void * pPayload ) { /* Traces channel initialization */ // APPD_EnableCPU2( ); - if (APP_BLE_Init()) { + if(ble_app_init()) { FURI_LOG_I("Core2", "BLE stack started"); ble_glue_status = BleGlueStatusStarted; } else { diff --git a/firmware/targets/f6/ble-glue/battery_service.c b/firmware/targets/f6/ble-glue/battery_service.c index 654edd53..1dd8c5a0 100644 --- a/firmware/targets/f6/ble-glue/battery_service.c +++ b/firmware/targets/f6/ble-glue/battery_service.c @@ -31,7 +31,7 @@ void battery_svc_start() { (Char_UUID_t *) &char_battery_level_uuid, 1, CHAR_PROP_READ | CHAR_PROP_NOTIFY, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, diff --git a/firmware/targets/f6/ble-glue/ble_app.c b/firmware/targets/f6/ble-glue/ble_app.c new file mode 100644 index 00000000..e28facd6 --- /dev/null +++ b/firmware/targets/f6/ble-glue/ble_app.c @@ -0,0 +1,119 @@ +#include "ble_app.h" + +#include "hci_tl.h" +#include "ble.h" +#include "shci.h" +#include "cmsis_os.h" +#include "gap.h" + +#include + +#define BLE_APP_TAG "ble app" + +PLACE_IN_SECTION("MB_MEM1") ALIGN(4) static TL_CmdPacket_t ble_app_cmd_buffer; + +typedef struct { + osMutexId_t hci_mtx; + osSemaphoreId_t hci_sem; + osThreadId_t hci_thread_id; + osThreadAttr_t hci_thread_attr; +} BleApp; + +static BleApp* ble_app; + +static void ble_app_hci_thread(void *arg); +static void ble_app_hci_event_handler(void * pPayload); +static void ble_app_hci_status_not_handler(HCI_TL_CmdStatus_t status); + +bool ble_app_init() { + ble_app = furi_alloc(sizeof(BleApp)); + + // Allocate semafore and mutex for ble command buffer access + ble_app->hci_mtx = osMutexNew(NULL); + ble_app->hci_sem = osSemaphoreNew(1, 0, NULL); + // HCI transport layer thread to handle user asynch events + ble_app->hci_thread_attr.name = "ble hci"; + ble_app->hci_thread_attr.stack_size = 1024; + ble_app->hci_thread_id = osThreadNew(ble_app_hci_thread, NULL, &ble_app->hci_thread_attr); + + // Initialize Ble Transport Layer + HCI_TL_HciInitConf_t hci_tl_config = { + .p_cmdbuffer = (uint8_t*)&ble_app_cmd_buffer, + .StatusNotCallBack = ble_app_hci_status_not_handler, + }; + hci_init(ble_app_hci_event_handler, (void*)&hci_tl_config); + + // Start ble stack on 2nd core + SHCI_C2_Ble_Init_Cmd_Packet_t ble_init_cmd_packet = { + .Header = {{0,0,0}}, // Header unused + .Param = { + 0, // pBleBufferAddress not used + 0, // BleBufferSize not used + CFG_BLE_NUM_GATT_ATTRIBUTES, + CFG_BLE_NUM_GATT_SERVICES, + CFG_BLE_ATT_VALUE_ARRAY_SIZE, + CFG_BLE_NUM_LINK, + CFG_BLE_DATA_LENGTH_EXTENSION, + CFG_BLE_PREPARE_WRITE_LIST_SIZE, + CFG_BLE_MBLOCK_COUNT, + CFG_BLE_MAX_ATT_MTU, + CFG_BLE_SLAVE_SCA, + CFG_BLE_MASTER_SCA, + CFG_BLE_LSE_SOURCE, + CFG_BLE_MAX_CONN_EVENT_LENGTH, + CFG_BLE_HSE_STARTUP_TIME, + CFG_BLE_VITERBI_MODE, + CFG_BLE_LL_ONLY, + 0, + } + }; + SHCI_CmdStatus_t status = SHCI_C2_BLE_Init(&ble_init_cmd_packet); + if(status) { + FURI_LOG_E(BLE_APP_TAG, "Failed to start ble stack: %d", status); + } + return status == SHCI_Success; +} + +static void ble_app_hci_thread(void *arg) { + while(1) { + osThreadFlagsWait(1, osFlagsWaitAny, osWaitForever); + hci_user_evt_proc(); + } +} + +// Called by WPAN lib +void hci_notify_asynch_evt(void* pdata) { + osThreadFlagsSet(ble_app->hci_thread_id, 1); +} + +void hci_cmd_resp_release(uint32_t flag) { + osSemaphoreRelease(ble_app->hci_sem); +} + +void hci_cmd_resp_wait(uint32_t timeout) { + osSemaphoreAcquire(ble_app->hci_sem, osWaitForever); +} + +static void ble_app_hci_event_handler( void * pPayload ) { + SVCCTL_UserEvtFlowStatus_t svctl_return_status; + tHCI_UserEvtRxParam *pParam = (tHCI_UserEvtRxParam *)pPayload; + + svctl_return_status = SVCCTL_UserEvtRx((void *)&(pParam->pckt->evtserial)); + if (svctl_return_status != SVCCTL_UserEvtFlowDisable) { + pParam->status = HCI_TL_UserEventFlow_Enable; + } else { + pParam->status = HCI_TL_UserEventFlow_Disable; + } +} + +static void ble_app_hci_status_not_handler( HCI_TL_CmdStatus_t status ) { + if(status == HCI_TL_CmdBusy) { + osMutexAcquire(ble_app->hci_mtx, osWaitForever ); + } else if(status == HCI_TL_CmdAvailable) { + osMutexRelease(ble_app->hci_mtx); + } +} + +void SVCCTL_ResumeUserEventFlow( void ) { + hci_resume_flow(); +} diff --git a/firmware/targets/f7/ble-glue/app_ble.h b/firmware/targets/f6/ble-glue/ble_app.h similarity index 72% rename from firmware/targets/f7/ble-glue/app_ble.h rename to firmware/targets/f6/ble-glue/ble_app.h index 08c60fe3..17d8dc5f 100644 --- a/firmware/targets/f7/ble-glue/app_ble.h +++ b/firmware/targets/f6/ble-glue/ble_app.h @@ -5,9 +5,8 @@ extern "C" { #endif #include -#include "hci_tl.h" -bool APP_BLE_Init(); +bool ble_app_init(); #ifdef __cplusplus } diff --git a/firmware/targets/f6/ble-glue/dev_info_service.c b/firmware/targets/f6/ble-glue/dev_info_service.c index db58226b..ae07d9bc 100644 --- a/firmware/targets/f6/ble-glue/dev_info_service.c +++ b/firmware/targets/f6/ble-glue/dev_info_service.c @@ -39,7 +39,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_man_name), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, @@ -53,7 +53,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_serial_num), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, @@ -67,7 +67,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_firmware_rev_num), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, @@ -81,7 +81,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_software_rev_num), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, diff --git a/firmware/targets/f6/ble-glue/gap.c b/firmware/targets/f6/ble-glue/gap.c index 19d1b5f1..74e1d35a 100644 --- a/firmware/targets/f6/ble-glue/gap.c +++ b/firmware/targets/f6/ble-glue/gap.c @@ -31,13 +31,22 @@ typedef struct { typedef struct { GapSvc gap_svc; GapState state; + osMutexId_t state_mutex; uint8_t mac_address[BD_ADDR_SIZE_LOCAL]; Bt* bt; osTimerId advertise_timer; osThreadAttr_t thread_attr; osThreadId_t thread_id; + osMessageQueueId_t command_queue; + bool enable_adv; } Gap; +typedef enum { + GapCommandAdvFast, + GapCommandAdvLowPower, + GapCommandAdvStop, +} GapCommand; + // Identity root key static const uint8_t gap_irk[16] = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0}; // Encryption root key @@ -49,150 +58,151 @@ static const uint8_t gap_default_mac_addr[] = {0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x7 static Gap* gap = NULL; -static void gap_advertise(GapState new_state); +static void gap_advertise_start(GapState new_state); static void gap_app(void *arg); SVCCTL_UserEvtFlowStatus_t SVCCTL_App_Notification( void *pckt ) { - hci_event_pckt *event_pckt; - evt_le_meta_event *meta_evt; - evt_blue_aci *blue_evt; - hci_le_phy_update_complete_event_rp0 *evt_le_phy_update_complete; - uint8_t tx_phy; - uint8_t rx_phy; - tBleStatus ret = BLE_STATUS_INVALID_PARAMS; + hci_event_pckt *event_pckt; + evt_le_meta_event *meta_evt; + evt_blue_aci *blue_evt; + hci_le_phy_update_complete_event_rp0 *evt_le_phy_update_complete; + uint8_t tx_phy; + uint8_t rx_phy; + tBleStatus ret = BLE_STATUS_INVALID_PARAMS; - event_pckt = (hci_event_pckt*) ((hci_uart_pckt *) pckt)->data; + event_pckt = (hci_event_pckt*) ((hci_uart_pckt *) pckt)->data; - switch (event_pckt->evt) { - case EVT_DISCONN_COMPLETE: - { - hci_disconnection_complete_event_rp0 *disconnection_complete_event = (hci_disconnection_complete_event_rp0 *) event_pckt->data; - if (disconnection_complete_event->Connection_Handle == gap->gap_svc.connection_handle) { - gap->gap_svc.connection_handle = 0; - gap->state = GapStateIdle; - FURI_LOG_I(GAP_TAG, "Disconnect from client"); + osMutexAcquire(gap->state_mutex, osWaitForever); + switch (event_pckt->evt) { + case EVT_DISCONN_COMPLETE: + { + hci_disconnection_complete_event_rp0 *disconnection_complete_event = (hci_disconnection_complete_event_rp0 *) event_pckt->data; + if (disconnection_complete_event->Connection_Handle == gap->gap_svc.connection_handle) { + gap->gap_svc.connection_handle = 0; + gap->state = GapStateIdle; + FURI_LOG_I(GAP_TAG, "Disconnect from client"); + } + if(gap->enable_adv) { + // Restart advertising + gap_start_advertising(); + furi_hal_power_insomnia_exit(); + } } - // Restart advertising - gap_advertise(GapStateAdvFast); - furi_hal_power_insomnia_exit(); - } - break; + break; - case EVT_LE_META_EVENT: - meta_evt = (evt_le_meta_event*) event_pckt->data; - switch (meta_evt->subevent) { - case EVT_LE_CONN_UPDATE_COMPLETE: - FURI_LOG_D(GAP_TAG, "Connection update event"); - break; + case EVT_LE_META_EVENT: + meta_evt = (evt_le_meta_event*) event_pckt->data; + switch (meta_evt->subevent) { + case EVT_LE_CONN_UPDATE_COMPLETE: + FURI_LOG_D(GAP_TAG, "Connection update event"); + break; - case EVT_LE_PHY_UPDATE_COMPLETE: - evt_le_phy_update_complete = (hci_le_phy_update_complete_event_rp0*)meta_evt->data; - if(evt_le_phy_update_complete->Status) { - FURI_LOG_E(GAP_TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status); - } else { - FURI_LOG_I(GAP_TAG, "Update PHY succeed"); + case EVT_LE_PHY_UPDATE_COMPLETE: + evt_le_phy_update_complete = (hci_le_phy_update_complete_event_rp0*)meta_evt->data; + if(evt_le_phy_update_complete->Status) { + FURI_LOG_E(GAP_TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status); + } else { + FURI_LOG_I(GAP_TAG, "Update PHY succeed"); + } + ret = hci_le_read_phy(gap->gap_svc.connection_handle,&tx_phy,&rx_phy); + if(ret) { + FURI_LOG_E(GAP_TAG, "Read PHY failed, status: %d", ret); + } else { + FURI_LOG_I(GAP_TAG, "PHY Params TX = %d, RX = %d ", tx_phy, rx_phy); + } + break; + + case EVT_LE_CONN_COMPLETE: + furi_hal_power_insomnia_enter(); + hci_le_connection_complete_event_rp0* connection_complete_event = (hci_le_connection_complete_event_rp0 *) meta_evt->data; + FURI_LOG_I(GAP_TAG, "Connection complete for connection handle 0x%x", connection_complete_event->Connection_Handle); + + // Stop advertising as connection completed + osTimerStop(gap->advertise_timer); + + // Update connection status and handle + gap->state = GapStateConnected; + gap->gap_svc.connection_handle = connection_complete_event->Connection_Handle; + + // Start pairing by sending security request + aci_gap_slave_security_req(connection_complete_event->Connection_Handle); + break; + + default: + break; } - ret = hci_le_read_phy(gap->gap_svc.connection_handle,&tx_phy,&rx_phy); - if(ret) { - FURI_LOG_E(GAP_TAG, "Read PHY failed, status: %d", ret); - } else { - FURI_LOG_I(GAP_TAG, "PHY Params TX= %d, RX= %d ", tx_phy, rx_phy); + break; + + case EVT_VENDOR: + blue_evt = (evt_blue_aci*) event_pckt->data; + switch (blue_evt->ecode) { + aci_gap_pairing_complete_event_rp0 *pairing_complete; + + case EVT_BLUE_GAP_LIMITED_DISCOVERABLE: + FURI_LOG_I(GAP_TAG, "Limited discoverable event"); + break; + + case EVT_BLUE_GAP_PASS_KEY_REQUEST: + { + // Generate random PIN code + uint32_t pin = rand() % 999999; + aci_gap_pass_key_resp(gap->gap_svc.connection_handle, pin); + FURI_LOG_I(GAP_TAG, "Pass key request event. Pin: %d", pin); + bt_pin_code_show(gap->bt, pin); } - break; + break; - case EVT_LE_CONN_COMPLETE: - furi_hal_power_insomnia_enter(); - hci_le_connection_complete_event_rp0* connection_complete_event = (hci_le_connection_complete_event_rp0 *) meta_evt->data; - FURI_LOG_I(GAP_TAG, "Connection complete for connection handle 0x%x", connection_complete_event->Connection_Handle); + case EVT_BLUE_GAP_AUTHORIZATION_REQUEST: + FURI_LOG_I(GAP_TAG, "Authorization request event"); + break; - // Stop advertising as connection completed - osTimerStop(gap->advertise_timer); + case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED: + FURI_LOG_I(GAP_TAG, "Slave security initiated"); + break; - // Update connection status and handle - gap->state = GapStateConnected; - gap->gap_svc.connection_handle = connection_complete_event->Connection_Handle; + case EVT_BLUE_GAP_BOND_LOST: + FURI_LOG_I(GAP_TAG, "Bond lost event. Start rebonding"); + aci_gap_allow_rebond(gap->gap_svc.connection_handle); + break; - // Start pairing by sending security request - aci_gap_slave_security_req(connection_complete_event->Connection_Handle); - break; + case EVT_BLUE_GAP_DEVICE_FOUND: + FURI_LOG_I(GAP_TAG, "Device found event"); + break; + case EVT_BLUE_GAP_ADDR_NOT_RESOLVED: + FURI_LOG_I(GAP_TAG, "Address not resolved event"); + break; + + case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION: + FURI_LOG_I(GAP_TAG, "Key press notification event"); + break; + + case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE: + FURI_LOG_I(GAP_TAG, "Hex_value = %lx", + ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value); + aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1); + break; + + case EVT_BLUE_GAP_PAIRING_CMPLT: + pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data; + if (pairing_complete->Status) { + FURI_LOG_E(GAP_TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status); + aci_gap_terminate(gap->gap_svc.connection_handle, 5); + } else { + FURI_LOG_I(GAP_TAG, "Pairing complete"); + } + break; + + case EVT_BLUE_GAP_PROCEDURE_COMPLETE: + FURI_LOG_I(GAP_TAG, "Procedure complete event"); + break; + } default: - break; - } - break; - - case EVT_VENDOR: - blue_evt = (evt_blue_aci*) event_pckt->data; - switch (blue_evt->ecode) { - aci_gap_pairing_complete_event_rp0 *pairing_complete; - - case EVT_BLUE_GAP_LIMITED_DISCOVERABLE: - FURI_LOG_I(GAP_TAG, "Limited discoverable event"); - break; - - case EVT_BLUE_GAP_PASS_KEY_REQUEST: - { - // Generate random PIN code - uint32_t pin = rand() % 999999; - aci_gap_pass_key_resp(gap->gap_svc.connection_handle, pin); - FURI_LOG_I(GAP_TAG, "Pass key request event. Pin: %d", pin); - bt_pin_code_show(gap->bt, pin); - } - break; - - case EVT_BLUE_GAP_AUTHORIZATION_REQUEST: - FURI_LOG_I(GAP_TAG, "Authorization request event"); - break; - - case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED: - FURI_LOG_I(GAP_TAG, "Slave security initiated"); - break; - - case EVT_BLUE_GAP_BOND_LOST: - FURI_LOG_I(GAP_TAG, "Bond lost event. Start rebonding"); - aci_gap_allow_rebond(gap->gap_svc.connection_handle); - break; - - case EVT_BLUE_GAP_DEVICE_FOUND: - FURI_LOG_I(GAP_TAG, "Device found event"); - break; - - case EVT_BLUE_GAP_ADDR_NOT_RESOLVED: - FURI_LOG_I(GAP_TAG, "Address not resolved event"); - break; - - case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION: - FURI_LOG_I(GAP_TAG, "Key press notification event"); - break; - - case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE: - FURI_LOG_I(GAP_TAG, "Hex_value = %lx", - ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value); - aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1); - break; - - case (EVT_BLUE_GAP_PAIRING_CMPLT): - { - pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data; - if (pairing_complete->Status) { - FURI_LOG_E(GAP_TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status); - aci_gap_terminate(gap->gap_svc.connection_handle, 5); - } else { - FURI_LOG_I(GAP_TAG, "Pairing complete"); - } - } - break; - - case EVT_BLUE_GAP_PROCEDURE_COMPLETE: - FURI_LOG_I(GAP_TAG, "Procedure complete event"); - break; - } - default: - break; - } - - return SVCCTL_UserEvtFlowEnable; + break; + } + osMutexRelease(gap->state_mutex); + return SVCCTL_UserEvtFlowEnable; } void SVCCTL_SvcInit() { @@ -213,7 +223,7 @@ static void set_advertisment_service_uid(uint8_t* uid, uint8_t uid_len) { gap->gap_svc.adv_svc_uuid_len += uid_len; } -GapState gap_get_status() { +GapState gap_get_state() { return gap->state; } @@ -293,7 +303,7 @@ static void gap_init_svc(Gap* gap) { aci_gap_configure_whitelist(); } -static void gap_advertise(GapState new_state) +static void gap_advertise_start(GapState new_state) { tBleStatus status; uint16_t min_interval; @@ -317,7 +327,6 @@ static void gap_advertise(GapState new_state) } } // Configure advertising - gap->state = new_state; const char* name = furi_hal_version_get_ble_local_device_name_ptr(); status = aci_gap_set_discoverable(ADV_IND, min_interval, max_interval, PUBLIC_ADDR, 0, strlen(name), (uint8_t*)name, @@ -325,17 +334,40 @@ static void gap_advertise(GapState new_state) if(status) { FURI_LOG_E(GAP_TAG, "Set discoverable err: %d", status); } + gap->state = new_state; + bt_update_statusbar(gap->bt); osTimerStart(gap->advertise_timer, INITIAL_ADV_TIMEOUT); } -static void gap_advertise_request(Gap* gap) { - osThreadFlagsSet(gap->thread_id, 1); +static void gap_advertise_stop() { + if(gap->state == GapStateConnected) { + // Terminate connection + aci_gap_terminate(gap->gap_svc.connection_handle, 0x13); + } + if(gap->state > GapStateIdle) { + // Stop advertising + osTimerStop(gap->advertise_timer); + aci_gap_set_non_discoverable(); + gap->state = GapStateIdle; + bt_update_statusbar(gap->bt); + } +} + +void gap_start_advertising() { + gap->enable_adv = true; + GapCommand command = GapCommandAdvFast; + furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK); +} + +void gap_stop_advertising() { + gap->enable_adv = false; + GapCommand command = GapCommandAdvStop; + furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK); } static void gap_advetise_timer_callback(void* context) { - furi_assert(context); - Gap* gap = context; - gap_advertise_request(gap); + GapCommand command = GapCommandAdvLowPower; + furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK); } bool gap_init() { @@ -348,20 +380,25 @@ bool gap_init() { // Open Bt record gap->bt = furi_record_open("bt"); // Create advertising timer - gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, &gap, NULL); - // Initialization of HCI & GATT & GAP layer + gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, NULL, NULL); + // Initialization of GATT & GAP layer gap_init_svc(gap); // Initialization of the BLE Services SVCCTL_Init(); - // Initialization of the BLE App Context + // Initialization of the GAP state + gap->state_mutex = osMutexNew(NULL); gap->state = GapStateIdle; gap->gap_svc.connection_handle = 0xFFFF; + gap->enable_adv = true; // Thread configuration gap->thread_attr.name = "BLE advertising"; - gap->thread_attr.stack_size = 512; + gap->thread_attr.stack_size = 1024; gap->thread_id = osThreadNew(gap_app, NULL, &gap->thread_attr); + // Command queue allocation + gap->command_queue = osMessageQueueNew(8, sizeof(GapCommand), NULL); + // Start Device Information service dev_info_svc_start(); // Start Battery service @@ -374,14 +411,21 @@ bool gap_init() { adv_service_uid[1] = 0x30; set_advertisment_service_uid(adv_service_uid, sizeof(adv_service_uid)); - gap_advertise(GapStateAdvFast); return true; } static void gap_app(void *arg) { - // TODO Exit from app, stop service, clean memory + GapCommand command; while(1) { - osThreadFlagsWait(1, osFlagsWaitAny, osWaitForever); - gap_advertise(GapStateAdvLowPower); + furi_check(osMessageQueueGet(gap->command_queue, &command, NULL, osWaitForever) == osOK); + osMutexAcquire(gap->state_mutex, osWaitForever); + if(command == GapCommandAdvFast) { + gap_advertise_start(GapStateAdvFast); + } else if(command == GapCommandAdvLowPower) { + gap_advertise_start(GapStateAdvLowPower); + } else if(command == GapCommandAdvStop) { + gap_advertise_stop(); + } + osMutexRelease(gap->state_mutex); } } diff --git a/firmware/targets/f6/ble-glue/gap.h b/firmware/targets/f6/ble-glue/gap.h index 3fc2cf4c..93e75122 100644 --- a/firmware/targets/f6/ble-glue/gap.h +++ b/firmware/targets/f6/ble-glue/gap.h @@ -15,7 +15,11 @@ typedef enum { bool gap_init(); -GapState gap_get_status(); +void gap_start_advertising(); + +void gap_stop_advertising(); + +GapState gap_get_state(); #ifdef __cplusplus } diff --git a/firmware/targets/f6/ble-glue/serial_service.c b/firmware/targets/f6/ble-glue/serial_service.c index eae2c275..e5ab9d2d 100644 --- a/firmware/targets/f6/ble-glue/serial_service.c +++ b/firmware/targets/f6/ble-glue/serial_service.c @@ -61,7 +61,7 @@ void serial_svc_start() { status = aci_gatt_add_char(serial_svc->svc_handle, UUID_TYPE_128, (const Char_UUID_t*)char_tx_uuid, SERIAL_SVC_DATA_LEN_MAX, CHAR_PROP_WRITE_WITHOUT_RESP | CHAR_PROP_WRITE | CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ | ATTR_PERMISSION_AUTHEN_WRITE, GATT_NOTIFY_ATTRIBUTE_WRITE, 10, CHAR_VALUE_LEN_VARIABLE, @@ -74,7 +74,7 @@ void serial_svc_start() { status = aci_gatt_add_char(serial_svc->svc_handle, UUID_TYPE_128, (const Char_UUID_t*)char_rx_uuid, SERIAL_SVC_DATA_LEN_MAX, CHAR_PROP_READ | CHAR_PROP_INDICATE, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_VARIABLE, @@ -108,13 +108,15 @@ void serial_svc_stop() { bool serial_svc_update_rx(uint8_t* data, uint8_t data_len) { - furi_assert(data_len < SERIAL_SVC_DATA_LEN_MAX); + if(data_len > SERIAL_SVC_DATA_LEN_MAX) { + return false; + } tBleStatus result = aci_gatt_update_char_value(serial_svc->svc_handle, - serial_svc->rx_char_handle, - 0, - data_len, - data); + serial_svc->rx_char_handle, + 0, + data_len, + data); if(result) { FURI_LOG_E(SERIAL_SERVICE_TAG, "Failed updating RX characteristic: %d", result); } diff --git a/firmware/targets/f6/furi-hal/furi-hal-bt.c b/firmware/targets/f6/furi-hal/furi-hal-bt.c index 4d5e0674..89e03b38 100644 --- a/firmware/targets/f6/furi-hal/furi-hal-bt.c +++ b/firmware/targets/f6/furi-hal/furi-hal-bt.c @@ -4,7 +4,6 @@ #include #include #include -#include #include void furi_hal_bt_init() { @@ -14,10 +13,22 @@ void furi_hal_bt_init() { APPE_Init(); } -bool furi_hal_bt_start_app() { +bool furi_hal_bt_init_app() { return gap_init(); } +void furi_hal_bt_start_advertising() { + if(gap_get_state() == GapStateIdle) { + gap_start_advertising(); + } +} + +void furi_hal_bt_stop_advertising() { + if(furi_hal_bt_is_alive()) { + gap_stop_advertising(); + } +} + void furi_hal_bt_dump_state(string_t buffer) { BleGlueStatus status = APPE_Status(); if (status == BleGlueStatusStarted) { @@ -41,7 +52,7 @@ void furi_hal_bt_dump_state(string_t buffer) { } bool furi_hal_bt_is_alive() { - return APPE_Status() == BleGlueStatusStarted; + return gap_get_state() > GapStateIdle; } bool furi_hal_bt_wait_startup() { diff --git a/firmware/targets/f7/ble-glue/app_ble.c b/firmware/targets/f7/ble-glue/app_ble.c deleted file mode 100644 index 652c29ef..00000000 --- a/firmware/targets/f7/ble-glue/app_ble.c +++ /dev/null @@ -1,140 +0,0 @@ -#include "main.h" - -#include "app_entry.h" -#include "app_common.h" -#include "dbg_trace.h" -#include "ble.h" -#include "tl.h" -#include "app_ble.h" -#include "shci.h" -#include "cmsis_os.h" - -#include - -PLACE_IN_SECTION("MB_MEM1") ALIGN(4) static TL_CmdPacket_t BleCmdBuffer; - -// PLACE_IN_SECTION("TAG_OTA_END") const uint32_t MagicKeywordValue = 0x94448A29 ; -// PLACE_IN_SECTION("TAG_OTA_START") const uint32_t MagicKeywordAddress = (uint32_t)&MagicKeywordValue; - -osMutexId_t MtxHciId; -osSemaphoreId_t SemHciId; -osThreadId_t HciUserEvtProcessId; - -const osThreadAttr_t HciUserEvtProcess_attr = { - .name = CFG_HCI_USER_EVT_PROCESS_NAME, - .attr_bits = CFG_HCI_USER_EVT_PROCESS_ATTR_BITS, - .cb_mem = CFG_HCI_USER_EVT_PROCESS_CB_MEM, - .cb_size = CFG_HCI_USER_EVT_PROCESS_CB_SIZE, - .stack_mem = CFG_HCI_USER_EVT_PROCESS_STACK_MEM, - .priority = CFG_HCI_USER_EVT_PROCESS_PRIORITY, - .stack_size = CFG_HCI_USER_EVT_PROCESS_STACK_SIZE -}; - -/* Private function prototypes -----------------------------------------------*/ -static void HciUserEvtProcess(void *argument); -static void BLE_UserEvtRx( void * pPayload ); -static void BLE_StatusNot( HCI_TL_CmdStatus_t status ); -static void Ble_Tl_Init( void ); - -bool APP_BLE_Init() { - SHCI_C2_Ble_Init_Cmd_Packet_t ble_init_cmd_packet = { - {{0,0,0}}, /**< Header unused */ - {0, /** pBleBufferAddress not used */ - 0, /** BleBufferSize not used */ - CFG_BLE_NUM_GATT_ATTRIBUTES, - CFG_BLE_NUM_GATT_SERVICES, - CFG_BLE_ATT_VALUE_ARRAY_SIZE, - CFG_BLE_NUM_LINK, - CFG_BLE_DATA_LENGTH_EXTENSION, - CFG_BLE_PREPARE_WRITE_LIST_SIZE, - CFG_BLE_MBLOCK_COUNT, - CFG_BLE_MAX_ATT_MTU, - CFG_BLE_SLAVE_SCA, - CFG_BLE_MASTER_SCA, - CFG_BLE_LSE_SOURCE, - CFG_BLE_MAX_CONN_EVENT_LENGTH, - CFG_BLE_HSE_STARTUP_TIME, - CFG_BLE_VITERBI_MODE, - CFG_BLE_LL_ONLY, - 0} - }; - - // Initialize Ble Transport Layer - Ble_Tl_Init( ); - // Register the hci transport layer to handle BLE User Asynchronous Events - HciUserEvtProcessId = osThreadNew(HciUserEvtProcess, NULL, &HciUserEvtProcess_attr); - // Starts the BLE Stack on CPU2 - return (SHCI_C2_BLE_Init( &ble_init_cmd_packet ) == SHCI_Success); -} - -static void Ble_Tl_Init( void ) { - HCI_TL_HciInitConf_t Hci_Tl_Init_Conf; - - MtxHciId = osMutexNew( NULL ); - SemHciId = osSemaphoreNew( 1, 0, NULL ); /*< Create the semaphore and make it busy at initialization */ - - Hci_Tl_Init_Conf.p_cmdbuffer = (uint8_t*)&BleCmdBuffer; - Hci_Tl_Init_Conf.StatusNotCallBack = BLE_StatusNot; - hci_init(BLE_UserEvtRx, (void*) &Hci_Tl_Init_Conf); -} - -static void HciUserEvtProcess(void *argument) { - UNUSED(argument); - - for(;;) - { - osThreadFlagsWait( 1, osFlagsWaitAny, osWaitForever); - hci_user_evt_proc( ); - } -} - -/************************************************************* - * - * WRAP FUNCTIONS - * - *************************************************************/ -void hci_notify_asynch_evt(void* pdata) { - UNUSED(pdata); - osThreadFlagsSet( HciUserEvtProcessId, 1 ); -} - -void hci_cmd_resp_release(uint32_t flag) { - UNUSED(flag); - osSemaphoreRelease( SemHciId ); -} - -void hci_cmd_resp_wait(uint32_t timeout) { - UNUSED(timeout); - osSemaphoreAcquire( SemHciId, osWaitForever ); -} - -static void BLE_UserEvtRx( void * pPayload ) { - SVCCTL_UserEvtFlowStatus_t svctl_return_status; - tHCI_UserEvtRxParam *pParam; - - pParam = (tHCI_UserEvtRxParam *)pPayload; - - svctl_return_status = SVCCTL_UserEvtRx((void *)&(pParam->pckt->evtserial)); - if (svctl_return_status != SVCCTL_UserEvtFlowDisable) { - pParam->status = HCI_TL_UserEventFlow_Enable; - } else { - pParam->status = HCI_TL_UserEventFlow_Disable; - } -} - -static void BLE_StatusNot( HCI_TL_CmdStatus_t status ) { - switch (status) { - case HCI_TL_CmdBusy: - osMutexAcquire( MtxHciId, osWaitForever ); - break; - case HCI_TL_CmdAvailable: - osMutexRelease( MtxHciId ); - break; - default: - break; - } -} - -void SVCCTL_ResumeUserEventFlow( void ) { - hci_resume_flow(); -} diff --git a/firmware/targets/f7/ble-glue/app_conf.h b/firmware/targets/f7/ble-glue/app_conf.h index 381d5ae7..bfd6f9dd 100644 --- a/firmware/targets/f7/ble-glue/app_conf.h +++ b/firmware/targets/f7/ble-glue/app_conf.h @@ -427,9 +427,6 @@ typedef enum #define DBG_TRACE_MSG_QUEUE_SIZE 4096 #define MAX_DBG_TRACE_MSG_SIZE 1024 -#define CFG_LED_SUPPORTED 0 -#define CFG_BUTTON_SUPPORTED 0 - /****************************************************************************** * FreeRTOS ******************************************************************************/ @@ -441,34 +438,5 @@ typedef enum #define CFG_SHCI_USER_EVT_PROCESS_PRIORITY osPriorityNone #define CFG_SHCI_USER_EVT_PROCESS_STACK_SIZE (128 * 7) -#define CFG_HCI_USER_EVT_PROCESS_NAME "ble_hci_evt" -#define CFG_HCI_USER_EVT_PROCESS_ATTR_BITS (0) -#define CFG_HCI_USER_EVT_PROCESS_CB_MEM (0) -#define CFG_HCI_USER_EVT_PROCESS_CB_SIZE (0) -#define CFG_HCI_USER_EVT_PROCESS_STACK_MEM (0) -#define CFG_HCI_USER_EVT_PROCESS_PRIORITY osPriorityNone -#define CFG_HCI_USER_EVT_PROCESS_STACK_SIZE (128 * 8) - -#define CFG_ADV_UPDATE_PROCESS_NAME "ble_adv_upd" -#define CFG_ADV_UPDATE_PROCESS_ATTR_BITS (0) -#define CFG_ADV_UPDATE_PROCESS_CB_MEM (0) -#define CFG_ADV_UPDATE_PROCESS_CB_SIZE (0) -#define CFG_ADV_UPDATE_PROCESS_STACK_MEM (0) -#define CFG_ADV_UPDATE_PROCESS_PRIORITY osPriorityNone -#define CFG_ADV_UPDATE_PROCESS_STACK_SIZE (128 * 6) - -#define CFG_HRS_PROCESS_NAME "hrs" -#define CFG_HRS_PROCESS_ATTR_BITS (0) -#define CFG_HRS_PROCESS_CB_MEM (0) -#define CFG_HRS_PROCESS_CB_SIZE (0) -#define CFG_HRS_PROCESS_STACK_MEM (0) -#define CFG_HRS_PROCESS_PRIORITY osPriorityNone -#define CFG_HRS_PROCESS_STACK_SIZE (128 * 8) - -typedef enum { - CFG_LPM_APP, - CFG_LPM_APP_BLE, -} CFG_LPM_Id_t; - #define CFG_OTP_BASE_ADDRESS OTP_AREA_BASE #define CFG_OTP_END_ADRESS OTP_AREA_END_ADDR diff --git a/firmware/targets/f7/ble-glue/app_entry.c b/firmware/targets/f7/ble-glue/app_entry.c index 431fed6a..a970da32 100644 --- a/firmware/targets/f7/ble-glue/app_entry.c +++ b/firmware/targets/f7/ble-glue/app_entry.c @@ -1,7 +1,7 @@ #include "app_common.h" #include "main.h" #include "app_entry.h" -#include "app_ble.h" +#include "ble_app.h" #include "ble.h" #include "tl.h" #include "cmsis_os.h" @@ -47,8 +47,6 @@ void APPE_Init() { ble_glue_status = BleGlueStatusStartup; SystemPower_Config(); /**< Configure the system Power Mode */ - HW_TS_Init(hw_ts_InitMode_Full, &hrtc); /**< Initialize the TimerServer */ - // APPD_Init(); furi_hal_power_insomnia_enter(); @@ -137,7 +135,7 @@ static void APPE_SysUserEvtRx( void * pPayload ) { /* Traces channel initialization */ // APPD_EnableCPU2( ); - if (APP_BLE_Init()) { + if(ble_app_init()) { FURI_LOG_I("Core2", "BLE stack started"); ble_glue_status = BleGlueStatusStarted; } else { diff --git a/firmware/targets/f7/ble-glue/battery_service.c b/firmware/targets/f7/ble-glue/battery_service.c index 654edd53..1dd8c5a0 100644 --- a/firmware/targets/f7/ble-glue/battery_service.c +++ b/firmware/targets/f7/ble-glue/battery_service.c @@ -31,7 +31,7 @@ void battery_svc_start() { (Char_UUID_t *) &char_battery_level_uuid, 1, CHAR_PROP_READ | CHAR_PROP_NOTIFY, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, diff --git a/firmware/targets/f7/ble-glue/ble_app.c b/firmware/targets/f7/ble-glue/ble_app.c new file mode 100644 index 00000000..e28facd6 --- /dev/null +++ b/firmware/targets/f7/ble-glue/ble_app.c @@ -0,0 +1,119 @@ +#include "ble_app.h" + +#include "hci_tl.h" +#include "ble.h" +#include "shci.h" +#include "cmsis_os.h" +#include "gap.h" + +#include + +#define BLE_APP_TAG "ble app" + +PLACE_IN_SECTION("MB_MEM1") ALIGN(4) static TL_CmdPacket_t ble_app_cmd_buffer; + +typedef struct { + osMutexId_t hci_mtx; + osSemaphoreId_t hci_sem; + osThreadId_t hci_thread_id; + osThreadAttr_t hci_thread_attr; +} BleApp; + +static BleApp* ble_app; + +static void ble_app_hci_thread(void *arg); +static void ble_app_hci_event_handler(void * pPayload); +static void ble_app_hci_status_not_handler(HCI_TL_CmdStatus_t status); + +bool ble_app_init() { + ble_app = furi_alloc(sizeof(BleApp)); + + // Allocate semafore and mutex for ble command buffer access + ble_app->hci_mtx = osMutexNew(NULL); + ble_app->hci_sem = osSemaphoreNew(1, 0, NULL); + // HCI transport layer thread to handle user asynch events + ble_app->hci_thread_attr.name = "ble hci"; + ble_app->hci_thread_attr.stack_size = 1024; + ble_app->hci_thread_id = osThreadNew(ble_app_hci_thread, NULL, &ble_app->hci_thread_attr); + + // Initialize Ble Transport Layer + HCI_TL_HciInitConf_t hci_tl_config = { + .p_cmdbuffer = (uint8_t*)&ble_app_cmd_buffer, + .StatusNotCallBack = ble_app_hci_status_not_handler, + }; + hci_init(ble_app_hci_event_handler, (void*)&hci_tl_config); + + // Start ble stack on 2nd core + SHCI_C2_Ble_Init_Cmd_Packet_t ble_init_cmd_packet = { + .Header = {{0,0,0}}, // Header unused + .Param = { + 0, // pBleBufferAddress not used + 0, // BleBufferSize not used + CFG_BLE_NUM_GATT_ATTRIBUTES, + CFG_BLE_NUM_GATT_SERVICES, + CFG_BLE_ATT_VALUE_ARRAY_SIZE, + CFG_BLE_NUM_LINK, + CFG_BLE_DATA_LENGTH_EXTENSION, + CFG_BLE_PREPARE_WRITE_LIST_SIZE, + CFG_BLE_MBLOCK_COUNT, + CFG_BLE_MAX_ATT_MTU, + CFG_BLE_SLAVE_SCA, + CFG_BLE_MASTER_SCA, + CFG_BLE_LSE_SOURCE, + CFG_BLE_MAX_CONN_EVENT_LENGTH, + CFG_BLE_HSE_STARTUP_TIME, + CFG_BLE_VITERBI_MODE, + CFG_BLE_LL_ONLY, + 0, + } + }; + SHCI_CmdStatus_t status = SHCI_C2_BLE_Init(&ble_init_cmd_packet); + if(status) { + FURI_LOG_E(BLE_APP_TAG, "Failed to start ble stack: %d", status); + } + return status == SHCI_Success; +} + +static void ble_app_hci_thread(void *arg) { + while(1) { + osThreadFlagsWait(1, osFlagsWaitAny, osWaitForever); + hci_user_evt_proc(); + } +} + +// Called by WPAN lib +void hci_notify_asynch_evt(void* pdata) { + osThreadFlagsSet(ble_app->hci_thread_id, 1); +} + +void hci_cmd_resp_release(uint32_t flag) { + osSemaphoreRelease(ble_app->hci_sem); +} + +void hci_cmd_resp_wait(uint32_t timeout) { + osSemaphoreAcquire(ble_app->hci_sem, osWaitForever); +} + +static void ble_app_hci_event_handler( void * pPayload ) { + SVCCTL_UserEvtFlowStatus_t svctl_return_status; + tHCI_UserEvtRxParam *pParam = (tHCI_UserEvtRxParam *)pPayload; + + svctl_return_status = SVCCTL_UserEvtRx((void *)&(pParam->pckt->evtserial)); + if (svctl_return_status != SVCCTL_UserEvtFlowDisable) { + pParam->status = HCI_TL_UserEventFlow_Enable; + } else { + pParam->status = HCI_TL_UserEventFlow_Disable; + } +} + +static void ble_app_hci_status_not_handler( HCI_TL_CmdStatus_t status ) { + if(status == HCI_TL_CmdBusy) { + osMutexAcquire(ble_app->hci_mtx, osWaitForever ); + } else if(status == HCI_TL_CmdAvailable) { + osMutexRelease(ble_app->hci_mtx); + } +} + +void SVCCTL_ResumeUserEventFlow( void ) { + hci_resume_flow(); +} diff --git a/firmware/targets/f6/ble-glue/app_ble.h b/firmware/targets/f7/ble-glue/ble_app.h similarity index 72% rename from firmware/targets/f6/ble-glue/app_ble.h rename to firmware/targets/f7/ble-glue/ble_app.h index 08c60fe3..17d8dc5f 100644 --- a/firmware/targets/f6/ble-glue/app_ble.h +++ b/firmware/targets/f7/ble-glue/ble_app.h @@ -5,9 +5,8 @@ extern "C" { #endif #include -#include "hci_tl.h" -bool APP_BLE_Init(); +bool ble_app_init(); #ifdef __cplusplus } diff --git a/firmware/targets/f7/ble-glue/dev_info_service.c b/firmware/targets/f7/ble-glue/dev_info_service.c index db58226b..ae07d9bc 100644 --- a/firmware/targets/f7/ble-glue/dev_info_service.c +++ b/firmware/targets/f7/ble-glue/dev_info_service.c @@ -39,7 +39,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_man_name), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, @@ -53,7 +53,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_serial_num), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, @@ -67,7 +67,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_firmware_rev_num), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, @@ -81,7 +81,7 @@ void dev_info_svc_start() { (Char_UUID_t*)&uuid, strlen(dev_info_software_rev_num), CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_CONSTANT, diff --git a/firmware/targets/f7/ble-glue/gap.c b/firmware/targets/f7/ble-glue/gap.c index 19d1b5f1..74e1d35a 100644 --- a/firmware/targets/f7/ble-glue/gap.c +++ b/firmware/targets/f7/ble-glue/gap.c @@ -31,13 +31,22 @@ typedef struct { typedef struct { GapSvc gap_svc; GapState state; + osMutexId_t state_mutex; uint8_t mac_address[BD_ADDR_SIZE_LOCAL]; Bt* bt; osTimerId advertise_timer; osThreadAttr_t thread_attr; osThreadId_t thread_id; + osMessageQueueId_t command_queue; + bool enable_adv; } Gap; +typedef enum { + GapCommandAdvFast, + GapCommandAdvLowPower, + GapCommandAdvStop, +} GapCommand; + // Identity root key static const uint8_t gap_irk[16] = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0}; // Encryption root key @@ -49,150 +58,151 @@ static const uint8_t gap_default_mac_addr[] = {0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x7 static Gap* gap = NULL; -static void gap_advertise(GapState new_state); +static void gap_advertise_start(GapState new_state); static void gap_app(void *arg); SVCCTL_UserEvtFlowStatus_t SVCCTL_App_Notification( void *pckt ) { - hci_event_pckt *event_pckt; - evt_le_meta_event *meta_evt; - evt_blue_aci *blue_evt; - hci_le_phy_update_complete_event_rp0 *evt_le_phy_update_complete; - uint8_t tx_phy; - uint8_t rx_phy; - tBleStatus ret = BLE_STATUS_INVALID_PARAMS; + hci_event_pckt *event_pckt; + evt_le_meta_event *meta_evt; + evt_blue_aci *blue_evt; + hci_le_phy_update_complete_event_rp0 *evt_le_phy_update_complete; + uint8_t tx_phy; + uint8_t rx_phy; + tBleStatus ret = BLE_STATUS_INVALID_PARAMS; - event_pckt = (hci_event_pckt*) ((hci_uart_pckt *) pckt)->data; + event_pckt = (hci_event_pckt*) ((hci_uart_pckt *) pckt)->data; - switch (event_pckt->evt) { - case EVT_DISCONN_COMPLETE: - { - hci_disconnection_complete_event_rp0 *disconnection_complete_event = (hci_disconnection_complete_event_rp0 *) event_pckt->data; - if (disconnection_complete_event->Connection_Handle == gap->gap_svc.connection_handle) { - gap->gap_svc.connection_handle = 0; - gap->state = GapStateIdle; - FURI_LOG_I(GAP_TAG, "Disconnect from client"); + osMutexAcquire(gap->state_mutex, osWaitForever); + switch (event_pckt->evt) { + case EVT_DISCONN_COMPLETE: + { + hci_disconnection_complete_event_rp0 *disconnection_complete_event = (hci_disconnection_complete_event_rp0 *) event_pckt->data; + if (disconnection_complete_event->Connection_Handle == gap->gap_svc.connection_handle) { + gap->gap_svc.connection_handle = 0; + gap->state = GapStateIdle; + FURI_LOG_I(GAP_TAG, "Disconnect from client"); + } + if(gap->enable_adv) { + // Restart advertising + gap_start_advertising(); + furi_hal_power_insomnia_exit(); + } } - // Restart advertising - gap_advertise(GapStateAdvFast); - furi_hal_power_insomnia_exit(); - } - break; + break; - case EVT_LE_META_EVENT: - meta_evt = (evt_le_meta_event*) event_pckt->data; - switch (meta_evt->subevent) { - case EVT_LE_CONN_UPDATE_COMPLETE: - FURI_LOG_D(GAP_TAG, "Connection update event"); - break; + case EVT_LE_META_EVENT: + meta_evt = (evt_le_meta_event*) event_pckt->data; + switch (meta_evt->subevent) { + case EVT_LE_CONN_UPDATE_COMPLETE: + FURI_LOG_D(GAP_TAG, "Connection update event"); + break; - case EVT_LE_PHY_UPDATE_COMPLETE: - evt_le_phy_update_complete = (hci_le_phy_update_complete_event_rp0*)meta_evt->data; - if(evt_le_phy_update_complete->Status) { - FURI_LOG_E(GAP_TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status); - } else { - FURI_LOG_I(GAP_TAG, "Update PHY succeed"); + case EVT_LE_PHY_UPDATE_COMPLETE: + evt_le_phy_update_complete = (hci_le_phy_update_complete_event_rp0*)meta_evt->data; + if(evt_le_phy_update_complete->Status) { + FURI_LOG_E(GAP_TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status); + } else { + FURI_LOG_I(GAP_TAG, "Update PHY succeed"); + } + ret = hci_le_read_phy(gap->gap_svc.connection_handle,&tx_phy,&rx_phy); + if(ret) { + FURI_LOG_E(GAP_TAG, "Read PHY failed, status: %d", ret); + } else { + FURI_LOG_I(GAP_TAG, "PHY Params TX = %d, RX = %d ", tx_phy, rx_phy); + } + break; + + case EVT_LE_CONN_COMPLETE: + furi_hal_power_insomnia_enter(); + hci_le_connection_complete_event_rp0* connection_complete_event = (hci_le_connection_complete_event_rp0 *) meta_evt->data; + FURI_LOG_I(GAP_TAG, "Connection complete for connection handle 0x%x", connection_complete_event->Connection_Handle); + + // Stop advertising as connection completed + osTimerStop(gap->advertise_timer); + + // Update connection status and handle + gap->state = GapStateConnected; + gap->gap_svc.connection_handle = connection_complete_event->Connection_Handle; + + // Start pairing by sending security request + aci_gap_slave_security_req(connection_complete_event->Connection_Handle); + break; + + default: + break; } - ret = hci_le_read_phy(gap->gap_svc.connection_handle,&tx_phy,&rx_phy); - if(ret) { - FURI_LOG_E(GAP_TAG, "Read PHY failed, status: %d", ret); - } else { - FURI_LOG_I(GAP_TAG, "PHY Params TX= %d, RX= %d ", tx_phy, rx_phy); + break; + + case EVT_VENDOR: + blue_evt = (evt_blue_aci*) event_pckt->data; + switch (blue_evt->ecode) { + aci_gap_pairing_complete_event_rp0 *pairing_complete; + + case EVT_BLUE_GAP_LIMITED_DISCOVERABLE: + FURI_LOG_I(GAP_TAG, "Limited discoverable event"); + break; + + case EVT_BLUE_GAP_PASS_KEY_REQUEST: + { + // Generate random PIN code + uint32_t pin = rand() % 999999; + aci_gap_pass_key_resp(gap->gap_svc.connection_handle, pin); + FURI_LOG_I(GAP_TAG, "Pass key request event. Pin: %d", pin); + bt_pin_code_show(gap->bt, pin); } - break; + break; - case EVT_LE_CONN_COMPLETE: - furi_hal_power_insomnia_enter(); - hci_le_connection_complete_event_rp0* connection_complete_event = (hci_le_connection_complete_event_rp0 *) meta_evt->data; - FURI_LOG_I(GAP_TAG, "Connection complete for connection handle 0x%x", connection_complete_event->Connection_Handle); + case EVT_BLUE_GAP_AUTHORIZATION_REQUEST: + FURI_LOG_I(GAP_TAG, "Authorization request event"); + break; - // Stop advertising as connection completed - osTimerStop(gap->advertise_timer); + case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED: + FURI_LOG_I(GAP_TAG, "Slave security initiated"); + break; - // Update connection status and handle - gap->state = GapStateConnected; - gap->gap_svc.connection_handle = connection_complete_event->Connection_Handle; + case EVT_BLUE_GAP_BOND_LOST: + FURI_LOG_I(GAP_TAG, "Bond lost event. Start rebonding"); + aci_gap_allow_rebond(gap->gap_svc.connection_handle); + break; - // Start pairing by sending security request - aci_gap_slave_security_req(connection_complete_event->Connection_Handle); - break; + case EVT_BLUE_GAP_DEVICE_FOUND: + FURI_LOG_I(GAP_TAG, "Device found event"); + break; + case EVT_BLUE_GAP_ADDR_NOT_RESOLVED: + FURI_LOG_I(GAP_TAG, "Address not resolved event"); + break; + + case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION: + FURI_LOG_I(GAP_TAG, "Key press notification event"); + break; + + case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE: + FURI_LOG_I(GAP_TAG, "Hex_value = %lx", + ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value); + aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1); + break; + + case EVT_BLUE_GAP_PAIRING_CMPLT: + pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data; + if (pairing_complete->Status) { + FURI_LOG_E(GAP_TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status); + aci_gap_terminate(gap->gap_svc.connection_handle, 5); + } else { + FURI_LOG_I(GAP_TAG, "Pairing complete"); + } + break; + + case EVT_BLUE_GAP_PROCEDURE_COMPLETE: + FURI_LOG_I(GAP_TAG, "Procedure complete event"); + break; + } default: - break; - } - break; - - case EVT_VENDOR: - blue_evt = (evt_blue_aci*) event_pckt->data; - switch (blue_evt->ecode) { - aci_gap_pairing_complete_event_rp0 *pairing_complete; - - case EVT_BLUE_GAP_LIMITED_DISCOVERABLE: - FURI_LOG_I(GAP_TAG, "Limited discoverable event"); - break; - - case EVT_BLUE_GAP_PASS_KEY_REQUEST: - { - // Generate random PIN code - uint32_t pin = rand() % 999999; - aci_gap_pass_key_resp(gap->gap_svc.connection_handle, pin); - FURI_LOG_I(GAP_TAG, "Pass key request event. Pin: %d", pin); - bt_pin_code_show(gap->bt, pin); - } - break; - - case EVT_BLUE_GAP_AUTHORIZATION_REQUEST: - FURI_LOG_I(GAP_TAG, "Authorization request event"); - break; - - case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED: - FURI_LOG_I(GAP_TAG, "Slave security initiated"); - break; - - case EVT_BLUE_GAP_BOND_LOST: - FURI_LOG_I(GAP_TAG, "Bond lost event. Start rebonding"); - aci_gap_allow_rebond(gap->gap_svc.connection_handle); - break; - - case EVT_BLUE_GAP_DEVICE_FOUND: - FURI_LOG_I(GAP_TAG, "Device found event"); - break; - - case EVT_BLUE_GAP_ADDR_NOT_RESOLVED: - FURI_LOG_I(GAP_TAG, "Address not resolved event"); - break; - - case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION: - FURI_LOG_I(GAP_TAG, "Key press notification event"); - break; - - case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE: - FURI_LOG_I(GAP_TAG, "Hex_value = %lx", - ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value); - aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1); - break; - - case (EVT_BLUE_GAP_PAIRING_CMPLT): - { - pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data; - if (pairing_complete->Status) { - FURI_LOG_E(GAP_TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status); - aci_gap_terminate(gap->gap_svc.connection_handle, 5); - } else { - FURI_LOG_I(GAP_TAG, "Pairing complete"); - } - } - break; - - case EVT_BLUE_GAP_PROCEDURE_COMPLETE: - FURI_LOG_I(GAP_TAG, "Procedure complete event"); - break; - } - default: - break; - } - - return SVCCTL_UserEvtFlowEnable; + break; + } + osMutexRelease(gap->state_mutex); + return SVCCTL_UserEvtFlowEnable; } void SVCCTL_SvcInit() { @@ -213,7 +223,7 @@ static void set_advertisment_service_uid(uint8_t* uid, uint8_t uid_len) { gap->gap_svc.adv_svc_uuid_len += uid_len; } -GapState gap_get_status() { +GapState gap_get_state() { return gap->state; } @@ -293,7 +303,7 @@ static void gap_init_svc(Gap* gap) { aci_gap_configure_whitelist(); } -static void gap_advertise(GapState new_state) +static void gap_advertise_start(GapState new_state) { tBleStatus status; uint16_t min_interval; @@ -317,7 +327,6 @@ static void gap_advertise(GapState new_state) } } // Configure advertising - gap->state = new_state; const char* name = furi_hal_version_get_ble_local_device_name_ptr(); status = aci_gap_set_discoverable(ADV_IND, min_interval, max_interval, PUBLIC_ADDR, 0, strlen(name), (uint8_t*)name, @@ -325,17 +334,40 @@ static void gap_advertise(GapState new_state) if(status) { FURI_LOG_E(GAP_TAG, "Set discoverable err: %d", status); } + gap->state = new_state; + bt_update_statusbar(gap->bt); osTimerStart(gap->advertise_timer, INITIAL_ADV_TIMEOUT); } -static void gap_advertise_request(Gap* gap) { - osThreadFlagsSet(gap->thread_id, 1); +static void gap_advertise_stop() { + if(gap->state == GapStateConnected) { + // Terminate connection + aci_gap_terminate(gap->gap_svc.connection_handle, 0x13); + } + if(gap->state > GapStateIdle) { + // Stop advertising + osTimerStop(gap->advertise_timer); + aci_gap_set_non_discoverable(); + gap->state = GapStateIdle; + bt_update_statusbar(gap->bt); + } +} + +void gap_start_advertising() { + gap->enable_adv = true; + GapCommand command = GapCommandAdvFast; + furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK); +} + +void gap_stop_advertising() { + gap->enable_adv = false; + GapCommand command = GapCommandAdvStop; + furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK); } static void gap_advetise_timer_callback(void* context) { - furi_assert(context); - Gap* gap = context; - gap_advertise_request(gap); + GapCommand command = GapCommandAdvLowPower; + furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK); } bool gap_init() { @@ -348,20 +380,25 @@ bool gap_init() { // Open Bt record gap->bt = furi_record_open("bt"); // Create advertising timer - gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, &gap, NULL); - // Initialization of HCI & GATT & GAP layer + gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, NULL, NULL); + // Initialization of GATT & GAP layer gap_init_svc(gap); // Initialization of the BLE Services SVCCTL_Init(); - // Initialization of the BLE App Context + // Initialization of the GAP state + gap->state_mutex = osMutexNew(NULL); gap->state = GapStateIdle; gap->gap_svc.connection_handle = 0xFFFF; + gap->enable_adv = true; // Thread configuration gap->thread_attr.name = "BLE advertising"; - gap->thread_attr.stack_size = 512; + gap->thread_attr.stack_size = 1024; gap->thread_id = osThreadNew(gap_app, NULL, &gap->thread_attr); + // Command queue allocation + gap->command_queue = osMessageQueueNew(8, sizeof(GapCommand), NULL); + // Start Device Information service dev_info_svc_start(); // Start Battery service @@ -374,14 +411,21 @@ bool gap_init() { adv_service_uid[1] = 0x30; set_advertisment_service_uid(adv_service_uid, sizeof(adv_service_uid)); - gap_advertise(GapStateAdvFast); return true; } static void gap_app(void *arg) { - // TODO Exit from app, stop service, clean memory + GapCommand command; while(1) { - osThreadFlagsWait(1, osFlagsWaitAny, osWaitForever); - gap_advertise(GapStateAdvLowPower); + furi_check(osMessageQueueGet(gap->command_queue, &command, NULL, osWaitForever) == osOK); + osMutexAcquire(gap->state_mutex, osWaitForever); + if(command == GapCommandAdvFast) { + gap_advertise_start(GapStateAdvFast); + } else if(command == GapCommandAdvLowPower) { + gap_advertise_start(GapStateAdvLowPower); + } else if(command == GapCommandAdvStop) { + gap_advertise_stop(); + } + osMutexRelease(gap->state_mutex); } } diff --git a/firmware/targets/f7/ble-glue/gap.h b/firmware/targets/f7/ble-glue/gap.h index 3fc2cf4c..93e75122 100644 --- a/firmware/targets/f7/ble-glue/gap.h +++ b/firmware/targets/f7/ble-glue/gap.h @@ -15,7 +15,11 @@ typedef enum { bool gap_init(); -GapState gap_get_status(); +void gap_start_advertising(); + +void gap_stop_advertising(); + +GapState gap_get_state(); #ifdef __cplusplus } diff --git a/firmware/targets/f7/ble-glue/serial_service.c b/firmware/targets/f7/ble-glue/serial_service.c index eae2c275..e5ab9d2d 100644 --- a/firmware/targets/f7/ble-glue/serial_service.c +++ b/firmware/targets/f7/ble-glue/serial_service.c @@ -61,7 +61,7 @@ void serial_svc_start() { status = aci_gatt_add_char(serial_svc->svc_handle, UUID_TYPE_128, (const Char_UUID_t*)char_tx_uuid, SERIAL_SVC_DATA_LEN_MAX, CHAR_PROP_WRITE_WITHOUT_RESP | CHAR_PROP_WRITE | CHAR_PROP_READ, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ | ATTR_PERMISSION_AUTHEN_WRITE, GATT_NOTIFY_ATTRIBUTE_WRITE, 10, CHAR_VALUE_LEN_VARIABLE, @@ -74,7 +74,7 @@ void serial_svc_start() { status = aci_gatt_add_char(serial_svc->svc_handle, UUID_TYPE_128, (const Char_UUID_t*)char_rx_uuid, SERIAL_SVC_DATA_LEN_MAX, CHAR_PROP_READ | CHAR_PROP_INDICATE, - ATTR_PERMISSION_NONE, + ATTR_PERMISSION_AUTHEN_READ, GATT_DONT_NOTIFY_EVENTS, 10, CHAR_VALUE_LEN_VARIABLE, @@ -108,13 +108,15 @@ void serial_svc_stop() { bool serial_svc_update_rx(uint8_t* data, uint8_t data_len) { - furi_assert(data_len < SERIAL_SVC_DATA_LEN_MAX); + if(data_len > SERIAL_SVC_DATA_LEN_MAX) { + return false; + } tBleStatus result = aci_gatt_update_char_value(serial_svc->svc_handle, - serial_svc->rx_char_handle, - 0, - data_len, - data); + serial_svc->rx_char_handle, + 0, + data_len, + data); if(result) { FURI_LOG_E(SERIAL_SERVICE_TAG, "Failed updating RX characteristic: %d", result); } diff --git a/firmware/targets/f7/furi-hal/furi-hal-bt.c b/firmware/targets/f7/furi-hal/furi-hal-bt.c index 4d5e0674..89e03b38 100644 --- a/firmware/targets/f7/furi-hal/furi-hal-bt.c +++ b/firmware/targets/f7/furi-hal/furi-hal-bt.c @@ -4,7 +4,6 @@ #include #include #include -#include #include void furi_hal_bt_init() { @@ -14,10 +13,22 @@ void furi_hal_bt_init() { APPE_Init(); } -bool furi_hal_bt_start_app() { +bool furi_hal_bt_init_app() { return gap_init(); } +void furi_hal_bt_start_advertising() { + if(gap_get_state() == GapStateIdle) { + gap_start_advertising(); + } +} + +void furi_hal_bt_stop_advertising() { + if(furi_hal_bt_is_alive()) { + gap_stop_advertising(); + } +} + void furi_hal_bt_dump_state(string_t buffer) { BleGlueStatus status = APPE_Status(); if (status == BleGlueStatusStarted) { @@ -41,7 +52,7 @@ void furi_hal_bt_dump_state(string_t buffer) { } bool furi_hal_bt_is_alive() { - return APPE_Status() == BleGlueStatusStarted; + return gap_get_state() > GapStateIdle; } bool furi_hal_bt_wait_startup() { diff --git a/firmware/targets/furi-hal-include/furi-hal-bt.h b/firmware/targets/furi-hal-include/furi-hal-bt.h index 801e3c48..c5c284db 100644 --- a/firmware/targets/furi-hal-include/furi-hal-bt.h +++ b/firmware/targets/furi-hal-include/furi-hal-bt.h @@ -11,7 +11,13 @@ extern "C" { void furi_hal_bt_init(); /** Start BLE app */ -bool furi_hal_bt_start_app(); +bool furi_hal_bt_init_app(); + +/** Start advertising */ +void furi_hal_bt_start_advertising(); + +/** Stop advertising */ +void furi_hal_bt_stop_advertising(); /** Get BT/BLE system component state */ void furi_hal_bt_dump_state(string_t buffer);