diff --git a/bthome_phy6222/Makefile b/bthome_phy6222/Makefile index 8cc1900..c64f473 100644 --- a/bthome_phy6222/Makefile +++ b/bthome_phy6222/Makefile @@ -208,6 +208,7 @@ DEFINES += -DPHY_MCU_TYPE=MCU_BUMBEE_M0 DEFINES += -DDEF_GAPBOND_MGR_ENABLE=0 DEFINES += -DUSE_FS=0 DEFINES += -DMAX_NUM_LL_CONN=1 +DEFINES += -DXFLASH_HIGH_SPEED=1 CFLAGS += $(DEFINES) $(INCLUDES) diff --git a/bthome_phy6222/SDK/components/driver/flash/flash.c b/bthome_phy6222/SDK/components/driver/flash/flash.c index 5f3cdbe..a97ff63 100644 --- a/bthome_phy6222/SDK/components/driver/flash/flash.c +++ b/bthome_phy6222/SDK/components/driver/flash/flash.c @@ -239,21 +239,15 @@ static void hw_spif_config_high_speed(sysclk_t ref_clk) AP_SPIF->config = tmp; subWriteReg(&AP_SPIF->rddata_capture, 4, 1, 2); } + #endif static void hw_spif_cache_config(void) { - extern volatile sysclk_t g_system_clk; - sysclk_t spif_ref_clk = (g_system_clk > SYS_CLK_XTAL_16M) ? SYS_CLK_DLL_64M : g_system_clk; - - if(s_xflashCtx.rd_instr == XFRD_FCMD_READ_QUAD) - spif_config(spif_ref_clk,/*div*/1,s_xflashCtx.rd_instr,0,1); - else - spif_config(spif_ref_clk,/*div*/1,s_xflashCtx.rd_instr,0,0); - - #ifdef XFLASH_HIGH_SPEED + spif_config(s_xflashCtx.spif_ref_clk,/*div*/1,s_xflashCtx.rd_instr,0,(s_xflashCtx.rd_instr == XFRD_FCMD_READ_QUAD)); +#ifdef XFLASH_HIGH_SPEED hw_spif_config_high_speed(s_xflashCtx.spif_ref_clk); - #endif +#endif AP_SPIF->wr_completion_ctrl=0xff010005;//set longest polling interval AP_SPIF->low_wr_protection = 0; AP_SPIF->up_wr_protection = 0x10; @@ -264,6 +258,7 @@ static void hw_spif_cache_config(void) hal_get_flash_info(); } + int hal_spif_cache_init(xflash_Ctx_t cfg) { memset(&(s_xflashCtx), 0, sizeof(s_xflashCtx)); memcpy(&(s_xflashCtx), &cfg, sizeof(s_xflashCtx)); diff --git a/bthome_phy6222/SDK/components/driver/watchdog/watchdog.c b/bthome_phy6222/SDK/components/driver/watchdog/watchdog.c index 6cff4b5..44fcc29 100644 --- a/bthome_phy6222/SDK/components/driver/watchdog/watchdog.c +++ b/bthome_phy6222/SDK/components/driver/watchdog/watchdog.c @@ -14,7 +14,7 @@ void hal_WATCHDOG_IRQHandler(void) { // volatile uint32_t a; // a = AP_WDT->EOI; - (volatile void)AP_WDT->EOI; + AP_WDT->EOI; AP_WDT->CRR = 0x76; //LOG("WDT IRQ[%08x]\n",rtc_get_counter()); } @@ -69,7 +69,7 @@ __ATTR_SECTION_SRAM__ void hal_watchdog_init(void) delay--; // a = AP_WDT->EOI; - (volatile void)AP_WDT->EOI; + AP_WDT->EOI; AP_WDT->TORR = g_wdt_cycle; #if (HAL_WDG_CFG_MODE==WDG_USE_INT_MODE) NVIC_SetPriority((IRQn_Type)WDT_IRQn, IRQ_PRIO_HAL); diff --git a/bthome_phy6222/SDK/lib/rf/patch.c b/bthome_phy6222/SDK/lib/rf/patch.c index dde7146..cb37d7b 100644 --- a/bthome_phy6222/SDK/lib/rf/patch.c +++ b/bthome_phy6222/SDK/lib/rf/patch.c @@ -7676,7 +7676,7 @@ __ATTR_SECTION_XIP__ void init_config(void) pGlobal_config[LL_SWITCH] = LL_DEBUG_ALLOW | SLAVE_LATENCY_ALLOW | LL_WHITELIST_ALLOW | SIMUL_CONN_ADV_ALLOW | SIMUL_CONN_SCAN_ALLOW; //RC32_TRACKINK_ALLOW - if(g_clk32K_config==CLK_32K_XTAL) + if(g_clk32K_config == CLK_32K_XTAL) pGlobal_config[LL_SWITCH] &= 0xffffffee; else pGlobal_config[LL_SWITCH] |= RC32_TRACKINK_ALLOW | LL_RC32K_SEL; @@ -7684,7 +7684,7 @@ __ATTR_SECTION_XIP__ void init_config(void) // sleep delay pGlobal_config[MIN_TIME_TO_STABLE_32KHZ_XOSC] = 10; // 10ms, temporary set // system clock setting - pGlobal_config[CLOCK_SETTING] = g_system_clk;//CLOCK_32MHZ; + pGlobal_config[CLOCK_SETTING] = g_system_clk; //CLOCK_32MHZ; //------------------------------------------------------------------------ // wakeup time cose // t1. HW_Wakeup->MCU relase 62.5us diff --git a/bthome_phy6222/source/battery.h b/bthome_phy6222/source/battery.h index 727f1fb..be7662e 100644 --- a/bthome_phy6222/source/battery.h +++ b/bthome_phy6222/source/battery.h @@ -1,51 +1,11 @@ /************************************************************************************************** - - Phyplus Microelectronics Limited confidential and proprietary. - All rights reserved. - - IMPORTANT: All rights of this software belong to Phyplus Microelectronics - Limited ("Phyplus"). Your use of this Software is limited to those - specific rights granted under the terms of the business contract, the - confidential agreement, the non-disclosure agreement and any other forms - of agreements as a customer or a partner of Phyplus. You may not use this - Software unless you agree to abide by the terms of these agreements. - You acknowledge that the Software may not be modified, copied, - distributed or disclosed unless embedded on a Phyplus Bluetooth Low Energy - (BLE) integrated circuit, either as a product or is integrated into your - products. Other than for the aforementioned purposes, you may not use, - reproduce, copy, prepare derivative works of, modify, distribute, perform, - display or sell this Software and/or its documentation for any purposes. - - YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE - PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, - INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, - NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL - PHYPLUS OR ITS SUBSIDIARIES BE LIABLE OR OBLIGATED UNDER CONTRACT, - NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER - LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES - INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE - OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT - OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES - (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. - + battery.h **************************************************************************************************/ - -/************************************************************** - * - * Module Name: battery - * File name: battery.h - * Brief description: - * battery module - * Author: Eagle.Lao - * Revision:V0.01 - -****************************************************************/ - #ifndef _BATTERY_HEAD_FILE #define _BATTERY_HEAD_FILE -#define BATT_TIMER_MEASURE_INTERVAL 3*60*1000 // 3 minute interval +#define BATT_TIMER_MEASURE_INTERVAL 3*60*1000 // 3 minute interval void batt_start_measure(void); diff --git a/bthome_phy6222/source/battservice.c b/bthome_phy6222/source/battservice.c index d66165b..cc81599 100644 --- a/bthome_phy6222/source/battservice.c +++ b/bthome_phy6222/source/battservice.c @@ -1,11 +1,9 @@ /************************************************************************************************** -******* + battservice.c **************************************************************************************************/ - - /********************************************************************* - INCLUDES + INCLUDES */ #include "bcomdef.h" #include "types.h" @@ -21,51 +19,51 @@ #include "battservice.h" #include "sensor.h" /********************************************************************* - MACROS + MACROS */ /********************************************************************* - CONSTANTS + CONSTANTS */ -#define BATT_LEVEL_VALUE_IDX 2 // Position of battery level in attribute array -#define BATT_LEVEL_VALUE_CCCD_IDX 3 // Position of battery level CCCD in attribute array +#define BATT_LEVEL_VALUE_IDX 2 // Position of battery level in attribute array +#define BATT_LEVEL_VALUE_CCCD_IDX 3 // Position of battery level CCCD in attribute array /********************************************************************* - TYPEDEFS + TYPEDEFS */ /********************************************************************* - GLOBAL VARIABLES + GLOBAL VARIABLES */ // Battery service CONST uint8 battServUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(BATT_SERV_UUID), HI_UINT16(BATT_SERV_UUID) + LO_UINT16(BATT_SERV_UUID), HI_UINT16(BATT_SERV_UUID) }; // Battery level characteristic CONST uint8 battLevelUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(BATT_LEVEL_UUID), HI_UINT16(BATT_LEVEL_UUID) + LO_UINT16(BATT_LEVEL_UUID), HI_UINT16(BATT_LEVEL_UUID) }; /********************************************************************* - EXTERNAL VARIABLES + EXTERNAL VARIABLES */ /********************************************************************* - EXTERNAL FUNCTIONS + EXTERNAL FUNCTIONS */ /********************************************************************* - LOCAL VARIABLES + LOCAL VARIABLES */ // Application callback static battServiceCB_t battServiceCB; /********************************************************************* - Profile Attributes - variables + Profile Attributes - variables */ // Battery Service attribute @@ -77,258 +75,258 @@ static uint8 battLevelProps = GATT_PROP_READ | GATT_PROP_NOTIFY; static gattCharCfg_t battLevelClientCharCfg[GATT_MAX_NUM_CONN]; /********************************************************************* - Profile Attributes - Table + Profile Attributes - Table */ static gattAttribute_t battAttrTbl[] = { - // Battery Service - { - { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ - GATT_PERMIT_READ, /* permissions */ - 0, /* handle */ - (uint8*)& battService /* pValue */ - }, + // Battery Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8*)& battService /* pValue */ + }, - // Battery Level Declaration - { - { ATT_BT_UUID_SIZE, characterUUID }, - GATT_PERMIT_READ, - 0, - &battLevelProps - }, + // Battery Level Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &battLevelProps + }, - // Battery Level Value - { - { ATT_BT_UUID_SIZE, battLevelUUID }, - GATT_PERMIT_READ, - 0, - &measured_data.battery - }, + // Battery Level Value + { + { ATT_BT_UUID_SIZE, battLevelUUID }, + GATT_PERMIT_READ, + 0, + &measured_data.battery + }, - // Battery Level Client Characteristic Configuration - { - { ATT_BT_UUID_SIZE, clientCharCfgUUID }, - GATT_PERMIT_READ | GATT_PERMIT_WRITE, - 0, - (uint8*)& battLevelClientCharCfg - } + // Battery Level Client Characteristic Configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8*)& battLevelClientCharCfg + } }; /********************************************************************* - LOCAL FUNCTIONS + LOCAL FUNCTIONS */ static uint8 battReadAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ); + uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ); static bStatus_t battWriteAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16 len, uint16 offset ); + uint8* pValue, uint16 len, uint16 offset ); static void battNotifyCB( linkDBItem_t* pLinkItem ); //static void battNotifyLevel( void ); /********************************************************************* - PROFILE CALLBACKS + PROFILE CALLBACKS */ // Battery Service Callbacks CONST gattServiceCBs_t battCBs = { - battReadAttrCB, // Read callback function pointer - battWriteAttrCB, // Write callback function pointer - NULL // Authorization callback function pointer + battReadAttrCB, // Read callback function pointer + battWriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer }; /********************************************************************* - PUBLIC FUNCTIONS + PUBLIC FUNCTIONS */ /********************************************************************* - @fn Batt_AddService + @fn Batt_AddService - @brief Initializes the Battery Service by registering - GATT attributes with the GATT server. + @brief Initializes the Battery Service by registering + GATT attributes with the GATT server. - @return Success or Failure + @return Success or Failure */ bStatus_t Batt_AddService( void ) { - uint8 status = SUCCESS; - // Initialize Client Characteristic Configuration attributes - GATTServApp_InitCharCfg( INVALID_CONNHANDLE, battLevelClientCharCfg ); - // Register GATT attribute list and CBs with GATT Server App - status = GATTServApp_RegisterService( battAttrTbl, - GATT_NUM_ATTRS( battAttrTbl ), - &battCBs ); - return ( status ); + uint8 status = SUCCESS; + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, battLevelClientCharCfg ); + // Register GATT attribute list and CBs with GATT Server App + status = GATTServApp_RegisterService( battAttrTbl, + GATT_NUM_ATTRS( battAttrTbl ), + &battCBs ); + return ( status ); } /********************************************************************* - @fn Batt_Register + @fn Batt_Register - @brief Register a callback function with the Battery Service. + @brief Register a callback function with the Battery Service. - @param pfnServiceCB - Callback function. + @param pfnServiceCB - Callback function. - @return None. + @return None. */ extern void Batt_Register( battServiceCB_t pfnServiceCB ) { - battServiceCB = pfnServiceCB; + battServiceCB = pfnServiceCB; } /********************************************************************* - @fn battReadAttrCB + @fn battReadAttrCB - @brief Read an attribute. + @brief Read an attribute. - @param connHandle - connection message was received on - @param pAttr - pointer to attribute - @param pValue - pointer to data to be read - @param pLen - length of data to be read - @param offset - offset of the first octet to be read - @param maxLen - maximum length of data to be read + @param connHandle - connection message was received on + @param pAttr - pointer to attribute + @param pValue - pointer to data to be read + @param pLen - length of data to be read + @param offset - offset of the first octet to be read + @param maxLen - maximum length of data to be read - @return Success or Failure + @return Success or Failure */ static uint8 battReadAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ) + uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ) { - (void)connHandle; - (void)maxLen; + (void)connHandle; + (void)maxLen; bStatus_t status = SUCCESS; - // Make sure it's not a blob operation (no attributes in the profile are long) - if ( offset > 0 ) - { - return ( ATT_ERR_ATTR_NOT_LONG ); - } + // Make sure it's not a blob operation (no attributes in the profile are long) + if ( offset > 0 ) + { + return ( ATT_ERR_ATTR_NOT_LONG ); + } - uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1] ); + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1] ); - // Measure battery level if reading level - if ( uuid == BATT_LEVEL_UUID ) - { + // Measure battery level if reading level + if ( uuid == BATT_LEVEL_UUID ) + { *pLen = 1; - pValue[0] = measured_data.battery; - } - else - { - status = ATT_ERR_ATTR_NOT_FOUND; - } + pValue[0] = measured_data.battery; + } + else + { + status = ATT_ERR_ATTR_NOT_FOUND; + } - return ( status ); + return ( status ); } /********************************************************************* - @fn battWriteAttrCB + @fn battWriteAttrCB - @brief Validate attribute data prior to a write operation + @brief Validate attribute data prior to a write operation - @param connHandle - connection message was received on - @param pAttr - pointer to attribute - @param pValue - pointer to data to be written - @param len - length of data - @param offset - offset of the first octet to be written + @param connHandle - connection message was received on + @param pAttr - pointer to attribute + @param pValue - pointer to data to be written + @param len - length of data + @param offset - offset of the first octet to be written - @return Success or Failure + @return Success or Failure */ static bStatus_t battWriteAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16 len, uint16 offset ) + uint8* pValue, uint16 len, uint16 offset ) { - bStatus_t status = SUCCESS; - uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + bStatus_t status = SUCCESS; + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); - switch ( uuid ) - { - case GATT_CLIENT_CHAR_CFG_UUID: - status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, - offset, GATT_CLIENT_CFG_NOTIFY ); + switch ( uuid ) + { + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); - if ( status == SUCCESS ) - { - uint16 charCfg = BUILD_UINT16( pValue[0], pValue[1] ); + if ( status == SUCCESS ) + { + uint16 charCfg = BUILD_UINT16( pValue[0], pValue[1] ); - if ( battServiceCB ) - { - (*battServiceCB)( (charCfg == GATT_CFG_NO_OPERATION) ? - BATT_LEVEL_NOTI_DISABLED : - BATT_LEVEL_NOTI_ENABLED); - } - } + if ( battServiceCB ) + { + (*battServiceCB)( (charCfg == GATT_CFG_NO_OPERATION) ? + BATT_LEVEL_NOTI_DISABLED : + BATT_LEVEL_NOTI_ENABLED); + } + } - break; + break; - default: - status = ATT_ERR_ATTR_NOT_FOUND; - break; - } + default: + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } - return ( status ); + return ( status ); } /********************************************************************* - @fn battNotifyCB + @fn battNotifyCB - @brief Send a notification of the level state characteristic. + @brief Send a notification of the level state characteristic. - @param connHandle - linkDB item + @param connHandle - linkDB item - @return None. + @return None. */ static void battNotifyCB( linkDBItem_t* pLinkItem ) { - if ( pLinkItem->stateFlags & LINK_CONNECTED ) - { - uint16 value = GATTServApp_ReadCharCfg( pLinkItem->connectionHandle, - battLevelClientCharCfg ); + if ( pLinkItem->stateFlags & LINK_CONNECTED ) + { + uint16 value = GATTServApp_ReadCharCfg( pLinkItem->connectionHandle, + battLevelClientCharCfg ); - if ( value & GATT_CLIENT_CFG_NOTIFY ) - { - attHandleValueNoti_t noti; - noti.handle = battAttrTbl[BATT_LEVEL_VALUE_IDX].handle; - noti.len = 1; - noti.value[0] = measured_data.battery; - GATT_Notification( pLinkItem->connectionHandle, ¬i, FALSE ); - } - } + if ( value & GATT_CLIENT_CFG_NOTIFY ) + { + attHandleValueNoti_t noti; + noti.handle = battAttrTbl[BATT_LEVEL_VALUE_IDX].handle; + noti.len = 1; + noti.value[0] = measured_data.battery; + GATT_Notification( pLinkItem->connectionHandle, ¬i, FALSE ); + } + } } /********************************************************************* - @fn battNotifyLevelState + @fn battNotifyLevelState - @brief Send a notification of the battery level state - characteristic if a connection is established. + @brief Send a notification of the battery level state + characteristic if a connection is established. - @return None. + @return None. */ void BattNotifyLevel( void ) { - // Execute linkDB callback to send notification - linkDB_PerformFunc( battNotifyCB ); + // Execute linkDB callback to send notification + linkDB_PerformFunc( battNotifyCB ); } /********************************************************************* - @fn Batt_HandleConnStatusCB + @fn Batt_HandleConnStatusCB - @brief Battery Service link status change handler function. + @brief Battery Service link status change handler function. - @param connHandle - connection handle - @param changeType - type of change + @param connHandle - connection handle + @param changeType - type of change - @return none + @return none */ void Batt_HandleConnStatusCB( uint16 connHandle, uint8 changeType ) { - // Make sure this is not loopback connection - if ( connHandle != LOOPBACK_CONNHANDLE ) - { - // Reset Client Char Config if connection has dropped - if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED ) || - ( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) && - ( !linkDB_Up( connHandle ) ) ) ) - { - GATTServApp_InitCharCfg( connHandle, battLevelClientCharCfg ); - } - } + // Make sure this is not loopback connection + if ( connHandle != LOOPBACK_CONNHANDLE ) + { + // Reset Client Char Config if connection has dropped + if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED ) || + ( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) && + ( !linkDB_Up( connHandle ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, battLevelClientCharCfg ); + } + } } diff --git a/bthome_phy6222/source/battservice.h b/bthome_phy6222/source/battservice.h index 4d93f77..780ed0d 100644 --- a/bthome_phy6222/source/battservice.h +++ b/bthome_phy6222/source/battservice.h @@ -1,5 +1,5 @@ /************************************************************************************************** -******* + battservice.h **************************************************************************************************/ @@ -12,33 +12,33 @@ extern "C" #endif /********************************************************************* - INCLUDES + INCLUDES */ /********************************************************************* - CONSTANTS + CONSTANTS */ // Battery Service Get/Set Parameters -#define BATT_PARAM_LEVEL 0 -#define BATT_PARAM_CRITICAL_LEVEL 1 -#define BATT_PARAM_SERVICE_HANDLE 2 +#define BATT_PARAM_LEVEL 0 +#define BATT_PARAM_CRITICAL_LEVEL 1 +#define BATT_PARAM_SERVICE_HANDLE 2 #define BATT_PARAM_BATT_LEVEL_IN_REPORT 3 // Callback events -#define BATT_LEVEL_NOTI_ENABLED 1 -#define BATT_LEVEL_NOTI_DISABLED 2 +#define BATT_LEVEL_NOTI_ENABLED 1 +#define BATT_LEVEL_NOTI_DISABLED 2 // HID Report IDs for the service -#define HID_RPT_ID_BATT_LEVEL_IN 4 // Battery Level input report ID +#define HID_RPT_ID_BATT_LEVEL_IN 4 // Battery Level input report ID #ifdef HID_VOICE_SPEC -#define GATT_DESC_LENGTH_UUID 0x3111 // Used with Unit percent +#define GATT_DESC_LENGTH_UUID 0x3111 // Used with Unit percent #endif /********************************************************************* - TYPEDEFS + TYPEDEFS */ // Battery Service callback function @@ -54,121 +54,121 @@ typedef uint8 (*battServiceCalcCB_t)(uint16 adcVal); typedef void (*battServiceTeardownCB_t)(void); /********************************************************************* - MACROS + MACROS */ /********************************************************************* - Profile Callbacks + Profile Callbacks */ /********************************************************************* - API FUNCTIONS + API FUNCTIONS */ /********************************************************************* - @fn Batt_AddService + @fn Batt_AddService - @brief Initializes the Battery service by registering - GATT attributes with the GATT server. + @brief Initializes the Battery service by registering + GATT attributes with the GATT server. - @return Success or Failure + @return Success or Failure */ extern bStatus_t Batt_AddService( void ); /********************************************************************* - @fn Batt_Register + @fn Batt_Register - @brief Register a callback function with the Battery Service. + @brief Register a callback function with the Battery Service. - @param pfnServiceCB - Callback function. + @param pfnServiceCB - Callback function. - @return None. + @return None. */ extern void Batt_Register( battServiceCB_t pfnServiceCB ); /********************************************************************* - @fn Batt_SetParameter + @fn Batt_SetParameter - @brief Set a Battery Service parameter. + @brief Set a Battery Service parameter. - @param param - Profile parameter ID - @param len - length of data to right - @param value - pointer to data to write. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + @param param - Profile parameter ID + @param len - length of data to right + @param value - pointer to data to write. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). - @return bStatus_t + @return bStatus_t */ extern bStatus_t Batt_SetParameter( uint8 param, uint8 len, void* value ); /********************************************************************* - @fn Batt_GetParameter + @fn Batt_GetParameter - @brief Get a Battery parameter. + @brief Get a Battery parameter. - @param param - Profile parameter ID - @param value - pointer to data to get. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + @param param - Profile parameter ID + @param value - pointer to data to get. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). - @return bStatus_t + @return bStatus_t */ extern bStatus_t Batt_GetParameter( uint8 param, void* value ); /********************************************************************* - @fn Batt_MeasLevel + @fn Batt_MeasLevel - @brief Measure the battery level and update the battery - level value in the service characteristics. If - the battery level-state characteristic is configured - for notification and the battery level has changed - since the last measurement, then a notification - will be sent. + @brief Measure the battery level and update the battery + level value in the service characteristics. If + the battery level-state characteristic is configured + for notification and the battery level has changed + since the last measurement, then a notification + will be sent. - @return Success or Failure + @return Success or Failure */ extern bStatus_t Batt_MeasLevel( void ); /********************************************************************* - @fn Batt_Setup + @fn Batt_Setup - @brief Set up which ADC source is to be used. Defaults to VDD/3. + @brief Set up which ADC source is to be used. Defaults to VDD/3. - @param adc_ch - ADC Channel, e.g. HAL_ADC_CHN_AIN6 - @param minVal - max battery level - @param maxVal - min battery level - @param sCB - HW setup callback - @param tCB - HW tear down callback - @param cCB - percentage calculation callback + @param adc_ch - ADC Channel, e.g. HAL_ADC_CHN_AIN6 + @param minVal - max battery level + @param maxVal - min battery level + @param sCB - HW setup callback + @param tCB - HW tear down callback + @param cCB - percentage calculation callback - @return none. + @return none. */ extern void Batt_Setup( uint8 adc_ch, uint16 minVal, uint16 maxVal, - battServiceSetupCB_t sCB, battServiceTeardownCB_t tCB, - battServiceCalcCB_t cCB ); + battServiceSetupCB_t sCB, battServiceTeardownCB_t tCB, + battServiceCalcCB_t cCB ); /********************************************************************* - @fn Batt_HandleConnStatusCB + @fn Batt_HandleConnStatusCB - @brief Battery Service link status change handler function. + @brief Battery Service link status change handler function. - @param connHandle - connection handle - @param changeType - type of change + @param connHandle - connection handle + @param changeType - type of change - @return none + @return none */ void Batt_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); /********************************************************************* - @fn battNotifyLevelState + @fn battNotifyLevelState - @brief Send a notification of the battery level state - characteristic if a connection is established. + @brief Send a notification of the battery level state + characteristic if a connection is established. - @return None. + @return None. */ void BattNotifyLevel( void ); diff --git a/bthome_phy6222/source/bthome_beacon.c b/bthome_phy6222/source/bthome_beacon.c index 137b251..ad332e1 100644 --- a/bthome_phy6222/source/bthome_beacon.c +++ b/bthome_phy6222/source/bthome_beacon.c @@ -24,7 +24,7 @@ void bthome_data_beacon(padv_bthome_ns1_t p) { bit3: Simultaneous LE and BR/EDR to Same Device Capable (Controller) bit4: Simultaneous LE and BR/EDR to Same Device Capable (Host) bit5..7: Reserved - */ + */ p->flag[2] = GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED | GAP_ADTYPE_FLAGS_GENERAL; // Flags p->head.type = GAP_ADTYPE_SERVICE_DATA; // 16-bit UUID p->head.UUID = ADV_BTHOME_UUID16; diff --git a/bthome_phy6222/source/bthome_beacon.h b/bthome_phy6222/source/bthome_beacon.h index b003c64..7dd45c0 100644 --- a/bthome_phy6222/source/bthome_beacon.h +++ b/bthome_phy6222/source/bthome_beacon.h @@ -66,18 +66,18 @@ typedef enum { BtHomeID_window = 0x2d, //0x2d, uint8, =0 Closed, =1 Open BtHomeID_humidity8 = 0x2e, //0x2e, uint8 BtHomeID_moisture8 = 0x2f, //0x2f, uint8 - BtHomeID_0x30 = 0x30, //0x30, uint8 - BtHomeID_0x31 = 0x31, //0x31, uint8 - BtHomeID_0x32 = 0x32, //0x32, uint8 - BtHomeID_0x33 = 0x33, //0x33, uint8 - BtHomeID_0x34 = 0x34, //0x34, uint8 - BtHomeID_0x35 = 0x35, //0x35, uint8 - BtHomeID_0x36 = 0x36, //0x36, uint8 - BtHomeID_0x37 = 0x37, //0x37, uint8 - BtHomeID_0x38 = 0x38, //0x38, uint8 - BtHomeID_0x39 = 0x39, //0x39, uint8 + BtHomeID_0x30 = 0x30, //0x30, uint8 + BtHomeID_0x31 = 0x31, //0x31, uint8 + BtHomeID_0x32 = 0x32, //0x32, uint8 + BtHomeID_0x33 = 0x33, //0x33, uint8 + BtHomeID_0x34 = 0x34, //0x34, uint8 + BtHomeID_0x35 = 0x35, //0x35, uint8 + BtHomeID_0x36 = 0x36, //0x36, uint8 + BtHomeID_0x37 = 0x37, //0x37, uint8 + BtHomeID_0x38 = 0x38, //0x38, uint8 + BtHomeID_0x39 = 0x39, //0x39, uint8 BtHomeID_button = 0x3a, //0x3a, uint8, =1 press, =2 double_press ... https://bthome.io/format/ - BtHomeID_0x3b = 0x3b, //0x3b, uint8 + BtHomeID_0x3b = 0x3b, //0x3b, uint8 BtHomeID_dimmer = 0x3c, //0x3c, uint16 ?, =1 rotate left 3 steps, ... https://bthome.io/format/ BtHomeID_count16 = 0x3d, //0x3d, uint16 BtHomeID_count32 = 0x3e, //0x3e, uint32 diff --git a/bthome_phy6222/source/devinfoservice.c b/bthome_phy6222/source/devinfoservice.c index 5eb7973..6b58b54 100644 --- a/bthome_phy6222/source/devinfoservice.c +++ b/bthome_phy6222/source/devinfoservice.c @@ -1,19 +1,13 @@ /************************************************************************************************** -******* -**************************************************************************************************/ - -/************************************************************************************************** - Filename: devinfoservice.c - Revised: $Date $ - Revision: $Revision $ - - Description: This file contains the Device Information service. - + Filename: devinfoservice.c + Revised: $Date $ + Revision: $Revision $ + Description: This file contains the Device Information service. **************************************************************************************************/ /********************************************************************* - INCLUDES + INCLUDES */ #include "bcomdef.h" #include "OSAL.h" @@ -27,7 +21,7 @@ #include "devinfoservice.h" /********************************************************************* - MACROS + MACROS */ #define SYSTEM_ID_ENABLE 0 #define MODEL_NUMBER_STR_ENABLE 1 @@ -40,91 +34,91 @@ #define PNP_ID_ENABLE 0 /********************************************************************* - CONSTANTS + CONSTANTS */ /********************************************************************* - TYPEDEFS + TYPEDEFS */ /********************************************************************* - GLOBAL VARIABLES + GLOBAL VARIABLES */ // Device information service CONST uint8 devInfoServUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(DEVINFO_SERV_UUID), HI_UINT16(DEVINFO_SERV_UUID) + LO_UINT16(DEVINFO_SERV_UUID), HI_UINT16(DEVINFO_SERV_UUID) }; // System ID CONST uint8 devInfoSystemIdUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(SYSTEM_ID_UUID), HI_UINT16(SYSTEM_ID_UUID) + LO_UINT16(SYSTEM_ID_UUID), HI_UINT16(SYSTEM_ID_UUID) }; // Model Number String CONST uint8 devInfoModelNumberUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(MODEL_NUMBER_UUID), HI_UINT16(MODEL_NUMBER_UUID) + LO_UINT16(MODEL_NUMBER_UUID), HI_UINT16(MODEL_NUMBER_UUID) }; // Serial Number String CONST uint8 devInfoSerialNumberUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(SERIAL_NUMBER_UUID), HI_UINT16(SERIAL_NUMBER_UUID) + LO_UINT16(SERIAL_NUMBER_UUID), HI_UINT16(SERIAL_NUMBER_UUID) }; // Firmware Revision String CONST uint8 devInfoFirmwareRevUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(FIRMWARE_REV_UUID), HI_UINT16(FIRMWARE_REV_UUID) + LO_UINT16(FIRMWARE_REV_UUID), HI_UINT16(FIRMWARE_REV_UUID) }; // Hardware Revision String CONST uint8 devInfoHardwareRevUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(HARDWARE_REV_UUID), HI_UINT16(HARDWARE_REV_UUID) + LO_UINT16(HARDWARE_REV_UUID), HI_UINT16(HARDWARE_REV_UUID) }; // Software Revision String CONST uint8 devInfoSoftwareRevUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(SOFTWARE_REV_UUID), HI_UINT16(SOFTWARE_REV_UUID) + LO_UINT16(SOFTWARE_REV_UUID), HI_UINT16(SOFTWARE_REV_UUID) }; // Manufacturer Name String CONST uint8 devInfoMfrNameUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(MANUFACTURER_NAME_UUID), HI_UINT16(MANUFACTURER_NAME_UUID) + LO_UINT16(MANUFACTURER_NAME_UUID), HI_UINT16(MANUFACTURER_NAME_UUID) }; // IEEE 11073-20601 Regulatory Certification Data List CONST uint8 devInfo11073CertUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(IEEE_11073_CERT_DATA_UUID), HI_UINT16(IEEE_11073_CERT_DATA_UUID) + LO_UINT16(IEEE_11073_CERT_DATA_UUID), HI_UINT16(IEEE_11073_CERT_DATA_UUID) }; // PnP ID CONST uint8 devInfoPnpIdUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(PNP_ID_UUID), HI_UINT16(PNP_ID_UUID) + LO_UINT16(PNP_ID_UUID), HI_UINT16(PNP_ID_UUID) }; /********************************************************************* - EXTERNAL VARIABLES + EXTERNAL VARIABLES */ /********************************************************************* - EXTERNAL FUNCTIONS + EXTERNAL FUNCTIONS */ /********************************************************************* - LOCAL VARIABLES + LOCAL VARIABLES */ /********************************************************************* - Profile Attributes - variables + Profile Attributes - variables */ // Device Information Service attribute @@ -132,72 +126,72 @@ static CONST gattAttrType_t devInfoService = { ATT_BT_UUID_SIZE, devInfoServUUID #if SYSTEM_ID_ENABLE // System ID characteristic -static uint8 devInfoSystemIdProps = GATT_PROP_READ; -static uint8 devInfoSystemId[DEVINFO_SYSTEM_ID_LEN] = {0, 0, 0, 0, 0, 0, 0, 0}; +static uint8 devInfoSystemIdProps = GATT_PROP_READ; +static uint8 devInfoSystemId[DEVINFO_SYSTEM_ID_LEN] = {0, 0, 0, 0, 0, 0, 0, 0}; #endif #if MODEL_NUMBER_STR_ENABLE // Model Number String characteristic -static uint8 devInfoModelNumberProps = GATT_PROP_READ; -static const uint8 devInfoModelNumber[] = "THB2"; +static uint8 devInfoModelNumberProps = GATT_PROP_READ; +static const uint8 devInfoModelNumber[] = "THB2"; #endif #if SERIAL_NUMBER_STR_ENABLE // Serial Number String characteristic -static uint8 devInfoSerialNumberProps = GATT_PROP_READ; -static const uint8 devInfoSerialNumber[] = "0001"; +static uint8 devInfoSerialNumberProps = GATT_PROP_READ; +static const uint8 devInfoSerialNumber[] = "0001"; #endif #if FIRMWARE_REVISION_ENABLE // Firmware Revision String characteristic -static uint8 devInfoFirmwareRevProps = GATT_PROP_READ; -static const uint8 devInfoFirmwareRev[] = "github.com/pvvx"; +static uint8 devInfoFirmwareRevProps = GATT_PROP_READ; +static const uint8 devInfoFirmwareRev[] = "github.com/pvvx"; #endif #if HARDWARE_REVISION_ENABLE // Hardware Revision String characteristic -static uint8 devInfoHardwareRevProps = GATT_PROP_READ; -static const uint8 devInfoHardwareRev[] = "0.1"; +static uint8 devInfoHardwareRevProps = GATT_PROP_READ; +static const uint8 devInfoHardwareRev[] = "0.1"; #endif #if SOFTWARE_REVISION_ENABLE // Software Revision String characteristic -static uint8 devInfoSoftwareRevProps = GATT_PROP_READ; -static const uint8 devInfoSoftwareRev[] = "V0.3"; +static uint8 devInfoSoftwareRevProps = GATT_PROP_READ; +static const uint8 devInfoSoftwareRev[] = "V0.3"; #endif #if MANUFACTURE_NAME_STR_ENABLE // Manufacturer Name String characteristic -static uint8 devInfoMfrNameProps = GATT_PROP_READ; -static const uint8 devInfoMfrName[] = "Tuya"; +static uint8 devInfoMfrNameProps = GATT_PROP_READ; +static const uint8 devInfoMfrName[] = "Tuya"; #endif #if IEEE_DATA_ENABLE // IEEE 11073-20601 Regulatory Certification Data List characteristic -static uint8 devInfo11073CertProps = GATT_PROP_READ; +static uint8 devInfo11073CertProps = GATT_PROP_READ; static const uint8 devInfo11073Cert[] = { - DEVINFO_11073_BODY_EXP, // authoritative body type - 0x00, // authoritative body structure type - // authoritative body data follows below: + DEVINFO_11073_BODY_EXP, // authoritative body type + 0x00, // authoritative body structure type + // authoritative body data follows below: 'e', 'x', 'p', 'e', 'r', 'i', 'm', 'e', 'n', 't', 'a', 'l' }; #endif #if PNP_ID_ENABLE // System ID characteristic -static uint8 devInfoPnpIdProps = GATT_PROP_READ; +static uint8 devInfoPnpIdProps = GATT_PROP_READ; static uint8 devInfoPnpId[DEVINFO_PNP_ID_LEN] = { - 1, // Vendor ID source (1=Bluetooth SIG) - LO_UINT16(0x0f0f), HI_UINT16(0x0f0f), // Vendor ID - LO_UINT16(0x0000), HI_UINT16(0x0000), // Product ID (vendor-specific) - LO_UINT16(0x0110), HI_UINT16(0x0110) // Product version (JJ.M.N) + 1, // Vendor ID source (1=Bluetooth SIG) + LO_UINT16(0x0f0f), HI_UINT16(0x0f0f), // Vendor ID + LO_UINT16(0x0000), HI_UINT16(0x0000), // Product ID (vendor-specific) + LO_UINT16(0x0110), HI_UINT16(0x0110) // Product version (JJ.M.N) }; #endif /********************************************************************* - Profile Attributes - Table + Profile Attributes - Table */ static gattAttribute_t devInfoAttrTbl[] = @@ -272,59 +266,59 @@ static gattAttribute_t devInfoAttrTbl[] = /********************************************************************* - LOCAL FUNCTIONS + LOCAL FUNCTIONS */ static uint8 devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ); + uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ); /********************************************************************* - PROFILE CALLBACKS + PROFILE CALLBACKS */ // Device Info Service Callbacks CONST gattServiceCBs_t devInfoCBs = { - devInfo_ReadAttrCB, // Read callback function pointer - NULL, // Write callback function pointer - NULL // Authorization callback function pointer + devInfo_ReadAttrCB, // Read callback function pointer + NULL, // Write callback function pointer + NULL // Authorization callback function pointer }; /********************************************************************* - NETWORK LAYER CALLBACKS + NETWORK LAYER CALLBACKS */ /********************************************************************* - PUBLIC FUNCTIONS + PUBLIC FUNCTIONS */ /********************************************************************* - @fn DevInfo_AddService + @fn DevInfo_AddService - @brief Initializes the Device Information service by registering - GATT attributes with the GATT server. + @brief Initializes the Device Information service by registering + GATT attributes with the GATT server. - @return Success or Failure + @return Success or Failure */ bStatus_t DevInfo_AddService( void ) { // Register GATT attribute list and CBs with GATT Server App return GATTServApp_RegisterService( devInfoAttrTbl, - GATT_NUM_ATTRS( devInfoAttrTbl ), - &devInfoCBs ); + GATT_NUM_ATTRS( devInfoAttrTbl ), + &devInfoCBs ); } /********************************************************************* - @fn DevInfo_SetParameter + @fn DevInfo_SetParameter - @brief Set a Device Information parameter. + @brief Set a Device Information parameter. - @param param - Profile parameter ID - @param len - length of data to write - @param value - pointer to data to write. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + @param param - Profile parameter ID + @param len - length of data to write + @param value - pointer to data to write. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). - @return bStatus_t + @return bStatus_t */ bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void* value ) { @@ -349,17 +343,17 @@ bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void* value ) } /********************************************************************* - @fn DevInfo_GetParameter + @fn DevInfo_GetParameter - @brief Get a Device Information parameter. + @brief Get a Device Information parameter. - @param param - Profile parameter ID - @param value - pointer to data to get. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + @param param - Profile parameter ID + @param value - pointer to data to get. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). - @return bStatus_t + @return bStatus_t */ bStatus_t DevInfo_GetParameter( uint8 param, void* value ) { @@ -372,55 +366,55 @@ bStatus_t DevInfo_GetParameter( uint8 param, void* value ) osal_memcpy(value, devInfoSystemId, sizeof(devInfoSystemId)); break; #endif - + #if MODEL_NUMBER_STR_ENABLE case DEVINFO_MODEL_NUMBER: osal_memcpy(value, devInfoModelNumber, sizeof(devInfoModelNumber)); break; #endif - + #if SERIAL_NUMBER_STR_ENABLE case DEVINFO_SERIAL_NUMBER: osal_memcpy(value, devInfoSerialNumber, sizeof(devInfoSerialNumber)); break; #endif - + #if FIRMWARE_REVISION_ENABLE case DEVINFO_FIRMWARE_REV: osal_memcpy(value, devInfoFirmwareRev, sizeof(devInfoFirmwareRev)); break; #endif - + #if HARDWARE_REVISION_ENABLE case DEVINFO_HARDWARE_REV: osal_memcpy(value, devInfoHardwareRev, sizeof(devInfoHardwareRev)); break; #endif - + #if SOFTWARE_REVISION_ENABLE case DEVINFO_SOFTWARE_REV: osal_memcpy(value, devInfoSoftwareRev, sizeof(devInfoSoftwareRev)); break; #endif - + #if MANUFACTURE_NAME_STR_ENABLE case DEVINFO_MANUFACTURER_NAME: osal_memcpy(value, devInfoMfrName, sizeof(devInfoMfrName)); break; #endif - + #if IEEE_DATA_ENABLE case DEVINFO_11073_CERT_DATA: osal_memcpy(value, devInfo11073Cert, sizeof(devInfo11073Cert)); break; #endif - + #if PNP_ID_ENABLE case DEVINFO_PNP_ID: osal_memcpy(value, devInfoPnpId, sizeof(devInfoPnpId)); break; #endif - + default: ret = INVALIDPARAMETER; break; @@ -430,21 +424,21 @@ bStatus_t DevInfo_GetParameter( uint8 param, void* value ) } /********************************************************************* - @fn devInfo_ReadAttrCB + @fn devInfo_ReadAttrCB - @brief Read an attribute. + @brief Read an attribute. - @param connHandle - connection message was received on - @param pAttr - pointer to attribute - @param pValue - pointer to data to be read - @param pLen - length of data to be read - @param offset - offset of the first octet to be read - @param maxLen - maximum length of data to be read + @param connHandle - connection message was received on + @param pAttr - pointer to attribute + @param pValue - pointer to data to be read + @param pLen - length of data to be read + @param offset - offset of the first octet to be read + @param maxLen - maximum length of data to be read - @return Success or Failure + @return Success or Failure */ static uint8 devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ) + uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ) { (void) connHandle; bStatus_t status = SUCCESS; @@ -577,7 +571,7 @@ static uint8 devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t* pAttr, } break; #endif - + default: *pLen = 0; status = ATT_ERR_ATTR_NOT_FOUND; diff --git a/bthome_phy6222/source/devinfoservice.h b/bthome_phy6222/source/devinfoservice.h index 7fba6cf..a9cd78c 100644 --- a/bthome_phy6222/source/devinfoservice.h +++ b/bthome_phy6222/source/devinfoservice.h @@ -1,17 +1,10 @@ /************************************************************************************************** -******* -**************************************************************************************************/ - -/************************************************************************************************** - Filename: devinfoservice.h - Revised: $Date $ - Revision: $Revision $ - - Description: This file contains the Device Information service definitions and - prototypes. - - + Filename: devinfoservice.h + Revised: $Date $ + Revision: $Revision $ + Description: This file contains the Device Information service definitions and + prototypes. **************************************************************************************************/ #ifndef DEVINFOSERVICE_H @@ -23,85 +16,85 @@ extern "C" #endif /********************************************************************* - INCLUDES + INCLUDES */ /********************************************************************* - CONSTANTS + CONSTANTS */ // Device Information Service Parameters -#define DEVINFO_SYSTEM_ID 0 -#define DEVINFO_MODEL_NUMBER 1 -#define DEVINFO_SERIAL_NUMBER 2 -#define DEVINFO_FIRMWARE_REV 3 -#define DEVINFO_HARDWARE_REV 4 -#define DEVINFO_SOFTWARE_REV 5 -#define DEVINFO_MANUFACTURER_NAME 6 -#define DEVINFO_11073_CERT_DATA 7 -#define DEVINFO_PNP_ID 8 +#define DEVINFO_SYSTEM_ID 0 +#define DEVINFO_MODEL_NUMBER 1 +#define DEVINFO_SERIAL_NUMBER 2 +#define DEVINFO_FIRMWARE_REV 3 +#define DEVINFO_HARDWARE_REV 4 +#define DEVINFO_SOFTWARE_REV 5 +#define DEVINFO_MANUFACTURER_NAME 6 +#define DEVINFO_11073_CERT_DATA 7 +#define DEVINFO_PNP_ID 8 // IEEE 11073 authoritative body values -#define DEVINFO_11073_BODY_EMPTY 0 -#define DEVINFO_11073_BODY_IEEE 1 -#define DEVINFO_11073_BODY_CONTINUA 2 -#define DEVINFO_11073_BODY_EXP 254 +#define DEVINFO_11073_BODY_EMPTY 0 +#define DEVINFO_11073_BODY_IEEE 1 +#define DEVINFO_11073_BODY_CONTINUA 2 +#define DEVINFO_11073_BODY_EXP 254 // System ID length -#define DEVINFO_SYSTEM_ID_LEN 8 +#define DEVINFO_SYSTEM_ID_LEN 8 // PnP ID length -#define DEVINFO_PNP_ID_LEN 7 +#define DEVINFO_PNP_ID_LEN 7 /********************************************************************* - TYPEDEFS + TYPEDEFS */ /********************************************************************* - MACROS + MACROS */ /********************************************************************* - Profile Callbacks + Profile Callbacks */ /********************************************************************* - API FUNCTIONS + API FUNCTIONS */ /* - DevInfo_AddService- Initializes the Device Information service by registering - GATT attributes with the GATT server. + DevInfo_AddService- Initializes the Device Information service by registering + GATT attributes with the GATT server. */ extern bStatus_t DevInfo_AddService( void ); /********************************************************************* - @fn DevInfo_SetParameter + @fn DevInfo_SetParameter - @brief Set a Device Information parameter. + @brief Set a Device Information parameter. - @param param - Profile parameter ID - @param len - length of data to right - @param value - pointer to data to write. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + @param param - Profile parameter ID + @param len - length of data to right + @param value - pointer to data to write. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). - @return bStatus_t + @return bStatus_t */ bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void* value ); /* - DevInfo_GetParameter - Get a Device Information parameter. + DevInfo_GetParameter - Get a Device Information parameter. - param - Profile parameter ID - value - pointer to data to write. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + param - Profile parameter ID + value - pointer to data to write. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). */ extern bStatus_t DevInfo_GetParameter( uint8 param, void* value ); diff --git a/bthome_phy6222/source/halperipheral.h b/bthome_phy6222/source/halperipheral.h index 72535e4..08a1a86 100644 --- a/bthome_phy6222/source/halperipheral.h +++ b/bthome_phy6222/source/halperipheral.h @@ -1,13 +1,7 @@ /************************************************************************************************** -******* -**************************************************************************************************/ - -/************************************************************************************************** - Filename: gpio_demo.h - Revised: $Date $ - Revision: $Revision $ - - + Filename: gpio_demo.h + Revised: $Date $ + Revision: $Revision $ **************************************************************************************************/ #ifndef __HAL_PERIPHERAL_H__ @@ -21,14 +15,12 @@ extern "C" { #endif -#define START_DEVICE_EVT 0x0001 -#define KEY_DEMO_UART_RX_EVT 0x0002 -#define LIGHT_PRCESS_EVT 0x0004 - - +#define START_DEVICE_EVT 0x0001 +#define KEY_DEMO_UART_RX_EVT 0x0002 +#define LIGHT_PRCESS_EVT 0x0004 /********************************************************************* - FUNCTIONS + FUNCTIONS */ uint16 HalPeripheral_ProcessEvent( uint8 task_id, uint16 events ); void HalPeripheral_Init(uint8 task_id); diff --git a/bthome_phy6222/source/main.c b/bthome_phy6222/source/main.c index a8a9ee9..15aaa0d 100644 --- a/bthome_phy6222/source/main.c +++ b/bthome_phy6222/source/main.c @@ -1,5 +1,5 @@ /************************************************************************************************** - ******* + main.c **************************************************************************************************/ #include "bus_dev.h" @@ -17,7 +17,7 @@ #include "watchdog.h" #include "fs.h" #include "adc.h" -#define DEFAULT_UART_BAUD 115200 +#define DEFAULT_UART_BAUD 115200 /********************************************************************* LOCAL FUNCTION PROTOTYPES @@ -34,36 +34,36 @@ extern void hal_rom_boot_init(void); CONNECTION CONTEXT RELATE DEFINITION */ -#define BLE_MAX_ALLOW_CONNECTION 1 -#define BLE_MAX_ALLOW_PKT_PER_EVENT_TX 3 -#define BLE_MAX_ALLOW_PKT_PER_EVENT_RX 3 -#define BLE_PKT_VERSION BLE_PKT_VERSION_5_1 // BLE_PKT_VERSION_4_0 +#define BLE_MAX_ALLOW_CONNECTION 1 +#define BLE_MAX_ALLOW_PKT_PER_EVENT_TX 3 +#define BLE_MAX_ALLOW_PKT_PER_EVENT_RX 3 +#define BLE_PKT_VERSION BLE_PKT_VERSION_5_1 // BLE_PKT_VERSION_4_0 -/* BLE_MAX_ALLOW_PER_CONNECTION +/* BLE_MAX_ALLOW_PER_CONNECTION { ... - struct ll_pkt_desc *tx_conn_desc[MAX_LL_BUF_LEN]; // new Tx data buffer + struct ll_pkt_desc *tx_conn_desc[MAX_LL_BUF_LEN]; // new Tx data buffer struct ll_pkt_desc *rx_conn_desc[MAX_LL_BUF_LEN]; struct ll_pkt_desc *tx_not_ack_pkt; struct ll_pkt_desc *tx_ntrm_pkts[MAX_LL_BUF_LEN]; ... } - tx_conn_desc[] + tx_ntrm_pkts[] --> BLE_MAX_ALLOW_PKT_PER_EVENT_TX * BLE_PKT_BUF_SIZE*2 - rx_conn_desc[] --> BLE_MAX_ALLOW_PKT_PER_EVENT_RX * BLE_PKT_BUF_SIZE - tx_not_ack_pkt --> 1*BLE_PKT_BUF_SIZE + tx_conn_desc[] + tx_ntrm_pkts[] --> BLE_MAX_ALLOW_PKT_PER_EVENT_TX * BLE_PKT_BUF_SIZE*2 + rx_conn_desc[] --> BLE_MAX_ALLOW_PKT_PER_EVENT_RX * BLE_PKT_BUF_SIZE + tx_not_ack_pkt --> 1*BLE_PKT_BUF_SIZE */ -#define BLE_PKT_BUF_SIZE (((BLE_PKT_VERSION == BLE_PKT_VERSION_5_1) ? 1 : 0) * BLE_PKT51_LEN \ - + ((BLE_PKT_VERSION == BLE_PKT_VERSION_4_0) ? 1 : 0) * BLE_PKT40_LEN \ - + (sizeof(struct ll_pkt_desc) - 2)) +#define BLE_PKT_BUF_SIZE (((BLE_PKT_VERSION == BLE_PKT_VERSION_5_1) ? 1 : 0) * BLE_PKT51_LEN \ + + ((BLE_PKT_VERSION == BLE_PKT_VERSION_4_0) ? 1 : 0) * BLE_PKT40_LEN \ + + (sizeof(struct ll_pkt_desc) - 2)) -#define BLE_MAX_ALLOW_PER_CONNECTION ( (BLE_MAX_ALLOW_PKT_PER_EVENT_TX * BLE_PKT_BUF_SIZE*2) \ - +(BLE_MAX_ALLOW_PKT_PER_EVENT_RX * BLE_PKT_BUF_SIZE) \ - + BLE_PKT_BUF_SIZE ) +#define BLE_MAX_ALLOW_PER_CONNECTION ( (BLE_MAX_ALLOW_PKT_PER_EVENT_TX * BLE_PKT_BUF_SIZE*2) \ + +(BLE_MAX_ALLOW_PKT_PER_EVENT_RX * BLE_PKT_BUF_SIZE) \ + + BLE_PKT_BUF_SIZE ) -#define BLE_CONN_BUF_SIZE (BLE_MAX_ALLOW_CONNECTION * BLE_MAX_ALLOW_PER_CONNECTION) +#define BLE_CONN_BUF_SIZE (BLE_MAX_ALLOW_CONNECTION * BLE_MAX_ALLOW_PER_CONNECTION) ALIGN4_U8 g_pConnectionBuffer[BLE_CONN_BUF_SIZE]; llConnState_t pConnContext[BLE_MAX_ALLOW_CONNECTION]; @@ -73,20 +73,20 @@ llConnState_t pConnContext[BLE_MAX_ALLOW_CONNECTION]; */ //#define BLE_SUPPORT_CTE_IQ_SAMPLE TRUE #ifdef BLE_SUPPORT_CTE_IQ_SAMPLE - uint16 g_llCteSampleI[LL_CTE_MAX_SUPP_LEN * LL_CTE_SUPP_LEN_UNIT]; - uint16 g_llCteSampleQ[LL_CTE_MAX_SUPP_LEN * LL_CTE_SUPP_LEN_UNIT]; + uint16 g_llCteSampleI[LL_CTE_MAX_SUPP_LEN * LL_CTE_SUPP_LEN_UNIT]; + uint16 g_llCteSampleQ[LL_CTE_MAX_SUPP_LEN * LL_CTE_SUPP_LEN_UNIT]; #endif /********************************************************************* OSAL LARGE HEAP CONFIG */ -#define LARGE_HEAP_SIZE (4*1024) +#define LARGE_HEAP_SIZE (4*1024) ALIGN4_U8 g_largeHeap[LARGE_HEAP_SIZE]; #if 0 // SDK_VER_RELEASE_ID >= 0x030103 ? -#define LL_LINKBUF_CFG_NUM 0 -#define LL_PKT_BUFSIZE 280 -#define LL_LINK_HEAP_SIZE ( ( BLE_MAX_ALLOW_CONNECTION * 3 + LL_LINKBUF_CFG_NUM ) * LL_PKT_BUFSIZE )//basic Space + configurable Space +#define LL_LINKBUF_CFG_NUM 0 +#define LL_PKT_BUFSIZE 280 +#define LL_LINK_HEAP_SIZE ( ( BLE_MAX_ALLOW_CONNECTION * 3 + LL_LINKBUF_CFG_NUM ) * LL_PKT_BUFSIZE )//basic Space + configurable Space ALIGN4_U8 g_llLinkHeap[LL_LINK_HEAP_SIZE]; #endif @@ -100,12 +100,11 @@ volatile sysclk_t g_spif_clk_config; EXTERNAL VARIABLES */ //extern uint32_t __initial_sp; -extern int _ebss; static void hal_low_power_io_init(void) { //========= disable all gpio pullup/down to preserve juice const ioinit_cfg_t ioInit[] = { -#if(SDK_VER_CHIP == __DEF_CHIP_QFN32__) +#if(SDK_VER_CHIP == __DEF_CHIP_QFN32__) { GPIO_P00, GPIO_PULL_DOWN }, { GPIO_P01, GPIO_PULL_DOWN }, { GPIO_P02, GPIO_PULL_DOWN }, @@ -124,24 +123,24 @@ static void hal_low_power_io_init(void) { { GPIO_P24, GPIO_PULL_DOWN }, { GPIO_P25, GPIO_PULL_DOWN }, { GPIO_P26, GPIO_FLOATING }, // LED -// {GPIO_P27, GPIO_FLOATING }, +// {GPIO_P27, GPIO_FLOATING }, { GPIO_P31, GPIO_PULL_DOWN }, { GPIO_P32, GPIO_PULL_DOWN }, { GPIO_P33, GPIO_PULL_DOWN }, { GPIO_P34, GPIO_PULL_DOWN } -#else - {GPIO_P02, GPIO_FLOATING }, - {GPIO_P03, GPIO_FLOATING }, - {GPIO_P07, GPIO_FLOATING }, - {GPIO_P09, GPIO_FLOATING }, - {GPIO_P10, GPIO_FLOATING }, - {GPIO_P11, GPIO_FLOATING }, - {GPIO_P14, GPIO_FLOATING }, - {GPIO_P15, GPIO_FLOATING }, - {GPIO_P18, GPIO_FLOATING }, - {GPIO_P20, GPIO_FLOATING }, - {GPIO_P34, GPIO_FLOATING }, - +#else + {GPIO_P02, GPIO_FLOATING }, + {GPIO_P03, GPIO_FLOATING }, + {GPIO_P07, GPIO_FLOATING }, + {GPIO_P09, GPIO_FLOATING }, + {GPIO_P10, GPIO_FLOATING }, + {GPIO_P11, GPIO_FLOATING }, + {GPIO_P14, GPIO_FLOATING }, + {GPIO_P15, GPIO_FLOATING }, + {GPIO_P18, GPIO_FLOATING }, + {GPIO_P20, GPIO_FLOATING }, + {GPIO_P34, GPIO_FLOATING }, + #endif }; @@ -151,20 +150,31 @@ static void hal_low_power_io_init(void) { DCDC_CONFIG_SETTING(0x0a); DCDC_REF_CLK_SETTING(1); DIG_LDO_CURRENT_SETTING(0x01); +#if defined ( __GNUC__ ) + extern int _ebss; if ((uint32_t) &_ebss >= 0x1fff8000) hal_pwrmgr_RAM_retention(RET_SRAM0 | RET_SRAM1); // RET_SRAM0|RET_SRAM1|RET_SRAM2 else hal_pwrmgr_RAM_retention(RET_SRAM0); // RET_SRAM0|RET_SRAM1|RET_SRAM2 +#else + +#if DEBUG_INFO || SDK_VER_RELEASE_ID != 0x03010102 + hal_pwrmgr_RAM_retention(RET_SRAM0|RET_SRAM1); // RET_SRAM0|RET_SRAM1|RET_SRAM2 +#else + hal_pwrmgr_RAM_retention(RET_SRAM0); // RET_SRAM0|RET_SRAM1|RET_SRAM2 +#endif + +#endif hal_pwrmgr_RAM_retention_set(); hal_pwrmgr_LowCurrentLdo_enable(); } static void ble_mem_init_config(void) { #if 0 // SDK_VER_RELEASE_ID >= 0x030103 ? - //ll linkmem setup + //ll linkmem setup extern void ll_osalmem_init(osalMemHdr_t* hdr, uint32 size); - ll_osalmem_init((osalMemHdr_t*)g_llLinkHeap, LL_LINK_HEAP_SIZE); -#endif + ll_osalmem_init((osalMemHdr_t*)g_llLinkHeap, LL_LINK_HEAP_SIZE); +#endif osal_mem_set_heap((osalMemHdr_t*) g_largeHeap, LARGE_HEAP_SIZE); LL_InitConnectContext(pConnContext, g_pConnectionBuffer, BLE_MAX_ALLOW_CONNECTION, @@ -172,22 +182,22 @@ static void ble_mem_init_config(void) { BLE_MAX_ALLOW_PKT_PER_EVENT_RX, BLE_PKT_VERSION); #if ( MAX_CONNECTION_SLAVE_NUM > 0 ) - static ALIGN4_U8 g_llDevList[BLE_CONN_LL_DEV_LIST_SIZE]; - ll_multi_conn_llDevList_Init(g_llDevList); + static ALIGN4_U8 g_llDevList[BLE_CONN_LL_DEV_LIST_SIZE]; + ll_multi_conn_llDevList_Init(g_llDevList); #endif #if MAX_NUM_LL_CONN > 1 - Host_InitContext( MAX_NUM_LL_CONN, - glinkDB,glinkCBs, - smPairingParam, - gMTU_Size, - gAuthenLink, - l2capReassembleBuf,l2capSegmentBuf, - gattClientInfo, - gattServerInfo); -#endif -#ifdef BLE_SUPPORT_CTE_IQ_SAMPLE - LL_EXT_Init_IQ_pBuff(g_llCteSampleI,g_llCteSampleQ); + Host_InitContext( MAX_NUM_LL_CONN, + glinkDB,glinkCBs, + smPairingParam, + gMTU_Size, + gAuthenLink, + l2capReassembleBuf,l2capSegmentBuf, + gattClientInfo, + gattServerInfo); +#endif +#ifdef BLE_SUPPORT_CTE_IQ_SAMPLE + LL_EXT_Init_IQ_pBuff(g_llCteSampleI,g_llCteSampleQ); #endif } @@ -207,9 +217,9 @@ static void hal_rfphy_init(void) { hal_rom_boot_init(); NVIC_SetPriority((IRQn_Type) BB_IRQn, IRQ_PRIO_REALTIME); - NVIC_SetPriority((IRQn_Type) TIM1_IRQn, IRQ_PRIO_HIGH); //ll_EVT - NVIC_SetPriority((IRQn_Type) TIM2_IRQn, IRQ_PRIO_HIGH); //OSAL_TICK - NVIC_SetPriority((IRQn_Type) TIM4_IRQn, IRQ_PRIO_HIGH); //LL_EXA_ADV + NVIC_SetPriority((IRQn_Type) TIM1_IRQn, IRQ_PRIO_HIGH); //ll_EVT + NVIC_SetPriority((IRQn_Type) TIM2_IRQn, IRQ_PRIO_HIGH); //OSAL_TICK + NVIC_SetPriority((IRQn_Type) TIM4_IRQn, IRQ_PRIO_HIGH); //LL_EXA_ADV //ble memory init and config ble_mem_init_config(); } @@ -222,7 +232,7 @@ static void hal_init(void) { xflash_Ctx_t cfg = { #if SDK_VER_RELEASE_ID == 0x03010102 .spif_ref_clk = SYS_CLK_DLL_64M, // SYS_CLK_RC_32M -#endif +#endif .rd_instr = XFRD_FCMD_READ_DUAL // XFRD_FCMD_READ_QUAD // XFRD_FCMD_READ_DUAL }; hal_spif_cache_init(cfg); @@ -234,8 +244,8 @@ static void hal_init(void) { ///////////////////////////////////////////////////////////////////////////////////////////////////////// int main(void) { - g_system_clk = SYS_CLK_XTAL_16M; //SYS_CLK_DBL_32M;//SYS_CLK_XTAL_16M;//SYS_CLK_DLL_64M; - g_clk32K_config = CLK_32K_RCOSC; //CLK_32K_XTAL;//CLK_32K_XTAL,CLK_32K_RCOSC + g_system_clk = SYS_CLK_XTAL_16M; //SYS_CLK_DBL_32M, SYS_CLK_XTAL_16M, SYS_CLK_DLL_64M + g_clk32K_config = CLK_32K_RCOSC; //CLK_32K_XTAL, CLK_32K_RCOSC #if 0 // defined ( __GNUC__ ) // -> *.ld extern const uint32_t *const jump_table_base[]; @@ -248,16 +258,16 @@ int main(void) { #if (FLASH_PROTECT_FEATURE == 1) #if SDK_VER_RELEASE_ID == 0x03010102 - hal_flash_lock(); -#else - hal_flash_enable_lock(MAIN_INIT); -#endif + hal_flash_lock(); +#else + hal_flash_enable_lock(MAIN_INIT); +#endif #endif drv_irq_init(); init_config(); #if ( HOST_CONFIG & OBSERVER_CFG ) - extern void ll_patch_advscan(void); - ll_patch_advscan(); + extern void ll_patch_advscan(void); + ll_patch_advscan(); #else extern void ll_patch_slave(void); ll_patch_slave(); @@ -269,10 +279,9 @@ int main(void) { LOG("rfClk %d rcClk %d sysClk %d tpCap[%02x %02x]\n",g_rfPhyClkSel,g_clk32K_config,g_system_clk,g_rfPhyTpCal0,g_rfPhyTpCal1); LOG("sizeof(struct ll_pkt_desc) = %d, buf size = %d\n", sizeof(struct ll_pkt_desc), BLE_CONN_BUF_SIZE); LOG("sizeof(g_pConnectionBuffer) = %d, sizeof(pConnContext) = %d, sizeof(largeHeap)=%d \n", - sizeof(g_pConnectionBuffer), sizeof(pConnContext),sizeof(g_largeHeap)); LOG("[REST CAUSE] %d\n ",g_system_reset_cause); + sizeof(g_pConnectionBuffer), sizeof(pConnContext),sizeof(g_largeHeap)); LOG("[REST CAUSE] %d\n ",g_system_reset_cause); app_main(); return 0; } -///////////////////////////////////// end /////////////////////////////////////// diff --git a/bthome_phy6222/source/osal_peripheral.c b/bthome_phy6222/source/osal_peripheral.c index 2913cd8..be8d6cf 100644 --- a/bthome_phy6222/source/osal_peripheral.c +++ b/bthome_phy6222/source/osal_peripheral.c @@ -1,20 +1,12 @@ /************************************************************************************************** -******* + Filename: OSAL_SimpleBLEPeripheral.c + Revised: + Revision: + Description: This file contains function that allows user setup tasks **************************************************************************************************/ /************************************************************************************************** - Filename: OSAL_SimpleBLEPeripheral.c - Revised: - Revision: - - Description: This file contains function that allows user setup tasks - - - -**************************************************************************************************/ - -/************************************************************************************************** - INCLUDES + INCLUDES **************************************************************************************************/ #if (APP_CFG == 0) #include "OSAL.h" @@ -27,7 +19,7 @@ #include "hci_tl.h" #if defined ( OSAL_CBTIMER_NUM_TASKS ) - #include "osal_cbtimer.h" + #include "osal_cbtimer.h" #endif /* L2CAP */ @@ -51,27 +43,27 @@ #include "halperipheral.h" /********************************************************************* - GLOBAL VARIABLES + GLOBAL VARIABLES */ // The order in this table must be identical to the task initialization calls below in osalInitTask. const pTaskEventHandlerFn tasksArr[] = { - LL_ProcessEvent, // task 0 - HCI_ProcessEvent, // task 1 + LL_ProcessEvent, // task 0 + HCI_ProcessEvent, // task 1 #if defined ( OSAL_CBTIMER_NUM_TASKS ) - OSAL_CBTIMER_PROCESS_EVENT( osal_CbTimerProcessEvent ), // task 3 + OSAL_CBTIMER_PROCESS_EVENT( osal_CbTimerProcessEvent ), // task 3 #endif - L2CAP_ProcessEvent, // task 2 - SM_ProcessEvent, // task 3 - GAP_ProcessEvent, // task 4 - GATT_ProcessEvent, // task 5 - GAPRole_ProcessEvent, // task 6 + L2CAP_ProcessEvent, // task 2 + SM_ProcessEvent, // task 3 + GAP_ProcessEvent, // task 4 + GATT_ProcessEvent, // task 5 + GAPRole_ProcessEvent, // task 6 #if (DEF_GAPBOND_MGR_ENABLE==1) - GAPBondMgr_ProcessEvent, // task , add 2017-11-15 + GAPBondMgr_ProcessEvent, // task , add 2017-11-15 #endif - GATTServApp_ProcessEvent, // task 7 - SimpleBLEPeripheral_ProcessEvent, // task 8 + GATTServApp_ProcessEvent, // task 7 + SimpleBLEPeripheral_ProcessEvent, // task 8 }; @@ -79,49 +71,48 @@ const uint8 tasksCnt = sizeof( tasksArr ) / sizeof( tasksArr[0] ); uint16* tasksEvents; /********************************************************************* - FUNCTIONS + FUNCTIONS *********************************************************************/ /********************************************************************* - @fn osalInitTasks + @fn osalInitTasks - @brief This function invokes the initialization function for each task. + @brief This function invokes the initialization function for each task. - @param void + @param void - @return none + @return none */ void osalInitTasks( void ) { - uint8 taskID = 0; - tasksEvents = (uint16*)osal_mem_alloc( sizeof( uint16 ) * tasksCnt); - osal_memset( tasksEvents, 0, (sizeof( uint16 ) * tasksCnt)); - /* LL Task */ - LL_Init( taskID++ ); - /* HCI Task */ - HCI_Init( taskID++ ); - #if defined ( OSAL_CBTIMER_NUM_TASKS ) - /* Callback Timer Tasks */ - osal_CbTimerInit( taskID ); - taskID += OSAL_CBTIMER_NUM_TASKS; - #endif - /* L2CAP Task */ - L2CAP_Init( taskID++ ); - /* SM Task */ - SM_Init( taskID++ ); - /* GAP Task */ - GAP_Init( taskID++ ); - /* GATT Task */ - GATT_Init( taskID++ ); - /* Profiles */ - GAPRole_Init( taskID++ ); + uint8 taskID = 0; + tasksEvents = (uint16*)osal_mem_alloc( sizeof( uint16 ) * tasksCnt); + osal_memset( tasksEvents, 0, (sizeof( uint16 ) * tasksCnt)); + /* LL Task */ + LL_Init( taskID++ ); + /* HCI Task */ + HCI_Init( taskID++ ); + #if defined ( OSAL_CBTIMER_NUM_TASKS ) + /* Callback Timer Tasks */ + osal_CbTimerInit( taskID ); + taskID += OSAL_CBTIMER_NUM_TASKS; + #endif + /* L2CAP Task */ + L2CAP_Init( taskID++ ); + /* SM Task */ + SM_Init( taskID++ ); + /* GAP Task */ + GAP_Init( taskID++ ); + /* GATT Task */ + GATT_Init( taskID++ ); + /* Profiles */ + GAPRole_Init( taskID++ ); #if(DEF_GAPBOND_MGR_ENABLE==1) - GAPBondMgr_Init( taskID++ ); // 2017-11-15 + GAPBondMgr_Init( taskID++ ); // 2017-11-15 #endif - GATTServApp_Init( taskID++ ); - /* Application */ - SimpleBLEPeripheral_Init( taskID++ ); + GATTServApp_Init( taskID++ ); + /* Application */ + SimpleBLEPeripheral_Init( taskID++ ); } #endif -/********************************************************************* -*********************************************************************/ + diff --git a/bthome_phy6222/source/peripheral_main.c b/bthome_phy6222/source/peripheral_main.c index 76cce85..5537be1 100644 --- a/bthome_phy6222/source/peripheral_main.c +++ b/bthome_phy6222/source/peripheral_main.c @@ -1,19 +1,13 @@ /************************************************************************************************** -******* -**************************************************************************************************/ - -/************************************************************************************************** - Filename: SimpleBLEPeripheral_Main.c - Revised: - Revision: - - Description: This file contains the main and callback functions for - the Simple BLE Peripheral sample application. - + Filename: SimpleBLEPeripheral_Main.c + Revised: + Revision: + Description: This file contains the main and callback functions for + the Simple BLE Peripheral sample application. **************************************************************************************************/ #if (APP_CFG == 0) /************************************************************************************************** - Includes + Includes **************************************************************************************************/ /* Hal Drivers */ @@ -23,36 +17,32 @@ #include "OSAL_PwrMgr.h" #include "osal_snv.h" - /************************************************************************************************** - FUNCTIONS + FUNCTIONS **************************************************************************************************/ - /************************************************************************************************** - @fn main + @fn main - @brief Start of application. + @brief Start of application. - @param none + @param none - @return none + @return none ************************************************************************************************** */ int app_main(void) { - /* Initialize the operating system */ - osal_init_system(); - osal_pwrmgr_device( PWRMGR_BATTERY ); - /* Start OSAL */ - osal_start_system(); // No Return from here - return 0; + /* Initialize the operating system */ + osal_init_system(); + osal_pwrmgr_device( PWRMGR_BATTERY ); + /* Start OSAL */ + osal_start_system(); // No Return from here + return 0; } #endif /************************************************************************************************** - CALL-BACKS + CALL-BACKS **************************************************************************************************/ -/************************************************************************************************* -**************************************************************************************************/ diff --git a/bthome_phy6222/source/sbp_profile_ota.c b/bthome_phy6222/source/sbp_profile_ota.c index 40f8ede..21b890f 100644 --- a/bthome_phy6222/source/sbp_profile_ota.c +++ b/bthome_phy6222/source/sbp_profile_ota.c @@ -1,20 +1,13 @@ /************************************************************************************************** -******* -**************************************************************************************************/ - -/************************************************************************************************** - Filename: sbpProfile_ota.c - Revised: - Revision: - - Description: This file contains the Simple GATT profile sample GATT service - profile for use with the BLE sample application. - - + Filename: sbpProfile_ota.c + Revised: + Revision: + Description: This file contains the Simple GATT profile sample GATT service + profile for use with the BLE sample application. **************************************************************************************************/ /********************************************************************* - INCLUDES + INCLUDES */ #include "bcomdef.h" #include "OSAL.h" @@ -36,7 +29,7 @@ * CONSTANTS */ -#define SERVAPP_NUM_ATTR_SUPPORTED 8 +#define SERVAPP_NUM_ATTR_SUPPORTED 8 /********************************************************************* * TYPEDEFS @@ -47,19 +40,19 @@ */ // Simple GATT Profile Service UUID: 0xFFF0 CONST uint8 simpleProfileServUUID[ATT_BT_UUID_SIZE] = -{ +{ LO_UINT16(SIMPLEPROFILE_SERV_UUID), HI_UINT16(SIMPLEPROFILE_SERV_UUID) }; // Characteristic 1 UUID: 0xFFF3 CONST uint8 simpleProfilechar1UUID[ATT_BT_UUID_SIZE] = -{ +{ LO_UINT16(SIMPLEPROFILE_CHAR1_UUID), HI_UINT16(SIMPLEPROFILE_CHAR1_UUID) }; // Characteristic 2 UUID: 0xFFF4 CONST uint8 simpleProfilechar2UUID[ATT_BT_UUID_SIZE] = -{ +{ LO_UINT16(SIMPLEPROFILE_CHAR2_UUID), HI_UINT16(SIMPLEPROFILE_CHAR2_UUID) }; @@ -87,22 +80,22 @@ static CONST gattAttrType_t simpleProfileService = { ATT_BT_UUID_SIZE, simplePro // Simple Profile Characteristic 1 Properties -static uint8 simpleProfileChar1Props = GATT_PROP_WRITE | GATT_PROP_WRITE_NO_RSP; +static uint8 simpleProfileChar1Props = GATT_PROP_WRITE | GATT_PROP_WRITE_NO_RSP; static uint8 simpleProfileChar1[BLE_ATT_CMD_LED]= {0,}; // Characteristic 1 Value -static uint8 simpleProfileChar1UserDesp[] = "Commond\0"; // Simple Profile Characteristic 1 User Description +static uint8 simpleProfileChar1UserDesp[] = "Commond\0"; // Simple Profile Characteristic 1 User Description // Simple Profile Characteristic 2 Properties -static uint8 simpleProfileChar2Props = GATT_PROP_READ |GATT_PROP_NOTIFY; -static uint8 simpleProfileChar2[BLE_ATT_CMD_LED]= {0,}; // Characteristic 2 Value -static uint8 simpleProfileChar2UserDesp[] = "Response\0"; // Simple Profile Characteristic 2 User Description +static uint8 simpleProfileChar2Props = GATT_PROP_READ |GATT_PROP_NOTIFY; +static uint8 simpleProfileChar2[BLE_ATT_CMD_LED]= {0,}; // Characteristic 2 Value +static uint8 simpleProfileChar2UserDesp[] = "Response\0"; // Simple Profile Characteristic 2 User Description static gattCharCfg_t simpleProfileChar2Config[GATT_MAX_NUM_CONN]; // /********************************************************************* * Profile Attributes - Table */ -static gattAttribute_t simpleProfileAttrTbl[SERVAPP_NUM_ATTR_SUPPORTED] = +static gattAttribute_t simpleProfileAttrTbl[SERVAPP_NUM_ATTR_SUPPORTED] = { /* type */ /* permissions */ /* handle */ /* pValue */ // Simple Profile Service @@ -113,16 +106,16 @@ static gattAttribute_t simpleProfileAttrTbl[SERVAPP_NUM_ATTR_SUPPORTED] = // Characteristic Value 1 {{ ATT_BT_UUID_SIZE, simpleProfilechar1UUID }, GATT_PERMIT_READ | GATT_PERMIT_WRITE, 0, &simpleProfileChar1[0]}, // Characteristic 1 User Description - {{ ATT_BT_UUID_SIZE, charUserDescUUID }, GATT_PERMIT_READ, 0, simpleProfileChar1UserDesp}, + {{ ATT_BT_UUID_SIZE, charUserDescUUID }, GATT_PERMIT_READ, 0, simpleProfileChar1UserDesp}, // Characteristic 2 Declaration {{ ATT_BT_UUID_SIZE, characterUUID }, GATT_PERMIT_READ, 0, &simpleProfileChar2Props}, // Characteristic Value 2 {{ ATT_BT_UUID_SIZE, simpleProfilechar2UUID }, GATT_PERMIT_READ | GATT_PERMIT_WRITE, 0, &simpleProfileChar2[0]}, // Characteristic 2 configuration - {{ ATT_BT_UUID_SIZE, clientCharCfgUUID }, GATT_PERMIT_READ | GATT_PERMIT_WRITE, 0, (uint8 *)simpleProfileChar2Config}, + {{ ATT_BT_UUID_SIZE, clientCharCfgUUID }, GATT_PERMIT_READ | GATT_PERMIT_WRITE, 0, (uint8 *)simpleProfileChar2Config}, // Characteristic 2 User Description - {{ ATT_BT_UUID_SIZE, charUserDescUUID }, GATT_PERMIT_READ, 0, simpleProfileChar2UserDesp}, + {{ ATT_BT_UUID_SIZE, charUserDescUUID }, GATT_PERMIT_READ, 0, simpleProfileChar2UserDesp}, }; @@ -130,8 +123,8 @@ static gattAttribute_t simpleProfileAttrTbl[SERVAPP_NUM_ATTR_SUPPORTED] = * LOCAL FUNCTIONS */ static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr,uint8 *pValue, uint16 *pLen, uint16 offset, uint8 maxLen ); -static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr,uint8 *pValue, uint16 len, uint16 offset ); -static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr,uint8 *pValue, uint16 len, uint16 offset ); +static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); /********************************************************************* * PROFILE CALLBACKS */ @@ -140,7 +133,7 @@ CONST gattServiceCBs_t simpleProfileCBs = { simpleProfile_ReadAttrCB, // Read callback function pointer simpleProfile_WriteAttrCB, // Write callback function pointer - NULL // Authorization callback function pointer + NULL // Authorization callback function pointer }; /********************************************************************* @@ -148,15 +141,15 @@ CONST gattServiceCBs_t simpleProfileCBs = */ /********************************************************************* - * @fn SimpleProfile_AddService + * @fn SimpleProfile_AddService * - * @brief Initializes the Simple Profile service by registering - * GATT attributes with the GATT server. + * @brief Initializes the Simple Profile service by registering + * GATT attributes with the GATT server. * - * @param services - services to add. This is a bit map and can - * contain more than one service. + * @param services - services to add. This is a bit map and can + * contain more than one service. * - * @return Success or Failure + * @return Success or Failure */ bStatus_t SimpleProfile_AddService( uint32 services ) { @@ -166,14 +159,14 @@ bStatus_t SimpleProfile_AddService( uint32 services ) GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar2Config ); // Register with Link DB to receive link status change callback - VOID linkDB_Register( simpleProfile_HandleConnStatusCB ); + VOID linkDB_Register( simpleProfile_HandleConnStatusCB ); if ( services & SIMPLEPROFILE_SERVICE ) { // Register GATT attribute list and CBs with GATT Server App - status = GATTServApp_RegisterService( simpleProfileAttrTbl, - GATT_NUM_ATTRS( simpleProfileAttrTbl ), - &simpleProfileCBs ); + status = GATTServApp_RegisterService( simpleProfileAttrTbl, + GATT_NUM_ATTRS( simpleProfileAttrTbl ), + &simpleProfileCBs ); } return ( status ); @@ -181,14 +174,14 @@ bStatus_t SimpleProfile_AddService( uint32 services ) /********************************************************************* - * @fn SimpleProfile_RegisterAppCBs + * @fn SimpleProfile_RegisterAppCBs * - * @brief Registers the application callback function. Only call - * this function once. + * @brief Registers the application callback function. Only call + * this function once. * - * @param callbacks - pointer to application callbacks. + * @param callbacks - pointer to application callbacks. * - * @return SUCCESS or bleAlreadyInRequestedMode + * @return SUCCESS or bleAlreadyInRequestedMode */ bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) { @@ -199,21 +192,21 @@ bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) return ( bleAlreadyInRequestedMode ); } } - + /********************************************************************* - * @fn SimpleProfile_SetParameter + * @fn SimpleProfile_SetParameter * - * @brief Set a Simple Profile parameter. + * @brief Set a Simple Profile parameter. * - * @param param - Profile parameter ID - * @param len - length of data to right - * @param value - pointer to data to write. This is dependent on - * the parameter ID and WILL be cast to the appropriate - * data type (example: data type of uint16 will be cast to - * uint16 pointer). + * @param param - Profile parameter ID + * @param len - length of data to right + * @param value - pointer to data to write. This is dependent on + * the parameter ID and WILL be cast to the appropriate + * data type (example: data type of uint16 will be cast to + * uint16 pointer). * - * @return bStatus_t + * @return bStatus_t */ bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) { @@ -222,7 +215,7 @@ bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) { case SIMPLEPROFILE_CHAR1: if ( len <= BLE_ATT_CMD_LED ){ - osal_memcpy(simpleProfileChar1, value, len); + osal_memcpy(simpleProfileChar1, value, len); }else{ ret = bleInvalidRange; } @@ -236,17 +229,17 @@ bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) } /********************************************************************* - * @fn SimpleProfile_GetParameter + * @fn SimpleProfile_GetParameter * - * @brief Get a Simple Profile parameter. + * @brief Get a Simple Profile parameter. * - * @param param - Profile parameter ID - * @param value - pointer to data to put. This is dependent on - * the parameter ID and WILL be cast to the appropriate - * data type (example: data type of uint16 will be cast to - * uint16 pointer). + * @param param - Profile parameter ID + * @param value - pointer to data to put. This is dependent on + * the parameter ID and WILL be cast to the appropriate + * data type (example: data type of uint16 will be cast to + * uint16 pointer). * - * @return bStatus_t + * @return bStatus_t */ bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) { @@ -254,12 +247,12 @@ bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) switch ( param ) { // case SIMPLEPROFILE_CHAR1: - // VOID osal_memcpy( value, simpleProfileChar1, BLE_ATT_CMD_LED); + // VOID osal_memcpy( value, simpleProfileChar1, BLE_ATT_CMD_LED); // break; case SIMPLEPROFILE_CHAR2: - VOID osal_memcpy( value, simpleProfileChar2, BLE_ATT_CMD_LED ); - break; + VOID osal_memcpy( value, simpleProfileChar2, BLE_ATT_CMD_LED ); + break; default: ret = INVALIDPARAMETER; @@ -269,25 +262,25 @@ bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) } /********************************************************************* - * @fn simpleProfile_ReadAttrCB + * @fn simpleProfile_ReadAttrCB * - * @brief Read an attribute. + * @brief Read an attribute. * - * @param connHandle - connection message was received on - * @param pAttr - pointer to attribute - * @param pValue - pointer to data to be read - * @param pLen - length of data to be read - * @param offset - offset of the first octet to be read - * @param maxLen - maximum length of data to be read + * @param connHandle - connection message was received on + * @param pAttr - pointer to attribute + * @param pValue - pointer to data to be read + * @param pLen - length of data to be read + * @param offset - offset of the first octet to be read + * @param maxLen - maximum length of data to be read * - * @return Success or Failure + * @return Success or Failure */ -static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, - uint8 *pValue, uint16 *pLen, uint16 offset, uint8 maxLen ) +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint8 maxLen ) { - (void)connHandle; - (void)maxLen; - bStatus_t status = SUCCESS; + (void)connHandle; + (void)maxLen; + bStatus_t status = SUCCESS; // If attribute permissions require authorization to read, return error if ( gattPermitAuthorRead( pAttr->permissions ) ) @@ -295,13 +288,13 @@ static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *p // Insufficient authorization return ( ATT_ERR_INSUFFICIENT_AUTHOR ); } - + // Make sure it's not a blob operation (no attributes in the profile are long) if ( offset > 0 ) { return ( ATT_ERR_ATTR_NOT_LONG ); } - + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) { // 16-bit UUID @@ -330,21 +323,21 @@ static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *p } /********************************************************************* - * @fn simpleProfile_WriteAttrCB + * @fn simpleProfile_WriteAttrCB * - * @brief Validate attribute data prior to a write operation + * @brief Validate attribute data prior to a write operation * - * @param connHandle - connection message was received on - * @param pAttr - pointer to attribute - * @param pValue - pointer to data to be written - * @param len - length of data - * @param offset - offset of the first octet to be written + * @param connHandle - connection message was received on + * @param pAttr - pointer to attribute + * @param pValue - pointer to data to be written + * @param len - length of data + * @param offset - offset of the first octet to be written * - * @return Success or Failure + * @return Success or Failure */ // TODO: test this function static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, - uint8 *pValue, uint16 len, uint16 offset ) + uint8 *pValue, uint16 len, uint16 offset ) { bStatus_t status = SUCCESS; uint8 notifyApp = 0xFF; @@ -355,7 +348,7 @@ static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t * // Insufficient authorization return ( ATT_ERR_INSUFFICIENT_AUTHOR ); } - + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) { // 16-bit UUID @@ -374,20 +367,20 @@ static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t * } //Write the value if ( status == SUCCESS ){ - uint8 *pCurValue = (uint8 *)pAttr->pValue; + uint8 *pCurValue = (uint8 *)pAttr->pValue; VOID osal_memcpy(pCurValue, pValue, len ); LOG("receive data = 0x "); LOG_DUMP_BYTE(pCurValue, len); // DO NOT deal data in call back!!!Copy data and start an event. osal_set_event(simpleBLEPeripheral_TaskID, SBP_DEALDATA); - notifyApp = SIMPLEPROFILE_CHAR1; - } + notifyApp = SIMPLEPROFILE_CHAR1; + } break; - + case GATT_CLIENT_CHAR_CFG_UUID: LOG("Enable/Disable Notity\n"); status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, - offset, GATT_CLIENT_CFG_NOTIFY ); + offset, GATT_CLIENT_CFG_NOTIFY ); break; default: @@ -401,27 +394,27 @@ static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t * } // If a charactersitic value changed then callback function to notify application of change if ( (notifyApp != 0xFF ) && simpleProfile_AppCBs && simpleProfile_AppCBs->pfnSimpleProfileChange ){ - simpleProfile_AppCBs->pfnSimpleProfileChange( notifyApp ); + simpleProfile_AppCBs->pfnSimpleProfileChange( notifyApp ); } return ( status ); } /********************************************************************* - * @fn simpleProfile_HandleConnStatusCB + * @fn simpleProfile_HandleConnStatusCB * - * @brief Simple Profile link status change handler function. + * @brief Simple Profile link status change handler function. * - * @param connHandle - connection handle - * @param changeType - type of change + * @param connHandle - connection handle + * @param changeType - type of change * - * @return none + * @return none */ static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ) -{ +{ // Make sure this is not loopback connection if ( connHandle != LOOPBACK_CONNHANDLE ){ // Reset Client Char Config if connection has dropped - if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED )||( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) &&( !linkDB_Up( connHandle ) ) ) ){ + if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED )||( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) &&( !linkDB_Up( connHandle ) ) ) ){ GATTServApp_InitCharCfg( connHandle, simpleProfileChar2Config ); } } @@ -431,9 +424,9 @@ bStatus_t simpleProfile_Notify( uint8 param, uint8 len, void *value ) { bStatus_t ret = SUCCESS; uint16 notfEnable; - + switch ( param ) - { + { case SIMPLEPROFILE_CHAR2: notfEnable = GATTServApp_ReadCharCfg( 0, simpleProfileChar2Config ); @@ -442,8 +435,8 @@ bStatus_t simpleProfile_Notify( uint8 param, uint8 len, void *value ) VOID osal_memcpy( simpleProfileChar2, value, len ); // ReadNotify_Len = len; ret = GATTServApp_ProcessCharCfg( simpleProfileChar2Config, simpleProfileChar2, FALSE, - simpleProfileAttrTbl, GATT_NUM_ATTRS( simpleProfileAttrTbl ), - INVALID_TASK_ID ); + simpleProfileAttrTbl, GATT_NUM_ATTRS( simpleProfileAttrTbl ), + INVALID_TASK_ID ); }else{ ret = bleNotReady; } @@ -456,6 +449,3 @@ bStatus_t simpleProfile_Notify( uint8 param, uint8 len, void *value ) return ( ret ); } - -/********************************************************************* -*********************************************************************/ diff --git a/bthome_phy6222/source/sbp_profile_ota.h b/bthome_phy6222/source/sbp_profile_ota.h index 009ae78..76d5a66 100644 --- a/bthome_phy6222/source/sbp_profile_ota.h +++ b/bthome_phy6222/source/sbp_profile_ota.h @@ -1,15 +1,9 @@ /************************************************************************************************** -******* -**************************************************************************************************/ - -/************************************************************************************************** - Filename: sbpProfile_ota.h - Revised: - Revision: - - Description: This file contains the Simple GATT profile definitions and - prototypes. - + Filename: sbpProfile_ota.h + Revised: + Revision: + Description: This file contains the Simple GATT profile definitions and + prototypes. **************************************************************************************************/ #ifndef SBPPROFILE_OTA_H @@ -31,15 +25,15 @@ extern "C" // Profile Parameters #define SIMPLEPROFILE_CHAR1 0 // RW uint8 - Profile Characteristic 1 value #define SIMPLEPROFILE_CHAR2 1 // RW uint8 - Profile Characteristic 2 value -//#define SIMPLEPROFILE_CHAR3 2 // RW uint8 - Profile Characteristic 3 value -//#define SIMPLEPROFILE_CHAR4 3 // RW uint8 - Profile Characteristic 4 value -//#define SIMPLEPROFILE_CHAR5 4 // RW uint8 - Profile Characteristic 4 value -//#define SIMPLEPROFILE_CHAR6 5 // RW uint8 - Profile Characteristic 4 value -//#define SIMPLEPROFILE_CHAR7 6 // RW uint8 - Profile Characteristic 4 value +//#define SIMPLEPROFILE_CHAR3 2 // RW uint8 - Profile Characteristic 3 value +//#define SIMPLEPROFILE_CHAR4 3 // RW uint8 - Profile Characteristic 4 value +//#define SIMPLEPROFILE_CHAR5 4 // RW uint8 - Profile Characteristic 4 value +//#define SIMPLEPROFILE_CHAR6 5 // RW uint8 - Profile Characteristic 4 value +//#define SIMPLEPROFILE_CHAR7 6 // RW uint8 - Profile Characteristic 4 value // Simple Profile Service UUID #define SIMPLEPROFILE_SERV_UUID 0xFFF0 - + // Key Pressed UUID #define SIMPLEPROFILE_CHAR1_UUID 0xFFF3 #define SIMPLEPROFILE_CHAR2_UUID 0xFFF4 @@ -73,10 +67,10 @@ typedef void (*simpleProfileChange_t)( uint8 paramID ); typedef struct { - simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes + simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes } simpleProfileCBs_t; - + /********************************************************************* * API FUNCTIONS @@ -85,42 +79,42 @@ typedef struct /* * SimpleProfile_AddService- Initializes the Simple GATT Profile service by registering - * GATT attributes with the GATT server. + * GATT attributes with the GATT server. * - * @param services - services to add. This is a bit map and can - * contain more than one service. + * @param services - services to add. This is a bit map and can + * contain more than one service. */ extern bStatus_t SimpleProfile_AddService( uint32 services ); /* * SimpleProfile_RegisterAppCBs - Registers the application callback function. - * Only call this function once. + * Only call this function once. * - * appCallbacks - pointer to application callbacks. + * appCallbacks - pointer to application callbacks. */ extern bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ); /* * SimpleProfile_SetParameter - Set a Simple GATT Profile parameter. * - * param - Profile parameter ID - * len - length of data to right - * value - pointer to data to write. This is dependent on - * the parameter ID and WILL be cast to the appropriate - * data type (example: data type of uint16 will be cast to - * uint16 pointer). + * param - Profile parameter ID + * len - length of data to right + * value - pointer to data to write. This is dependent on + * the parameter ID and WILL be cast to the appropriate + * data type (example: data type of uint16 will be cast to + * uint16 pointer). */ extern bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ); /* * SimpleProfile_GetParameter - Get a Simple GATT Profile parameter. * - * param - Profile parameter ID - * value - pointer to data to write. This is dependent on - * the parameter ID and WILL be cast to the appropriate - * data type (example: data type of uint16 will be cast to - * uint16 pointer). + * param - Profile parameter ID + * value - pointer to data to write. This is dependent on + * the parameter ID and WILL be cast to the appropriate + * data type (example: data type of uint16 will be cast to + * uint16 pointer). */ extern bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ); diff --git a/bthome_phy6222/source/sensor.h b/bthome_phy6222/source/sensor.h index 082c27c..56b4016 100644 --- a/bthome_phy6222/source/sensor.h +++ b/bthome_phy6222/source/sensor.h @@ -6,17 +6,17 @@ // Timing -#define SENSOR_POWER_TIMEOUT_ms 5 +#define SENSOR_POWER_TIMEOUT_ms 5 #define SENSOR_RESET_TIMEOUT_ms 5 #define SENSOR_MEASURING_TIMEOUT_ms 7 -// I2C addres +// I2C addres #define CHT8310_I2C_ADDR0 0x40 #define CHT8310_I2C_ADDR1 0x44 #define CHT8310_I2C_ADDR2 0x48 #define CHT8310_I2C_ADDR3 0x4C -// Registers +// Registers #define CHT8310_REG_TMP 0x00 #define CHT8310_REG_HMD 0x01 #define CHT8310_REG_STA 0x02 @@ -30,32 +30,32 @@ #define CHT8310_REG_RST 0xfc #define CHT8310_REG_ID 0xfe -// Status register mask -#define CHT8310_STA_BUSY 0x8000 -#define CHT8310_STA_THI 0x4000 -#define CHT8310_STA_TLO 0x2000 -#define CHT8310_STA_HHI 0x1000 -#define CHT8310_STA_HLO 0x0800 +// Status register mask +#define CHT8310_STA_BUSY 0x8000 +#define CHT8310_STA_THI 0x4000 +#define CHT8310_STA_TLO 0x2000 +#define CHT8310_STA_HHI 0x1000 +#define CHT8310_STA_HLO 0x0800 -// Config register mask -#define CHT8310_CFG_MASK 0x8000 -#define CHT8310_CFG_SD 0x4000 -#define CHT8310_CFG_ALTH 0x2000 -#define CHT8310_CFG_EM 0x1000 -#define CHT8310_CFG_EHT 0x0100 -#define CHT8310_CFG_TME 0x0080 -#define CHT8310_CFG_POL 0x0020 -#define CHT8310_CFG_ALT 0x0018 -#define CHT8310_CFG_CONSEC_FQ 0x0006 -#define CHT8310_CFG_ATM 0x0001 +// Config register mask +#define CHT8310_CFG_MASK 0x8000 +#define CHT8310_CFG_SD 0x4000 +#define CHT8310_CFG_ALTH 0x2000 +#define CHT8310_CFG_EM 0x1000 +#define CHT8310_CFG_EHT 0x0100 +#define CHT8310_CFG_TME 0x0080 +#define CHT8310_CFG_POL 0x0020 +#define CHT8310_CFG_ALT 0x0018 +#define CHT8310_CFG_CONSEC_FQ 0x0006 +#define CHT8310_CFG_ATM 0x0001 typedef struct _measured_data_t { - uint16_t count; + uint16_t count; int16_t temp; // x 0.01 C int16_t humi; // x 0.01 % uint16_t battery_mv; // mV - uint8_t battery; // 0..100 % + uint8_t battery; // 0..100 % } measured_data_t; extern measured_data_t measured_data; diff --git a/bthome_phy6222/source/sensors.c b/bthome_phy6222/source/sensors.c index 389b44c..774cd24 100644 --- a/bthome_phy6222/source/sensors.c +++ b/bthome_phy6222/source/sensors.c @@ -8,7 +8,7 @@ /* Tuya: * I2C0 SCL P24 * I2C0 SDA P23 - + SCL P20 SDA P18 KEY P07 @@ -20,56 +20,56 @@ measured_data_t measured_data; void init_i2c(void) { - hal_gpio_fmux_set(I2C_SCL, FMUX_IIC0_SCL); - hal_gpio_fmux_set(I2C_SDA, FMUX_IIC0_SDA); - - //hal_i2c_init(I2C_0, I2C_CLOCK_400K); - - int pclk = clk_get_pclk(); - - AP_I2C_TypeDef* pi2cdev = AP_I2C0; - hal_clk_gate_enable(MOD_I2C0); - pi2cdev->IC_ENABLE = 0; - pi2cdev->IC_CON = 0x61; - pi2cdev->IC_CON = ((pi2cdev->IC_CON) & 0xfffffff9)|(0x02 << 1); - if(pclk == 16000000) - { - pi2cdev->IC_FS_SCL_HCNT = 10; - pi2cdev->IC_FS_SCL_LCNT = 17; - } - else if(pclk == 32000000) - { - pi2cdev->IC_FS_SCL_HCNT = 30; - pi2cdev->IC_FS_SCL_LCNT = 35; - } - else if(pclk == 48000000) - { - pi2cdev->IC_FS_SCL_HCNT = 48; - pi2cdev->IC_FS_SCL_LCNT = 54; - } - else if(pclk == 64000000) - { - pi2cdev->IC_FS_SCL_HCNT = 67; - pi2cdev->IC_FS_SCL_LCNT = 75; - } - else if(pclk == 96000000) - { - pi2cdev->IC_FS_SCL_HCNT = 105; - pi2cdev->IC_FS_SCL_LCNT = 113; - } - pi2cdev->IC_TAR = I2C_MASTER_ADDR_DEF; - pi2cdev->IC_INTR_MASK = 0; - pi2cdev->IC_RX_TL = 0x0; - pi2cdev->IC_TX_TL = 0x1; - pi2cdev->IC_ENABLE = 1; + hal_gpio_fmux_set(I2C_SCL, FMUX_IIC0_SCL); + hal_gpio_fmux_set(I2C_SDA, FMUX_IIC0_SDA); + + //hal_i2c_init(I2C_0, I2C_CLOCK_400K); + + int pclk = clk_get_pclk(); + + AP_I2C_TypeDef* pi2cdev = AP_I2C0; + hal_clk_gate_enable(MOD_I2C0); + pi2cdev->IC_ENABLE = 0; + pi2cdev->IC_CON = 0x61; + pi2cdev->IC_CON = ((pi2cdev->IC_CON) & 0xfffffff9)|(0x02 << 1); + if(pclk == 16000000) + { + pi2cdev->IC_FS_SCL_HCNT = 10; + pi2cdev->IC_FS_SCL_LCNT = 17; + } + else if(pclk == 32000000) + { + pi2cdev->IC_FS_SCL_HCNT = 30; + pi2cdev->IC_FS_SCL_LCNT = 35; + } + else if(pclk == 48000000) + { + pi2cdev->IC_FS_SCL_HCNT = 48; + pi2cdev->IC_FS_SCL_LCNT = 54; + } + else if(pclk == 64000000) + { + pi2cdev->IC_FS_SCL_HCNT = 67; + pi2cdev->IC_FS_SCL_LCNT = 75; + } + else if(pclk == 96000000) + { + pi2cdev->IC_FS_SCL_HCNT = 105; + pi2cdev->IC_FS_SCL_LCNT = 113; + } + pi2cdev->IC_TAR = I2C_MASTER_ADDR_DEF; + pi2cdev->IC_INTR_MASK = 0; + pi2cdev->IC_RX_TL = 0x0; + pi2cdev->IC_TX_TL = 0x1; + pi2cdev->IC_ENABLE = 1; } void deinit_i2c(void) { - AP_I2C_TypeDef * pi2cdev = AP_I2C0; - pi2cdev->IC_ENABLE = 0; - hal_clk_gate_disable(MOD_I2C0); - hal_gpio_pin_init(I2C_SCL, IE); - hal_gpio_pin_init(I2C_SDA, IE); + AP_I2C_TypeDef * pi2cdev = AP_I2C0; + pi2cdev->IC_ENABLE = 0; + hal_clk_gate_disable(MOD_I2C0); + hal_gpio_pin_init(I2C_SCL, IE); + hal_gpio_pin_init(I2C_SDA, IE); } extern volatile uint32 osal_sys_tick; @@ -78,13 +78,13 @@ extern volatile uint32 osal_sys_tick; int read_i2c_bytes(uint8 addr, uint8 reg, uint8 * data, uint8 size) { int i = size; AP_I2C_TypeDef * pi2cdev = AP_I2C0; - pi2cdev->IC_ENABLE = 0; - pi2cdev->IC_TAR = addr; - HAL_ENTER_CRITICAL_SECTION(); - pi2cdev->IC_ENABLE = 1; + pi2cdev->IC_ENABLE = 0; + pi2cdev->IC_TAR = addr; + HAL_ENTER_CRITICAL_SECTION(); + pi2cdev->IC_ENABLE = 1; pi2cdev->IC_DATA_CMD = reg; - //while(!(pi2cdev->IC_RAW_INTR_STAT & 0x10)); - while(i--) + //while(!(pi2cdev->IC_RAW_INTR_STAT & 0x10)); + while(i--) pi2cdev->IC_DATA_CMD = 0x100; HAL_EXIT_CRITICAL_SECTION(); uint32 to = osal_sys_tick; @@ -102,43 +102,43 @@ int read_i2c_bytes(uint8 addr, uint8 reg, uint8 * data, uint8 size) { } int send_i2c_byte(uint8 addr, uint8 data) { - AP_I2C_TypeDef * pi2cdev = AP_I2C0; - pi2cdev->IC_ENABLE = 0; - pi2cdev->IC_TAR = addr; - HAL_ENTER_CRITICAL_SECTION(); - pi2cdev->IC_ENABLE = 1; - pi2cdev->IC_DATA_CMD = data; - // while(!(pi2cdev->IC_RAW_INTR_STAT & 0x10)); - HAL_EXIT_CRITICAL_SECTION(); - uint32 to = osal_sys_tick; - while(1) { - if(pi2cdev->IC_RAW_INTR_STAT & 0x200)// check tx empty - break; - if(osal_sys_tick - to > 10) - return 1; - } - return 0; + AP_I2C_TypeDef * pi2cdev = AP_I2C0; + pi2cdev->IC_ENABLE = 0; + pi2cdev->IC_TAR = addr; + HAL_ENTER_CRITICAL_SECTION(); + pi2cdev->IC_ENABLE = 1; + pi2cdev->IC_DATA_CMD = data; + // while(!(pi2cdev->IC_RAW_INTR_STAT & 0x10)); + HAL_EXIT_CRITICAL_SECTION(); + uint32 to = osal_sys_tick; + while(1) { + if(pi2cdev->IC_RAW_INTR_STAT & 0x200)// check tx empty + break; + if(osal_sys_tick - to > 10) + return 1; + } + return 0; } int send_i2c_wreg(uint8 addr, uint8 reg, uint16 data) { - AP_I2C_TypeDef * pi2cdev = AP_I2C0; - pi2cdev->IC_ENABLE = 0; - pi2cdev->IC_TAR = addr; - HAL_ENTER_CRITICAL_SECTION(); - pi2cdev->IC_ENABLE = 1; + AP_I2C_TypeDef * pi2cdev = AP_I2C0; + pi2cdev->IC_ENABLE = 0; + pi2cdev->IC_TAR = addr; + HAL_ENTER_CRITICAL_SECTION(); + pi2cdev->IC_ENABLE = 1; pi2cdev->IC_DATA_CMD = reg; while(!(pi2cdev->IC_RAW_INTR_STAT & 0x10)); pi2cdev->IC_DATA_CMD = (data >> 8) & 0xff; while(!(pi2cdev->IC_RAW_INTR_STAT & 0x10)); pi2cdev->IC_DATA_CMD = data & 0xff; - HAL_EXIT_CRITICAL_SECTION(); + HAL_EXIT_CRITICAL_SECTION(); uint32 to = osal_sys_tick; while(1) { if(pi2cdev->IC_RAW_INTR_STAT & 0x200)// check tx empty break; if(osal_sys_tick - to > 10) return 1; - } + } return 0; } @@ -152,7 +152,7 @@ __ATTR_SECTION_XIP__ void init_sensor(void) { int read_sensor(void) { int32 _r32; - int16 _r16; + int16 _r16; uint8 reg_data[4]; init_i2c(); _r32 = read_i2c_bytes(CHT8310_I2C_ADDR0, CHT8310_REG_TMP, reg_data, 2); @@ -160,21 +160,20 @@ int read_sensor(void) { _r32 |= read_i2c_bytes(CHT8310_I2C_ADDR0, CHT8310_REG_HMD, ®_data[2], 2); deinit_i2c(); if (!_r32) { -/* - * https://esp8266.ru/forum/threads/ble-soc-phy6202.4666/post-95300 - температура в 0.01 C (_r16 * 100 + 50) >> 8 - влажность в 0.01 % (_r32 * 10000 + 5000) >> 15 - заряд батареи в % ((battery_mv - 2000) * 6534 + 3277) >> 16 - заряд батареи в 0.1% (((battery_mv - 2000) << 16) + 32768) >> 16 +/* https://esp8266.ru/forum/threads/ble-soc-phy6202.4666/post-95300 + температура в 0.01 C (_r16 * 100 + 50) >> 8 + влажность в 0.01 % (_r32 * 10000 + 5000) >> 15 + заряд батареи в % ((battery_mv - 2000) * 6534 + 3277) >> 16 + заряд батареи в 0.1% (((battery_mv - 2000) << 16) + 32768) >> 16 */ - _r16 = (reg_data[0] << 8) | reg_data[1]; - measured_data.temp = (int32)(_r16 * 25606) >> 16; // x 0.01 C - _r32 = ((reg_data[2] << 8) | reg_data[3]) & 0x7fff; - measured_data.humi = (uint32)(_r32 * 20000) >> 16; // x 0.01 % - if (measured_data.humi > 9999) - measured_data.humi = 9999; - measured_data.count++; - return 0; + _r16 = (reg_data[0] << 8) | reg_data[1]; + measured_data.temp = (int32)(_r16 * 25606) >> 16; // x 0.01 C + _r32 = ((reg_data[2] << 8) | reg_data[3]) & 0x7fff; + measured_data.humi = (uint32)(_r32 * 20000) >> 16; // x 0.01 % + if (measured_data.humi > 9999) + measured_data.humi = 9999; + measured_data.count++; + return 0; } init_sensor(); return 1; diff --git a/bthome_phy6222/source/thb2_main.c b/bthome_phy6222/source/thb2_main.c index 32882eb..ae2e17c 100644 --- a/bthome_phy6222/source/thb2_main.c +++ b/bthome_phy6222/source/thb2_main.c @@ -1,14 +1,10 @@ /************************************************************************************************** -******* -**************************************************************************************************/ + Filename: simpleBLEPeripheral.c + Revised: + Revision: -/************************************************************************************************** - Filename: simpleBLEPeripheral.c - Revised: - Revision: + Description: This file contains the Simple BLE Peripheral sample application - Description: This file contains the Simple BLE Peripheral sample application - **************************************************************************************************/ /********************************************************************* @@ -46,7 +42,7 @@ /********************************************************************* * MACROS */ -//#define LOG(...) +//#define LOG(...) /********************************************************************* * CONSTANTS */ @@ -87,17 +83,17 @@ volatile uint8_t g_current_advType = LL_ADV_CONNECTABLE_UNDIRECTED_EVT; /********************************************************************* * LOCAL VARIABLES */ -uint8 simpleBLEPeripheral_TaskID; // Task ID for internal task/event processing +uint8 simpleBLEPeripheral_TaskID; // Task ID for internal task/event processing static gaprole_States_t gapProfileState = GAPROLE_INIT; /** Advertisement payload */ -static const uint8 advertData[] = +static const uint8 advertData[] = { - 0x02, // length of this data - GAP_ADTYPE_FLAGS, - GAP_ADTYPE_FLAGS_GENERAL | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED + 0x02, // length of this data + GAP_ADTYPE_FLAGS, + GAP_ADTYPE_FLAGS_GENERAL | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED }; // GAP GATT Attributes @@ -128,7 +124,7 @@ static void set_mac(void) { extern uint8 ownPublicAddr[LL_DEVICE_ADDR_LEN]; uint8 * p = &attDeviceName[5]; -#if 1 // =0 - test! +#if 1 // =0 - test! uint16 len; if(hal_fs_item_read(0xACAD, ownPublicAddr, LL_DEVICE_ADDR_LEN, &len) != PPlus_SUCCESS) { LL_Rand(ownPublicAddr,3); @@ -144,10 +140,10 @@ static void set_mac(void) ownPublicAddr[3] = 0x34; ownPublicAddr[4] = 0x12; ownPublicAddr[5] = 0x25; -#endif +#endif - p = str_bin2hex(p, &ownPublicAddr[2], 1); - p = str_bin2hex(p, &ownPublicAddr[1], 1); + p = str_bin2hex(p, &ownPublicAddr[2], 1); + p = str_bin2hex(p, &ownPublicAddr[1], 1); str_bin2hex(p, &ownPublicAddr[0], 1); scanRspData[0] = sizeof(attDeviceName) + 1; scanRspData[1] = GAP_ADTYPE_LOCAL_NAME_COMPLETE; @@ -177,22 +173,22 @@ extern gapPeriConnectParams_t periConnParameters; // Set new advertising interval static void set_adv_interval(uint16 advInt) { - GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt ); - GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt ); - GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt ); - GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt ); - GAP_EndDiscoverable( gapRole_TaskID ); - gapRole_state = GAPROLE_WAITING_AFTER_TIMEOUT; -/* - LL_SetAdvParam(advInt, advInt, // actual time = advInt * 625us - LL_ADV_CONNECTABLE_UNDIRECTED_EVT, - gapRole_AdvEventType, - gapRole_AdvDirectType, - gapRole_AdvDirectAddr, - gapRole_AdvChanMap, - gapRole_AdvFilterPolicy ); */ - // Turn advertising back on. - osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); + GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt ); + GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt ); + GAP_EndDiscoverable( gapRole_TaskID ); + gapRole_state = GAPROLE_WAITING_AFTER_TIMEOUT; +/* + LL_SetAdvParam(advInt, advInt, // actual time = advInt * 625us + LL_ADV_CONNECTABLE_UNDIRECTED_EVT, + gapRole_AdvEventType, + gapRole_AdvDirectType, + gapRole_AdvDirectAddr, + gapRole_AdvChanMap, + gapRole_AdvFilterPolicy ); */ + // Turn advertising back on. + osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); } static void adv_measure(void) { @@ -203,18 +199,21 @@ static void adv_measure(void) { LL_SetAdvData(sizeof(adv_bthome_ns1_t), gapRole_AdvertData); if(adv_con_count) { if(--adv_con_count == 0) { - set_adv_interval(DEF_ADV_INERVAL); + set_adv_interval(DEF_ADV_INERVAL); } } - } - else if(adv_count >= BATT_TIMER_MEASURE_INTERVAL/DEF_ADV_INERVAL_MS) // = 60 + } + else if(adv_count >= BATT_TIMER_MEASURE_INTERVAL/DEF_ADV_INERVAL_MS) // = 60 { - adv_count = 0; - batt_start_measure(); + adv_count = 0; + batt_start_measure(); } } } +/********************************************************************* + * LED and Key + */ static void posedge_int_wakeup_cb(GPIO_Pin_e pin,IO_Wakeup_Pol_e type) { (void) pin; @@ -232,6 +231,7 @@ static void posedge_int_wakeup_cb(GPIO_Pin_e pin,IO_Wakeup_Pol_e type) LOG("error\n"); } } + static void negedge_int_wakeup_cb(GPIO_Pin_e pin,IO_Wakeup_Pol_e type) { (void) pin; @@ -245,10 +245,11 @@ static void negedge_int_wakeup_cb(GPIO_Pin_e pin,IO_Wakeup_Pol_e type) LOG("error\n"); } } + static void init_led_key(void) { //hal_gpio_pin_init(GPIO_KEY, GPIO_INPUT); - hal_gpioin_register(GPIO_KEY, posedge_int_wakeup_cb, negedge_int_wakeup_cb); + hal_gpioin_register(GPIO_KEY, posedge_int_wakeup_cb, negedge_int_wakeup_cb); hal_gpioretention_register(GPIO_LED);//enable this pin retention //hal_gpioretention_unregister(pin);//disable this pin retention hal_gpio_write(GPIO_LED, 1); @@ -261,23 +262,23 @@ static void init_led_key(void) // GAP Role Callbacks static gapRolesCBs_t simpleBLEPeripheral_PeripheralCBs = { - peripheralStateNotificationCB, // Profile State Change Callbacks - peripheralStateReadRssiCB // When a valid RSSI is read from controller (not used by application) + peripheralStateNotificationCB, // Profile State Change Callbacks + peripheralStateReadRssiCB // When a valid RSSI is read from controller (not used by application) }; #if (DEF_GAPBOND_MGR_ENABLE==1) // GAP Bond Manager Callbacks, add 2017-11-15 static gapBondCBs_t simpleBLEPeripheral_BondMgrCBs = { - NULL, // Passcode callback (not used by application) - NULL // Pairing / Bonding state Callback (not used by application) + NULL, // Passcode callback (not used by application) + NULL // Pairing / Bonding state Callback (not used by application) }; #endif // Simple GATT Profile Callbacks -//static +//static #if 0 simpleProfileCBs_t simpleBLEPeripheral_SimpleProfileCBs = { - simpleProfileChangeCB // Charactersitic value change callback + simpleProfileChangeCB // Charactersitic value change callback }; #endif /********************************************************************* @@ -285,44 +286,44 @@ simpleProfileCBs_t simpleBLEPeripheral_SimpleProfileCBs = */ extern gapPeriConnectParams_t periConnParameters; /********************************************************************* - * @fn SimpleBLEPeripheral_Init + * @fn SimpleBLEPeripheral_Init * - * @brief Initialization function for the Simple BLE Peripheral App Task. - * This is called during initialization and should contain - * any application specific initialization (ie. hardware - * initialization/setup, table initialization, power up - * notificaiton ... ). + * @brief Initialization function for the Simple BLE Peripheral App Task. + * This is called during initialization and should contain + * any application specific initialization (ie. hardware + * initialization/setup, table initialization, power up + * notificaiton ... ). * - * @param task_id - the ID assigned by OSAL. This ID should be - * used to send messages and set timers. + * @param task_id - the ID assigned by OSAL. This ID should be + * used to send messages and set timers. * - * @return none + * @return none */ void SimpleBLEPeripheral_Init( uint8 task_id ) { - simpleBLEPeripheral_TaskID = task_id; - - init_led_key(); - - init_sensor(); + simpleBLEPeripheral_TaskID = task_id; - // Setup the GAP - VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL ); - - // Setup the GAP Peripheral Role Profile - { - // device starts advertising upon initialization - uint8 initial_advertising_enable = FALSE; + init_led_key(); - uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST; - uint8 advChnMap = GAP_ADVCHAN_37 | GAP_ADVCHAN_38 | GAP_ADVCHAN_39; - - // By setting this to zero, the device will go into the waiting state after - // being discoverable for 30.72 second, and will not being advertising again - // until the enabler is set back to TRUE - uint16 gapRole_AdvertOffTime = 0; - - uint8 peerPublicAddr[] = { + init_sensor(); + + // Setup the GAP + VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL ); + + // Setup the GAP Peripheral Role Profile + { + // device starts advertising upon initialization + uint8 initial_advertising_enable = FALSE; + + uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST; + uint8 advChnMap = GAP_ADVCHAN_37 | GAP_ADVCHAN_38 | GAP_ADVCHAN_39; + + // By setting this to zero, the device will go into the waiting state after + // being discoverable for 30.72 second, and will not being advertising again + // until the enabler is set back to TRUE + uint16 gapRole_AdvertOffTime = 0; + + uint8 peerPublicAddr[] = { 0x01, 0x02, 0x03, @@ -332,37 +333,37 @@ void SimpleBLEPeripheral_Init( uint8 task_id ) }; set_mac(); uint8 advType = LL_ADV_CONNECTABLE_UNDIRECTED_EVT; - GAPRole_SetParameter( GAPROLE_ADV_EVENT_TYPE, sizeof( uint8 ), &advType ); + GAPRole_SetParameter( GAPROLE_ADV_EVENT_TYPE, sizeof( uint8 ), &advType ); GAPRole_SetParameter( GAPROLE_ADV_DIRECT_ADDR, sizeof(peerPublicAddr), peerPublicAddr); - // set adv channel map - GAPRole_SetParameter( GAPROLE_ADV_CHANNEL_MAP, sizeof( uint8 ), &advChnMap); - // Set the GAP Role Parameters - GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); - GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime ); - GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof(advertData), (void *)advertData); // advertData - GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, scanRspData[0] + 1, scanRspData ); - GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request); - GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &periConnParameters.intervalMin); - GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &periConnParameters.intervalMax ); - GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &periConnParameters.latency ); - GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &periConnParameters.timeout ); - } + // set adv channel map + GAPRole_SetParameter( GAPROLE_ADV_CHANNEL_MAP, sizeof( uint8 ), &advChnMap); + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime ); + GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof(advertData), (void *)advertData); // advertData + GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, scanRspData[0] + 1, scanRspData ); + GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request); + GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &periConnParameters.intervalMin); + GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &periConnParameters.intervalMax ); + GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &periConnParameters.latency ); + GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &periConnParameters.timeout ); + } // Set the GAP Characteristics GGS_SetParameter( GGS_DEVICE_NAME_ATT, sizeof(attDeviceName), (void *)attDeviceName ); // GAP_DEVICE_NAME_LEN, attDeviceName ); - // Set advertising interval - { + // Set advertising interval + { uint16 advInt = DEF_ADV_INERVAL; // actual time = advInt * 625us GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt ); GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt ); GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt ); - GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt ); - } + GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt ); + } HCI_PPLUS_AdvEventDoneNoticeCmd(simpleBLEPeripheral_TaskID, ADV_BROADCAST_EVT); -#if (DEF_GAPBOND_MGR_ENABLE==1) - // Setup the GAP Bond Manager, add 2017-11-15 - { +#if (DEF_GAPBOND_MGR_ENABLE==1) + // Setup the GAP Bond Manager, add 2017-11-15 + { uint32 passkey = DEFAULT_PASSCODE; uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; uint8 mitm = TRUE; @@ -373,167 +374,164 @@ void SimpleBLEPeripheral_Init( uint8 task_id ) GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); - } -#endif - // Initialize GATT attributes - GGS_AddService( GATT_ALL_SERVICES ); // GAP - GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes - DevInfo_AddService(); // Device Information Service - //SimpleProfile_AddService( GATT_ALL_SERVICES ); // Simple GATT Profile - Batt_AddService(); - //Batt_Register(NULL); - TH_AddService(); + } +#endif + // Initialize GATT attributes + GGS_AddService( GATT_ALL_SERVICES ); // GAP + GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes + DevInfo_AddService(); // Device Information Service + //SimpleProfile_AddService( GATT_ALL_SERVICES ); // Simple GATT Profile + Batt_AddService(); + //Batt_Register(NULL); + TH_AddService(); - //uint8 OTA_Passward_AscII[8] = {'1','2','3','4','5','6','7','8'}; - //ota_app_AddService_UseKey(8, OTA_Passward_AscII); - // ota_app_AddService(); + //uint8 OTA_Passward_AscII[8] = {'1','2','3','4','5','6','7','8'}; + //ota_app_AddService_UseKey(8, OTA_Passward_AscII); + // ota_app_AddService(); #if (1) - llInitFeatureSet2MPHY(TRUE); - llInitFeatureSetDLE(TRUE); + llInitFeatureSet2MPHY(TRUE); + llInitFeatureSetDLE(TRUE); #else - llInitFeatureSet2MPHY(FALSE); - llInitFeatureSetDLE(FALSE); + llInitFeatureSet2MPHY(FALSE); + llInitFeatureSetDLE(FALSE); #endif #ifdef MTU_SIZE - ATT_SetMTUSizeMax(MTU_SIZE); + ATT_SetMTUSizeMax(MTU_SIZE); #else - ATT_SetMTUSizeMax(23); -#endif - // Setup a delayed profile startup - osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT ); - // for receive HCI complete message - GAP_RegisterForHCIMsgs(simpleBLEPeripheral_TaskID); - LL_PLUS_PerStats_Init(&g_perStatsByChanTest); - - batt_start_measure(); + ATT_SetMTUSizeMax(23); +#endif + // Setup a delayed profile startup + osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT ); + // for receive HCI complete message + GAP_RegisterForHCIMsgs(simpleBLEPeripheral_TaskID); + LL_PLUS_PerStats_Init(&g_perStatsByChanTest); - LOG("=====SimpleBLEPeripheral_Init Done=======\n"); + batt_start_measure(); + + LOG("=====SimpleBLEPeripheral_Init Done=======\n"); } /********************************************************************* - * @fn SimpleBLEPeripheral_ProcessEvent + * @fn SimpleBLEPeripheral_ProcessEvent * - * @brief Simple BLE Peripheral Application Task event processor. This function - * is called to process all events for the task. Events - * include timers, messages and any other user defined events. + * @brief Simple BLE Peripheral Application Task event processor. This function + * is called to process all events for the task. Events + * include timers, messages and any other user defined events. * - * @param task_id - The OSAL assigned task ID. - * @param events - events to process. This is a bit map and can - * contain more than one event. + * @param task_id - The OSAL assigned task ID. + * @param events - events to process. This is a bit map and can + * contain more than one event. * - * @return events not processed + * @return events not processed */ uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events ) { - VOID task_id; // OSAL required parameter that isn't used in this function - if ( events & ADV_BROADCAST_EVT) + VOID task_id; // OSAL required parameter that isn't used in this function + if ( events & ADV_BROADCAST_EVT) + { + adv_measure(); + LOG("advN%u\n", adv_count); + // return unprocessed events + return (events ^ ADV_BROADCAST_EVT); + } + + if ( events & SYS_EVENT_MSG ) + { + uint8 *pMsg; + + if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL ) { - adv_measure(); - LOG("advN%u\n", adv_count); - // return unprocessed events - return (events ^ ADV_BROADCAST_EVT); + simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg ); + // Release the OSAL message + VOID osal_msg_deallocate( pMsg ); } - if ( events & SYS_EVENT_MSG ) - { - uint8 *pMsg; + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } - if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL ) - { - simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg ); - - // Release the OSAL message - VOID osal_msg_deallocate( pMsg ); - } - - // return unprocessed events - return (events ^ SYS_EVENT_MSG); - } - - // enable adv - if ( events & SBP_RESET_ADV_EVT ) - { - LOG("SBP_RESET_ADV_EVT\n"); - adv_count = 0; - - //adv_con_count = 1; - // set_adv_interval(DEF_ADV_INERVAL); // actual time = advInt * 625us - uint8 initial_advertising_enable = TRUE; - GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); - return ( events ^ SBP_RESET_ADV_EVT ); - } - if( events & TIMER_BATT_EVT) - { - LOG("TIMER_EVT\n"); - read_sensor(); - // TH Notify - TH_NotifyLevel(); - if(++adv_count >= 6) { // 60 sec - adv_count = 0; - batt_start_measure(); - } - // return unprocessed events - return ( events ^ TIMER_BATT_EVT); - } - if( events & BATT_VALUE_EVT) - { - LOG("Vbat: %d mV, %d %%\n", measured_data.battery_mv, measured_data.battery); - // Batt Notify - if(!gapRole_AdvEnabled) { - BattNotifyLevel(); - } - // return unprocessed events - return ( events ^ BATT_VALUE_EVT); - } - if ( events & SBP_START_DEVICE_EVT ) - { - // Start the Device - VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs ); + // enable adv + if ( events & SBP_RESET_ADV_EVT ) + { + LOG("SBP_RESET_ADV_EVT\n"); + adv_count = 0; + //adv_con_count = 1; + // set_adv_interval(DEF_ADV_INERVAL); // actual time = advInt * 625us + uint8 initial_advertising_enable = TRUE; + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + return ( events ^ SBP_RESET_ADV_EVT ); + } + if( events & TIMER_BATT_EVT) + { + LOG("TIMER_EVT\n"); + read_sensor(); + // TH Notify + TH_NotifyLevel(); + if(++adv_count >= 6) { // 60 sec + adv_count = 0; + batt_start_measure(); + } + // return unprocessed events + return ( events ^ TIMER_BATT_EVT); + } + if( events & BATT_VALUE_EVT) + { + LOG("Vbat: %d mV, %d %%\n", measured_data.battery_mv, measured_data.battery); + // Batt Notify + if(!gapRole_AdvEnabled) { + BattNotifyLevel(); + } + // return unprocessed events + return ( events ^ BATT_VALUE_EVT); + } + if ( events & SBP_START_DEVICE_EVT ) + { + // Start the Device + VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs ); #if (DEF_GAPBOND_MGR_ENABLE==1) - // Start Bond Manager, 2017-11-15 - VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs ); + // Start Bond Manager, 2017-11-15 + VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs ); #endif - HCI_LE_ReadResolvingListSizeCmd(); - // return unprocessed events - return ( events ^ SBP_START_DEVICE_EVT ); - } - - if(events & SBP_DEALDATA) - { - LOG("\ndeal app datas in events!!!\n"); - // return unprocessed events - return(events ^ SBP_DEALDATA); - } - // Discard unknown events - return 0; + HCI_LE_ReadResolvingListSizeCmd(); + // return unprocessed events + return ( events ^ SBP_START_DEVICE_EVT ); + } + if(events & SBP_DEALDATA) + { + LOG("\ndeal app datas in events!!!\n"); + // return unprocessed events + return(events ^ SBP_DEALDATA); + } + // Discard unknown events + return 0; } /********************************************************************* - * @fn simpleBLEPeripheral_ProcessOSALMsg + * @fn simpleBLEPeripheral_ProcessOSALMsg * - * @brief Process an incoming task message. + * @brief Process an incoming task message. * - * @param pMsg - message to process + * @param pMsg - message to process * - * @return none + * @return none */ static void simpleBLEPeripheral_ProcessOSALMsg( osal_event_hdr_t *pMsg ) { -#if DEBUG_INFO +#if DEBUG_INFO hciEvt_CmdComplete_t *pHciMsg; -#endif - switch ( pMsg->event ){ +#endif + switch ( pMsg->event ){ case HCI_GAP_EVENT_EVENT:{ switch( pMsg->status ){ case HCI_COMMAND_COMPLETE_EVENT_CODE: -#if DEBUG_INFO +#if DEBUG_INFO pHciMsg = (hciEvt_CmdComplete_t *)pMsg; LOG("==> HCI_COMMAND_COMPLETE_EVENT_CODE: %x\n", pHciMsg->cmdOpcode); //safeToDealloc = gapProcessHCICmdCompleteEvt( (hciEvt_CmdComplete_t *)pMsg ); -#endif +#endif break; default: @@ -544,101 +542,101 @@ static void simpleBLEPeripheral_ProcessOSALMsg( osal_event_hdr_t *pMsg ) } } /********************************************************************* - * @fn peripheralStateReadRssiCB + * @fn peripheralStateReadRssiCB * - * @brief Notification from the profile of a state change. + * @brief Notification from the profile of a state change. * - * @param newState - new state + * @param newState - new state * - * @return none + * @return none */ -static void peripheralStateReadRssiCB( int8 rssi ) +static void peripheralStateReadRssiCB( int8 rssi ) { - (void)rssi; + (void)rssi; } /********************************************************************* - * @fn peripheralStateNotificationCB + * @fn peripheralStateNotificationCB * - * @brief Notification from the profile of a state change. + * @brief Notification from the profile of a state change. * - * @param newState - new state + * @param newState - new state * - * @return none + * @return none */ static void peripheralStateNotificationCB( gaprole_States_t newState ) { - switch ( newState ) - { - case GAPROLE_STARTED: - { - // set_mac(); - LOG("Gaprole_start\n"); - osal_set_event(simpleBLEPeripheral_TaskID, SBP_RESET_ADV_EVT); - } - break; - - case GAPROLE_ADVERTISING: - { - LOG("Gaprole_adversting\n"); - osal_stop_timerEx(simpleBLEPeripheral_TaskID, TIMER_BATT_EVT); - adv_count = 0; - //bthome_data_beacon((padv_bthome_ns1_t) gapRole_AdvertData); - //LL_SetAdvData(sizeof(adv_bthome_ns1_t), gapRole_AdvertData); - } - break; - - case GAPROLE_CONNECTED: - adv_con_count = 0; - osal_start_reload_timer(simpleBLEPeripheral_TaskID, TIMER_BATT_EVT, 2*DEF_ADV_INERVAL_MS); - HCI_PPLUS_ConnEventDoneNoticeCmd(simpleBLEPeripheral_TaskID, NULL); - LOG("Gaprole_Connected\n"); - break; - - case GAPROLE_CONNECTED_ADV: - - break; - - case GAPROLE_WAITING: - LOG("Gaprole_Disconnection\n"); - adv_con_count = 1; - osal_stop_timerEx(simpleBLEPeripheral_TaskID, TIMER_BATT_EVT); - break; - - case GAPROLE_WAITING_AFTER_TIMEOUT: - LOG("Gaprole_waitting_after_timerout\n"); - break; - - case GAPROLE_ERROR: - LOG("Gaprole error!\n"); - break; - - default: - break; - } - gapProfileState = newState; + switch ( newState ) + { + case GAPROLE_STARTED: + { + // set_mac(); + LOG("Gaprole_start\n"); + osal_set_event(simpleBLEPeripheral_TaskID, SBP_RESET_ADV_EVT); + } + break; + + case GAPROLE_ADVERTISING: + { + LOG("Gaprole_adversting\n"); + osal_stop_timerEx(simpleBLEPeripheral_TaskID, TIMER_BATT_EVT); + adv_count = 0; + //bthome_data_beacon((padv_bthome_ns1_t) gapRole_AdvertData); + //LL_SetAdvData(sizeof(adv_bthome_ns1_t), gapRole_AdvertData); + } + break; + + case GAPROLE_CONNECTED: + adv_con_count = 0; + osal_start_reload_timer(simpleBLEPeripheral_TaskID, TIMER_BATT_EVT, 2*DEF_ADV_INERVAL_MS); + HCI_PPLUS_ConnEventDoneNoticeCmd(simpleBLEPeripheral_TaskID, NULL); + LOG("Gaprole_Connected\n"); + break; + + case GAPROLE_CONNECTED_ADV: + + break; + + case GAPROLE_WAITING: + LOG("Gaprole_Disconnection\n"); + adv_con_count = 1; + osal_stop_timerEx(simpleBLEPeripheral_TaskID, TIMER_BATT_EVT); + break; + + case GAPROLE_WAITING_AFTER_TIMEOUT: + LOG("Gaprole_waitting_after_timerout\n"); + break; + + case GAPROLE_ERROR: + LOG("Gaprole error!\n"); + break; + + default: + break; + } + gapProfileState = newState; LOG("[GAP ROLE %d]\n",newState); - - VOID gapProfileState; + + VOID gapProfileState; } #if 0 /********************************************************************* - * @fn simpleProfileChangeCB + * @fn simpleProfileChangeCB * - * @brief Callback from SimpleBLEProfile indicating a value change + * @brief Callback from SimpleBLEProfile indicating a value change * - * @param paramID - parameter ID of the value that was changed. + * @param paramID - parameter ID of the value that was changed. * - * @return none + * @return none */ static void simpleProfileChangeCB( uint8 paramID ) { - + switch( paramID ) { case SIMPLEPROFILE_CHAR1: - + break; default: @@ -648,5 +646,3 @@ static void simpleProfileChangeCB( uint8 paramID ) } #endif -/********************************************************************* -*********************************************************************/ diff --git a/bthome_phy6222/source/thb2_peripheral.c b/bthome_phy6222/source/thb2_peripheral.c index 4cfd12b..8c142ed 100644 --- a/bthome_phy6222/source/thb2_peripheral.c +++ b/bthome_phy6222/source/thb2_peripheral.c @@ -1,47 +1,14 @@ /************************************************************************************************** + Filename: peripheral.c + Revised: + Revision: - Phyplus Microelectronics Limited confidential and proprietary. - All rights reserved. - - IMPORTANT: All rights of this software belong to Phyplus Microelectronics - Limited ("Phyplus"). Your use of this Software is limited to those - specific rights granted under the terms of the business contract, the - confidential agreement, the non-disclosure agreement and any other forms - of agreements as a customer or a partner of Phyplus. You may not use this - Software unless you agree to abide by the terms of these agreements. - You acknowledge that the Software may not be modified, copied, - distributed or disclosed unless embedded on a Phyplus Bluetooth Low Energy - (BLE) integrated circuit, either as a product or is integrated into your - products. Other than for the aforementioned purposes, you may not use, - reproduce, copy, prepare derivative works of, modify, distribute, perform, - display or sell this Software and/or its documentation for any purposes. - - YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE - PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, - INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, - NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL - PHYPLUS OR ITS SUBSIDIARIES BE LIABLE OR OBLIGATED UNDER CONTRACT, - NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER - LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES - INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE - OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT - OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES - (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. - -**************************************************************************************************/ - -/************************************************************************************************** - Filename: peripheral.c - Revised: - Revision: - - Description: GAP Peripheral Role - + Description: GAP Peripheral Role **************************************************************************************************/ /********************************************************************* - INCLUDES + INCLUDES */ #include "bcomdef.h" #include "OSAL.h" @@ -57,65 +24,65 @@ #ifndef DEF_GAPBOND_MGR_ENABLE - #define DEF_GAPBOND_MGR_ENABLE 1 + #define DEF_GAPBOND_MGR_ENABLE 1 #endif /********************************************************************* - MACROS + MACROS */ /********************************************************************* - CONSTANTS + CONSTANTS */ -#define DEFAULT_ADVERT_OFF_TIME 30000 // 30 seconds +#define DEFAULT_ADVERT_OFF_TIME 30000 // 30 seconds -#define RSSI_NOT_AVAILABLE 127 +#define RSSI_NOT_AVAILABLE 127 -#define DEFAULT_MIN_CONN_INTERVAL 0x0006 // 100 milliseconds -#define DEFAULT_MAX_CONN_INTERVAL 0x0C80 // 4 seconds +#define DEFAULT_MIN_CONN_INTERVAL 0x0006 // 100 milliseconds +#define DEFAULT_MAX_CONN_INTERVAL 0x0C80 // 4 seconds -#define MIN_CONN_INTERVAL 0x0006 -#define MAX_CONN_INTERVAL 0x0C80 +#define MIN_CONN_INTERVAL 0x0006 +#define MAX_CONN_INTERVAL 0x0C80 -#define DEFAULT_TIMEOUT_MULTIPLIER 1000 +#define DEFAULT_TIMEOUT_MULTIPLIER 1000 -#define CONN_INTERVAL_MULTIPLIER 6 +#define CONN_INTERVAL_MULTIPLIER 6 -#define MIN_SLAVE_LATENCY 0 -#define MAX_SLAVE_LATENCY 500 +#define MIN_SLAVE_LATENCY 0 +#define MAX_SLAVE_LATENCY 500 -#define MIN_TIMEOUT_MULTIPLIER 0x000a -#define MAX_TIMEOUT_MULTIPLIER 0x0c80 +#define MIN_TIMEOUT_MULTIPLIER 0x000a +#define MAX_TIMEOUT_MULTIPLIER 0x0c80 -#define MAX_TIMEOUT_VALUE 0xFFFF +#define MAX_TIMEOUT_VALUE 0xFFFF /********************************************************************* - TYPEDEFS + TYPEDEFS */ /********************************************************************* - GLOBAL VARIABLES + GLOBAL VARIABLES */ /********************************************************************* - EXTERNAL VARIABLES + EXTERNAL VARIABLES */ /********************************************************************* - EXTERNAL FUNCTIONS + EXTERNAL FUNCTIONS */ /********************************************************************* - LOCAL VARIABLES + LOCAL VARIABLES */ -uint8 gapRole_TaskID; // Task ID for internal task/event processing +uint8 gapRole_TaskID; // Task ID for internal task/event processing gaprole_States_t gapRole_state; /********************************************************************* - Profile Parameters - reference GAPROLE_PROFILE_PARAMETERS for - descriptions + Profile Parameters - reference GAPROLE_PROFILE_PARAMETERS for + descriptions */ static uint8 gapRole_profileRole; @@ -129,11 +96,11 @@ static uint16 gapRole_AdvertOffTime = DEFAULT_ADVERT_OFF_TIME; uint8 gapRole_AdvertDataLen = 3; uint8 gapRole_AdvertData[B_MAX_ADV_LEN] = { - 0x02, // length of this data - GAP_ADTYPE_FLAGS, // AD Type = Flags - // Limited Discoverable & BR/EDR not supported - (GAP_ADTYPE_FLAGS_GENERAL | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED), - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + 0x02, // length of this data + GAP_ADTYPE_FLAGS, // AD Type = Flags + // Limited Discoverable & BR/EDR not supported + (GAP_ADTYPE_FLAGS_GENERAL | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED), + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; static uint8 gapRole_ScanRspDataLen = 0; static uint8 gapRole_ScanRspData[B_MAX_ADV_LEN] = {0}; @@ -168,31 +135,31 @@ static gapRolesCBs_t* pGapRoles_AppCGs = NULL; static gapRolesParamUpdateCB_t* pGapRoles_ParamUpdateCB = NULL; #ifdef EXT_ADV_ENABLE - // for extended adv host - #define GAP_MAX_EXT_ADV_INSTANCE 1 - #define GAP_MAX_EXT_ADV_DATA_LENGTH 1200 - // extended advertiser variables - static extAdvInfo_t extAdvInfo[GAP_MAX_EXT_ADV_INSTANCE]; - static uint8 advertisingData[GAP_MAX_EXT_ADV_INSTANCE][GAP_MAX_EXT_ADV_DATA_LENGTH]; - static uint8 extScanRspData[GAP_MAX_EXT_ADV_INSTANCE][GAP_MAX_EXT_ADV_DATA_LENGTH]; + // for extended adv host + #define GAP_MAX_EXT_ADV_INSTANCE 1 + #define GAP_MAX_EXT_ADV_DATA_LENGTH 1200 + // extended advertiser variables + static extAdvInfo_t extAdvInfo[GAP_MAX_EXT_ADV_INSTANCE]; + static uint8 advertisingData[GAP_MAX_EXT_ADV_INSTANCE][GAP_MAX_EXT_ADV_DATA_LENGTH]; + static uint8 extScanRspData[GAP_MAX_EXT_ADV_INSTANCE][GAP_MAX_EXT_ADV_DATA_LENGTH]; - static gapAdvSetParameter_t advConfig[GAP_MAX_EXT_ADV_INSTANCE]; + static gapAdvSetParameter_t advConfig[GAP_MAX_EXT_ADV_INSTANCE]; - uint8 gapRole_ExtAdvEnabled[GAP_MAX_EXT_ADV_INSTANCE]; - uint8 gapRole_ExtAdvEnableHandle = 0; - uint8 gapRole_ExtAdv_RandomAddr[GAP_MAX_EXT_ADV_INSTANCE][6]; + uint8 gapRole_ExtAdvEnabled[GAP_MAX_EXT_ADV_INSTANCE]; + uint8 gapRole_ExtAdvEnableHandle = 0; + uint8 gapRole_ExtAdv_RandomAddr[GAP_MAX_EXT_ADV_INSTANCE][6]; #endif /********************************************************************* - Profile Attributes - variables + Profile Attributes - variables */ /********************************************************************* - Profile Attributes - Table + Profile Attributes - Table */ /********************************************************************* - LOCAL FUNCTIONS + LOCAL FUNCTIONS */ static void gapRole_ProcessOSALMsg( osal_event_hdr_t* pMsg ); static void gapRole_ProcessGAPMsg( gapEventHdr_t* pMsg ); @@ -202,1696 +169,1694 @@ static void gapRole_startConnUpdate( uint8 handleFailure ); #ifdef EXT_ADV_ENABLE - static void gapInitExtAdvertiser(void); - static void gapExtAdvParameterInit(gapAdvSetParameter_t* p); + static void gapInitExtAdvertiser(void); + static void gapExtAdvParameterInit(gapAdvSetParameter_t* p); #endif /********************************************************************* - NETWORK LAYER CALLBACKS + NETWORK LAYER CALLBACKS */ /********************************************************************* - PUBLIC FUNCTIONS + PUBLIC FUNCTIONS */ /********************************************************************* - @brief Set a GAP Role parameter. + @brief Set a GAP Role parameter. - Public function defined in peripheral.h. + Public function defined in peripheral.h. */ bStatus_t GAPRole_SetParameter( uint16 param, uint8 len, void* pValue ) { - bStatus_t ret = SUCCESS; + bStatus_t ret = SUCCESS; - switch ( param ) - { - case GAPROLE_IRK: - if ( len == KEYLEN ) - { - VOID osal_memcpy( gapRole_IRK, pValue, KEYLEN ) ; - } - else - { - ret = bleInvalidRange; - } + switch ( param ) + { + case GAPROLE_IRK: + if ( len == KEYLEN ) + { + VOID osal_memcpy( gapRole_IRK, pValue, KEYLEN ) ; + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_SRK: - if ( len == KEYLEN ) - { - VOID osal_memcpy( gapRole_SRK, pValue, KEYLEN ) ; - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_SRK: + if ( len == KEYLEN ) + { + VOID osal_memcpy( gapRole_SRK, pValue, KEYLEN ) ; + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_SIGNCOUNTER: - if ( len == sizeof ( uint32 ) ) - { - gapRole_signCounter = *((uint32*)pValue); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_SIGNCOUNTER: + if ( len == sizeof ( uint32 ) ) + { + gapRole_signCounter = *((uint32*)pValue); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADVERT_ENABLED: - if ( len == sizeof( uint8 ) ) - { - uint8 oldAdvEnabled = gapRole_AdvEnabled; - gapRole_AdvEnabled = *((uint8*)pValue); + case GAPROLE_ADVERT_ENABLED: + if ( len == sizeof( uint8 ) ) + { + uint8 oldAdvEnabled = gapRole_AdvEnabled; + gapRole_AdvEnabled = *((uint8*)pValue); - if ( (oldAdvEnabled) && (gapRole_AdvEnabled == FALSE) ) - { - // Turn off Advertising - if ( ( gapRole_state == GAPROLE_ADVERTISING ) - || ( gapRole_state == GAPROLE_CONNECTED_ADV ) - || ( gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT ) ) - { - VOID GAP_EndDiscoverable( gapRole_TaskID ); - } - } - else if ( (oldAdvEnabled == FALSE) && (gapRole_AdvEnabled) ) - { - // Turn on Advertising - if ( (gapRole_state == GAPROLE_STARTED) - || (gapRole_state == GAPROLE_WAITING) - || (gapRole_state == GAPROLE_CONNECTED) - || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) ) - { - VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); - } - } - } - else - { - ret = bleInvalidRange; - } + if ( (oldAdvEnabled) && (gapRole_AdvEnabled == FALSE) ) + { + // Turn off Advertising + if ( ( gapRole_state == GAPROLE_ADVERTISING ) + || ( gapRole_state == GAPROLE_CONNECTED_ADV ) + || ( gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT ) ) + { + VOID GAP_EndDiscoverable( gapRole_TaskID ); + } + } + else if ( (oldAdvEnabled == FALSE) && (gapRole_AdvEnabled) ) + { + // Turn on Advertising + if ( (gapRole_state == GAPROLE_STARTED) + || (gapRole_state == GAPROLE_WAITING) + || (gapRole_state == GAPROLE_CONNECTED) + || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) ) + { + VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); + } + } + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADVERT_OFF_TIME: - if ( len == sizeof ( uint16 ) ) - { - gapRole_AdvertOffTime = *((uint16*)pValue); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_ADVERT_OFF_TIME: + if ( len == sizeof ( uint16 ) ) + { + gapRole_AdvertOffTime = *((uint16*)pValue); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADVERT_DATA: - if ( len <= B_MAX_ADV_LEN ) - { - VOID osal_memset( gapRole_AdvertData, 0, B_MAX_ADV_LEN ); - VOID osal_memcpy( gapRole_AdvertData, pValue, len ); - gapRole_AdvertDataLen = len; - // Update the advertising data - ret = GAP_UpdateAdvertisingData( gapRole_TaskID, - TRUE, len, gapRole_AdvertData ); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_ADVERT_DATA: + if ( len <= B_MAX_ADV_LEN ) + { + VOID osal_memset( gapRole_AdvertData, 0, B_MAX_ADV_LEN ); + VOID osal_memcpy( gapRole_AdvertData, pValue, len ); + gapRole_AdvertDataLen = len; + // Update the advertising data + ret = GAP_UpdateAdvertisingData( gapRole_TaskID, + TRUE, len, gapRole_AdvertData ); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_SCAN_RSP_DATA: - if ( len <= B_MAX_ADV_LEN ) - { - VOID osal_memset( gapRole_ScanRspData, 0, B_MAX_ADV_LEN ); - VOID osal_memcpy( gapRole_ScanRspData, pValue, len ); - gapRole_ScanRspDataLen = len; - // Update the Response Data - ret = GAP_UpdateAdvertisingData( gapRole_TaskID, - FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData ); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_SCAN_RSP_DATA: + if ( len <= B_MAX_ADV_LEN ) + { + VOID osal_memset( gapRole_ScanRspData, 0, B_MAX_ADV_LEN ); + VOID osal_memcpy( gapRole_ScanRspData, pValue, len ); + gapRole_ScanRspDataLen = len; + // Update the Response Data + ret = GAP_UpdateAdvertisingData( gapRole_TaskID, + FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData ); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADV_EVENT_TYPE: - if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= GAP_ADTYPE_ADV_LDC_DIRECT_IND) ) - { - gapRole_AdvEventType = *((uint8*)pValue); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_ADV_EVENT_TYPE: + if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= GAP_ADTYPE_ADV_LDC_DIRECT_IND) ) + { + gapRole_AdvEventType = *((uint8*)pValue); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADV_DIRECT_TYPE: - if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= ADDRTYPE_PRIVATE_RESOLVE) ) - { - gapRole_AdvDirectType = *((uint8*)pValue); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_ADV_DIRECT_TYPE: + if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= ADDRTYPE_PRIVATE_RESOLVE) ) + { + gapRole_AdvDirectType = *((uint8*)pValue); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADV_DIRECT_ADDR: - if ( len == B_ADDR_LEN ) - { - VOID osal_memcpy( gapRole_AdvDirectAddr, pValue, B_ADDR_LEN ) ; - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_ADV_DIRECT_ADDR: + if ( len == B_ADDR_LEN ) + { + VOID osal_memcpy( gapRole_AdvDirectAddr, pValue, B_ADDR_LEN ) ; + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADV_CHANNEL_MAP: - if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= 0x07) ) - { - gapRole_AdvChanMap = *((uint8*)pValue); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_ADV_CHANNEL_MAP: + if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= 0x07) ) + { + gapRole_AdvChanMap = *((uint8*)pValue); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_ADV_FILTER_POLICY: - if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= GAP_FILTER_POLICY_WHITE) ) - { - gapRole_AdvFilterPolicy = *((uint8*)pValue); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_ADV_FILTER_POLICY: + if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= GAP_FILTER_POLICY_WHITE) ) + { + gapRole_AdvFilterPolicy = *((uint8*)pValue); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_RSSI_READ_RATE: - if ( len == sizeof ( uint16 ) ) - { - gapRole_RSSIReadRate = *((uint16*)pValue); + case GAPROLE_RSSI_READ_RATE: + if ( len == sizeof ( uint16 ) ) + { + gapRole_RSSIReadRate = *((uint16*)pValue); - if ( (gapRole_RSSIReadRate) && (gapRole_state == GAPROLE_CONNECTED) ) - { - // Start the RSSI Reads - VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate ); - } - } - else - { - ret = bleInvalidRange; - } + if ( (gapRole_RSSIReadRate) && (gapRole_state == GAPROLE_CONNECTED) ) + { + // Start the RSSI Reads + VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate ); + } + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_PARAM_UPDATE_ENABLE: - if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= TRUE) ) - { - gapRole_ParamUpdateEnable = *((uint8*)pValue); - } - else - { - ret = bleInvalidRange; - } + case GAPROLE_PARAM_UPDATE_ENABLE: + if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= TRUE) ) + { + gapRole_ParamUpdateEnable = *((uint8*)pValue); + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAPROLE_MIN_CONN_INTERVAL: - { - uint16 newInterval = *((uint16*)pValue); + case GAPROLE_MIN_CONN_INTERVAL: + { + uint16 newInterval = *((uint16*)pValue); - if ( len == sizeof ( uint16 ) && - ( newInterval >= MIN_CONN_INTERVAL ) && - ( newInterval <= MAX_CONN_INTERVAL ) ) - { - gapRole_MinConnInterval = newInterval; - } - else - { - ret = bleInvalidRange; - } - } - break; + if ( len == sizeof ( uint16 ) && + ( newInterval >= MIN_CONN_INTERVAL ) && + ( newInterval <= MAX_CONN_INTERVAL ) ) + { + gapRole_MinConnInterval = newInterval; + } + else + { + ret = bleInvalidRange; + } + } + break; - case GAPROLE_MAX_CONN_INTERVAL: - { - uint16 newInterval = *((uint16*)pValue); + case GAPROLE_MAX_CONN_INTERVAL: + { + uint16 newInterval = *((uint16*)pValue); - if ( len == sizeof ( uint16 ) && - ( newInterval >= MIN_CONN_INTERVAL) && - ( newInterval <= MAX_CONN_INTERVAL) ) - { - gapRole_MaxConnInterval = newInterval; - } - else - { - ret = bleInvalidRange; - } - } - break; + if ( len == sizeof ( uint16 ) && + ( newInterval >= MIN_CONN_INTERVAL) && + ( newInterval <= MAX_CONN_INTERVAL) ) + { + gapRole_MaxConnInterval = newInterval; + } + else + { + ret = bleInvalidRange; + } + } + break; - case GAPROLE_SLAVE_LATENCY: - { - uint16 latency = *((uint16*)pValue); + case GAPROLE_SLAVE_LATENCY: + { + uint16 latency = *((uint16*)pValue); - if ( len == sizeof ( uint16 ) && (latency < MAX_SLAVE_LATENCY) ) - { - gapRole_SlaveLatency = latency; - } - else - { - ret = bleInvalidRange; - } - } - break; + if ( len == sizeof ( uint16 ) && (latency < MAX_SLAVE_LATENCY) ) + { + gapRole_SlaveLatency = latency; + } + else + { + ret = bleInvalidRange; + } + } + break; - case GAPROLE_TIMEOUT_MULTIPLIER: - { - uint16 newTimeout = *((uint16*)pValue); + case GAPROLE_TIMEOUT_MULTIPLIER: + { + uint16 newTimeout = *((uint16*)pValue); - if ( len == sizeof ( uint16 ) - && (newTimeout >= MIN_TIMEOUT_MULTIPLIER) && (newTimeout <= MAX_TIMEOUT_MULTIPLIER) ) - { - gapRole_TimeoutMultiplier = newTimeout; - } - else - { - ret = bleInvalidRange; - } - } - break; + if ( len == sizeof ( uint16 ) + && (newTimeout >= MIN_TIMEOUT_MULTIPLIER) && (newTimeout <= MAX_TIMEOUT_MULTIPLIER) ) + { + gapRole_TimeoutMultiplier = newTimeout; + } + else + { + ret = bleInvalidRange; + } + } + break; - case GAPROLE_PARAM_UPDATE_REQ: - { - uint8 req = *((uint8*)pValue); + case GAPROLE_PARAM_UPDATE_REQ: + { + uint8 req = *((uint8*)pValue); - if ( len == sizeof ( uint8 ) && (req == TRUE) ) - { - // Make sure we don't send an L2CAP Connection Parameter Update Request - // command within TGAP(conn_param_timeout) of an L2CAP Connection Parameter - // Update Response being received. - if ( osal_get_timeoutEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ) == 0 ) - { - // Start connection update procedure - gapRole_startConnUpdate( GAPROLE_NO_ACTION ); - // Connection update requested by app, cancel such pending procedure (if active) - VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT ); - } - else - { - ret = blePending; - } - } - else - { - ret = bleInvalidRange; - } - } - break; + if ( len == sizeof ( uint8 ) && (req == TRUE) ) + { + // Make sure we don't send an L2CAP Connection Parameter Update Request + // command within TGAP(conn_param_timeout) of an L2CAP Connection Parameter + // Update Response being received. + if ( osal_get_timeoutEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ) == 0 ) + { + // Start connection update procedure + gapRole_startConnUpdate( GAPROLE_NO_ACTION ); + // Connection update requested by app, cancel such pending procedure (if active) + VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT ); + } + else + { + ret = blePending; + } + } + else + { + ret = bleInvalidRange; + } + } + break; - default: + default: - // The param value isn't part of this profile, try the GAP. - if ( (param < TGAP_PARAMID_MAX) && (len == sizeof ( uint16 )) ) - { - ret = GAP_SetParamValue( param, *((uint16*)pValue) ); - } - else - { - ret = INVALIDPARAMETER; - } + // The param value isn't part of this profile, try the GAP. + if ( (param < TGAP_PARAMID_MAX) && (len == sizeof ( uint16 )) ) + { + ret = GAP_SetParamValue( param, *((uint16*)pValue) ); + } + else + { + ret = INVALIDPARAMETER; + } - break; - } + break; + } - return ( ret ); + return ( ret ); } /********************************************************************* - @brief Get a GAP Role parameter. + @brief Get a GAP Role parameter. - Public function defined in peripheral.h. + Public function defined in peripheral.h. */ bStatus_t GAPRole_GetParameter( uint16 param, void* pValue ) { - bStatus_t ret = SUCCESS; + bStatus_t ret = SUCCESS; - switch ( param ) - { - case GAPROLE_PROFILEROLE: - *((uint8*)pValue) = gapRole_profileRole; - break; + switch ( param ) + { + case GAPROLE_PROFILEROLE: + *((uint8*)pValue) = gapRole_profileRole; + break; - case GAPROLE_IRK: - VOID osal_memcpy( pValue, gapRole_IRK, KEYLEN ) ; - break; + case GAPROLE_IRK: + VOID osal_memcpy( pValue, gapRole_IRK, KEYLEN ) ; + break; - case GAPROLE_SRK: - VOID osal_memcpy( pValue, gapRole_SRK, KEYLEN ) ; - break; + case GAPROLE_SRK: + VOID osal_memcpy( pValue, gapRole_SRK, KEYLEN ) ; + break; - case GAPROLE_SIGNCOUNTER: - *((uint32*)pValue) = gapRole_signCounter; - break; + case GAPROLE_SIGNCOUNTER: + *((uint32*)pValue) = gapRole_signCounter; + break; - case GAPROLE_BD_ADDR: - VOID osal_memcpy( pValue, gapRole_bdAddr, B_ADDR_LEN ) ; - break; + case GAPROLE_BD_ADDR: + VOID osal_memcpy( pValue, gapRole_bdAddr, B_ADDR_LEN ) ; + break; - case GAPROLE_ADVERT_ENABLED: - *((uint8*)pValue) = gapRole_AdvEnabled; - break; + case GAPROLE_ADVERT_ENABLED: + *((uint8*)pValue) = gapRole_AdvEnabled; + break; - case GAPROLE_ADVERT_OFF_TIME: - *((uint16*)pValue) = gapRole_AdvertOffTime; - break; + case GAPROLE_ADVERT_OFF_TIME: + *((uint16*)pValue) = gapRole_AdvertOffTime; + break; - case GAPROLE_ADVERT_DATA: - VOID osal_memcpy( pValue, gapRole_AdvertData, gapRole_AdvertDataLen ); - break; + case GAPROLE_ADVERT_DATA: + VOID osal_memcpy( pValue, gapRole_AdvertData, gapRole_AdvertDataLen ); + break; - case GAPROLE_SCAN_RSP_DATA: - VOID osal_memcpy( pValue, gapRole_ScanRspData, gapRole_ScanRspDataLen ) ; - break; + case GAPROLE_SCAN_RSP_DATA: + VOID osal_memcpy( pValue, gapRole_ScanRspData, gapRole_ScanRspDataLen ) ; + break; - case GAPROLE_ADV_EVENT_TYPE: - *((uint8*)pValue) = gapRole_AdvEventType; - break; + case GAPROLE_ADV_EVENT_TYPE: + *((uint8*)pValue) = gapRole_AdvEventType; + break; - case GAPROLE_ADV_DIRECT_TYPE: - *((uint8*)pValue) = gapRole_AdvDirectType; - break; + case GAPROLE_ADV_DIRECT_TYPE: + *((uint8*)pValue) = gapRole_AdvDirectType; + break; - case GAPROLE_ADV_DIRECT_ADDR: - VOID osal_memcpy( pValue, gapRole_AdvDirectAddr, B_ADDR_LEN ) ; - break; + case GAPROLE_ADV_DIRECT_ADDR: + VOID osal_memcpy( pValue, gapRole_AdvDirectAddr, B_ADDR_LEN ) ; + break; - case GAPROLE_ADV_CHANNEL_MAP: - *((uint8*)pValue) = gapRole_AdvChanMap; - break; + case GAPROLE_ADV_CHANNEL_MAP: + *((uint8*)pValue) = gapRole_AdvChanMap; + break; - case GAPROLE_ADV_FILTER_POLICY: - *((uint8*)pValue) = gapRole_AdvFilterPolicy; - break; + case GAPROLE_ADV_FILTER_POLICY: + *((uint8*)pValue) = gapRole_AdvFilterPolicy; + break; - case GAPROLE_CONNHANDLE: - *((uint16*)pValue) = gapRole_ConnectionHandle; - break; + case GAPROLE_CONNHANDLE: + *((uint16*)pValue) = gapRole_ConnectionHandle; + break; - case GAPROLE_RSSI_READ_RATE: - *((uint16*)pValue) = gapRole_RSSIReadRate; - break; + case GAPROLE_RSSI_READ_RATE: + *((uint16*)pValue) = gapRole_RSSIReadRate; + break; - case GAPROLE_PARAM_UPDATE_ENABLE: - *((uint16*)pValue) = gapRole_ParamUpdateEnable; - break; + case GAPROLE_PARAM_UPDATE_ENABLE: + *((uint16*)pValue) = gapRole_ParamUpdateEnable; + break; - case GAPROLE_MIN_CONN_INTERVAL: - *((uint16*)pValue) = gapRole_MinConnInterval; - break; + case GAPROLE_MIN_CONN_INTERVAL: + *((uint16*)pValue) = gapRole_MinConnInterval; + break; - case GAPROLE_MAX_CONN_INTERVAL: - *((uint16*)pValue) = gapRole_MaxConnInterval; - break; + case GAPROLE_MAX_CONN_INTERVAL: + *((uint16*)pValue) = gapRole_MaxConnInterval; + break; - case GAPROLE_SLAVE_LATENCY: - *((uint16*)pValue) = gapRole_SlaveLatency; - break; + case GAPROLE_SLAVE_LATENCY: + *((uint16*)pValue) = gapRole_SlaveLatency; + break; - case GAPROLE_TIMEOUT_MULTIPLIER: - *((uint16*)pValue) = gapRole_TimeoutMultiplier; - break; + case GAPROLE_TIMEOUT_MULTIPLIER: + *((uint16*)pValue) = gapRole_TimeoutMultiplier; + break; - case GAPROLE_CONN_BD_ADDR: - VOID osal_memcpy( pValue, gapRole_ConnectedDevAddr, B_ADDR_LEN ) ; - break; + case GAPROLE_CONN_BD_ADDR: + VOID osal_memcpy( pValue, gapRole_ConnectedDevAddr, B_ADDR_LEN ) ; + break; - case GAPROLE_CONN_INTERVAL: - *((uint16*)pValue) = gapRole_ConnInterval; - break; + case GAPROLE_CONN_INTERVAL: + *((uint16*)pValue) = gapRole_ConnInterval; + break; - case GAPROLE_CONN_LATENCY: - *((uint16*)pValue) = gapRole_ConnSlaveLatency; - break; + case GAPROLE_CONN_LATENCY: + *((uint16*)pValue) = gapRole_ConnSlaveLatency; + break; - case GAPROLE_CONN_TIMEOUT: - *((uint16*)pValue) = gapRole_ConnTimeout; - break; + case GAPROLE_CONN_TIMEOUT: + *((uint16*)pValue) = gapRole_ConnTimeout; + break; - case GAPROLE_STATE: - *((uint8*)pValue) = gapRole_state; - break; + case GAPROLE_STATE: + *((uint8*)pValue) = gapRole_state; + break; - case GAPROLE_CONNECTION_INTERVAL: - *((uint16*)pValue) = gapRole_ConnectionInterval; - break; + case GAPROLE_CONNECTION_INTERVAL: + *((uint16*)pValue) = gapRole_ConnectionInterval; + break; - case GAPROLE_CONNECTION_LATENCY: - *((uint16*)pValue) = gapRole_ConnectionLatency; - break; + case GAPROLE_CONNECTION_LATENCY: + *((uint16*)pValue) = gapRole_ConnectionLatency; + break; - default: + default: - // The param value isn't part of this profile, try the GAP. - if ( param < TGAP_PARAMID_MAX ) - { - *((uint16*)pValue) = GAP_GetParamValue( param ); - } - else - { - ret = INVALIDPARAMETER; - } + // The param value isn't part of this profile, try the GAP. + if ( param < TGAP_PARAMID_MAX ) + { + *((uint16*)pValue) = GAP_GetParamValue( param ); + } + else + { + ret = INVALIDPARAMETER; + } - break; - } + break; + } - return ( ret ); + return ( ret ); } /********************************************************************* - @brief Does the device initialization. + @brief Does the device initialization. - Public function defined in peripheral.h. + Public function defined in peripheral.h. */ bStatus_t GAPRole_StartDevice( gapRolesCBs_t* pAppCallbacks ) { - if ( gapRole_state == GAPROLE_INIT ) - { - // Clear all of the Application callbacks - if ( pAppCallbacks ) - { - pGapRoles_AppCGs = pAppCallbacks; - } + if ( gapRole_state == GAPROLE_INIT ) + { + // Clear all of the Application callbacks + if ( pAppCallbacks ) + { + pGapRoles_AppCGs = pAppCallbacks; + } - // Start the GAP - gapRole_SetupGAP(); - return ( SUCCESS ); - } - else - { - return ( bleAlreadyInRequestedMode ); - } + // Start the GAP + gapRole_SetupGAP(); + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } } /********************************************************************* - @brief Register application's callbacks. + @brief Register application's callbacks. - Public function defined in peripheral.h. + Public function defined in peripheral.h. */ void GAPRole_RegisterAppCBs( gapRolesParamUpdateCB_t* pParamUpdateCB ) { - if ( pParamUpdateCB != NULL ) - { - pGapRoles_ParamUpdateCB = pParamUpdateCB; - } + if ( pParamUpdateCB != NULL ) + { + pGapRoles_ParamUpdateCB = pParamUpdateCB; + } } /********************************************************************* - @brief Terminates the existing connection. + @brief Terminates the existing connection. - Public function defined in peripheral.h. + Public function defined in peripheral.h. */ bStatus_t GAPRole_TerminateConnection( void ) { - if ( gapRole_state == GAPROLE_CONNECTED ) - { - return ( GAP_TerminateLinkReq( gapRole_TaskID, gapRole_ConnectionHandle, - HCI_DISCONNECT_REMOTE_USER_TERM ) ); - } - else - { - return ( bleIncorrectMode ); - } + if ( gapRole_state == GAPROLE_CONNECTED ) + { + return ( GAP_TerminateLinkReq( gapRole_TaskID, gapRole_ConnectionHandle, + HCI_DISCONNECT_REMOTE_USER_TERM ) ); + } + else + { + return ( bleIncorrectMode ); + } } /********************************************************************* - LOCAL FUNCTION PROTOTYPES + LOCAL FUNCTION PROTOTYPES */ /********************************************************************* - @brief Task Initialization function. + @brief Task Initialization function. - Internal function defined in peripheral.h. + Internal function defined in peripheral.h. */ void GAPRole_Init( uint8 task_id ) { - gapRole_TaskID = task_id; - gapRole_state = GAPROLE_INIT; - gapRole_ConnectionHandle = INVALID_CONNHANDLE; - GAP_RegisterForHCIMsgs( gapRole_TaskID ); - // Initialize the Profile Advertising and Connection Parameters - #if ( HOST_CONFIG & OBSERVER_CFG ) - gapRole_profileRole = GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER; - #else - gapRole_profileRole = GAP_PROFILE_PERIPHERAL; - #endif - VOID osal_memset( gapRole_IRK, 0, KEYLEN ); - VOID osal_memset( gapRole_SRK, 0, KEYLEN ); - gapRole_signCounter = 0; - gapRole_AdvEventType = GAP_ADTYPE_ADV_IND; - gapRole_AdvDirectType = ADDRTYPE_PUBLIC; - gapRole_AdvChanMap = GAP_ADVCHAN_ALL; - gapRole_AdvFilterPolicy = GAP_FILTER_POLICY_ALL; - // Restore Items from NV -// VOID osal_snv_read( BLE_NVID_IRK, KEYLEN, gapRole_IRK ); -// VOID osal_snv_read( BLE_NVID_CSRK, KEYLEN, gapRole_SRK ); -// VOID osal_snv_read( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter ); - #ifdef EXT_ADV_ENABLE - // init extended adv variables, include LL init - gapInitExtAdvertiser(); + gapRole_TaskID = task_id; + gapRole_state = GAPROLE_INIT; + gapRole_ConnectionHandle = INVALID_CONNHANDLE; + GAP_RegisterForHCIMsgs( gapRole_TaskID ); + // Initialize the Profile Advertising and Connection Parameters +#if ( HOST_CONFIG & OBSERVER_CFG ) + gapRole_profileRole = GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER; +#else + gapRole_profileRole = GAP_PROFILE_PERIPHERAL; +#endif + VOID osal_memset( gapRole_IRK, 0, KEYLEN ); + VOID osal_memset( gapRole_SRK, 0, KEYLEN ); + gapRole_signCounter = 0; + gapRole_AdvEventType = GAP_ADTYPE_ADV_IND; + gapRole_AdvDirectType = ADDRTYPE_PUBLIC; + gapRole_AdvChanMap = GAP_ADVCHAN_ALL; + gapRole_AdvFilterPolicy = GAP_FILTER_POLICY_ALL; + // Restore Items from NV +// VOID osal_snv_read( BLE_NVID_IRK, KEYLEN, gapRole_IRK ); +// VOID osal_snv_read( BLE_NVID_CSRK, KEYLEN, gapRole_SRK ); +// VOID osal_snv_read( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter ); +#ifdef EXT_ADV_ENABLE + // init extended adv variables, include LL init + gapInitExtAdvertiser(); - // init adv set configuration - for (int i = 0; i < GAP_MAX_EXT_ADV_INSTANCE; i++) - { - advConfig[i].advHandle = i; - gapExtAdvParameterInit(&advConfig[i]); - gapRole_ExtAdvEnabled[i]= FALSE; - } + // init adv set configuration + for (int i = 0; i < GAP_MAX_EXT_ADV_INSTANCE; i++) + { + advConfig[i].advHandle = i; + gapExtAdvParameterInit(&advConfig[i]); + gapRole_ExtAdvEnabled[i]= FALSE; + } - #endif +#endif } /********************************************************************* - @brief Task Event Processor function. + @brief Task Event Processor function. - Internal function defined in peripheral.h. + Internal function defined in peripheral.h. */ uint16 GAPRole_ProcessEvent( uint8 task_id, uint16 events ) { - VOID task_id; // OSAL required parameter that isn't used in this function + VOID task_id; // OSAL required parameter that isn't used in this function - if ( events & SYS_EVENT_MSG ) - { - uint8* pMsg; + if ( events & SYS_EVENT_MSG ) + { + uint8* pMsg; - if ( (pMsg = osal_msg_receive( gapRole_TaskID )) != NULL ) - { - gapRole_ProcessOSALMsg( (osal_event_hdr_t*)pMsg ); - // Release the OSAL message - VOID osal_msg_deallocate( pMsg ); - } + if ( (pMsg = osal_msg_receive( gapRole_TaskID )) != NULL ) + { + gapRole_ProcessOSALMsg( (osal_event_hdr_t*)pMsg ); + // Release the OSAL message + VOID osal_msg_deallocate( pMsg ); + } - // return unprocessed events - return (events ^ SYS_EVENT_MSG); - } + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } - if ( events & GAP_EVENT_SIGN_COUNTER_CHANGED ) - { - // Sign counter changed, save it to NV - // VOID osal_snv_write( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter ); - return ( events ^ GAP_EVENT_SIGN_COUNTER_CHANGED ); - } + if ( events & GAP_EVENT_SIGN_COUNTER_CHANGED ) + { + // Sign counter changed, save it to NV + // VOID osal_snv_write( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter ); + return ( events ^ GAP_EVENT_SIGN_COUNTER_CHANGED ); + } - if ( events & START_ADVERTISING_EVT ) - { - if ( gapRole_AdvEnabled ) - { - gapAdvertisingParams_t params; + if ( events & START_ADVERTISING_EVT ) + { + if ( gapRole_AdvEnabled ) + { + gapAdvertisingParams_t params; - // Setup advertisement parameters - if ( gapRole_state == GAPROLE_CONNECTED ) - { - // While in a connection, we can only advertise non-connectable undirected. - params.eventType = GAP_ADTYPE_ADV_NONCONN_IND; - } - else - { - params.eventType = gapRole_AdvEventType; - params.initiatorAddrType = gapRole_AdvDirectType; - VOID osal_memcpy( params.initiatorAddr, gapRole_AdvDirectAddr, B_ADDR_LEN ); - } + // Setup advertisement parameters + if ( gapRole_state == GAPROLE_CONNECTED ) + { + // While in a connection, we can only advertise non-connectable undirected. + params.eventType = GAP_ADTYPE_ADV_NONCONN_IND; + } + else + { + params.eventType = gapRole_AdvEventType; + params.initiatorAddrType = gapRole_AdvDirectType; + VOID osal_memcpy( params.initiatorAddr, gapRole_AdvDirectAddr, B_ADDR_LEN ); + } - params.channelMap = gapRole_AdvChanMap; - params.filterPolicy = gapRole_AdvFilterPolicy; - uint8 ret = GAP_MakeDiscoverable( gapRole_TaskID, ¶ms ); + params.channelMap = gapRole_AdvChanMap; + params.filterPolicy = gapRole_AdvFilterPolicy; + uint8 ret = GAP_MakeDiscoverable( gapRole_TaskID, ¶ms ); - if ( ret != SUCCESS ) - { - gapRole_state = GAPROLE_ERROR; + if ( ret != SUCCESS ) + { + gapRole_state = GAPROLE_ERROR; - // Notify the application with the new state change - if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) - { - pGapRoles_AppCGs->pfnStateChange( gapRole_state ); - } - } - } + // Notify the application with the new state change + if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) + { + pGapRoles_AppCGs->pfnStateChange( gapRole_state ); + } + } + } - return ( events ^ START_ADVERTISING_EVT ); - } + return ( events ^ START_ADVERTISING_EVT ); + } - if ( events & RSSI_READ_EVT ) - { - // Only get RSSI when in a connection - if ( gapRole_state == GAPROLE_CONNECTED ) - { - // Ask for RSSI - VOID HCI_ReadRssiCmd( gapRole_ConnectionHandle ); + if ( events & RSSI_READ_EVT ) + { + // Only get RSSI when in a connection + if ( gapRole_state == GAPROLE_CONNECTED ) + { + // Ask for RSSI + VOID HCI_ReadRssiCmd( gapRole_ConnectionHandle ); - // Setup next event - if ( gapRole_RSSIReadRate ) - { - VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate ); - } - } + // Setup next event + if ( gapRole_RSSIReadRate ) + { + VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate ); + } + } - return ( events ^ RSSI_READ_EVT ); - } + return ( events ^ RSSI_READ_EVT ); + } - if ( events & START_CONN_UPDATE_EVT ) - { - // Start connection update procedure - gapRole_startConnUpdate( GAPROLE_NO_ACTION ); - return ( events ^ START_CONN_UPDATE_EVT ); - } + if ( events & START_CONN_UPDATE_EVT ) + { + // Start connection update procedure + gapRole_startConnUpdate( GAPROLE_NO_ACTION ); + return ( events ^ START_CONN_UPDATE_EVT ); + } - if ( events & CONN_PARAM_TIMEOUT_EVT ) - { - // Unsuccessful in updating connection parameters - gapRole_HandleParamUpdateNoSuccess(); - return ( events ^ CONN_PARAM_TIMEOUT_EVT ); - } + if ( events & CONN_PARAM_TIMEOUT_EVT ) + { + // Unsuccessful in updating connection parameters + gapRole_HandleParamUpdateNoSuccess(); + return ( events ^ CONN_PARAM_TIMEOUT_EVT ); + } - // Discard unknown events - return 0; + // Discard unknown events + return 0; } /********************************************************************* - @fn gapRole_ProcessOSALMsg + @fn gapRole_ProcessOSALMsg - @brief Process an incoming task message. + @brief Process an incoming task message. - @param pMsg - message to process + @param pMsg - message to process - @return none + @return none */ static void gapRole_ProcessOSALMsg( osal_event_hdr_t* pMsg ) { - switch ( pMsg->event ) - { - case HCI_GAP_EVENT_EVENT: + switch ( pMsg->event ) + { + case HCI_GAP_EVENT_EVENT: - //LOG("GAP EVT[%d]\n", pMsg->status); - if ( pMsg->status == HCI_COMMAND_COMPLETE_EVENT_CODE ) - { - hciEvt_CmdComplete_t* pPkt = (hciEvt_CmdComplete_t*)pMsg; + //LOG("GAP EVT[%d]\n", pMsg->status); + if ( pMsg->status == HCI_COMMAND_COMPLETE_EVENT_CODE ) + { + hciEvt_CmdComplete_t* pPkt = (hciEvt_CmdComplete_t*)pMsg; - if ( pPkt->cmdOpcode == HCI_READ_RSSI ) - { - int8 rssi = (int8)pPkt->pReturnParam[3]; + if ( pPkt->cmdOpcode == HCI_READ_RSSI ) + { + int8 rssi = (int8)pPkt->pReturnParam[3]; - if ( (gapRole_state == GAPROLE_CONNECTED) && (rssi != RSSI_NOT_AVAILABLE) ) - { - // Report RSSI to app - if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnRssiRead ) - { - pGapRoles_AppCGs->pfnRssiRead( rssi ); - } - } - } - else if(pPkt->cmdOpcode == HCI_LE_SET_DATA_LENGTH) - { - LOG("[HCI DLE]%d %d %d\n",pPkt->pReturnParam[0],pPkt->pReturnParam[1],pPkt->pReturnParam[2]); - } + if ( (gapRole_state == GAPROLE_CONNECTED) && (rssi != RSSI_NOT_AVAILABLE) ) + { + // Report RSSI to app + if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnRssiRead ) + { + pGapRoles_AppCGs->pfnRssiRead( rssi ); + } + } + } + else if(pPkt->cmdOpcode == HCI_LE_SET_DATA_LENGTH) + { + LOG("[HCI DLE]%d %d %d\n",pPkt->pReturnParam[0],pPkt->pReturnParam[1],pPkt->pReturnParam[2]); + } - #ifdef EXT_ADV_ENABLE - else if(pPkt->cmdOpcode == HCI_LE_Set_EXTENDED_ADVERTISING_ENABLE) - { - //LOG("status=%d\n",pPkt->pReturnParam[0]); - if(pPkt->pReturnParam[0] == LL_STATUS_SUCCESS) - { - if(gapRole_ExtAdvEnabled[gapRole_ExtAdvEnableHandle] ==TRUE) - { - if(gapRole_state == GAPROLE_STARTED || - gapRole_state == GAPROLE_WAITING || - gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT || - gapRole_state == GAPROLE_ADVERTISING) - gapRole_state = GAPROLE_ADVERTISING; - else if(gapRole_state == GAPROLE_CONNECTED || - gapRole_state == GAPROLE_CONNECTED_ADV) - gapRole_state = GAPROLE_CONNECTED_ADV; - else - gapRole_state = GAPROLE_ERROR; - } - else if(gapRole_ExtAdvEnabled[gapRole_ExtAdvEnableHandle] ==FALSE) - { - if(gapRole_state == GAPROLE_ADVERTISING) - gapRole_state = GAPROLE_WAITING; - else if(gapRole_state == GAPROLE_CONNECTED_ADV) - gapRole_state = GAPROLE_CONNECTED; - else - gapRole_state = GAPROLE_ERROR; - } +#ifdef EXT_ADV_ENABLE + else if(pPkt->cmdOpcode == HCI_LE_Set_EXTENDED_ADVERTISING_ENABLE) + { + //LOG("status=%d\n",pPkt->pReturnParam[0]); + if(pPkt->pReturnParam[0] == LL_STATUS_SUCCESS) + { + if(gapRole_ExtAdvEnabled[gapRole_ExtAdvEnableHandle] ==TRUE) + { + if(gapRole_state == GAPROLE_STARTED || + gapRole_state == GAPROLE_WAITING || + gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT || + gapRole_state == GAPROLE_ADVERTISING) + gapRole_state = GAPROLE_ADVERTISING; + else if(gapRole_state == GAPROLE_CONNECTED || + gapRole_state == GAPROLE_CONNECTED_ADV) + gapRole_state = GAPROLE_CONNECTED_ADV; + else + gapRole_state = GAPROLE_ERROR; + } + else if(gapRole_ExtAdvEnabled[gapRole_ExtAdvEnableHandle] ==FALSE) + { + if(gapRole_state == GAPROLE_ADVERTISING) + gapRole_state = GAPROLE_WAITING; + else if(gapRole_state == GAPROLE_CONNECTED_ADV) + gapRole_state = GAPROLE_CONNECTED; + else + gapRole_state = GAPROLE_ERROR; + } - // Notify the application with the new state change - if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) - { - pGapRoles_AppCGs->pfnStateChange( gapRole_state ); - } - } - else - { - gapRole_state = GAPROLE_ERROR; + // Notify the application with the new state change + if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) + { + pGapRoles_AppCGs->pfnStateChange( gapRole_state ); + } + } + else + { + gapRole_state = GAPROLE_ERROR; - // Notify the application with the new state change - if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) - { - pGapRoles_AppCGs->pfnStateChange( gapRole_state ); - } - } - } + // Notify the application with the new state change + if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) + { + pGapRoles_AppCGs->pfnStateChange( gapRole_state ); + } + } + } - #endif - } - else if(pMsg->status==HCI_COMMAND_STATUS_EVENT_CODE) - { - hciEvt_CommandStatus_t* pPkt = (hciEvt_CommandStatus_t*)pMsg; +#endif + } + else if(pMsg->status==HCI_COMMAND_STATUS_EVENT_CODE) + { + hciEvt_CommandStatus_t* pPkt = (hciEvt_CommandStatus_t*)pMsg; - if ( pPkt->cmdOpcode == HCI_LE_SET_PHY ) - { - LOG_DEBUG("[HCI PHY] %2x \n",pPkt->cmdStatus); - } - } - else if(pMsg->status==HCI_LE_EVENT_CODE) - { - hciEvt_BLEEvent_Hdr_t* pPkt = (hciEvt_BLEEvent_Hdr_t*)pMsg; + if ( pPkt->cmdOpcode == HCI_LE_SET_PHY ) + { + LOG_DEBUG("[HCI PHY] %2x \n",pPkt->cmdStatus); + } + } + else if(pMsg->status==HCI_LE_EVENT_CODE) + { + hciEvt_BLEEvent_Hdr_t* pPkt = (hciEvt_BLEEvent_Hdr_t*)pMsg; - if ( pPkt->BLEEventCode == HCI_BLE_DATA_LENGTH_CHANGE_EVENT ) - { -// hciEvt_BLEDataLenChange_t * pkt = (hciEvt_BLEDataLenChange_t *)pMsg; -// LOG_DEBUG("[HCI DLE EVT]%d %d %d %d\n",pkt->MaxRxOctets,pkt->MaxRxTime, -// pkt->MaxTxOctets,pkt->MaxTxTime); - } - else if(pPkt->BLEEventCode == HCI_BLE_PHY_UPDATE_COMPLETE_EVENT ) - { -// hciEvt_BLEPhyUpdateComplete_t * pkt = (hciEvt_BLEPhyUpdateComplete_t *)pMsg; -// LOG_DEBUG("[HCI PHY EVT]s%d r%d t%d\n",pkt->status, pkt->rxPhy,pkt->txPhy); - } - } + if ( pPkt->BLEEventCode == HCI_BLE_DATA_LENGTH_CHANGE_EVENT ) + { +// hciEvt_BLEDataLenChange_t * pkt = (hciEvt_BLEDataLenChange_t *)pMsg; +// LOG_DEBUG("[HCI DLE EVT]%d %d %d %d\n",pkt->MaxRxOctets,pkt->MaxRxTime, +// pkt->MaxTxOctets,pkt->MaxTxTime); + } + else if(pPkt->BLEEventCode == HCI_BLE_PHY_UPDATE_COMPLETE_EVENT ) + { +// hciEvt_BLEPhyUpdateComplete_t * pkt = (hciEvt_BLEPhyUpdateComplete_t *)pMsg; +// LOG_DEBUG("[HCI PHY EVT]s%d r%d t%d\n",pkt->status, pkt->rxPhy,pkt->txPhy); + } + } - break; + break; - case GAP_MSG_EVENT: - gapRole_ProcessGAPMsg( (gapEventHdr_t*)pMsg ); - break; + case GAP_MSG_EVENT: + gapRole_ProcessGAPMsg( (gapEventHdr_t*)pMsg ); + break; - case L2CAP_SIGNAL_EVENT: - { - l2capSignalEvent_t* pPkt = (l2capSignalEvent_t*)pMsg; + case L2CAP_SIGNAL_EVENT: + { + l2capSignalEvent_t* pPkt = (l2capSignalEvent_t*)pMsg; - // Process the Parameter Update Response - if ( pPkt->opcode == L2CAP_PARAM_UPDATE_RSP ) - { - l2capParamUpdateRsp_t* pRsp = (l2capParamUpdateRsp_t*)&(pPkt->cmd.updateRsp); + // Process the Parameter Update Response + if ( pPkt->opcode == L2CAP_PARAM_UPDATE_RSP ) + { + l2capParamUpdateRsp_t* pRsp = (l2capParamUpdateRsp_t*)&(pPkt->cmd.updateRsp); - if ( ( pRsp->result == L2CAP_CONN_PARAMS_REJECTED ) && - ( paramUpdateNoSuccessOption == GAPROLE_TERMINATE_LINK ) ) - { - // Cancel connection param update timeout timer - VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ); - // Terminate connection immediately - GAPRole_TerminateConnection(); - } - else - { - uint16 timeout = GAP_GetParamValue( TGAP_CONN_PARAM_TIMEOUT ); - // Let's wait for Controller to update connection parameters if they're - // accepted. Otherwise, decide what to do based on no success option. - VOID osal_start_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT, timeout ); - } - } - } - break; + if ( ( pRsp->result == L2CAP_CONN_PARAMS_REJECTED ) && + ( paramUpdateNoSuccessOption == GAPROLE_TERMINATE_LINK ) ) + { + // Cancel connection param update timeout timer + VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ); + // Terminate connection immediately + GAPRole_TerminateConnection(); + } + else + { + uint16 timeout = GAP_GetParamValue( TGAP_CONN_PARAM_TIMEOUT ); + // Let's wait for Controller to update connection parameters if they're + // accepted. Otherwise, decide what to do based on no success option. + VOID osal_start_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT, timeout ); + } + } + } + break; - default: - break; - } + default: + break; + } } /********************************************************************* - @fn gapRole_ProcessGAPMsg + @fn gapRole_ProcessGAPMsg - @brief Process an incoming task message. + @brief Process an incoming task message. - @param pMsg - message to process + @param pMsg - message to process - @return none + @return none */ static void gapRole_ProcessGAPMsg( gapEventHdr_t* pMsg ) { - uint8 notify = FALSE; // State changed notify the app? (default no) + uint8 notify = FALSE; // State changed notify the app? (default no) - switch ( pMsg->opcode ) - { - case GAP_DEVICE_INIT_DONE_EVENT: - { - gapDeviceInitDoneEvent_t* pPkt = (gapDeviceInitDoneEvent_t*)pMsg; - bStatus_t stat = pPkt->hdr.status; + switch ( pMsg->opcode ) + { + case GAP_DEVICE_INIT_DONE_EVENT: + { + gapDeviceInitDoneEvent_t* pPkt = (gapDeviceInitDoneEvent_t*)pMsg; + bStatus_t stat = pPkt->hdr.status; - if ( stat == SUCCESS ) - { - // Save off the generated keys - // VOID osal_snv_write( BLE_NVID_IRK, KEYLEN, gapRole_IRK ); - // VOID osal_snv_write( BLE_NVID_CSRK, KEYLEN, gapRole_SRK ); - // Save off the information - VOID osal_memcpy( gapRole_bdAddr, pPkt->devAddr, B_ADDR_LEN ); - gapRole_state = GAPROLE_STARTED; + if ( stat == SUCCESS ) + { + // Save off the generated keys + // VOID osal_snv_write( BLE_NVID_IRK, KEYLEN, gapRole_IRK ); + // VOID osal_snv_write( BLE_NVID_CSRK, KEYLEN, gapRole_SRK ); + // Save off the information + VOID osal_memcpy( gapRole_bdAddr, pPkt->devAddr, B_ADDR_LEN ); + gapRole_state = GAPROLE_STARTED; - // Update the advertising data - if(gapRole_AdvertDataLen !=0) - stat = GAP_UpdateAdvertisingData( gapRole_TaskID, - TRUE, gapRole_AdvertDataLen, gapRole_AdvertData ); - else - stat = SUCCESS; - } + // Update the advertising data + if(gapRole_AdvertDataLen !=0) + stat = GAP_UpdateAdvertisingData( gapRole_TaskID, + TRUE, gapRole_AdvertDataLen, gapRole_AdvertData ); + else + stat = SUCCESS; + } - if ( stat != SUCCESS ) - { - gapRole_state = GAPROLE_ERROR; - } + if ( stat != SUCCESS ) + { + gapRole_state = GAPROLE_ERROR; + } - notify = TRUE; - } - break; + notify = TRUE; + } + break; - case GAP_ADV_DATA_UPDATE_DONE_EVENT: - { - gapAdvDataUpdateEvent_t* pPkt = (gapAdvDataUpdateEvent_t*)pMsg; + case GAP_ADV_DATA_UPDATE_DONE_EVENT: + { + gapAdvDataUpdateEvent_t* pPkt = (gapAdvDataUpdateEvent_t*)pMsg; - if ( pPkt->hdr.status == SUCCESS ) - { - if ( pPkt->adType ) - { - // Setup the Response Data - pPkt->hdr.status = GAP_UpdateAdvertisingData( gapRole_TaskID, - FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData ); - } - else if ( ( gapRole_state != GAPROLE_ADVERTISING ) && - ( osal_get_timeoutEx( gapRole_TaskID, START_ADVERTISING_EVT ) == 0 ) ) - { - // Start advertising - VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); - } - } + if ( pPkt->hdr.status == SUCCESS ) + { + if ( pPkt->adType ) + { + // Setup the Response Data + pPkt->hdr.status = GAP_UpdateAdvertisingData( gapRole_TaskID, + FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData ); + } + else if ( ( gapRole_state != GAPROLE_ADVERTISING ) && + ( osal_get_timeoutEx( gapRole_TaskID, START_ADVERTISING_EVT ) == 0 ) ) + { + // Start advertising + VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); + } + } - if ( pPkt->hdr.status != SUCCESS ) - { - // Set into Error state - gapRole_state = GAPROLE_ERROR; - notify = TRUE; - } - } - break; + if ( pPkt->hdr.status != SUCCESS ) + { + // Set into Error state + gapRole_state = GAPROLE_ERROR; + notify = TRUE; + } + } + break; - case GAP_MAKE_DISCOVERABLE_DONE_EVENT: - case GAP_END_DISCOVERABLE_DONE_EVENT: - { - gapMakeDiscoverableRspEvent_t* pPkt = (gapMakeDiscoverableRspEvent_t*)pMsg; + case GAP_MAKE_DISCOVERABLE_DONE_EVENT: + case GAP_END_DISCOVERABLE_DONE_EVENT: + { + gapMakeDiscoverableRspEvent_t* pPkt = (gapMakeDiscoverableRspEvent_t*)pMsg; - if ( pPkt->hdr.status == SUCCESS ) - { - if ( pMsg->opcode == GAP_MAKE_DISCOVERABLE_DONE_EVENT ) - { - if (gapRole_state == GAPROLE_CONNECTED) - { - gapRole_state = GAPROLE_CONNECTED_ADV; - } - else - { - gapRole_state = GAPROLE_ADVERTISING; - } - } - else // GAP_END_DISCOVERABLE_DONE_EVENT - { - if ( gapRole_AdvertOffTime != 0 ) - { - if ( ( gapRole_AdvEnabled ) ) - { - VOID osal_start_timerEx( gapRole_TaskID, START_ADVERTISING_EVT, gapRole_AdvertOffTime ); - } - } - else - { - // Since gapRole_AdvertOffTime is set to 0, the device should not - // automatically become discoverable again after a period of time. - // Set enabler to FALSE; device will become discoverable again when - // this value gets set to TRUE - gapRole_AdvEnabled = FALSE; - } + if ( pPkt->hdr.status == SUCCESS ) + { + if ( pMsg->opcode == GAP_MAKE_DISCOVERABLE_DONE_EVENT ) + { + if (gapRole_state == GAPROLE_CONNECTED) + { + gapRole_state = GAPROLE_CONNECTED_ADV; + } + else + { + gapRole_state = GAPROLE_ADVERTISING; + } + } + else // GAP_END_DISCOVERABLE_DONE_EVENT + { + if ( gapRole_AdvertOffTime != 0 ) + { + if ( ( gapRole_AdvEnabled ) ) + { + VOID osal_start_timerEx( gapRole_TaskID, START_ADVERTISING_EVT, gapRole_AdvertOffTime ); + } + } + else + { + // Since gapRole_AdvertOffTime is set to 0, the device should not + // automatically become discoverable again after a period of time. + // Set enabler to FALSE; device will become discoverable again when + // this value gets set to TRUE + gapRole_AdvEnabled = FALSE; + } - if (gapRole_state == GAPROLE_CONNECTED_ADV) - { - // In the Advertising Off period - gapRole_state = GAPROLE_CONNECTED; - } - else if (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) - { - // Advertising was just turned off after the link disconnected so begin - // advertising again. - gapRole_AdvEnabled = TRUE; - // Turn advertising back on. - VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); - } - else - { - // In the Advertising Off period - gapRole_state = GAPROLE_WAITING; - } - } - } - else - { - gapRole_state = GAPROLE_ERROR; - } + if (gapRole_state == GAPROLE_CONNECTED_ADV) + { + // In the Advertising Off period + gapRole_state = GAPROLE_CONNECTED; + } + else if (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) + { + // Advertising was just turned off after the link disconnected so begin + // advertising again. + gapRole_AdvEnabled = TRUE; + // Turn advertising back on. + VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT ); + } + else + { + // In the Advertising Off period + gapRole_state = GAPROLE_WAITING; + } + } + } + else + { + gapRole_state = GAPROLE_ERROR; + } - notify = TRUE; - } - break; + notify = TRUE; + } + break; - case GAP_LINK_ESTABLISHED_EVENT: - { - gapEstLinkReqEvent_t* pPkt = (gapEstLinkReqEvent_t*)pMsg; + case GAP_LINK_ESTABLISHED_EVENT: + { + gapEstLinkReqEvent_t* pPkt = (gapEstLinkReqEvent_t*)pMsg; - if ( pPkt->hdr.status == SUCCESS ) - { - VOID osal_memcpy( gapRole_ConnectedDevAddr, pPkt->devAddr, B_ADDR_LEN ); - gapRole_ConnectionHandle = pPkt->connectionHandle; - gapRole_ConnectionInterval = pPkt->connInterval; - gapRole_ConnectionLatency = pPkt->connLatency; - gapRole_state = GAPROLE_CONNECTED; + if ( pPkt->hdr.status == SUCCESS ) + { + VOID osal_memcpy( gapRole_ConnectedDevAddr, pPkt->devAddr, B_ADDR_LEN ); + gapRole_ConnectionHandle = pPkt->connectionHandle; + gapRole_ConnectionInterval = pPkt->connInterval; + gapRole_ConnectionLatency = pPkt->connLatency; + gapRole_state = GAPROLE_CONNECTED; - //LOG("connect by[%02x%02x%02x%02x%02x%02x] handle[%d] interval[%d] latency[%d] timeout[%d]\n", - // gapRole_ConnectedDevAddr[0], gapRole_ConnectedDevAddr[1], gapRole_ConnectedDevAddr[2], - // gapRole_ConnectedDevAddr[3],gapRole_ConnectedDevAddr[4], gapRole_ConnectedDevAddr[5], - // pPkt->connectionHandle, pPkt->connInterval,pPkt->connLatency, pPkt->connTimeout); - if ( gapRole_RSSIReadRate ) - { - // Start the RSSI Reads - VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate ); - } + //LOG("connect by[%02x%02x%02x%02x%02x%02x] handle[%d] interval[%d] latency[%d] timeout[%d]\n", + // gapRole_ConnectedDevAddr[0], gapRole_ConnectedDevAddr[1], gapRole_ConnectedDevAddr[2], + // gapRole_ConnectedDevAddr[3],gapRole_ConnectedDevAddr[4], gapRole_ConnectedDevAddr[5], + // pPkt->connectionHandle, pPkt->connInterval,pPkt->connLatency, pPkt->connTimeout); + if ( gapRole_RSSIReadRate ) + { + // Start the RSSI Reads + VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate ); + } - // Store connection information - gapRole_ConnInterval = pPkt->connInterval; - gapRole_ConnSlaveLatency = pPkt->connLatency; - gapRole_ConnTimeout = pPkt->connTimeout; + // Store connection information + gapRole_ConnInterval = pPkt->connInterval; + gapRole_ConnSlaveLatency = pPkt->connLatency; + gapRole_ConnTimeout = pPkt->connTimeout; - // Check whether update parameter request is enabled - if ( gapRole_ParamUpdateEnable == TRUE ) - { - // Get the minimum time upon connection establishment before the - // peripheral can start a connection update procedure. - uint16 timeout = GAP_GetParamValue( TGAP_CONN_PAUSE_PERIPHERAL ); - osal_start_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT, timeout*1000 ); - } + // Check whether update parameter request is enabled + if ( gapRole_ParamUpdateEnable == TRUE ) + { + // Get the minimum time upon connection establishment before the + // peripheral can start a connection update procedure. + uint16 timeout = GAP_GetParamValue( TGAP_CONN_PAUSE_PERIPHERAL ); + osal_start_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT, timeout*1000 ); + } - // Notify the Bond Manager to the connection - #if(DEF_GAPBOND_MGR_ENABLE == TRUE) - VOID GAPBondMgr_LinkEst( pPkt->devAddrType, pPkt->devAddr, pPkt->connectionHandle, GAP_PROFILE_PERIPHERAL ); - #endif - // Set enabler to FALSE; device will become discoverable again when - // this value gets set to TRUE - gapRole_AdvEnabled = FALSE; - } - else if ( pPkt->hdr.status == bleGAPConnNotAcceptable ) - { - // Set enabler to FALSE; device will become discoverable again when - // this value gets set to TRUE - gapRole_AdvEnabled = FALSE; - // Go to WAITING state, and then start advertising - gapRole_state = GAPROLE_WAITING; - } - else - { - gapRole_state = GAPROLE_ERROR; - } + // Notify the Bond Manager to the connection +#if(DEF_GAPBOND_MGR_ENABLE == TRUE) + VOID GAPBondMgr_LinkEst( pPkt->devAddrType, pPkt->devAddr, pPkt->connectionHandle, GAP_PROFILE_PERIPHERAL ); +#endif + // Set enabler to FALSE; device will become discoverable again when + // this value gets set to TRUE + gapRole_AdvEnabled = FALSE; + } + else if ( pPkt->hdr.status == bleGAPConnNotAcceptable ) + { + // Set enabler to FALSE; device will become discoverable again when + // this value gets set to TRUE + gapRole_AdvEnabled = FALSE; + // Go to WAITING state, and then start advertising + gapRole_state = GAPROLE_WAITING; + } + else + { + gapRole_state = GAPROLE_ERROR; + } - notify = TRUE; - } - break; + notify = TRUE; + } + break; - case GAP_LINK_TERMINATED_EVENT: - { - gapTerminateLinkEvent_t* pPkt = (gapTerminateLinkEvent_t*)pMsg; - // VOID GAPBondMgr_ProcessGAPMsg( (gapEventHdr_t *)pMsg ); - osal_memset( gapRole_ConnectedDevAddr, 0, B_ADDR_LEN ); - // Erase connection information - gapRole_ConnInterval = 0; - gapRole_ConnSlaveLatency = 0; - gapRole_ConnTimeout = 0; - // Cancel all connection parameter update timers (if any active) - VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT ); - VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ); + case GAP_LINK_TERMINATED_EVENT: + { + gapTerminateLinkEvent_t* pPkt = (gapTerminateLinkEvent_t*)pMsg; + // VOID GAPBondMgr_ProcessGAPMsg( (gapEventHdr_t *)pMsg ); + osal_memset( gapRole_ConnectedDevAddr, 0, B_ADDR_LEN ); + // Erase connection information + gapRole_ConnInterval = 0; + gapRole_ConnSlaveLatency = 0; + gapRole_ConnTimeout = 0; + // Cancel all connection parameter update timers (if any active) + VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT ); + VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ); - // Go to WAITING state, and then start advertising - if( pPkt->reason == LL_SUPERVISION_TIMEOUT_TERM ) - { - gapRole_state = GAPROLE_WAITING_AFTER_TIMEOUT; - } - else - { - gapRole_state = GAPROLE_WAITING; - } + // Go to WAITING state, and then start advertising + if( pPkt->reason == LL_SUPERVISION_TIMEOUT_TERM ) + { + gapRole_state = GAPROLE_WAITING_AFTER_TIMEOUT; + } + else + { + gapRole_state = GAPROLE_WAITING; + } - LOG_DEBUG("[DISC].reason %02x\n",pPkt->reason); - notify = TRUE; + LOG_DEBUG("[DISC].reason %02x\n",pPkt->reason); + notify = TRUE; - //LOG("disconnected reason[%d]!\n", pPkt->reason); - // Check if still advertising from within last connection. - if (gapRole_AdvertDataLen != 0) - { - if ( gapRole_AdvEnabled) - { - // End advertising so we can restart advertising in order - // to change to connectable advertising from nonconnectable. - VOID GAP_EndDiscoverable( gapRole_TaskID ); - } - else // Turn advertising back on. - { - gapRole_AdvEnabled = TRUE; - VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT); - } - } + //LOG("disconnected reason[%d]!\n", pPkt->reason); + // Check if still advertising from within last connection. + if (gapRole_AdvertDataLen != 0) + { + if ( gapRole_AdvEnabled) + { + // End advertising so we can restart advertising in order + // to change to connectable advertising from nonconnectable. + VOID GAP_EndDiscoverable( gapRole_TaskID ); + } + else // Turn advertising back on. + { + gapRole_AdvEnabled = TRUE; + VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT); + } + } - gapRole_ConnectionHandle = INVALID_CONNHANDLE; - } - break; + gapRole_ConnectionHandle = INVALID_CONNHANDLE; + } + break; - case GAP_LINK_PARAM_UPDATE_EVENT: - { - gapLinkUpdateEvent_t* pPkt = (gapLinkUpdateEvent_t*)pMsg; - // Cancel connection param update timeout timer (if active) - VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ); + case GAP_LINK_PARAM_UPDATE_EVENT: + { + gapLinkUpdateEvent_t* pPkt = (gapLinkUpdateEvent_t*)pMsg; + // Cancel connection param update timeout timer (if active) + VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ); - if ( pPkt->hdr.status == SUCCESS ) - { - // Store new connection parameters - gapRole_ConnInterval = pPkt->connInterval; - gapRole_ConnSlaveLatency = pPkt->connLatency; - gapRole_ConnTimeout = pPkt->connTimeout; + if ( pPkt->hdr.status == SUCCESS ) + { + // Store new connection parameters + gapRole_ConnInterval = pPkt->connInterval; + gapRole_ConnSlaveLatency = pPkt->connLatency; + gapRole_ConnTimeout = pPkt->connTimeout; - // Make sure there's no pending connection update procedure - if ( osal_get_timeoutEx( gapRole_TaskID, START_CONN_UPDATE_EVT ) == 0 ) - { - // Notify the application with the new connection parameters - if ( pGapRoles_ParamUpdateCB != NULL ) - { - (*pGapRoles_ParamUpdateCB)( gapRole_ConnInterval, - gapRole_ConnSlaveLatency, - gapRole_ConnTimeout ); - } - } - } - } - break; + // Make sure there's no pending connection update procedure + if ( osal_get_timeoutEx( gapRole_TaskID, START_CONN_UPDATE_EVT ) == 0 ) + { + // Notify the application with the new connection parameters + if ( pGapRoles_ParamUpdateCB != NULL ) + { + (*pGapRoles_ParamUpdateCB)( gapRole_ConnInterval, + gapRole_ConnSlaveLatency, + gapRole_ConnTimeout ); + } + } + } + } + break; - default: - break; - } + default: + break; + } - if ( notify == TRUE ) - { - // Notify the application with the new state change - if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) - { - pGapRoles_AppCGs->pfnStateChange( gapRole_state ); - } - } + if ( notify == TRUE ) + { + // Notify the application with the new state change + if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange ) + { + pGapRoles_AppCGs->pfnStateChange( gapRole_state ); + } + } } /********************************************************************* - @fn gapRole_SetupGAP + @fn gapRole_SetupGAP - @brief Call the GAP Device Initialization function using the - Profile Parameters. + @brief Call the GAP Device Initialization function using the + Profile Parameters. - @param none + @param none - @return none + @return none */ static void gapRole_SetupGAP( void ) { - #if ( HOST_CONFIG & OBSERVER_CFG ) - GAP_DeviceInit( gapRole_TaskID, - gapRole_profileRole, 0x10, - gapRole_IRK, gapRole_SRK, - &gapRole_signCounter ); - #else - GAP_DeviceInit( gapRole_TaskID, - gapRole_profileRole, 0, - gapRole_IRK, gapRole_SRK, - &gapRole_signCounter ); - #endif + #if ( HOST_CONFIG & OBSERVER_CFG ) + GAP_DeviceInit( gapRole_TaskID, + gapRole_profileRole, 0x10, + gapRole_IRK, gapRole_SRK, + &gapRole_signCounter ); + #else + GAP_DeviceInit( gapRole_TaskID, + gapRole_profileRole, 0, + gapRole_IRK, gapRole_SRK, + &gapRole_signCounter ); + #endif } /********************************************************************* - @fn gapRole_HandleParamUpdateNoSuccess + @fn gapRole_HandleParamUpdateNoSuccess - @brief Handle unsuccessful connection parameters update. + @brief Handle unsuccessful connection parameters update. - @param none + @param none - @return none + @return none */ static void gapRole_HandleParamUpdateNoSuccess( void ) { - // See which option was choosen for unsuccessful updates - switch ( paramUpdateNoSuccessOption ) - { - case GAPROLE_RESEND_PARAM_UPDATE: - GAPRole_SendUpdateParam( gapRole_MinConnInterval, gapRole_MaxConnInterval, - gapRole_SlaveLatency, gapRole_TimeoutMultiplier, - GAPROLE_RESEND_PARAM_UPDATE ); - break; + // See which option was choosen for unsuccessful updates + switch ( paramUpdateNoSuccessOption ) + { + case GAPROLE_RESEND_PARAM_UPDATE: + GAPRole_SendUpdateParam( gapRole_MinConnInterval, gapRole_MaxConnInterval, + gapRole_SlaveLatency, gapRole_TimeoutMultiplier, + GAPROLE_RESEND_PARAM_UPDATE ); + break; - case GAPROLE_TERMINATE_LINK: - GAPRole_TerminateConnection(); - break; + case GAPROLE_TERMINATE_LINK: + GAPRole_TerminateConnection(); + break; - case GAPROLE_NO_ACTION: + case GAPROLE_NO_ACTION: - // fall through - default: - //do nothing - break; - } + // fall through + default: + //do nothing + break; + } } /******************************************************************** - @fn gapRole_startConnUpdate + @fn gapRole_startConnUpdate - @brief Start the connection update procedure + @brief Start the connection update procedure - @param handleFailure - what to do if the update does not occur. - Method may choose to terminate connection, try again, or take no action + @param handleFailure - what to do if the update does not occur. + Method may choose to terminate connection, try again, or take no action - @return none + @return none */ static void gapRole_startConnUpdate( uint8 handleFailure ) { - // First check the current connection parameters versus the configured parameters - if ( (gapRole_ConnInterval < gapRole_MinConnInterval) || - (gapRole_ConnInterval > gapRole_MaxConnInterval) || - (gapRole_ConnSlaveLatency != gapRole_SlaveLatency) || - (gapRole_ConnTimeout != gapRole_TimeoutMultiplier) ) - { - l2capParamUpdateReq_t updateReq; - uint16 timeout = GAP_GetParamValue( TGAP_CONN_PARAM_TIMEOUT ); - updateReq.intervalMin = gapRole_MinConnInterval; - updateReq.intervalMax = gapRole_MaxConnInterval; - updateReq.slaveLatency = gapRole_SlaveLatency; - updateReq.timeoutMultiplier = gapRole_TimeoutMultiplier; - L2CAP_ConnParamUpdateReq( gapRole_ConnectionHandle, &updateReq, gapRole_TaskID ); - paramUpdateNoSuccessOption = handleFailure; - // Let's wait for L2CAP Connection Parameters Update Response - VOID osal_start_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT, timeout ); - } + // First check the current connection parameters versus the configured parameters + if ( (gapRole_ConnInterval < gapRole_MinConnInterval) || + (gapRole_ConnInterval > gapRole_MaxConnInterval) || + (gapRole_ConnSlaveLatency != gapRole_SlaveLatency) || + (gapRole_ConnTimeout != gapRole_TimeoutMultiplier) ) + { + l2capParamUpdateReq_t updateReq; + uint16 timeout = GAP_GetParamValue( TGAP_CONN_PARAM_TIMEOUT ); + updateReq.intervalMin = gapRole_MinConnInterval; + updateReq.intervalMax = gapRole_MaxConnInterval; + updateReq.slaveLatency = gapRole_SlaveLatency; + updateReq.timeoutMultiplier = gapRole_TimeoutMultiplier; + L2CAP_ConnParamUpdateReq( gapRole_ConnectionHandle, &updateReq, gapRole_TaskID ); + paramUpdateNoSuccessOption = handleFailure; + // Let's wait for L2CAP Connection Parameters Update Response + VOID osal_start_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT, timeout ); + } } /******************************************************************** - @fn GAPRole_SendUpdateParam + @fn GAPRole_SendUpdateParam - @brief Update the parameters of an existing connection + @brief Update the parameters of an existing connection - @param minConnInterval - the new min connection interval - @param maxConnInterval - the new max connection interval - @param latency - the new slave latency - @param connTimeout - the new timeout value - @param handleFailure - what to do if the update does not occur. - Method may choose to terminate connection, try again, or take no action + @param minConnInterval - the new min connection interval + @param maxConnInterval - the new max connection interval + @param latency - the new slave latency + @param connTimeout - the new timeout value + @param handleFailure - what to do if the update does not occur. + Method may choose to terminate connection, try again, or take no action - @return SUCCESS, bleNotConnected, or bleInvalidRange + @return SUCCESS, bleNotConnected, or bleInvalidRange */ bStatus_t GAPRole_SendUpdateParam( uint16 minConnInterval, uint16 maxConnInterval, - uint16 latency, uint16 connTimeout, uint8 handleFailure ) + uint16 latency, uint16 connTimeout, uint8 handleFailure ) { - // If there is no existing connection no update need be sent - if ( gapRole_state != GAPROLE_CONNECTED ) - { - return ( bleNotConnected ); - } + // If there is no existing connection no update need be sent + if ( gapRole_state != GAPROLE_CONNECTED ) + { + return ( bleNotConnected ); + } - // Check that all parameters are in range before sending request - if ( ( minConnInterval >= DEFAULT_MIN_CONN_INTERVAL ) && - ( minConnInterval < DEFAULT_MAX_CONN_INTERVAL ) && - ( maxConnInterval >= DEFAULT_MIN_CONN_INTERVAL ) && - ( maxConnInterval < DEFAULT_MAX_CONN_INTERVAL ) && - ( latency < MAX_SLAVE_LATENCY ) && - ( connTimeout >= MIN_TIMEOUT_MULTIPLIER ) && - ( connTimeout < MAX_TIMEOUT_MULTIPLIER ) ) - { - gapRole_MinConnInterval = minConnInterval; - gapRole_MaxConnInterval = maxConnInterval; - gapRole_SlaveLatency = latency; - gapRole_TimeoutMultiplier = connTimeout; - // Start connection update procedure - gapRole_startConnUpdate( handleFailure ); - // Connection update requested by app, cancel such pending procedure (if active) - VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT ); - return ( SUCCESS ); - } + // Check that all parameters are in range before sending request + if ( ( minConnInterval >= DEFAULT_MIN_CONN_INTERVAL ) && + ( minConnInterval < DEFAULT_MAX_CONN_INTERVAL ) && + ( maxConnInterval >= DEFAULT_MIN_CONN_INTERVAL ) && + ( maxConnInterval < DEFAULT_MAX_CONN_INTERVAL ) && + ( latency < MAX_SLAVE_LATENCY ) && + ( connTimeout >= MIN_TIMEOUT_MULTIPLIER ) && + ( connTimeout < MAX_TIMEOUT_MULTIPLIER ) ) + { + gapRole_MinConnInterval = minConnInterval; + gapRole_MaxConnInterval = maxConnInterval; + gapRole_SlaveLatency = latency; + gapRole_TimeoutMultiplier = connTimeout; + // Start connection update procedure + gapRole_startConnUpdate( handleFailure ); + // Connection update requested by app, cancel such pending procedure (if active) + VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT ); + return ( SUCCESS ); + } - return ( bleInvalidRange ); + return ( bleInvalidRange ); } #ifdef EXT_ADV_ENABLE bStatus_t GAPRole_extAdv_ConfigAdvSet(uint8 adv_handle) { - bStatus_t ret = SUCCESS; // return value - gapAdvSetParameter_t* para; + bStatus_t ret = SUCCESS; // return value + gapAdvSetParameter_t* para; - if (adv_handle < GAP_MAX_EXT_ADV_INSTANCE) - para = &advConfig[adv_handle]; - else - return FAILURE; + if (adv_handle < GAP_MAX_EXT_ADV_INSTANCE) + para = &advConfig[adv_handle]; + else + return FAILURE; - //LOG("advEventProperties:%d,wlPolicy:%d,secondaryAdvMaxSkip:%d\n",para->advEventProperties,para->wlPolicy,para->secondaryAdvMaxSkip); - ret = HCI_LE_SetExtAdvParamCmd(adv_handle, - para->advEventProperties, //LL_EXT_ADV_PROP_ADV_IND - para->priAdvIntMin, // primary_advertising_interval_Min, - para->priAdvIntMax, // primary_advertising_interval_Max, - para->priAdvChnMap, // primary_advertising_channel_map, - para->ownAddrType, // own_address_type, - para->peerAddrType, // peer_address_type, - para->peerAddress, // peer address - para->wlPolicy, // advertising_filter_policy, - para->advTxPower, // advertising_tx_power, - para->primaryAdvPHY, // primary_advertising_PHY, // 01: 1M PHY, 0x03: coded PHY - para->secondaryAdvMaxSkip, // secondary_advertising_max_skip, - para->secondaryAdvPHY, // secondary_advertising_PHY, // 1M PHY - para->advertisingSID, // advertising_SID, - para->scanReqNotificationEnable //scan_request_notification_enable - ); + //LOG("advEventProperties:%d,wlPolicy:%d,secondaryAdvMaxSkip:%d\n",para->advEventProperties,para->wlPolicy,para->secondaryAdvMaxSkip); + ret = HCI_LE_SetExtAdvParamCmd(adv_handle, + para->advEventProperties, //LL_EXT_ADV_PROP_ADV_IND + para->priAdvIntMin, // primary_advertising_interval_Min, + para->priAdvIntMax, // primary_advertising_interval_Max, + para->priAdvChnMap, // primary_advertising_channel_map, + para->ownAddrType, // own_address_type, + para->peerAddrType, // peer_address_type, + para->peerAddress, // peer address + para->wlPolicy, // advertising_filter_policy, + para->advTxPower, // advertising_tx_power, + para->primaryAdvPHY, // primary_advertising_PHY, // 01: 1M PHY, 0x03: coded PHY + para->secondaryAdvMaxSkip, // secondary_advertising_max_skip, + para->secondaryAdvPHY, // secondary_advertising_PHY, // 1M PHY + para->advertisingSID, // advertising_SID, + para->scanReqNotificationEnable //scan_request_notification_enable + ); - if (ret != SUCCESS) - return ret; + if (ret != SUCCESS) + return ret; - if(para->ownAddrType!=0) - { - extern bStatus_t gapExtSetStaticAddr( uint8 advhandle,uint8* pNewAddr ); - gapExtSetStaticAddr(adv_handle,&(gapRole_ExtAdv_RandomAddr[adv_handle][0])); - } + if(para->ownAddrType!=0) + { + extern bStatus_t gapExtSetStaticAddr( uint8 advhandle,uint8* pNewAddr ); + gapExtSetStaticAddr(adv_handle,&(gapRole_ExtAdv_RandomAddr[adv_handle][0])); + } - if(para->advEventProperties & (LE_ADV_PROP_DIRECT_BITMASK | LE_ADV_PROP_HI_DC_CONN_BITMASK)) - return ret; + if(para->advEventProperties & (LE_ADV_PROP_DIRECT_BITMASK | LE_ADV_PROP_HI_DC_CONN_BITMASK)) + return ret; - if (para->advDataLen > GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH) - { - // configure adv data fragment in several HCI commands - uint16 offset = 0, length = 0; - // 1st segment - length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; - ret = HCI_LE_SetExtAdvDataCmd(adv_handle, - GAP_EXT_ADV_OP_FIRST_FRAG, //operation, - GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, - length, //advertising_data_length, - ¶->advData[offset]); - offset += length; + if (para->advDataLen > GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH) + { + // configure adv data fragment in several HCI commands + uint16 offset = 0, length = 0; + // 1st segment + length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; + ret = HCI_LE_SetExtAdvDataCmd(adv_handle, + GAP_EXT_ADV_OP_FIRST_FRAG, //operation, + GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, + length, //advertising_data_length, + ¶->advData[offset]); + offset += length; - // other segments - while (offset < para->advDataLen) - { - uint8 op = GAP_EXT_ADV_OP_INTERM_FRAG; + // other segments + while (offset < para->advDataLen) + { + uint8 op = GAP_EXT_ADV_OP_INTERM_FRAG; - if (offset + GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH < para->advDataLen) - length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; - else - { - length = para->advDataLen - offset; - op = GAP_EXT_ADV_OP_LAST_FRAG; - } + if (offset + GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH < para->advDataLen) + length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; + else + { + length = para->advDataLen - offset; + op = GAP_EXT_ADV_OP_LAST_FRAG; + } - ret = HCI_LE_SetExtAdvDataCmd(adv_handle, - op, //operation, - GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, - length, //advertising_data_length, - ¶->advData[offset]); - offset += length; - } - } - else - ret = HCI_LE_SetExtAdvDataCmd(adv_handle, - GAP_EXT_ADV_OP_COMPLETE_DATA, //operation, - GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, - para->advDataLen, //advertising_data_length, - para->advData); + ret = HCI_LE_SetExtAdvDataCmd(adv_handle, + op, //operation, + GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, + length, //advertising_data_length, + ¶->advData[offset]); + offset += length; + } + } + else + ret = HCI_LE_SetExtAdvDataCmd(adv_handle, + GAP_EXT_ADV_OP_COMPLETE_DATA, //operation, + GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, + para->advDataLen, //advertising_data_length, + para->advData); - if (ret != SUCCESS) - return ret; + if (ret != SUCCESS) + return ret; - if (para->scanRspLen > GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH) - { - uint16 offset = 0, length = 0; - length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; - ret = HCI_LE_SetExtScanRspDataCmd(adv_handle, - GAP_EXT_ADV_OP_FIRST_FRAG, //operation, - GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, - length, //advertising_data_length, - ¶->scanRspData[offset]); - offset += length; + if (para->scanRspLen > GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH) + { + uint16 offset = 0, length = 0; + length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; + ret = HCI_LE_SetExtScanRspDataCmd(adv_handle, + GAP_EXT_ADV_OP_FIRST_FRAG, //operation, + GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, + length, //advertising_data_length, + ¶->scanRspData[offset]); + offset += length; - // other segments - while (offset < para->scanRspLen) - { - uint8 op = GAP_EXT_ADV_OP_INTERM_FRAG; + // other segments + while (offset < para->scanRspLen) + { + uint8 op = GAP_EXT_ADV_OP_INTERM_FRAG; - if (offset + GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH < para->scanRspLen) - length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; - else - { - length = para->scanRspLen - offset; - op = GAP_EXT_ADV_OP_LAST_FRAG; - } + if (offset + GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH < para->scanRspLen) + length = GAP_EXT_ADV_DATA_MAX_FRAG_LENGTH; + else + { + length = para->scanRspLen - offset; + op = GAP_EXT_ADV_OP_LAST_FRAG; + } - ret = HCI_LE_SetExtScanRspDataCmd(adv_handle, - op, //operation, - GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, - length, //advertising_data_length, - ¶->scanRspData[offset]); - offset += length; - } - } - else - ret = HCI_LE_SetExtScanRspDataCmd(adv_handle, - GAP_EXT_ADV_OP_COMPLETE_DATA, // operation, - GAP_EXT_ADV_PREFER_FRAG, // fragment_preference, - para->scanRspLen, // scan_rsp_data_length, - para->scanRspData // scan_rsp_data - ); + ret = HCI_LE_SetExtScanRspDataCmd(adv_handle, + op, //operation, + GAP_EXT_ADV_PREFER_FRAG, //fragment_preference, + length, //advertising_data_length, + ¶->scanRspData[offset]); + offset += length; + } + } + else + ret = HCI_LE_SetExtScanRspDataCmd(adv_handle, + GAP_EXT_ADV_OP_COMPLETE_DATA, // operation, + GAP_EXT_ADV_PREFER_FRAG, // fragment_preference, + para->scanRspLen, // scan_rsp_data_length, + para->scanRspData // scan_rsp_data + ); - return ret; + return ret; } /********************************************************************* - @brief enable extended advertiser + @brief enable extended advertiser - @param adv_handle - advertising handler + @param adv_handle - advertising handler - @return enable success or the error code + @return enable success or the error code */ bStatus_t GAPRole_extAdv_EnableAdvSet(uint8 adv_handle) { - bStatus_t ret = GAPRole_extAdv_ConfigAdvSet(adv_handle); + bStatus_t ret = GAPRole_extAdv_ConfigAdvSet(adv_handle); - if(ret != SUCCESS) - return ret; + if(ret != SUCCESS) + return ret; - uint8 enable = TRUE; - gapAdvSetParameter_t* para; + uint8 enable = TRUE; + gapAdvSetParameter_t* para; - if (adv_handle < GAP_MAX_EXT_ADV_INSTANCE) - para = &advConfig[adv_handle]; - else - return FAILURE; + if (adv_handle < GAP_MAX_EXT_ADV_INSTANCE) + para = &advConfig[adv_handle]; + else + return FAILURE; - gapRole_ExtAdvEnabled[adv_handle] = TRUE; - gapRole_ExtAdvEnableHandle = adv_handle; - ret = HCI_LE_SetExtAdvEnableCmd(enable, - 1, - &adv_handle, - ¶->duration, - ¶->maxExtAdvEvents); - return ret; + gapRole_ExtAdvEnabled[adv_handle] = TRUE; + gapRole_ExtAdvEnableHandle = adv_handle; + ret = HCI_LE_SetExtAdvEnableCmd(enable, + 1, + &adv_handle, + ¶->duration, + ¶->maxExtAdvEvents); + return ret; } /********************************************************************* - @brief disable extended advertiser + @brief disable extended advertiser - @param adv_handle - advertising handler + @param adv_handle - advertising handler - @return enable success or the error code + @return enable success or the error code */ bStatus_t GAPRole_extAdv_DisableAdvSet(uint8 adv_handle) { - bStatus_t ret = SUCCESS; // return value - uint8 enable = FALSE; - uint16 duration = 0; - uint8 max_extended_advertising_events = 0; + bStatus_t ret = SUCCESS; // return value + uint8 enable = FALSE; + uint16 duration = 0; + uint8 max_extended_advertising_events = 0; - if (adv_handle >= GAP_MAX_EXT_ADV_INSTANCE) - return FAILURE; + if (adv_handle >= GAP_MAX_EXT_ADV_INSTANCE) + return FAILURE; - gapRole_ExtAdvEnabled[adv_handle] = FALSE; - gapRole_ExtAdvEnableHandle = adv_handle; - ret = HCI_LE_SetExtAdvEnableCmd(enable, - 1, - &adv_handle, - &duration, - &max_extended_advertising_events); - return ret; + gapRole_ExtAdvEnabled[adv_handle] = FALSE; + gapRole_ExtAdvEnableHandle = adv_handle; + ret = HCI_LE_SetExtAdvEnableCmd(enable, + 1, + &adv_handle, + &duration, + &max_extended_advertising_events); + return ret; } bStatus_t GAPRole_extAdv_SetRandomAddress(uint8 adv_handle, uint8* random_address) { - bStatus_t ret = SUCCESS; // return value + bStatus_t ret = SUCCESS; // return value - if (random_address == NULL) - return FAILURE; + if (random_address == NULL) + return FAILURE; - ret = HCI_LE_SetExtAdvSetRandomAddressCmd(adv_handle, random_address); - return ret; + ret = HCI_LE_SetExtAdvSetRandomAddressCmd(adv_handle, random_address); + return ret; } /********************************************************************* - @brief Remove advertiser set + @brief Remove advertiser set */ bStatus_t GAPRole_extAdv_RemoveAdvSet(uint8 adv_handle) { - bStatus_t ret = SUCCESS; + bStatus_t ret = SUCCESS; - if (adv_handle == GAP_ALL_ADV_SET) - ret = HCI_LE_ClearAdvSetsCmd(); - else - ret = HCI_LE_RemoveAdvSetCmd(adv_handle); + if (adv_handle == GAP_ALL_ADV_SET) + ret = HCI_LE_ClearAdvSetsCmd(); + else + ret = HCI_LE_RemoveAdvSetCmd(adv_handle); - return ret; + return ret; } /********************************************************************* - @brief Set a GAP extenede advertiser Manager parameter. + @brief Set a GAP extenede advertiser Manager parameter. */ bStatus_t GAPRole_extAdv_SetParameter(uint8 adv_handler, uint16 param, uint16 len, void* pValue) { - bStatus_t ret = SUCCESS; - gapAdvSetParameter_t* para; + bStatus_t ret = SUCCESS; + gapAdvSetParameter_t* para; - if (adv_handler < GAP_MAX_EXT_ADV_INSTANCE) - para = &advConfig[adv_handler]; - else - return FAILURE; + if (adv_handler < GAP_MAX_EXT_ADV_INSTANCE) + para = &advConfig[adv_handler]; + else + return FAILURE; - switch (param) - { - case GAP_ADV_SID: - if (len == 1) - para->advertisingSID = *(uint8*)pValue; - else - ret = bleInvalidRange; + switch (param) + { + case GAP_ADV_SID: + if (len == 1) + para->advertisingSID = *(uint8*)pValue; + else + ret = bleInvalidRange; - break; + break; - case GAP_ADV_EVENT_PROP: - if (len == 1) - para->advEventProperties = *(uint8*)pValue; - else - ret = bleInvalidRange; + case GAP_ADV_EVENT_PROP: + if (len == 1) + para->advEventProperties = *(uint8*)pValue; + else + ret = bleInvalidRange; - break; + break; - case GAP_PRI_CHN_ADV_INT_MIN: - if(len == sizeof ( uint32 )) - para->priAdvIntMin = *((uint32*)pValue); - else - ret = bleInvalidRange; + case GAP_PRI_CHN_ADV_INT_MIN: + if(len == sizeof ( uint32 )) + para->priAdvIntMin = *((uint32*)pValue); + else + ret = bleInvalidRange; - break; + break; - case GAP_PRI_CHN_ADV_INT_MAX: - if(len == sizeof ( uint32 )) - para->priAdvIntMax = *((uint32*)pValue); - else - ret = bleInvalidRange; + case GAP_PRI_CHN_ADV_INT_MAX: + if(len == sizeof ( uint32 )) + para->priAdvIntMax = *((uint32*)pValue); + else + ret = bleInvalidRange; - break; + break; - case GAP_EXT_ADV_DATA: - if (len <= GAP_MAX_EXT_ADV_DATA_LENGTH) - { - VOID osal_memset(para->advData, 0, GAP_MAX_EXT_ADV_DATA_LENGTH); - VOID osal_memcpy(para->advData, pValue, len); - para->advDataLen = len; - } - else - { - ret = bleInvalidRange; - } + case GAP_EXT_ADV_DATA: + if (len <= GAP_MAX_EXT_ADV_DATA_LENGTH) + { + VOID osal_memset(para->advData, 0, GAP_MAX_EXT_ADV_DATA_LENGTH); + VOID osal_memcpy(para->advData, pValue, len); + para->advDataLen = len; + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAP_EXT_SCAN_RSP_DATA: - if (len <= GAP_MAX_EXT_ADV_DATA_LENGTH) - { - VOID osal_memset(para->scanRspData, 0, GAP_MAX_EXT_ADV_DATA_LENGTH); - VOID osal_memcpy(para->scanRspData, pValue, len); - para->scanRspLen = len; - } - else - { - ret = bleInvalidRange; - } + case GAP_EXT_SCAN_RSP_DATA: + if (len <= GAP_MAX_EXT_ADV_DATA_LENGTH) + { + VOID osal_memset(para->scanRspData, 0, GAP_MAX_EXT_ADV_DATA_LENGTH); + VOID osal_memcpy(para->scanRspData, pValue, len); + para->scanRspLen = len; + } + else + { + ret = bleInvalidRange; + } - break; + break; - case GAP_PRI_ADV_PHY: - if (len == 1 && - (*(uint8*)pValue == GAP_ADV_PHY_1MBPS || - *(uint8*)pValue == GAP_ADV_PHY_CODED)) - para->primaryAdvPHY = *(uint8*)pValue; - else - ret = bleInvalidRange; + case GAP_PRI_ADV_PHY: + if (len == 1 && + (*(uint8*)pValue == GAP_ADV_PHY_1MBPS || + *(uint8*)pValue == GAP_ADV_PHY_CODED)) + para->primaryAdvPHY = *(uint8*)pValue; + else + ret = bleInvalidRange; - break; + break; - case GAP_SEC_ADV_PHY: - if (len == 1) - para->secondaryAdvPHY = *(uint8*)pValue; - else - ret = bleInvalidRange; + case GAP_SEC_ADV_PHY: + if (len == 1) + para->secondaryAdvPHY = *(uint8*)pValue; + else + ret = bleInvalidRange; - break; + break; - case GAP_PEER_ADDR_TYPE: - if (len == 1) - para->peerAddrType = *(uint8*)pValue; - else - ret = bleInvalidRange; + case GAP_PEER_ADDR_TYPE: + if (len == 1) + para->peerAddrType = *(uint8*)pValue; + else + ret = bleInvalidRange; - break; + break; - case GAP_PEER_ADDR: - if (len == 6) - osal_memcpy(para->peerAddress,pValue,6); - else - ret = bleInvalidRange; + case GAP_PEER_ADDR: + if (len == 6) + osal_memcpy(para->peerAddress,pValue,6); + else + ret = bleInvalidRange; - break; + break; - case GAP_OWN_ADDR_TYPE: - if (len == 1) - para->ownAddrType = *(uint8*)pValue; - else - ret = bleInvalidRange; + case GAP_OWN_ADDR_TYPE: + if (len == 1) + para->ownAddrType = *(uint8*)pValue; + else + ret = bleInvalidRange; - break; + break; - case GAP_OWN_RANDOM_ADDR: - if (len == 6) - osal_memcpy(&(gapRole_ExtAdv_RandomAddr[adv_handler][0]),pValue,6); - else - ret = bleInvalidRange; + case GAP_OWN_RANDOM_ADDR: + if (len == 6) + osal_memcpy(&(gapRole_ExtAdv_RandomAddr[adv_handler][0]),pValue,6); + else + ret = bleInvalidRange; - break; + break; - default: - ret = INVALIDPARAMETER; - break; - } + default: + ret = INVALIDPARAMETER; + break; + } - return (ret); + return (ret); } /********************************************************************* - @brief Get a GAP extenede advertiser Manager parameter. + @brief Get a GAP extenede advertiser Manager parameter. */ bStatus_t GAPRole_extAdv_GetParameter(uint8 adv_handler, uint16 param, void* pValue) { - bStatus_t ret = SUCCESS; // return value - gapAdvSetParameter_t* para; + bStatus_t ret = SUCCESS; // return value + gapAdvSetParameter_t* para; - if (adv_handler < GAP_MAX_EXT_ADV_INSTANCE) - para = &advConfig[adv_handler]; - else - return FAILURE; + if (adv_handler < GAP_MAX_EXT_ADV_INSTANCE) + para = &advConfig[adv_handler]; + else + return FAILURE; - VOID para; - return ret; + VOID para; + return ret; } /********************************************************************* - Local Functions implementation + Local Functions implementation */ static void gapExtAdvParameterInit(gapAdvSetParameter_t* p) { - osal_memset(p, 0, sizeof(gapAdvSetParameter_t)); - p->advEventProperties = LE_ADV_PROP_CONN_BITMASK; - p->priAdvIntMax = 640; // 400ms - p->priAdvIntMin = 320; // 200ms - p->primaryAdvPHY = 1; - p->secondaryAdvPHY = 1; //1; - p->priAdvChnMap = 0x07; - p->advTxPower = 127; - p->ownAddrType = 0; - p->peerAddrType = 0; - p->wlPolicy = 0; - p->secondaryAdvMaxSkip = 0; - p->scanReqNotificationEnable = FALSE; - p->advertisingSID = 0; - p->advDataLen = 0; - p->advData = &advertisingData[p->advHandle][0]; - p->scanRspLen = 0; - p->scanRspData = &extScanRspData[p->advHandle][0]; - // adv set enable parameters - p->duration = 0; - p->maxExtAdvEvents = 0; + osal_memset(p, 0, sizeof(gapAdvSetParameter_t)); + p->advEventProperties = LE_ADV_PROP_CONN_BITMASK; + p->priAdvIntMax = 640; // 400ms + p->priAdvIntMin = 320; // 200ms + p->primaryAdvPHY = 1; + p->secondaryAdvPHY = 1; //1; + p->priAdvChnMap = 0x07; + p->advTxPower = 127; + p->ownAddrType = 0; + p->peerAddrType = 0; + p->wlPolicy = 0; + p->secondaryAdvMaxSkip = 0; + p->scanReqNotificationEnable = FALSE; + p->advertisingSID = 0; + p->advDataLen = 0; + p->advData = &advertisingData[p->advHandle][0]; + p->scanRspLen = 0; + p->scanRspData = &extScanRspData[p->advHandle][0]; + // adv set enable parameters + p->duration = 0; + p->maxExtAdvEvents = 0; } extern llStatus_t LL_InitialExtendedAdv(extAdvInfo_t* extAdvInfo, - uint8 extAdvSetNumber, - uint16 advSetMaxLen); + uint8 extAdvSetNumber, + uint16 advSetMaxLen); static void gapInitExtAdvertiser(void) { - int i; + int i; - // init advertisement data buffer - for (i = 0; i < GAP_MAX_EXT_ADV_INSTANCE; i++) - { - extAdvInfo[i].data.advertisingData = NULL; - } + // init advertisement data buffer + for (i = 0; i < GAP_MAX_EXT_ADV_INSTANCE; i++) + { + extAdvInfo[i].data.advertisingData = NULL; + } - for (i = 0; i < GAP_MAX_EXT_ADV_INSTANCE; i++) - { - extAdvInfo[i].data.advertisingData = &advertisingData[i][0]; - extAdvInfo[i].scanRspData = &extScanRspData[i][0]; - } + for (i = 0; i < GAP_MAX_EXT_ADV_INSTANCE; i++) + { + extAdvInfo[i].data.advertisingData = &advertisingData[i][0]; + extAdvInfo[i].scanRspData = &extScanRspData[i][0]; + } - // init LL extended global variables - LL_InitialExtendedAdv(extAdvInfo, GAP_MAX_EXT_ADV_INSTANCE, GAP_MAX_EXT_ADV_DATA_LENGTH); + // init LL extended global variables + LL_InitialExtendedAdv(extAdvInfo, GAP_MAX_EXT_ADV_INSTANCE, GAP_MAX_EXT_ADV_DATA_LENGTH); } #endif -/********************************************************************* -*********************************************************************/ diff --git a/bthome_phy6222/source/thb2_peripheral.h b/bthome_phy6222/source/thb2_peripheral.h index c8ca359..70b3d65 100644 --- a/bthome_phy6222/source/thb2_peripheral.h +++ b/bthome_phy6222/source/thb2_peripheral.h @@ -1,45 +1,9 @@ -/************************************************************************************************** - - Phyplus Microelectronics Limited confidential and proprietary. - All rights reserved. - - IMPORTANT: All rights of this software belong to Phyplus Microelectronics - Limited ("Phyplus"). Your use of this Software is limited to those - specific rights granted under the terms of the business contract, the - confidential agreement, the non-disclosure agreement and any other forms - of agreements as a customer or a partner of Phyplus. You may not use this - Software unless you agree to abide by the terms of these agreements. - You acknowledge that the Software may not be modified, copied, - distributed or disclosed unless embedded on a Phyplus Bluetooth Low Energy - (BLE) integrated circuit, either as a product or is integrated into your - products. Other than for the aforementioned purposes, you may not use, - reproduce, copy, prepare derivative works of, modify, distribute, perform, - display or sell this Software and/or its documentation for any purposes. - - YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE - PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, - INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, - NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL - PHYPLUS OR ITS SUBSIDIARIES BE LIABLE OR OBLIGATED UNDER CONTRACT, - NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER - LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES - INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE - OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT - OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES - (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. - -**************************************************************************************************/ - /** - @headerfile: peripheral.h - $Date: - $Revision: - - - - This GAP profile advertises and allows connections. - + @headerfile: peripheral.h + $Date: + $Revision: + This GAP profile advertises and allows connections. */ #ifndef PERIPHERAL_H @@ -51,286 +15,286 @@ extern "C" { #endif -/* ------------------------------------------------------------------- - INCLUDES +/* ------------------------------------------------------------------- + INCLUDES */ -/* ------------------------------------------------------------------- - CONSTANTS +/* ------------------------------------------------------------------- + CONSTANTS */ /** @defgroup GAPROLE_PROFILE_PARAMETERS GAP Role Parameters - @{ + @{ */ -#define GAPROLE_PROFILEROLE 0x300 //!< Reading this parameter will return GAP Role type. Read Only. Size is uint8. -#define GAPROLE_IRK 0x301 //!< Identity Resolving Key. Read/Write. Size is uint8[KEYLEN]. Default is all 0, which means that the IRK will be randomly generated. -#define GAPROLE_SRK 0x302 //!< Signature Resolving Key. Read/Write. Size is uint8[KEYLEN]. Default is all 0, which means that the SRK will be randomly generated. -#define GAPROLE_SIGNCOUNTER 0x303 //!< Sign Counter. Read/Write. Size is uint32. Default is 0. -#define GAPROLE_BD_ADDR 0x304 //!< Device's Address. Read Only. Size is uint8[B_ADDR_LEN]. This item is read from the controller. -#define GAPROLE_ADVERT_ENABLED 0x305 //!< Enable/Disable Advertising. Read/Write. Size is uint8. Default is TRUE=Enabled. -#define GAPROLE_ADVERT_OFF_TIME 0x306 //!< Advertising Off Time for Limited advertisements (in milliseconds). Read/Write. Size is uint16. Default is 30 seconds. -#define GAPROLE_ADVERT_DATA 0x307 //!< Advertisement Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Default is "02:01:01", which means that it is a Limited Discoverable Advertisement. -#define GAPROLE_SCAN_RSP_DATA 0x308 //!< Scan Response Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Defaults to all 0. -#define GAPROLE_ADV_EVENT_TYPE 0x309 //!< Advertisement Type. Read/Write. Size is uint8. Default is GAP_ADTYPE_ADV_IND (defined in GAP.h). -#define GAPROLE_ADV_DIRECT_TYPE 0x30A //!< Direct Advertisement Address Type. Read/Write. Size is uint8. Default is ADDRTYPE_PUBLIC (defined in GAP.h). -#define GAPROLE_ADV_DIRECT_ADDR 0x30B //!< Direct Advertisement Address. Read/Write. Size is uint8[B_ADDR_LEN]. Default is NULL. -#define GAPROLE_ADV_CHANNEL_MAP 0x30C //!< Which channels to advertise on. Read/Write Size is uint8. Default is GAP_ADVCHAN_ALL (defined in GAP.h) -#define GAPROLE_ADV_FILTER_POLICY 0x30D //!< Filter Policy. Ignored when directed advertising is used. Read/Write. Size is uint8. Default is GAP_FILTER_POLICY_ALL (defined in GAP.h). -#define GAPROLE_CONNHANDLE 0x30E //!< Connection Handle. Read Only. Size is uint16. -#define GAPROLE_RSSI_READ_RATE 0x30F //!< How often to read the RSSI during a connection. Read/Write. Size is uint16. The value is in milliseconds. Default is 0 = OFF. +#define GAPROLE_PROFILEROLE 0x300 //!< Reading this parameter will return GAP Role type. Read Only. Size is uint8. +#define GAPROLE_IRK 0x301 //!< Identity Resolving Key. Read/Write. Size is uint8[KEYLEN]. Default is all 0, which means that the IRK will be randomly generated. +#define GAPROLE_SRK 0x302 //!< Signature Resolving Key. Read/Write. Size is uint8[KEYLEN]. Default is all 0, which means that the SRK will be randomly generated. +#define GAPROLE_SIGNCOUNTER 0x303 //!< Sign Counter. Read/Write. Size is uint32. Default is 0. +#define GAPROLE_BD_ADDR 0x304 //!< Device's Address. Read Only. Size is uint8[B_ADDR_LEN]. This item is read from the controller. +#define GAPROLE_ADVERT_ENABLED 0x305 //!< Enable/Disable Advertising. Read/Write. Size is uint8. Default is TRUE=Enabled. +#define GAPROLE_ADVERT_OFF_TIME 0x306 //!< Advertising Off Time for Limited advertisements (in milliseconds). Read/Write. Size is uint16. Default is 30 seconds. +#define GAPROLE_ADVERT_DATA 0x307 //!< Advertisement Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Default is "02:01:01", which means that it is a Limited Discoverable Advertisement. +#define GAPROLE_SCAN_RSP_DATA 0x308 //!< Scan Response Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Defaults to all 0. +#define GAPROLE_ADV_EVENT_TYPE 0x309 //!< Advertisement Type. Read/Write. Size is uint8. Default is GAP_ADTYPE_ADV_IND (defined in GAP.h). +#define GAPROLE_ADV_DIRECT_TYPE 0x30A //!< Direct Advertisement Address Type. Read/Write. Size is uint8. Default is ADDRTYPE_PUBLIC (defined in GAP.h). +#define GAPROLE_ADV_DIRECT_ADDR 0x30B //!< Direct Advertisement Address. Read/Write. Size is uint8[B_ADDR_LEN]. Default is NULL. +#define GAPROLE_ADV_CHANNEL_MAP 0x30C //!< Which channels to advertise on. Read/Write Size is uint8. Default is GAP_ADVCHAN_ALL (defined in GAP.h) +#define GAPROLE_ADV_FILTER_POLICY 0x30D //!< Filter Policy. Ignored when directed advertising is used. Read/Write. Size is uint8. Default is GAP_FILTER_POLICY_ALL (defined in GAP.h). +#define GAPROLE_CONNHANDLE 0x30E //!< Connection Handle. Read Only. Size is uint16. +#define GAPROLE_RSSI_READ_RATE 0x30F //!< How often to read the RSSI during a connection. Read/Write. Size is uint16. The value is in milliseconds. Default is 0 = OFF. #define GAPROLE_PARAM_UPDATE_ENABLE 0x310 //!< Slave Connection Parameter Update Enable. Read/Write. Size is uint8. If TRUE then automatic connection parameter update request is sent. Default is FALSE. -#define GAPROLE_MIN_CONN_INTERVAL 0x311 //!< Minimum Connection Interval to allow (n * 1.25ms). Range: 7.5 msec to 4 seconds (0x0006 to 0x0C80). Read/Write. Size is uint16. Default is 7.5 milliseconds (0x0006). -#define GAPROLE_MAX_CONN_INTERVAL 0x312 //!< Maximum Connection Interval to allow (n * 1.25ms). Range: 7.5 msec to 4 seconds (0x0006 to 0x0C80). Read/Write. Size is uint16. Default is 4 seconds (0x0C80). -#define GAPROLE_SLAVE_LATENCY 0x313 //!< Update Parameter Slave Latency. Range: 0 - 499. Read/Write. Size is uint16. Default is 0. -#define GAPROLE_TIMEOUT_MULTIPLIER 0x314 //!< Update Parameter Timeout Multiplier (n * 10ms). Range: 100ms to 32 seconds (0x000a - 0x0c80). Read/Write. Size is uint16. Default is 1000. -#define GAPROLE_CONN_BD_ADDR 0x315 //!< Address of connected device. Read only. Size is uint8[B_MAX_ADV_LEN]. Set to all zeros when not connected. -#define GAPROLE_CONN_INTERVAL 0x316 //!< Current connection interval. Read only. Size is uint16. Range is 7.5ms to 4 seconds (0x0006 to 0x0C80). Default is 0 (no connection). -#define GAPROLE_CONN_LATENCY 0x317 //!< Current slave latency. Read only. Size is uint16. Range is 0 to 499. Default is 0 (no slave latency or no connection). -#define GAPROLE_CONN_TIMEOUT 0x318 //!< Current timeout value. Read only. size is uint16. Range is 100ms to 32 seconds. Default is 0 (no connection). -#define GAPROLE_PARAM_UPDATE_REQ 0x319 //!< Slave Connection Parameter Update Request. Write. Size is uint8. If TRUE then connection parameter update request is sent. -#define GAPROLE_STATE 0x31A //!< Reading this parameter will return GAP Peripheral Role State. Read Only. Size is uint8. +#define GAPROLE_MIN_CONN_INTERVAL 0x311 //!< Minimum Connection Interval to allow (n * 1.25ms). Range: 7.5 msec to 4 seconds (0x0006 to 0x0C80). Read/Write. Size is uint16. Default is 7.5 milliseconds (0x0006). +#define GAPROLE_MAX_CONN_INTERVAL 0x312 //!< Maximum Connection Interval to allow (n * 1.25ms). Range: 7.5 msec to 4 seconds (0x0006 to 0x0C80). Read/Write. Size is uint16. Default is 4 seconds (0x0C80). +#define GAPROLE_SLAVE_LATENCY 0x313 //!< Update Parameter Slave Latency. Range: 0 - 499. Read/Write. Size is uint16. Default is 0. +#define GAPROLE_TIMEOUT_MULTIPLIER 0x314 //!< Update Parameter Timeout Multiplier (n * 10ms). Range: 100ms to 32 seconds (0x000a - 0x0c80). Read/Write. Size is uint16. Default is 1000. +#define GAPROLE_CONN_BD_ADDR 0x315 //!< Address of connected device. Read only. Size is uint8[B_MAX_ADV_LEN]. Set to all zeros when not connected. +#define GAPROLE_CONN_INTERVAL 0x316 //!< Current connection interval. Read only. Size is uint16. Range is 7.5ms to 4 seconds (0x0006 to 0x0C80). Default is 0 (no connection). +#define GAPROLE_CONN_LATENCY 0x317 //!< Current slave latency. Read only. Size is uint16. Range is 0 to 499. Default is 0 (no slave latency or no connection). +#define GAPROLE_CONN_TIMEOUT 0x318 //!< Current timeout value. Read only. size is uint16. Range is 100ms to 32 seconds. Default is 0 (no connection). +#define GAPROLE_PARAM_UPDATE_REQ 0x319 //!< Slave Connection Parameter Update Request. Write. Size is uint8. If TRUE then connection parameter update request is sent. +#define GAPROLE_STATE 0x31A //!< Reading this parameter will return GAP Peripheral Role State. Read Only. Size is uint8. -#define GAPROLE_CONNECTION_INTERVAL 0x31B +#define GAPROLE_CONNECTION_INTERVAL 0x31B #define GAPROLE_CONNECTION_LATENCY 0x31C /** @} End GAPROLE_PROFILE_PARAMETERS */ -#define GAP_EXTADV_PROP_NONCONN_NONSCAN 0 -#define GAP_EXTADV_PROP_CONNECTABLE_NONSCAN 0x1 -#define GAP_EXTADV_PROP_NONCONN_SCANNABLE 0x2 -#define GAP_EXTADV_PROP_LDC_CONNECTABLE 0x5 -#define GAP_EXTADV_PROP_LEGACY_ADV_IND LL_EXT_ADV_PROP_ADV_IND -#define GAP_EXTADV_PROP_LEGACY_LDC_ADV LL_EXT_ADV_PROP_ADV_LDC_ADV -#define GAP_EXTADV_PROP_LEGACY_HDC_ADV LL_EXT_ADV_PROP_ADV_HDC_ADV -#define GAP_EXTADV_PROP_LEGACY_SCAN_IND LL_EXT_ADV_PROP_ADV_SCAN_IND -#define GAP_EXTADV_PROP_LEGACY_NOCONN_IND LL_EXT_ADV_PROP_ADV_NOCONN_IND +#define GAP_EXTADV_PROP_NONCONN_NONSCAN 0 +#define GAP_EXTADV_PROP_CONNECTABLE_NONSCAN 0x1 +#define GAP_EXTADV_PROP_NONCONN_SCANNABLE 0x2 +#define GAP_EXTADV_PROP_LDC_CONNECTABLE 0x5 +#define GAP_EXTADV_PROP_LEGACY_ADV_IND LL_EXT_ADV_PROP_ADV_IND +#define GAP_EXTADV_PROP_LEGACY_LDC_ADV LL_EXT_ADV_PROP_ADV_LDC_ADV +#define GAP_EXTADV_PROP_LEGACY_HDC_ADV LL_EXT_ADV_PROP_ADV_HDC_ADV +#define GAP_EXTADV_PROP_LEGACY_SCAN_IND LL_EXT_ADV_PROP_ADV_SCAN_IND +#define GAP_EXTADV_PROP_LEGACY_NOCONN_IND LL_EXT_ADV_PROP_ADV_NOCONN_IND typedef enum { - GAP_ADV_SET_CFG_START = 0x350, - GAP_ADV_SID = 0x350, - GAP_ADV_EVENT_PROP, - GAP_PRI_CHN_ADV_INT_MIN, - GAP_PRI_CHN_ADV_INT_MAX, - GAP_PRI_CHN_ADV_CHNMAP, - GAP_OWN_ADDR_TYPE, - GAP_OWN_RANDOM_ADDR, - GAP_PEER_ADDR_TYPE, - GAP_PEER_ADDR, - GAP_WL_POLICY, - GAP_PRI_ADV_PHY, - GAP_SEC_ADV_PHY, - GAP_SEC_ADV_MAX_SKIP, - GAP_SCANREQ_NOTI_ENABLE, - GAP_EXT_ADV_DURATION, - GAP_EXT_ADV_MAX_EVT, - GAP_EXT_ADV_TX_PWR, - GAP_EXT_ADV_DATA, - GAP_EXT_SCAN_RSP_DATA, - GAP_ADV_SET_MAX_ENUM + GAP_ADV_SET_CFG_START = 0x350, + GAP_ADV_SID = 0x350, + GAP_ADV_EVENT_PROP, + GAP_PRI_CHN_ADV_INT_MIN, + GAP_PRI_CHN_ADV_INT_MAX, + GAP_PRI_CHN_ADV_CHNMAP, + GAP_OWN_ADDR_TYPE, + GAP_OWN_RANDOM_ADDR, + GAP_PEER_ADDR_TYPE, + GAP_PEER_ADDR, + GAP_WL_POLICY, + GAP_PRI_ADV_PHY, + GAP_SEC_ADV_PHY, + GAP_SEC_ADV_MAX_SKIP, + GAP_SCANREQ_NOTI_ENABLE, + GAP_EXT_ADV_DURATION, + GAP_EXT_ADV_MAX_EVT, + GAP_EXT_ADV_TX_PWR, + GAP_EXT_ADV_DATA, + GAP_EXT_SCAN_RSP_DATA, + GAP_ADV_SET_MAX_ENUM } GAP_AdvSetConfig_e; typedef enum { - GAP_ADV_PHY_NONE = 0x00, // applicable to secondary PHY conf only - GAP_ADV_PHY_1MBPS = 0x01, // applicable to both primary & secondary PHY conf - GAP_ADV_PHY_2MBPS = 0x02, // applicable to secondary PHY conf only - GAP_ADV_PHY_CODED = 0x03 // applicable to both primary & secondary PHY conf + GAP_ADV_PHY_NONE = 0x00, // applicable to secondary PHY conf only + GAP_ADV_PHY_1MBPS = 0x01, // applicable to both primary & secondary PHY conf + GAP_ADV_PHY_2MBPS = 0x02, // applicable to secondary PHY conf only + GAP_ADV_PHY_CODED = 0x03 // applicable to both primary & secondary PHY conf } GAP_ExtAdv_PHY_e; -/* ------------------------------------------------------------------- - TYPEDEFS +/* ------------------------------------------------------------------- + TYPEDEFS */ /** - GAP Peripheral Role States. + GAP Peripheral Role States. */ typedef enum { - GAPROLE_INIT = 0, //!< Waiting to be started - GAPROLE_STARTED, //!< Started but not advertising - GAPROLE_ADVERTISING, //!< Currently Advertising - GAPROLE_WAITING, //!< Device is started but not advertising, is in waiting period before advertising again - GAPROLE_WAITING_AFTER_TIMEOUT, //!< Device just timed out from a connection but is not yet advertising, is in waiting period before advertising again - GAPROLE_CONNECTED, //!< In a connection - GAPROLE_CONNECTED_ADV, //!< In a connection + advertising - GAPROLE_ERROR //!< Error occurred - invalid state + GAPROLE_INIT = 0, //!< Waiting to be started + GAPROLE_STARTED, //!< Started but not advertising + GAPROLE_ADVERTISING, //!< Currently Advertising + GAPROLE_WAITING, //!< Device is started but not advertising, is in waiting period before advertising again + GAPROLE_WAITING_AFTER_TIMEOUT, //!< Device just timed out from a connection but is not yet advertising, is in waiting period before advertising again + GAPROLE_CONNECTED, //!< In a connection + GAPROLE_CONNECTED_ADV, //!< In a connection + advertising + GAPROLE_ERROR //!< Error occurred - invalid state } gaprole_States_t; /** - Possible actions the peripheral device may take if an unsuccessful parameter - update is received. + Possible actions the peripheral device may take if an unsuccessful parameter + update is received. - Parameters for GAPRole_SendUpdateParam() only + Parameters for GAPRole_SendUpdateParam() only */ -#define GAPROLE_NO_ACTION 0 // Take no action upon unsuccessful parameter updates -#define GAPROLE_RESEND_PARAM_UPDATE 1 // Continue to resend request until successful update -#define GAPROLE_TERMINATE_LINK 2 // Terminate link upon unsuccessful parameter updates +#define GAPROLE_NO_ACTION 0 // Take no action upon unsuccessful parameter updates +#define GAPROLE_RESEND_PARAM_UPDATE 1 // Continue to resend request until successful update +#define GAPROLE_TERMINATE_LINK 2 // Terminate link upon unsuccessful parameter updates -/* ------------------------------------------------------------------- - MACROS +/* ------------------------------------------------------------------- + MACROS */ -/* ------------------------------------------------------------------- - Profile Callbacks +/* ------------------------------------------------------------------- + Profile Callbacks */ /** - Callback when the connection parameteres are updated. + Callback when the connection parameteres are updated. */ typedef void (*gapRolesParamUpdateCB_t)( uint16 connInterval, - uint16 connSlaveLatency, - uint16 connTimeout ); + uint16 connSlaveLatency, + uint16 connTimeout ); /** - Callback when the device has been started. Callback event to - the Notify of a state change. + Callback when the device has been started. Callback event to + the Notify of a state change. */ typedef void (*gapRolesStateNotify_t)( gaprole_States_t newState ); /** - Callback when the device has read an new RSSI value during a connection. + Callback when the device has read an new RSSI value during a connection. */ typedef void (*gapRolesRssiRead_t)( int8 newRSSI ); /** - Callback structure - must be setup by the application and used when gapRoles_StartDevice() is called. + Callback structure - must be setup by the application and used when gapRoles_StartDevice() is called. */ typedef struct { - gapRolesStateNotify_t pfnStateChange; //!< Whenever the device changes state - gapRolesRssiRead_t pfnRssiRead; //!< When a valid RSSI is read from controller + gapRolesStateNotify_t pfnStateChange; //!< Whenever the device changes state + gapRolesRssiRead_t pfnRssiRead; //!< When a valid RSSI is read from controller } gapRolesCBs_t; -/* ------------------------------------------------------------------- - API FUNCTIONS +/* ------------------------------------------------------------------- + API FUNCTIONS */ /** - @defgroup GAPROLES_PERIPHERAL_API GAP Peripheral Role API Functions + @defgroup GAPROLES_PERIPHERAL_API GAP Peripheral Role API Functions - @{ + @{ */ /** - @brief Set a GAP Role parameter. + @brief Set a GAP Role parameter. - NOTE: You can call this function with a GAP Parameter ID and it will set the - GAP Parameter. GAP Parameters are defined in (gap.h). Also, - the "len" field must be set to the size of a "uint16" and the - "pValue" field must point to a "uint16". + NOTE: You can call this function with a GAP Parameter ID and it will set the + GAP Parameter. GAP Parameters are defined in (gap.h). Also, + the "len" field must be set to the size of a "uint16" and the + "pValue" field must point to a "uint16". - @param param - Profile parameter ID: @ref GAPROLE_PROFILE_PARAMETERS - @param len - length of data to write - @param pValue - pointer to data to write. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + @param param - Profile parameter ID: @ref GAPROLE_PROFILE_PARAMETERS + @param len - length of data to write + @param pValue - pointer to data to write. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). - @return SUCCESS or INVALIDPARAMETER (invalid paramID) + @return SUCCESS or INVALIDPARAMETER (invalid paramID) */ extern bStatus_t GAPRole_SetParameter( uint16 param, uint8 len, void* pValue ); /** - @brief Get a GAP Role parameter. + @brief Get a GAP Role parameter. - NOTE: You can call this function with a GAP Parameter ID and it will get a - GAP Parameter. GAP Parameters are defined in (gap.h). Also, the - "pValue" field must point to a "uint16". + NOTE: You can call this function with a GAP Parameter ID and it will get a + GAP Parameter. GAP Parameters are defined in (gap.h). Also, the + "pValue" field must point to a "uint16". - @param param - Profile parameter ID: @ref GAPROLE_PROFILE_PARAMETERS - @param pValue - pointer to location to get the value. This is dependent on - the parameter ID and WILL be cast to the appropriate - data type (example: data type of uint16 will be cast to - uint16 pointer). + @param param - Profile parameter ID: @ref GAPROLE_PROFILE_PARAMETERS + @param pValue - pointer to location to get the value. This is dependent on + the parameter ID and WILL be cast to the appropriate + data type (example: data type of uint16 will be cast to + uint16 pointer). - @return SUCCESS or INVALIDPARAMETER (invalid paramID) + @return SUCCESS or INVALIDPARAMETER (invalid paramID) */ extern bStatus_t GAPRole_GetParameter( uint16 param, void* pValue ); /** - @brief Does the device initialization. Only call this function once. + @brief Does the device initialization. Only call this function once. - @param pAppCallbacks - pointer to application callbacks. + @param pAppCallbacks - pointer to application callbacks. - @return SUCCESS or bleAlreadyInRequestedMode + @return SUCCESS or bleAlreadyInRequestedMode */ extern bStatus_t GAPRole_StartDevice( gapRolesCBs_t* pAppCallbacks ); /** - @brief Terminates the existing connection. + @brief Terminates the existing connection. - @return SUCCESS or bleIncorrectMode + @return SUCCESS or bleIncorrectMode */ extern bStatus_t GAPRole_TerminateConnection( void ); /** - @brief Update the parameters of an existing connection + @brief Update the parameters of an existing connection - @param connInterval - the new connection interval - @param latency - the new slave latency - @param connTimeout - the new timeout value - @param handleFailure - what to do if the update does not occur. - Method may choose to terminate connection, try again, or take no action + @param connInterval - the new connection interval + @param latency - the new slave latency + @param connTimeout - the new timeout value + @param handleFailure - what to do if the update does not occur. + Method may choose to terminate connection, try again, or take no action - @return SUCCESS, bleNotConnected or bleInvalidRange + @return SUCCESS, bleNotConnected or bleInvalidRange */ extern bStatus_t GAPRole_SendUpdateParam( uint16 minConnInterval, uint16 maxConnInterval, - uint16 latency, uint16 connTimeout, uint8 handleFailure ); + uint16 latency, uint16 connTimeout, uint8 handleFailure ); /** - @brief Register application's callbacks. + @brief Register application's callbacks. - @param pParamUpdateCB - pointer to param update callback. + @param pParamUpdateCB - pointer to param update callback. - @return none + @return none */ extern void GAPRole_RegisterAppCBs( gapRolesParamUpdateCB_t* pParamUpdateCB ); /** - @} End GAPROLES_PERIPHERAL_API + @} End GAPROLES_PERIPHERAL_API */ -/* ------------------------------------------------------------------- - TASK FUNCTIONS - Don't call these. These are system functions. +/* ------------------------------------------------------------------- + TASK FUNCTIONS - Don't call these. These are system functions. */ /** - @internal + @internal - @brief Initialization function for the GAP Role Task. - This is called during initialization and should contain - any application specific initialization (ie. hardware - initialization/setup, table initialization, power up - notificaiton ... ). + @brief Initialization function for the GAP Role Task. + This is called during initialization and should contain + any application specific initialization (ie. hardware + initialization/setup, table initialization, power up + notificaiton ... ). - @param the ID assigned by OSAL. This ID should be - used to send messages and set timers. + @param the ID assigned by OSAL. This ID should be + used to send messages and set timers. - @return void + @return void */ extern void GAPRole_Init( uint8 task_id ); /** - @internal + @internal - @brief GAP Role Task event processor. - This function is called to process all events for the task. - Events include timers, messages and any other user defined - events. + @brief GAP Role Task event processor. + This function is called to process all events for the task. + Events include timers, messages and any other user defined + events. - @param task_id - The OSAL assigned task ID. - @param events - events to process. This is a bit map and can - contain more than one event. + @param task_id - The OSAL assigned task ID. + @param events - events to process. This is a bit map and can + contain more than one event. - @return events not processed + @return events not processed */ extern uint16 GAPRole_ProcessEvent( uint8 task_id, uint16 events ); -/* ------------------------------------------------------------------- - -------------------------------------------------------------------*/ +/* ------------------------------------------------------------------- + -------------------------------------------------------------------*/ extern bStatus_t GAPRole_extAdv_ConfigAdvSet( uint8 adv_handle ); extern bStatus_t GAPRole_extAdv_EnableAdvSet( uint8 adv_handle ); @@ -342,10 +306,10 @@ extern bStatus_t GAPRole_extAdv_GetParameter( uint8 adv_handler, uint16 param, v // Profile Events -#define START_ADVERTISING_EVT 0x0001 // Start Advertising -#define RSSI_READ_EVT 0x0002 // Read RSSI -#define START_CONN_UPDATE_EVT 0x0004 // Start Connection Update Procedure -#define CONN_PARAM_TIMEOUT_EVT 0x0008 // Connection Parameters Update Timeout +#define START_ADVERTISING_EVT 0x0001 // Start Advertising +#define RSSI_READ_EVT 0x0002 // Read RSSI +#define START_CONN_UPDATE_EVT 0x0004 // Start Connection Update Procedure +#define CONN_PARAM_TIMEOUT_EVT 0x0008 // Connection Parameters Update Timeout extern uint8 gapRole_AdvEnabled; extern uint8 gapRole_AdvertData[B_MAX_ADV_LEN]; diff --git a/bthome_phy6222/source/thservice.c b/bthome_phy6222/source/thservice.c index 247c555..ebbd0d9 100644 --- a/bthome_phy6222/source/thservice.c +++ b/bthome_phy6222/source/thservice.c @@ -1,11 +1,9 @@ /************************************************************************************************** -******* + thservice.c **************************************************************************************************/ - - /********************************************************************* - INCLUDES + INCLUDES */ #include "bcomdef.h" #include "types.h" @@ -22,60 +20,60 @@ #include "thservice.h" #include "sensor.h" /********************************************************************* - MACROS + MACROS */ /********************************************************************* - CONSTANTS + CONSTANTS */ -#define TEMP_LEVEL_VALUE_IDX 2 // Position of temp level in attribute array -#define TEMP_LEVEL_VALUE_CCCD_IDX 3 // Position of temp level CCCD in attribute array -#define HUMI_LEVEL_VALUE_IDX 5 // Position of humi level in attribute array -#define HUMI_LEVEL_VALUE_CCCD_IDX 6 // Position of humi level CCCD in attribute array +#define TEMP_LEVEL_VALUE_IDX 2 // Position of temp level in attribute array +#define TEMP_LEVEL_VALUE_CCCD_IDX 3 // Position of temp level CCCD in attribute array +#define HUMI_LEVEL_VALUE_IDX 5 // Position of humi level in attribute array +#define HUMI_LEVEL_VALUE_CCCD_IDX 6 // Position of humi level CCCD in attribute array /********************************************************************* - TYPEDEFS + TYPEDEFS */ /********************************************************************* - GLOBAL VARIABLES + GLOBAL VARIABLES */ // Battery service CONST uint8 temphumServUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(ENV_SENSING_SERV_UUID), HI_UINT16(ENV_SENSING_SERV_UUID) + LO_UINT16(ENV_SENSING_SERV_UUID), HI_UINT16(ENV_SENSING_SERV_UUID) }; // Temperatyre level characteristic CONST uint8 tempLevelUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(TEMPERATYRE_UUID), HI_UINT16(TEMPERATYRE_UUID) + LO_UINT16(TEMPERATYRE_UUID), HI_UINT16(TEMPERATYRE_UUID) }; // Humidity level characteristic CONST uint8 humiLevelUUID[ATT_BT_UUID_SIZE] = { - LO_UINT16(HUMIDITY_UUID), HI_UINT16(HUMIDITY_UUID) + LO_UINT16(HUMIDITY_UUID), HI_UINT16(HUMIDITY_UUID) }; /********************************************************************* - EXTERNAL VARIABLES + EXTERNAL VARIABLES */ /********************************************************************* - EXTERNAL FUNCTIONS + EXTERNAL FUNCTIONS */ /********************************************************************* - LOCAL VARIABLES + LOCAL VARIABLES */ // Application callback static thServiceCB_t thServiceCB; /********************************************************************* - Profile Attributes - variables + Profile Attributes - variables */ // TH Service attribute @@ -89,305 +87,302 @@ static gattCharCfg_t humiLevelClientCharCfg[GATT_MAX_NUM_CONN]; /********************************************************************* - Profile Attributes - Table + Profile Attributes - Table */ static gattAttribute_t thAttrTbl[] = { - // 0 TH Service - { - { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ - GATT_PERMIT_READ, /* permissions */ - 0, /* handle */ - (uint8*)& thService /* pValue */ - }, + // 0 TH Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8*)& thService /* pValue */ + }, - // 1 Temp Level Declaration - { - { ATT_BT_UUID_SIZE, characterUUID }, - GATT_PERMIT_READ, - 0, - &thProps - }, + // 1 Temp Level Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &thProps + }, - // 2 Temp Level Value - { - { ATT_BT_UUID_SIZE, tempLevelUUID }, - GATT_PERMIT_READ, - 0, - (uint8_t*)&measured_data.temp - }, + // 2 Temp Level Value + { + { ATT_BT_UUID_SIZE, tempLevelUUID }, + GATT_PERMIT_READ, + 0, + (uint8_t*)&measured_data.temp + }, - // 3 Temp Level Client Characteristic Configuration - { - { ATT_BT_UUID_SIZE, clientCharCfgUUID }, - GATT_PERMIT_READ | GATT_PERMIT_WRITE, - 0, - (uint8*)& tempLevelClientCharCfg - }, + // 3 Temp Level Client Characteristic Configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8*)& tempLevelClientCharCfg + }, - // 4 Humi Level Declaration - { - { ATT_BT_UUID_SIZE, characterUUID }, - GATT_PERMIT_READ, - 0, - &thProps - }, + // 4 Humi Level Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &thProps + }, - // 5 Humi Level Value - { - { ATT_BT_UUID_SIZE, humiLevelUUID }, - GATT_PERMIT_READ, - 0, - (uint8_t*)&measured_data.humi - }, + // 5 Humi Level Value + { + { ATT_BT_UUID_SIZE, humiLevelUUID }, + GATT_PERMIT_READ, + 0, + (uint8_t*)&measured_data.humi + }, - // 6 Humi Level Client Characteristic Configuration - { - { ATT_BT_UUID_SIZE, clientCharCfgUUID }, - GATT_PERMIT_READ | GATT_PERMIT_WRITE, - 0, - (uint8*)& humiLevelClientCharCfg - }, + // 6 Humi Level Client Characteristic Configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8*)& humiLevelClientCharCfg + }, }; /********************************************************************* - LOCAL FUNCTIONS + LOCAL FUNCTIONS */ static uint8 thReadAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ); + uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ); static bStatus_t thWriteAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16 len, uint16 offset ); + uint8* pValue, uint16 len, uint16 offset ); static void thNotifyCB( linkDBItem_t* pLinkItem ); /********************************************************************* - PROFILE CALLBACKS + PROFILE CALLBACKS */ // TH Service Callbacks CONST gattServiceCBs_t thCBs = { - thReadAttrCB, // Read callback function pointer - thWriteAttrCB, // Write callback function pointer - NULL // Authorization callback function pointer + thReadAttrCB, // Read callback function pointer + thWriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer }; /********************************************************************* - PUBLIC FUNCTIONS + PUBLIC FUNCTIONS */ /********************************************************************* - @fn TH_AddService + @fn TH_AddService - @brief Initializes the Battery Service by registering - GATT attributes with the GATT server. + @brief Initializes the Battery Service by registering + GATT attributes with the GATT server. - @return Success or Failure + @return Success or Failure */ bStatus_t TH_AddService( void ) { - uint8 status = SUCCESS; - // Initialize Client Characteristic Configuration attributes - GATTServApp_InitCharCfg( INVALID_CONNHANDLE, tempLevelClientCharCfg ); - GATTServApp_InitCharCfg( INVALID_CONNHANDLE, humiLevelClientCharCfg ); - // Register GATT attribute list and CBs with GATT Server App - status = GATTServApp_RegisterService( thAttrTbl, - GATT_NUM_ATTRS( thAttrTbl ), - &thCBs ); - return ( status ); + uint8 status = SUCCESS; + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, tempLevelClientCharCfg ); + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, humiLevelClientCharCfg ); + // Register GATT attribute list and CBs with GATT Server App + status = GATTServApp_RegisterService( thAttrTbl, + GATT_NUM_ATTRS( thAttrTbl ), + &thCBs ); + return ( status ); } /********************************************************************* - @fn Batt_Register + @fn Batt_Register - @brief Register a callback function with the Battery Service. + @brief Register a callback function with the Battery Service. - @param pfnServiceCB - Callback function. + @param pfnServiceCB - Callback function. - @return None. + @return None. */ extern void TH_Register( thServiceCB_t pfnServiceCB ) { - thServiceCB = pfnServiceCB; + thServiceCB = pfnServiceCB; } /********************************************************************* - @fn thReadAttrCB + @fn thReadAttrCB - @brief Read an attribute. + @brief Read an attribute. - @param connHandle - connection message was received on - @param pAttr - pointer to attribute - @param pValue - pointer to data to be read - @param pLen - length of data to be read - @param offset - offset of the first octet to be read - @param maxLen - maximum length of data to be read + @param connHandle - connection message was received on + @param pAttr - pointer to attribute + @param pValue - pointer to data to be read + @param pLen - length of data to be read + @param offset - offset of the first octet to be read + @param maxLen - maximum length of data to be read - @return Success or Failure + @return Success or Failure */ static uint8 thReadAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ) + uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ) { - (void)connHandle; - (void)maxLen; - bStatus_t status = SUCCESS; + (void)connHandle; + (void)maxLen; + bStatus_t status = SUCCESS; - // Make sure it's not a blob operation (no attributes in the profile are long) - if ( offset > 0 ) - { - return ( ATT_ERR_ATTR_NOT_LONG ); - } + // Make sure it's not a blob operation (no attributes in the profile are long) + if ( offset > 0 ) + { + return ( ATT_ERR_ATTR_NOT_LONG ); + } - uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1] ); + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1] ); - // Measure temp level if reading level - if ( uuid == TEMPERATYRE_UUID ) - { + // Measure temp level if reading level + if ( uuid == TEMPERATYRE_UUID ) + { *pLen = 2; - pValue[0] = measured_data.temp; - pValue[1] = measured_data.temp >> 8; - } - // Measure humi level if reading level - else if ( uuid == HUMIDITY_UUID) - { - *pLen = 2; - pValue[0] = measured_data.humi; - pValue[1] = measured_data.humi >> 8; - } - else - { - status = ATT_ERR_ATTR_NOT_FOUND; - } - return ( status ); + pValue[0] = measured_data.temp; + pValue[1] = measured_data.temp >> 8; + } + // Measure humi level if reading level + else if ( uuid == HUMIDITY_UUID) + { + *pLen = 2; + pValue[0] = measured_data.humi; + pValue[1] = measured_data.humi >> 8; + } + else + { + status = ATT_ERR_ATTR_NOT_FOUND; + } + return ( status ); } /********************************************************************* - @fn thWriteAttrCB + @fn thWriteAttrCB - @brief Validate attribute data prior to a write operation + @brief Validate attribute data prior to a write operation - @param connHandle - connection message was received on - @param pAttr - pointer to attribute - @param pValue - pointer to data to be written - @param len - length of data - @param offset - offset of the first octet to be written + @param connHandle - connection message was received on + @param pAttr - pointer to attribute + @param pValue - pointer to data to be written + @param len - length of data + @param offset - offset of the first octet to be written - @return Success or Failure + @return Success or Failure */ static bStatus_t thWriteAttrCB( uint16 connHandle, gattAttribute_t* pAttr, - uint8* pValue, uint16 len, uint16 offset ) + uint8* pValue, uint16 len, uint16 offset ) { - bStatus_t status = SUCCESS; - uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + bStatus_t status = SUCCESS; + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); - switch ( uuid ) - { - case GATT_CLIENT_CHAR_CFG_UUID: - status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, - offset, GATT_CLIENT_CFG_NOTIFY ); + switch ( uuid ) + { + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); - if ( status == SUCCESS ) - { - uint16 charCfg = BUILD_UINT16( pValue[0], pValue[1] ); + if ( status == SUCCESS ) + { + uint16 charCfg = BUILD_UINT16( pValue[0], pValue[1] ); - if ( thServiceCB ) - { - (*thServiceCB)( (charCfg == GATT_CFG_NO_OPERATION) ? - TEMP_LEVEL_NOTI_DISABLED : - TEMP_LEVEL_NOTI_ENABLED); - } - } + if ( thServiceCB ) + { + (*thServiceCB)( (charCfg == GATT_CFG_NO_OPERATION) ? + TEMP_LEVEL_NOTI_DISABLED : + TEMP_LEVEL_NOTI_ENABLED); + } + } - break; + break; - default: - status = ATT_ERR_ATTR_NOT_FOUND; - break; - } + default: + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } - return ( status ); + return ( status ); } /********************************************************************* - @fn thNotifyCB + @fn thNotifyCB - @brief Send a notification of the level state characteristic. + @brief Send a notification of the level state characteristic. - @param connHandle - linkDB item + @param connHandle - linkDB item - @return None. + @return None. */ static void thNotifyCB( linkDBItem_t* pLinkItem ) { - attHandleValueNoti_t noti; - - if ( pLinkItem->stateFlags & LINK_CONNECTED ) - { - if ( GATTServApp_ReadCharCfg( pLinkItem->connectionHandle, - tempLevelClientCharCfg ) - & GATT_CLIENT_CFG_NOTIFY ) - { - noti.handle = thAttrTbl[TEMP_LEVEL_VALUE_IDX].handle; - noti.len = 2; - noti.value[0] = measured_data.temp; - noti.value[1] = measured_data.temp >> 8; - GATT_Notification( pLinkItem->connectionHandle, ¬i, FALSE ); - } + attHandleValueNoti_t noti; - if ( GATTServApp_ReadCharCfg( pLinkItem->connectionHandle, - humiLevelClientCharCfg ) + if ( pLinkItem->stateFlags & LINK_CONNECTED ) + { + if ( GATTServApp_ReadCharCfg( pLinkItem->connectionHandle, + tempLevelClientCharCfg ) + & GATT_CLIENT_CFG_NOTIFY ) + { + noti.handle = thAttrTbl[TEMP_LEVEL_VALUE_IDX].handle; + noti.len = 2; + noti.value[0] = measured_data.temp; + noti.value[1] = measured_data.temp >> 8; + GATT_Notification( pLinkItem->connectionHandle, ¬i, FALSE ); + } + + if ( GATTServApp_ReadCharCfg( pLinkItem->connectionHandle, + humiLevelClientCharCfg ) & GATT_CLIENT_CFG_NOTIFY ) - { - noti.handle = thAttrTbl[HUMI_LEVEL_VALUE_IDX].handle; - noti.len = 2; - noti.value[0] = measured_data.humi; - noti.value[1] = measured_data.humi >> 8; - GATT_Notification( pLinkItem->connectionHandle, ¬i, FALSE ); - } - } + { + noti.handle = thAttrTbl[HUMI_LEVEL_VALUE_IDX].handle; + noti.len = 2; + noti.value[0] = measured_data.humi; + noti.value[1] = measured_data.humi >> 8; + GATT_Notification( pLinkItem->connectionHandle, ¬i, FALSE ); + } + } } /********************************************************************* - @fn thNotifyLevelState + @fn thNotifyLevelState - @brief Send a notification of the battery level state - characteristic if a connection is established. + @brief Send a notification of the battery level state + characteristic if a connection is established. - @return None. + @return None. */ void TH_NotifyLevel(void) { - // Execute linkDB callback to send notification - linkDB_PerformFunc( thNotifyCB ); + // Execute linkDB callback to send notification + linkDB_PerformFunc( thNotifyCB ); } /********************************************************************* - @fn TH_HandleConnStatusCB + @fn TH_HandleConnStatusCB - @brief TH Service link status change handler function. + @brief TH Service link status change handler function. - @param connHandle - connection handle - @param changeType - type of change + @param connHandle - connection handle + @param changeType - type of change - @return none + @return none */ void TH_HandleConnStatusCB( uint16 connHandle, uint8 changeType ) { - // Make sure this is not loopback connection - if ( connHandle != LOOPBACK_CONNHANDLE ) - { - // Reset Client Char Config if connection has dropped - if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED ) || - ( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) && - ( !linkDB_Up( connHandle ) ) ) ) - { - GATTServApp_InitCharCfg( connHandle, tempLevelClientCharCfg ); - GATTServApp_InitCharCfg( connHandle, humiLevelClientCharCfg ); - } - } + // Make sure this is not loopback connection + if ( connHandle != LOOPBACK_CONNHANDLE ) + { + // Reset Client Char Config if connection has dropped + if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED ) || + ( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) && + ( !linkDB_Up( connHandle ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, tempLevelClientCharCfg ); + GATTServApp_InitCharCfg( connHandle, humiLevelClientCharCfg ); + } + } } - -/********************************************************************* -*********************************************************************/ diff --git a/bthome_phy6222/source/thservice.h b/bthome_phy6222/source/thservice.h index 29276ed..6bf03c0 100644 --- a/bthome_phy6222/source/thservice.h +++ b/bthome_phy6222/source/thservice.h @@ -1,5 +1,5 @@ /************************************************************************************************** -******* + thservice.h **************************************************************************************************/ @@ -12,30 +12,30 @@ extern "C" #endif /********************************************************************* - INCLUDES + INCLUDES */ /********************************************************************* - CONSTANTS + CONSTANTS */ -#define ENV_SENSING_SERV_UUID 0x181A -#define TEMPERATYRE_UUID 0x2A6E -#define HUMIDITY_UUID 0x2A6F +#define ENV_SENSING_SERV_UUID 0x181A +#define TEMPERATYRE_UUID 0x2A6E +#define HUMIDITY_UUID 0x2A6F // Battery Service Get/Set Parameters -#define BATT_PARAM_LEVEL 0 -#define BATT_PARAM_CRITICAL_LEVEL 1 -#define BATT_PARAM_SERVICE_HANDLE 2 +#define BATT_PARAM_LEVEL 0 +#define BATT_PARAM_CRITICAL_LEVEL 1 +#define BATT_PARAM_SERVICE_HANDLE 2 #define BATT_PARAM_BATT_LEVEL_IN_REPORT 3 // Callback events -#define TEMP_LEVEL_NOTI_ENABLED 1 -#define TEMP_LEVEL_NOTI_DISABLED 2 +#define TEMP_LEVEL_NOTI_ENABLED 1 +#define TEMP_LEVEL_NOTI_DISABLED 2 /********************************************************************* - TYPEDEFS + TYPEDEFS */ // TH Service callback function @@ -51,58 +51,58 @@ typedef uint8 (*thServiceCalcCB_t)(uint16 adcVal); typedef void (*thServiceTeardownCB_t)(void); /********************************************************************* - MACROS + MACROS */ /********************************************************************* - Profile Callbacks + Profile Callbacks */ /********************************************************************* - API FUNCTIONS + API FUNCTIONS */ /********************************************************************* - @fn Batt_AddService + @fn Batt_AddService - @brief Initializes the Battery service by registering - GATT attributes with the GATT server. + @brief Initializes the Battery service by registering + GATT attributes with the GATT server. - @return Success or Failure + @return Success or Failure */ extern bStatus_t TH_AddService( void ); /********************************************************************* - @fn Batt_Register + @fn Batt_Register - @brief Register a callback function with the Battery Service. + @brief Register a callback function with the Battery Service. - @param pfnServiceCB - Callback function. + @param pfnServiceCB - Callback function. - @return None. + @return None. */ extern void TH_Register( thServiceCB_t pfnServiceCB ); /********************************************************************* - @fn Batt_HandleConnStatusCB + @fn Batt_HandleConnStatusCB - @brief Battery Service link status change handler function. + @brief Battery Service link status change handler function. - @param connHandle - connection handle - @param changeType - type of change + @param connHandle - connection handle + @param changeType - type of change - @return none + @return none */ void TH_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); /********************************************************************* - @fn thNotifyLevelState + @fn thNotifyLevelState - @brief Send a notification of the battery level state - characteristic if a connection is established. + @brief Send a notification of the battery level state + characteristic if a connection is established. - @return None. + @return None. */ void TH_NotifyLevel(void); /*********************************************************************