diff --git a/README.md b/README.md index 4aad1d5..6cbdc6b 100644 --- a/README.md +++ b/README.md @@ -36,12 +36,15 @@ ### [选型建议](https://github.com/SoCXin) -[CH579](https://github.com/SoCXin/CH579) +[CH579](https://github.com/SoCXin/CH579) 是一款非常有特色的SoC,在紧凑的封装内集成了以太网所有功能,同时还具有无线通信。 * QFN48(5X5) * QFN28(4X4) [![sites](docs/diff.png)](http://www.wch.cn/products/CH579.html) +#### 相关开发板 + +[![sites](docs/B.png)](https://item.taobao.com/item.htm?spm=a230r.1.14.18.a51ac05bwhVsnp&id=608342676773&ns=1&abbucket=19#detail) ### [探索芯世界 www.SoC.xin](http://www.SoC.Xin) diff --git a/docs/B.png b/docs/B.png new file mode 100644 index 0000000..15fcf12 Binary files /dev/null and b/docs/B.png differ diff --git a/index.json b/index.json index 678a2c5..0195faf 100644 --- a/index.json +++ b/index.json @@ -19,7 +19,7 @@ "type": "git", "url": "https://github.com/SoCXin/CH579.git" }, - "series":["CH579M","CH579F","CH578","CH577"], + "series":["CH579","CH578","CH577"], "package":["QFN28","QFN48"], "peripheral": ["TIM","ADC","USB","UART","SPI","LDO","PWM"], "price":[4,8], @@ -45,7 +45,7 @@ "Cortex-M", "WCH", "CH579", - "DAC","SDIO","CAN","I2C","RTC","SPI", + "ETH","SDIO","BLE","I2C","RTC","SPI", "3.6V","1.8V" ] } diff --git a/src/CH579_List.txt b/src/CH579_List.txt index d5d3b45..10f69e0 100644 --- a/src/CH579_List.txt +++ b/src/CH579_List.txt @@ -1,5 +1,5 @@ -Ͼߺ΢ӹɷ޹˾ 2021.02 +Ͼߺ΢ӹɷ޹˾ 2021.05 뵽ǵվϲѯ http://wch.cn @@ -7,7 +7,7 @@ http://wch.cn ļĿ¼ | |-- CH579: ͹ - 32λCortex-M0ں΢ - | |-- CH579׿OTAV1.1: CH579 OTAAPP߼Դ + | |-- ׿OTA: CH579 OTAAPP߼Դ,OTA˵ĵϲ | |-- EVT: CH579CH579 | | |-- PUB: | | | |-- CH579˵.pdf: CH579˵̴˵ @@ -60,19 +60,6 @@ http://wch.cn | | | | |-- UDP_ServerUDP_ServeṛԹ㲥IPָ˿ڱģܵĵĵַΪĿַͱ | | | | |-- CH57xNETЭջ˵.pdf̫Эջ˵ | | | |-- BLE - | | | | |-- BLE_MESH - | | | | | |-- Ali_Genie_Lightẹ̀ϵҶѰӣܵ - | | | | | |-- Generic_Model_With_Proxyͨģ̣֧PB-ADVPB-GATTִ֧ - | | | | | |-- Generic_Model_With_Proxy_Onlyͨģ̣֧PB-GATTִ֧ - | | | | | |-- Generic_OnOff_Modelsͨģ̣֧PB-ADV֧ת - | | | | | |-- Self_Provision_Friendѽڵ㣬͹Ľڵʹ - | | | | | |-- Self_Provision_Low_Power_Node͹Ľڵ㣬ѽڵʹ - | | | | | |-- Self_Provision_Generic_OnOff_Publisḥͨÿģڷ̣ - | | | | | |-- Self_Provision_Generic_OnOff_SubscriptioṇͨÿģͶ - | | | | | |-- Self_Provisioneṛ豸ͨGeneric_OnOff_Modelsʹ - | | | | | |-- Commonͨļ - | | | | | |-- LIBBLE MeshЭջļͷļ - | | | | | |-- ֤֤飺Mesh BQB֤֤Լè֤ | | | | |-- Broadcaster㲥߽ɫ̣ڹ㲥̬һֱ㲥 | | | | |-- CyclingSensorд̣ʱϴٶȺ̤Ƶ | | | | |-- CentPeriһ̣̺ʹӻ̵Ĺͬʱ @@ -88,9 +75,22 @@ http://wch.cn | | | | |-- Observer۲߽ɫ̣ʱɨ裬ɨΪգӡɨ赽Ĺ㲥ַ | | | | |-- DirectTestֱӲָ̣ͨƵݰ | | | | |-- RF_PHYDZ׼շ - | | | | |-- OTA - | | | | |-- OTA_OnlyUpdateApp̶,ֻû - | | | | |-- Peripheral_OnlyUpdateApp̶û,OTA_OnlyUpdateAppʹãúϳɹ߽IAPļûļļϳɵBINļISP¼ + | | | | |-- BackupUpgrade_IAPIAP̣⵱ǰ־жǷ˱뵽ûû + | | | | |-- BackupUpgrade_OTAụ̂ӻ̻OTAܣɽ̼浽תIAP + | | | | |-- OnlyUpdateApp_IAP̶IAP̣߱OTAܣ̼û + | | | | |-- OnlyUpdateApp_Peripheral̶ụ̂ӻ̻תIAPкĹ + | | | | |-- MESH + | | | | | |-- adv_ali_lightẹ̀ͨèҶ豸ƿ״̬Ĭֻпԣԣȣ¶ȵȣҪиݰƲƷõӶӦԼ״̬ϱ + | | | | | |-- adv_ali_light_add_lightnessMESH̡ͨè̵Ļϣԣڶԭẹ̀ϤMESHͨԵķ + | | | | | |-- adv_ali_light_add_windspeedè̡è̵Ļϣ˷ԣڶԭẹ̀ϤèԵķ + | | | | | |-- adv_ali_light_with_peripheralè̵Ļϣֻ֧BLEӿơ + | | | | | |-- adv_proxyڵ̣ͨPV_GATT㣨BLEӣ + | | | | | |-- adv_vendorԶģ̣self_provisioner_vendorʹã֧ӦӦ͸ͨԣⶨͨЭ顣 + | | | | | |-- adv_vendor_friendԶģ̵Ļϣ֧ѽڵ㹦 + | | | | | |-- adv_vendor_low_powerԶģ̵Ļϣֵ֧͹Ľڵ㹦ܣѽڵʹ + | | | | | |-- self_provisioner_vendorԶģ̣adv_vendorʹãԶΧδ豸mesh磬Ĭ֧6豸Ĭ豸1APPKEY,ӦӦ͸豸1ĵַȺӦϢ + | | | | | |-- self_provisioner_vendor_with_peripheralԶģ̵Ļϣֻ֧BLEӿƣתֻmeshͨţⶨͨЭʵֻmesh豸 + | | | | | |-- MESH_LIBMESHЭջļͷļ | | | | |-- HAL̹õӲļ | | | | |-- LIBBLEЭջļͷļ | | | | |-- CH57xBLEЭջ˵.pdfЭջ˵ diff --git a/src/EXAM/ADC/CH57x.uvprojx b/src/EXAM/ADC/CH57x.uvprojx index 411b107..15bf269 100644 --- a/src/EXAM/ADC/CH57x.uvprojx +++ b/src/EXAM/ADC/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/APP/include/ota.h b/src/EXAM/BLE/BackupUpgrade_IAP/APP/include/ota.h new file mode 100644 index 0000000..d56102e --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/APP/include/ota.h @@ -0,0 +1,118 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : ota.h +* Author : WCH +* Version : V1.10 +* Date : 2018/12/14 +* Description : oadö +*******************************************************************************/ + + +/******************************************************************************/ +#ifndef __OTA_H +#define __OTA_H + + +/* ------------------------------------------------------------------------------------------------ + * OTA FLASH + * ------------------------------------------------------------------------------------------------ + */ + +/* ûcodeֳ飬120K120K10KֱimageAû룩imageB ݴ룩imageIAP*/ + +/* FLASH */ +#define FLASH_BLOCK_SIZE 512 +#define IMAGE_SIZE 120*1024 + +/* imageA */ +#define IMAGE_A_FLAG 0x01 +#define IMAGE_A_START_ADD 0 +#define IMAGE_A_SIZE IMAGE_SIZE +#define IMAGE_A_ENTRY_ADD (IMAGE_A_START_ADD + 4) + +/* imageB */ +#define IMAGE_B_FLAG 0x02 +#define IMAGE_B_START_ADD (IMAGE_A_START_ADD + IMAGE_SIZE) +#define IMAGE_B_SIZE IMAGE_SIZE +#define IMAGE_B_ENTRY_ADD (IMAGE_B_START_ADD + 4) + +/* imageIAP */ +#define IMAGE_IAP_FLAG 0x03 +#define IMAGE_IAP_START_ADD (IMAGE_B_START_ADD + IMAGE_SIZE) +#define IMAGE_IAP_SIZE 10*1024 +#define IMAGE_IAP_ENTRY_ADD (IMAGE_IAP_START_ADD + 4) + +/* IAP */ +/* ΪIAP */ +#define CMD_IAP_PROM 0x80 // IAP +#define CMD_IAP_ERASE 0x81 // IAP +#define CMD_IAP_VERIFY 0x82 // IAPУ +#define CMD_IAP_END 0x83 // IAP־ +#define CMD_IAP_INFO 0x84 // IAPȡ豸Ϣ + + +/* ֡ȶ */ +#define IAP_LEN 20 + +/* DataFlashַռλ */ +#define OTA_DATAFLASH_ADD 0x0003E800 + + +/* DataFlashOTAϢ */ +typedef struct +{ + unsigned char ImageFlag; //¼ĵǰimage־ + unsigned char Revd[3]; +}OTADataFlashInfo_t; + +/* OTA IAPͨѶЭ鶨 */ +/* ַʹ4ƫ */ +typedef union +{ + struct + { + unsigned char cmd; /* 0x81 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char block_num[2]; /* */ + + } erase; /* */ + struct + { + unsigned char cmd; /* 0x83 */ + unsigned char len; /* ݳ */ + unsigned char status[2]; /* ֽ״̬ */ + } end; /* */ + struct + { + unsigned char cmd; /* 0x82 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* Уַ */ + unsigned char buf[IAP_LEN-4]; /* У */ + } verify; /* У */ + struct + { + unsigned char cmd; /* 0x80 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char buf[IAP_LEN-4]; /* */ + } program; /* */ + struct + { + unsigned char cmd; /* 0x84 */ + unsigned char len; /* ݳ */ + unsigned char buf[IAP_LEN-2]; /* */ + } info; /* */ + struct + { + unsigned char buf[IAP_LEN]; /* ݰ*/ + } other; +} OTA_IAP_CMD_t; + + +/* ¼ǰImage */ +extern unsigned char CurrImageFlag; + + +#endif + +/******************************** endfile @ oad ******************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/APP/include/peripheral.h b/src/EXAM/BLE/BackupUpgrade_IAP/APP/include/peripheral.h new file mode 100644 index 0000000..86e442a --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/APP/include/peripheral.h @@ -0,0 +1,59 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef PERIPHERAL_H +#define PERIPHERAL_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + + +// Simple BLE Peripheral Task Events +#define SBP_START_DEVICE_EVT 0x0001 +#define SBP_PERIODIC_EVT 0x0002 +#define OTA_FLASH_ERASE_EVT 0x0004 //OTA Flash + + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * FUNCTIONS + */ + +/* + * Task Initialization for the BLE Application + */ +extern void Peripheral_Init( void ); + +/* + * Task Event Processor for the BLE Application + */ +extern uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/APP/peripheral.c b/src/EXAM/BLE/BackupUpgrade_IAP/APP/peripheral.c new file mode 100644 index 0000000..96dfa5b --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/APP/peripheral.c @@ -0,0 +1,819 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : Peripheral.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ӻӦó򣬳ʼ㲥ӲȻ㲥ֱͨԶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "devinfoservice.h" +#include "GATTprofile.h" +#include "Peripheral.h" +#include "OTA.h" +#include "OTAprofile.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// How often to perform periodic event +#define SBP_PERIODIC_EVT_PERIOD 1000 + +// What is the advertising interval when device is discoverable (units of 625us, 160=100ms) +#define DEFAULT_ADVERTISING_INTERVAL 160 + +// Limited discoverable mode advertises for 30.72s, and then stops +// General discoverable mode advertises indefinitely + +#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL + +// Minimum connection interval (units of 1.25ms, 80=100ms) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 6 + +// Maximum connection interval (units of 1.25ms, 800=1000ms) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 12 + +// Slave latency to use if automatic parameter update request is enabled +#define DEFAULT_DESIRED_SLAVE_LATENCY 0 + +// Supervision timeout value (units of 10ms, 1000=10s) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_CONN_TIMEOUT 1000 + +// Whether to enable automatic parameter update request when a connection is formed +#define DEFAULT_ENABLE_UPDATE_REQUEST TRUE + +// Connection Pause Peripheral time value (in seconds) +#define DEFAULT_CONN_PAUSE_PERIPHERAL 6 + +// Company Identifier: WCH +#define WCH_COMPANY_ID 0x07D7 + +#define INVALID_CONNHANDLE 0xFFFF + +// Length of bd addr as a string +#define B_ADDR_STR_LEN 15 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ +static uint8 Peripheral_TaskID=0xff; // Task ID for internal task/event processing + +// GAP - SCAN RSP data (max size = 31 bytes) +static uint8 scanRspData[31] = +{ + // complete name + 0x12, // length of this data + GAP_ADTYPE_LOCAL_NAME_COMPLETE, + 's','i','m','p','l','e',' ','P','e','r','i','p','h','e','r','a','l', + // connection interval range + 0x05, // length of this data + GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE, + LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), // 100ms + HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), + LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), // 1s + HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), + + // Tx power level + 0x02, // length of this data + GAP_ADTYPE_POWER_LEVEL, + 0 // 0dBm +}; + +// GAP - Advertisement data (max size = 31 bytes, though this is +// best kept short to conserve power while advertisting) +static uint8 advertData[] = +{ + // Flags; this sets the device to use limited discoverable + // mode (advertises for 30 seconds at a time) instead of general + // discoverable mode (advertises indefinitely) + 0x02, // length of this data + GAP_ADTYPE_FLAGS, + DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED, + + // service UUID, to notify central devices what services are included + // in this peripheral + 0x03, // length of this data + GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all + LO_UINT16( SIMPLEPROFILE_SERV_UUID ), + HI_UINT16( SIMPLEPROFILE_SERV_UUID ) + +}; + +// GAP GATT Attributes +static uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "Simple Peripheral"; + +// OTA IAP VARIABLES +/* OTAͨѶ֡ */ +OTA_IAP_CMD_t iap_rec_data; + +/* OTA */ +__align(8) UINT32 OpParaData[4]; +UINT32 OpParaDataLen = 0; +UINT32 OpAdd = 0; + +/* flashһʱ洢 */ +__align(8) uint8 vectors_block_buf[FLASH_BLOCK_SIZE]; + +/* dataflashʱ */ +__align(8) uint8 dataflash_block_buf[FLASH_BLOCK_SIZE]; + +/* Imageתַ */ +typedef int( *pImageTaskFn)( void ); +pImageTaskFn user_image_tasks; + +/* Flash */ +UINT32 EraseAdd = 0; //ַ +UINT32 EraseBlockNum = 0; //ҪĿ +UINT32 EraseBlockCnt = 0; //Ŀ + +/* FLASH У */ +UINT8 VerifyStatus = 0; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ); +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent ); +static void performPeriodicTask( void ); +static void simpleProfileChangeCB( uint8 paramID ); +void OTA_IAPReadDataComplete( unsigned char index ); +void OTA_IAPWriteData( unsigned char index, unsigned char *p_data, unsigned char w_len ); +void Rec_OTA_IAP_DataDeal(void); +void OTA_IAP_SendCMDDealSta(UINT8 deal_status); + +/********************************************************************* + * PROFILE CALLBACKS + */ + +// GAP Role Callbacks +static gapRolesCBs_t Peripheral_PeripheralCBs = +{ + peripheralStateNotificationCB, // Profile State Change Callbacks + NULL, // When a valid RSSI is read from controller (not used by application) + NULL +}; + +// GAP Bond Manager Callbacks +static gapBondCBs_t Peripheral_BondMgrCBs = +{ + NULL, // Passcode callback (not used by application) + NULL // Pairing / Bonding state Callback (not used by application) +}; + +// Simple GATT Profile Callbacks +static simpleProfileCBs_t Peripheral_SimpleProfileCBs = +{ + simpleProfileChangeCB // Charactersitic value change callback +}; + +// Simple GATT Profile Callbacks +static OTAProfileCBs_t Peripheral_OTA_IAPProfileCBs = +{ + OTA_IAPReadDataComplete, // Charactersitic value change callback + OTA_IAPWriteData +}; + + + +// Callback when the connection parameteres are updated. +void PeripheralParamUpdate(uint16 connInterval,uint16 connSlaveLatency, uint16 connTimeout); + +gapRolesParamUpdateCB_t PeripheralParamUpdate_t = NULL; + + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn Peripheral_Init + * + * @brief Initialization function for the 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 TMOS. This ID should be + * used to send messages and set timers. + * + * @return none + */ +void Peripheral_Init( ) +{ + Peripheral_TaskID = TMOS_ProcessEventRegister(Peripheral_ProcessEvent); + + // Setup the GAP Peripheral Role Profile + { + // For other hardware platforms, device starts advertising upon initialization + uint8 initial_advertising_enable = TRUE; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); + GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); + + //PeripheralParamUpdate_t = (gapRolesParamUpdateCB_t *)PeripheralParamUpdate; + + //PRINT( "PeripheralParamUpdate_t %08x \n",(int)PeripheralParamUpdate_t ); + + //GAPRole_PeripheralRegisterAppCBs( (gapRolesParamUpdateCB_t *)&PeripheralParamUpdate ); + } + + // Set the GAP Characteristics + GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); + + // Set advertising interval + { + uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; + + GAP_SetParamValue( TGAP_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_DISC_ADV_INT_MAX, advInt ); + } + + // Setup the GAP Bond Manager + { + uint32 passkey = 0; // passkey "000000" + uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; + uint8 mitm = TRUE; + uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; + uint8 bonding = TRUE; + GAPBondMgr_SetParameter( GAPBOND_PERI_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); + GAPBondMgr_SetParameter( GAPBOND_PERI_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); + GAPBondMgr_SetParameter( GAPBOND_PERI_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); + GAPBondMgr_SetParameter( GAPBOND_PERI_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); + GAPBondMgr_SetParameter( GAPBOND_PERI_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); + } + + // 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 + OTAProfile_AddService( GATT_ALL_SERVICES ); + + // Setup the SimpleProfile Characteristic Values + { + uint8 charValue1 = 1; + uint8 charValue2 = 2; + uint8 charValue3 = 3; + uint8 charValue4[SIMPLEPROFILE_CHAR4_LEN] = "01234567"; + uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 }; + + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, sizeof ( uint8 ), &charValue1 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, sizeof ( uint8 ), &charValue2 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 ); + + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, charValue4 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); + } + + // + { + //GAPRole_PeripheralRegisterAppCBs( (gapRolesParamUpdateCB_t *)PeripheralParamUpdate_t ); + + } + + // Register callback with SimpleGATTprofile + SimpleProfile_RegisterAppCBs( &Peripheral_SimpleProfileCBs ); + + // Register callback with OTAGATTprofile + OTAProfile_RegisterAppCBs( &Peripheral_OTA_IAPProfileCBs ); + + // Setup a delayed profile startup + tmos_set_event( Peripheral_TaskID, SBP_START_DEVICE_EVT ); + +} + +void PeripheralParamUpdate(uint16 connInterval,uint16 connSlaveLatency, uint16 connTimeout) +{ + PRINT( "update %d %d %d \n",connInterval,connSlaveLatency,connTimeout ); + +// GAPRole_SendUpdateParam( DEFAULT_DESIRED_MIN_CONN_INTERVAL, DEFAULT_DESIRED_MAX_CONN_INTERVAL, +// DEFAULT_DESIRED_SLAVE_LATENCY, DEFAULT_DESIRED_CONN_TIMEOUT, GAPROLE_NO_ACTION ); + +} + +/********************************************************************* + * @fn Peripheral_ProcessEvent + * + * @brief 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 TMOS assigned task ID. + * @param events - events to process. This is a bit map and can + * contain more than one event. + * + * @return events not processed + */ +uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ) +{ + +// VOID task_id; // TMOS required parameter that isn't used in this function + + if ( events & SYS_EVENT_MSG ){ + uint8 *pMsg; + + if ( (pMsg = tmos_msg_receive( Peripheral_TaskID )) != NULL ){ + Peripheral_ProcessTMOSMsg( (tmos_event_hdr_t *)pMsg ); + // Release the TMOS message + tmos_msg_deallocate( pMsg ); + } + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } + + if ( events & SBP_START_DEVICE_EVT ){ + // Start the Device + GAPRole_PeripheralStartDevice( Peripheral_TaskID, &Peripheral_BondMgrCBs, &Peripheral_PeripheralCBs ); + // Set timer for first periodic event + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + return ( events ^ SBP_START_DEVICE_EVT ); + } + + if ( events & SBP_PERIODIC_EVT ){ + // Restart timer + if ( SBP_PERIODIC_EVT_PERIOD ){ + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + } + // Perform periodic application task + performPeriodicTask(); + return (events ^ SBP_PERIODIC_EVT); + } + + //OTA_FLASH_ERASE_EVT + if ( events & OTA_FLASH_ERASE_EVT ) + { + UINT8 status; + + PRINT("ERASE:%08x num:%d\r\n",(int)(EraseAdd+EraseBlockCnt*FLASH_BLOCK_SIZE),(int)EraseBlockCnt); + status = FlashBlockErase(EraseAdd+EraseBlockCnt*FLASH_BLOCK_SIZE); + + /* ʧ */ + if(status != SUCCESS) + { + OTA_IAP_SendCMDDealSta(status); + return (events ^ OTA_FLASH_ERASE_EVT); + } + + EraseBlockCnt++; + + /* */ + if( EraseBlockCnt >= EraseBlockNum ) + { + PRINT("ERASE Complete\r\n"); + OTA_IAP_SendCMDDealSta(status); + return (events ^ OTA_FLASH_ERASE_EVT); + } + + return (events); + } + + // Discard unknown events + return 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessTMOSMsg + * + * @brief Process an incoming task message. + * + * @param pMsg - message to process + * + * @return none + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ) +{ + switch ( pMsg->event ){ + default: + break; + } +} + +/********************************************************************* + * @fn peripheralStateNotificationCB + * + * @brief Notification from the profile of a state change. + * + * @param newState - new state + * + * @return none + */ +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent ) +{ + switch ( newState ) + { + case GAPROLE_STARTED: + PRINT( "Initialized..\n" ); + break; + + case GAPROLE_ADVERTISING: + PRINT( "Advertising..\n" ); + break; + + case GAPROLE_CONNECTED: + { + gapEstLinkReqEvent_t *event = (gapEstLinkReqEvent_t *) pEvent; + uint16 conn_interval = 0; + + conn_interval = event->connInterval; + PRINT( "Connected.. \n" ); + + if( conn_interval > DEFAULT_DESIRED_MAX_CONN_INTERVAL) + { + PRINT("Send Update\r\n"); + GAPRole_PeripheralConnParamUpdateReq( event->connectionHandle, + DEFAULT_DESIRED_MIN_CONN_INTERVAL, + DEFAULT_DESIRED_MAX_CONN_INTERVAL, + DEFAULT_DESIRED_SLAVE_LATENCY, + DEFAULT_DESIRED_CONN_TIMEOUT, + Peripheral_TaskID ); + + } + break; + } + case GAPROLE_CONNECTED_ADV: + PRINT( "Connected Advertising..\n" ); + break; + case GAPROLE_WAITING: + { + uint8 initial_advertising_enable = TRUE; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + PRINT( "Disconnected..\n" ); + } + break; + + case GAPROLE_ERROR: + PRINT( "Error..\n" ); + break; + + default: + break; + + } +} + +/********************************************************************* + * @fn performPeriodicTask + * + * @brief Perform a periodic application task. This function gets + * called every five seconds as a result of the SBP_PERIODIC_EVT + * TMOS event. In this example, the value of the third + * characteristic in the SimpleGATTProfile service is retrieved + * from the profile, and then copied into the value of the + * the fourth characteristic. + * + * @param none + * + * @return none + */ +static void performPeriodicTask( void ) +{ + uint8 valueToCopy[SIMPLEPROFILE_CHAR4_LEN]; + uint8 stat; + + // Call to retrieve the value of the third characteristic in the profile + stat = SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR4, valueToCopy); + if( stat == SUCCESS ){ + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, valueToCopy); + } +} + +/********************************************************************* + * @fn simpleProfileChangeCB + * + * @brief Callback from Profile indicating a value change + * + * @param paramID - parameter ID of the value that was changed. + * + * @return none + */ +static void simpleProfileChangeCB( uint8 paramID ) +{ + uint8 newValue; + + switch( paramID ) + { + case SIMPLEPROFILE_CHAR1: + PRINT("profile ChangeCB CHAR1..\n"); + SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, &newValue ); + break; + + case SIMPLEPROFILE_CHAR3: + PRINT("profile ChangeCB CHAR3..\n"); + SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, &newValue ); + break; + + default: + // should not reach here! + break; + } +} + +/******************************************************************************* +* Function Name : OTA_IAP_SendData +* Description : OTA IAPݣʹʱ20ֽ +* Input : p_send_dataݵָ + send_lenݵij +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_SendData(UINT8 *p_send_data,UINT8 send_len) +{ + OTAProfile_SendData(OTAPROFILE_CHAR ,p_send_data, send_len ); +} + +/******************************************************************************* +* Function Name : OTA_IAP_SendCMDDealSta +* Description : OTA IAPִе״̬ +* Input : deal_statusص״̬ +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_SendCMDDealSta(UINT8 deal_status) +{ + UINT8 send_buf[2]; + + send_buf[0] = deal_status; + send_buf[1] = 0; + OTA_IAP_SendData(send_buf,2); +} + +/******************************************************************************* +* Function Name : OTA_IAP_CMDErrDeal +* Description : OTA IAP쳣봦 +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_CMDErrDeal(void) +{ + OTA_IAP_SendCMDDealSta(0xfe); +} + +/******************************************************************************* +* Function Name : SwitchImageFlag +* Description : лdataflashImageFlag +* Input : new_flagлImageFlag +* Output : none +* Return : none +*******************************************************************************/ +void SwitchImageFlag(UINT8 new_flag) +{ + UINT8 *p_flash; + UINT16 i; + UINT8 ver_flag; + + /* ȡһ */ + p_flash = (UINT8 *)OTA_DATAFLASH_ADD; + for(i=0; iICER[0] = 0xffffffff; + SysTick->CTRL = 0; //رSysTickж +} + +/******************************************************************************* +* Function Name : GotoResetVector +* Description : ȡתַת +* Input : entry_addResetַ +* Output : none +* Return : none +*******************************************************************************/ +void GotoResetVector(UINT32 entry_add) +{ + user_image_tasks = (pImageTaskFn)(*(UINT32 *)(entry_add)); + (user_image_tasks)(); +} + +/******************************************************************************* +* Function Name : Rec_OTA_IAP_DataDeal +* Description : յOTAݰ +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void Rec_OTA_IAP_DataDeal(void) +{ + switch(iap_rec_data.other.buf[0]) + { + /* */ + case CMD_IAP_PROM: + { + UINT32 i; + UINT8 status; + + OpParaDataLen = iap_rec_data.program.len; + + OpAdd = (UINT32)(iap_rec_data.program.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.program.addr[1]) << 8); + OpAdd = OpAdd * 4; + + PRINT("IAP_PROM: %08x len:%d \r\n",(int)OpAdd,(int)OpParaDataLen); + + for(i=0; i<(OpParaDataLen/4); i++) + { + OpParaData[i] = (UINT32)(iap_rec_data.program.buf[0+4*i]); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[1+4*i]) << 8); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[2+4*i]) << 16); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[3+4*i]) << 24); + } + + status = FlashWriteBuf(OpAdd, OpParaData, (UINT16) OpParaDataLen); + + if( status ) OTA_IAP_SendCMDDealSta(status); + break; + } + /* -- */ + case CMD_IAP_ERASE: + { + OpAdd = (UINT32)(iap_rec_data.erase.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.erase.addr[1]) << 8); + OpAdd = OpAdd * 4; + + EraseBlockNum = (UINT32)(iap_rec_data.erase.block_num[0]); + EraseBlockNum |= ((UINT32)(iap_rec_data.erase.block_num[1]) << 8); + EraseAdd = OpAdd; + EraseBlockCnt = 0; + + /* ͷڲ0 */ + VerifyStatus = 0; + + PRINT("IAP_ERASE start:%08x num:%d\r\n",(int)OpAdd,(int)EraseBlockNum); + + /* */ + tmos_set_event( Peripheral_TaskID, OTA_FLASH_ERASE_EVT ); + break; + } + /* У */ + case CMD_IAP_VERIFY: + { + UINT32 i; + UINT8 *p_flash; + UINT8 status = 0; + + OpParaDataLen = iap_rec_data.verify.len; + + OpAdd = (UINT32)(iap_rec_data.verify.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.verify.addr[1]) << 8); + OpAdd = OpAdd * 4; + + PRINT("IAP_VERIFY: %08x len:%d \r\n",(int)OpAdd,(int)OpParaDataLen); + + p_flash = (UINT8 *)OpAdd; + + /* ǰImageAֱӶȡImageBУ */ + for(i=0; i>8) & 0xff); + send_buf[3] = (UINT8)((IMAGE_SIZE>>16) & 0xff); + send_buf[4] = (UINT8)((IMAGE_SIZE>>24) & 0xff); + + /* BLOCK SIZE */ + send_buf[5] = (UINT8)(FLASH_BLOCK_SIZE & 0xff); + send_buf[6] = (UINT8)((FLASH_BLOCK_SIZE>>8) & 0xff); + + /* Ҫ */ + + /* Ϣ */ + OTA_IAP_SendData(send_buf,20); + + break; + } + + default: + { + OTA_IAP_CMDErrDeal(); + break; + } + } +} + +/******************************************************************************* +* Function Name : OTA_IAPReadDataComplete +* Description : OTA ݶȡɴ +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAPReadDataComplete( unsigned char index ) +{ + PRINT("OTA Send Comp \r\n"); +} + +/******************************************************************************* +* Function Name : OTA_IAPWriteData +* Description : OTA ͨݽɴ +* Input : indexOTA ͨ + p_dataд + w_lenдij +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAPWriteData( unsigned char index, unsigned char *p_data, unsigned char w_len ) +{ + unsigned char rec_len; + unsigned char *rec_data; + + rec_len = w_len; + rec_data = p_data; + tmos_memcpy( (unsigned char *)&iap_rec_data, rec_data, rec_len ); + Rec_OTA_IAP_DataDeal(); +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/APP/peripheral_main.c b/src/EXAM/BLE/BackupUpgrade_IAP/APP/peripheral_main.c new file mode 100644 index 0000000..3765fe7 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/APP/peripheral_main.c @@ -0,0 +1,189 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.1 +* Date : 2019/11/05 +* Description : ӻӦϵͳʼ +*******************************************************************************/ + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "GATTprofile.h" +#include "Peripheral.h" +#include "OTA.h" +#include "OTAprofile.h" + + +/* ¼ǰImage */ +unsigned char CurrImageFlag = 0xff; + +__align(8) unsigned char flash_buf[FLASH_BLOCK_SIZE]; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +#if (defined (BLE_MAC)) && (BLE_MAC == TRUE) +u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; +#endif + +/******************************************************************************* +* Function Name : SwitchImageFlag +* Description : лdataflashImageFlag +* Input : new_flagлImageFlag +* Output : none +* Return : none +*******************************************************************************/ +void SwitchImageFlag(UINT8 new_flag) +{ + UINT8 *p_flash; + UINT16 i; + UINT8 ver_flag; + + /* ȡһ */ + p_flash = (UINT8 *)OTA_DATAFLASH_ADD; + for(i=0; itype.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch ( uuid ) + { + case OTAPROFILE_CHAR_UUID: + { + *pLen = 0; + if( OTAProfileReadLen ) + { + *pLen = OTAProfileReadLen; + tmos_memcpy( pValue, OTAProfileReadBuf, OTAProfileReadLen ); + OTAProfileReadLen = 0; + if( OTAProfile_AppCBs && OTAProfile_AppCBs->pfnOTAProfileRead ) + { + OTAProfile_AppCBs->pfnOTAProfileRead(OTAPROFILE_CHAR); + } + } + break; + } + default: + { + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn OTAProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t OTAProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + //uint8 notifyApp = 0xFF; + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch ( uuid ) + { + case OTAPROFILE_CHAR_UUID: + { + //Write the value + if ( status == SUCCESS ) + { + uint16 i; + uint8 *p_rec_buf; + + OTAProfileWriteLen = len; + p_rec_buf = pValue; + for(i=0; ipfnOTAProfileWrite) + { + OTAProfile_AppCBs->pfnOTAProfileWrite(OTAPROFILE_CHAR,OTAProfileWriteBuf,OTAProfileWriteLen); + OTAProfileWriteLen = 0; + } + + return ( status ); +} + +/******************************************************************************* +* Function Name : OTAProfile_SendData +* Description : OTA Profileͨ +* Input : paramIDOTAͨѡ + p_dataָ + send_lenݳ +* Output : None +* Return : ִ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_SendData(unsigned char paramID ,unsigned char *p_data, unsigned char send_len ) +{ + bStatus_t status = SUCCESS; + + /* ݳȳΧ */ + if( send_len > 20 ) return 0xfe; + + OTAProfileReadLen = send_len; + tmos_memcpy( OTAProfileReadBuf, p_data, OTAProfileReadLen ); + + return status; +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/Profile/devinfoservice.c b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/devinfoservice.c new file mode 100644 index 0000000..c63f6a7 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/devinfoservice.c @@ -0,0 +1,631 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.c +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : 豸Ϣ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "devinfoservice.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// Device information service +CONST uint8 devInfoServUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Model Number String +CONST uint8 devInfoModelNumberUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Firmware Revision String +CONST uint8 devInfoFirmwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Software Revision String +CONST uint8 devInfoSoftwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// 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) +}; + +// PnP ID +CONST uint8 devInfoPnpIdUUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(PNP_ID_UUID), HI_UINT16(PNP_ID_UUID) +}; + + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +/********************************************************************* + * Profile Attributes - variables + */ + +// Device Information Service attribute +static CONST gattAttrType_t devInfoService = { ATT_BT_UUID_SIZE, devInfoServUUID }; + +// System ID characteristic +static uint8 devInfoSystemIdProps = GATT_PROP_READ; +static uint8 devInfoSystemId[DEVINFO_SYSTEM_ID_LEN] = {0, 0, 0, 0, 0, 0, 0, 0}; + +// Model Number String characteristic +static uint8 devInfoModelNumberProps = GATT_PROP_READ; +static const uint8 devInfoModelNumber[] = "Model Number"; + +// Serial Number String characteristic +static uint8 devInfoSerialNumberProps = GATT_PROP_READ; +static const uint8 devInfoSerialNumber[] = "Serial Number"; + +// Firmware Revision String characteristic +static uint8 devInfoFirmwareRevProps = GATT_PROP_READ; +static const uint8 devInfoFirmwareRev[] = "Firmware Revision"; + +// Hardware Revision String characteristic +static uint8 devInfoHardwareRevProps = GATT_PROP_READ; +static const uint8 devInfoHardwareRev[] = "Hardware Revision"; + +// Software Revision String characteristic +static uint8 devInfoSoftwareRevProps = GATT_PROP_READ; +static const uint8 devInfoSoftwareRev[] = "Software Revision"; + +// Manufacturer Name String characteristic +static uint8 devInfoMfrNameProps = GATT_PROP_READ; +static const uint8 devInfoMfrName[] = "Manufacturer Name"; + +// IEEE 11073-20601 Regulatory Certification Data List characteristic +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: + 'e', 'x', 'p', 'e', 'r', 'i', 'm', 'e', 'n', 't', 'a', 'l' +}; + +// System ID characteristic +static uint8 devInfoPnpIdProps = GATT_PROP_READ; +static uint8 devInfoPnpId[DEVINFO_PNP_ID_LEN] = +{ + 1, // Vendor ID source (1=Bluetooth SIG) + LO_UINT16(0x07D7), HI_UINT16(0x07D7), // Vendor ID (WCH) + LO_UINT16(0x0000), HI_UINT16(0x0000), // Product ID (vendor-specific) + LO_UINT16(0x0110), HI_UINT16(0x0110) // Product version (JJ.M.N) +}; + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t devInfoAttrTbl[] = +{ + // Device Information Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&devInfoService /* pValue */ + }, + + // System ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSystemIdProps + }, + + // System ID Value + { + { ATT_BT_UUID_SIZE, devInfoSystemIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSystemId + }, + + // Model Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoModelNumberProps + }, + + // Model Number Value + { + { ATT_BT_UUID_SIZE, devInfoModelNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoModelNumber + }, + + // Serial Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSerialNumberProps + }, + + // Serial Number Value + { + { ATT_BT_UUID_SIZE, devInfoSerialNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSerialNumber + }, + + // Firmware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoFirmwareRevProps + }, + + // Firmware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoFirmwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoFirmwareRev + }, + + // Hardware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoHardwareRevProps + }, + + // Hardware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoHardwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoHardwareRev + }, + + // Software Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSoftwareRevProps + }, + + // Software Revision Value + { + { ATT_BT_UUID_SIZE, devInfoSoftwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSoftwareRev + }, + + // Manufacturer Name String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoMfrNameProps + }, + + // Manufacturer Name Value + { + { ATT_BT_UUID_SIZE, devInfoMfrNameUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoMfrName + }, + + // IEEE 11073-20601 Regulatory Certification Data List Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfo11073CertProps + }, + + // IEEE 11073-20601 Regulatory Certification Data List Value + { + { ATT_BT_UUID_SIZE, devInfo11073CertUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfo11073Cert + }, + + // PnP ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoPnpIdProps + }, + + // PnP ID Value + { + { ATT_BT_UUID_SIZE, devInfoPnpIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoPnpId + } +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Device Info Service Callbacks +gattServiceCBs_t devInfoCBs = +{ + devInfo_ReadAttrCB, // Read callback function pointer + NULL, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * NETWORK LAYER CALLBACKS + */ + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn DevInfo_AddService + * + * @brief Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + * @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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &devInfoCBs ); +} + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(devInfoSystemId, value, len); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn DevInfo_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(value, devInfoSystemId, sizeof(devInfoSystemId)); + break; + + case DEVINFO_MODEL_NUMBER: + tmos_memcpy(value, devInfoModelNumber, sizeof(devInfoModelNumber)); + break; + case DEVINFO_SERIAL_NUMBER: + tmos_memcpy(value, devInfoSerialNumber, sizeof(devInfoSerialNumber)); + break; + + case DEVINFO_FIRMWARE_REV: + tmos_memcpy(value, devInfoFirmwareRev, sizeof(devInfoFirmwareRev)); + break; + + case DEVINFO_HARDWARE_REV: + tmos_memcpy(value, devInfoHardwareRev, sizeof(devInfoHardwareRev)); + break; + + case DEVINFO_SOFTWARE_REV: + tmos_memcpy(value, devInfoSoftwareRev, sizeof(devInfoSoftwareRev)); + break; + + case DEVINFO_MANUFACTURER_NAME: + tmos_memcpy(value, devInfoMfrName, sizeof(devInfoMfrName)); + break; + + case DEVINFO_11073_CERT_DATA: + tmos_memcpy(value, devInfo11073Cert, sizeof(devInfo11073Cert)); + break; + + case DEVINFO_PNP_ID: + tmos_memcpy(value, devInfoPnpId, sizeof(devInfoPnpId)); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn devInfo_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch (uuid) + { + case SYSTEM_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoSystemId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoSystemId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSystemId[offset], *pLen); + } + break; + + case MODEL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoModelNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoModelNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoModelNumber[offset], *pLen); + } + break; + + case SERIAL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoSerialNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSerialNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSerialNumber[offset], *pLen); + } + break; + + case FIRMWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoFirmwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoFirmwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoFirmwareRev[offset], *pLen); + } + break; + + case HARDWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoHardwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoHardwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoHardwareRev[offset], *pLen); + } + break; + + case SOFTWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoSoftwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSoftwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSoftwareRev[offset], *pLen); + } + break; + + case MANUFACTURER_NAME_UUID: + // verify offset + if (offset >= (sizeof(devInfoMfrName) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoMfrName) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoMfrName[offset], *pLen); + } + break; + + case IEEE_11073_CERT_DATA_UUID: + // verify offset + if (offset >= sizeof(devInfo11073Cert)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfo11073Cert) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfo11073Cert[offset], *pLen); + } + break; + + case PNP_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoPnpId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoPnpId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoPnpId[offset], *pLen); + } + break; + + default: + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + + return ( status ); +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/Profile/gattprofile.c b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/gattprofile.c new file mode 100644 index 0000000..27c745c --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/gattprofile.c @@ -0,0 +1,702 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : GATTprofile.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ԶֲͬԵķ񣬰ɶд֪ͨɶдȫɶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "GATTprofile.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +#define SERVAPP_NUM_ATTR_SUPPORTED 17 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// 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: 0xFFF1 +CONST uint8 simpleProfilechar1UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR1_UUID), HI_UINT16(SIMPLEPROFILE_CHAR1_UUID) +}; + +// Characteristic 2 UUID: 0xFFF2 +CONST uint8 simpleProfilechar2UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR2_UUID), HI_UINT16(SIMPLEPROFILE_CHAR2_UUID) +}; + +// Characteristic 3 UUID: 0xFFF3 +CONST uint8 simpleProfilechar3UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR3_UUID), HI_UINT16(SIMPLEPROFILE_CHAR3_UUID) +}; + +// Characteristic 4 UUID: 0xFFF4 +CONST uint8 simpleProfilechar4UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR4_UUID), HI_UINT16(SIMPLEPROFILE_CHAR4_UUID) +}; + +// Characteristic 5 UUID: 0xFFF5 +CONST uint8 simpleProfilechar5UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR5_UUID), HI_UINT16(SIMPLEPROFILE_CHAR5_UUID) +}; + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +static simpleProfileCBs_t *simpleProfile_AppCBs = NULL; + +/********************************************************************* + * Profile Attributes - variables + */ + +// Simple Profile Service attribute +static CONST gattAttrType_t simpleProfileService = { ATT_BT_UUID_SIZE, simpleProfileServUUID }; + + +// Simple Profile Characteristic 1 Properties +static uint8 simpleProfileChar1Props = GATT_PROP_READ | GATT_PROP_WRITE; + +// Characteristic 1 Value +static uint8 simpleProfileChar1 = 0; + +// Simple Profile Characteristic 1 User Description +static uint8 simpleProfileChar1UserDesp[17] = "Characteristic 1\0"; + + +// Simple Profile Characteristic 2 Properties +static uint8 simpleProfileChar2Props = GATT_PROP_READ; + +// Characteristic 2 Value +static uint8 simpleProfileChar2 = 0; + +// Simple Profile Characteristic 2 User Description +static uint8 simpleProfileChar2UserDesp[17] = "Characteristic 2\0"; + + +// Simple Profile Characteristic 3 Properties +static uint8 simpleProfileChar3Props = GATT_PROP_WRITE; + +// Characteristic 3 Value +static uint8 simpleProfileChar3 = 0; + +// Simple Profile Characteristic 3 User Description +static uint8 simpleProfileChar3UserDesp[17] = "Characteristic 3\0"; + + +// Simple Profile Characteristic 4 Properties +static uint8 simpleProfileChar4Props = GATT_PROP_NOTIFY; + +// Characteristic 4 Value +static uint8 simpleProfileChar4 = 0; + +// Simple Profile Characteristic 4 Configuration Each client has its own +// instantiation of the Client Characteristic Configuration. Reads of the +// Client Characteristic Configuration only shows the configuration for +// that client and writes only affect the configuration of that client. +static gattCharCfg_t simpleProfileChar4Config[4]; + +// Simple Profile Characteristic 4 User Description +static uint8 simpleProfileChar4UserDesp[17] = "Characteristic 4\0"; + + +// Simple Profile Characteristic 5 Properties +static uint8 simpleProfileChar5Props = GATT_PROP_READ; + +// Characteristic 5 Value +static uint8 simpleProfileChar5[SIMPLEPROFILE_CHAR5_LEN] = { 0, 0, 0, 0, 0 }; + +// Simple Profile Characteristic 5 User Description +static uint8 simpleProfileChar5UserDesp[17] = "Characteristic 5\0"; + + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t simpleProfileAttrTbl[SERVAPP_NUM_ATTR_SUPPORTED] = +{ + // Simple Profile Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&simpleProfileService /* pValue */ + }, + + // Characteristic 1 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar1Props + }, + + // Characteristic Value 1 + { + { ATT_BT_UUID_SIZE, simpleProfilechar1UUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + &simpleProfileChar1 + }, + + // Characteristic 1 User Description + { + { 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, + 0, + &simpleProfileChar2 + }, + + // Characteristic 2 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar2UserDesp + }, + + // Characteristic 3 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar3Props + }, + + // Characteristic Value 3 + { + { ATT_BT_UUID_SIZE, simpleProfilechar3UUID }, + GATT_PERMIT_WRITE, + 0, + &simpleProfileChar3 + }, + + // Characteristic 3 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar3UserDesp + }, + + // Characteristic 4 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar4Props + }, + + // Characteristic Value 4 + { + { ATT_BT_UUID_SIZE, simpleProfilechar4UUID }, + 0, + 0, + &simpleProfileChar4 + }, + + // Characteristic 4 configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8 *)simpleProfileChar4Config + }, + + // Characteristic 4 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar4UserDesp + }, + + // Characteristic 5 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar5Props + }, + + // Characteristic Value 5 + { + { ATT_BT_UUID_SIZE, simpleProfilechar5UUID }, + GATT_PERMIT_AUTHEN_READ, + 0, + simpleProfileChar5 + }, + + // Characteristic 5 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar5UserDesp + }, + + +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ); + +static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); + + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Simple Profile Service Callbacks +gattServiceCBs_t simpleProfileCBs = +{ + simpleProfile_ReadAttrCB, // Read callback function pointer + simpleProfile_WriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn SimpleProfile_AddService + * + * @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. + * + * @return Success or Failure + */ +bStatus_t SimpleProfile_AddService( uint32 services ) +{ + uint8 status = SUCCESS; + + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar4Config ); + + // Register with Link DB to receive link status change callback + 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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &simpleProfileCBs ); + } + + return ( status ); +} + + +/********************************************************************* + * @fn SimpleProfile_RegisterAppCBs + * + * @brief Registers the application callback function. Only call + * this function once. + * + * @param callbacks - pointer to application callbacks. + * + * @return SUCCESS or bleAlreadyInRequestedMode + */ +bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) +{ + if ( appCallbacks ) + { + simpleProfile_AppCBs = appCallbacks; + + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } +} + + +/********************************************************************* + * @fn SimpleProfile_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar1 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR2: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar2 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR3: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar3 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR4: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar4 = *((uint8*)value); + + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR5: + if ( len == SIMPLEPROFILE_CHAR5_LEN ) + { + tmos_memcpy( simpleProfileChar5, value, SIMPLEPROFILE_CHAR5_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn SimpleProfile_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + *((uint8*)value) = simpleProfileChar1; + break; + + case SIMPLEPROFILE_CHAR2: + *((uint8*)value) = simpleProfileChar2; + break; + + case SIMPLEPROFILE_CHAR3: + *((uint8*)value) = simpleProfileChar3; + break; + + case SIMPLEPROFILE_CHAR4: + *((uint8*)value) = simpleProfileChar4; + break; + + case SIMPLEPROFILE_CHAR5: + tmos_memcpy( value, simpleProfileChar5, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn simpleProfile_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + + // If attribute permissions require authorization to read, return error + if ( gattPermitAuthorRead( pAttr->permissions ) ) + { + // 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 + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + // No need for "GATT_SERVICE_UUID" or "GATT_CLIENT_CHAR_CFG_UUID" cases; + // gattserverapp handles those reads + + // characteristics 1 and 2 have read permissions + // characteritisc 3 does not have read permissions; therefore it is not + // included here + // characteristic 4 does not have read permissions, but because it + // can be sent as a notification, it is included here + case SIMPLEPROFILE_CHAR1_UUID: + case SIMPLEPROFILE_CHAR2_UUID: + case SIMPLEPROFILE_CHAR4_UUID: + *pLen = 1; + pValue[0] = *pAttr->pValue; + break; + + case SIMPLEPROFILE_CHAR5_UUID: + *pLen = SIMPLEPROFILE_CHAR5_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint8 notifyApp = 0xFF; + + // If attribute permissions require authorization to write, return error + if ( gattPermitAuthorWrite( pAttr->permissions ) ) + { + // Insufficient authorization + return ( ATT_ERR_INSUFFICIENT_AUTHOR ); + } + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + case SIMPLEPROFILE_CHAR1_UUID: + case SIMPLEPROFILE_CHAR3_UUID: + + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len != 1 ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + uint8 *pCurValue = (uint8 *)pAttr->pValue; + *pCurValue = pValue[0]; + + if( pAttr->pValue == &simpleProfileChar1 ) + { + notifyApp = SIMPLEPROFILE_CHAR1; + } + else + { + notifyApp = SIMPLEPROFILE_CHAR3; + } + } + + break; + + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); + break; + + default: + // Should never get here! (characteristics 2 and 4 do not have write permissions) + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + status = ATT_ERR_INVALID_HANDLE; + } + + // 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 ); + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_HandleConnStatusCB + * + * @brief Simple Profile link status change handler function. + * + * @param connHandle - connection handle + * @param changeType - type of change + * + * @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 ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, simpleProfileChar4Config ); + } + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/OTAprofile.h b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/OTAprofile.h new file mode 100644 index 0000000..b786bd3 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/OTAprofile.h @@ -0,0 +1,98 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : OTAprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : +*******************************************************************************/ + +#ifndef OTAPROFILE_H +#define OTAPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// OTA ProfileͨIndex +#define OTAPROFILE_CHAR 0 + +// OTA UUID +#define OTAPROFILE_SERV_UUID 0xFEE0 + +// OTA ͨѶͨUUID +#define OTAPROFILE_CHAR_UUID 0xFEE1 + +// Simple Keys Profile Services bit fields +#define OTAPROFILE_SERVICE 0x00000001 + + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// дص +typedef void (*OTAProfileRead_t)( unsigned char paramID ); +typedef void (*OTAProfileWrite_t)( unsigned char paramID ,unsigned char *p_data, unsigned char w_len); + +typedef struct +{ + OTAProfileRead_t pfnOTAProfileRead; + OTAProfileWrite_t pfnOTAProfileWrite; +} OTAProfileCBs_t; + +/********************************************************************* + * API FUNCTIONS + */ + +/******************************************************************************* +* Function Name : OTAProfile_AddService +* Description : OTA Profileʼ +* Input : services +* Output : None +* Return : ʼ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_AddService( uint32 services ); +/******************************************************************************* +* Function Name : OTAProfile_RegisterAppCBs +* Description : OTA Profileдصע +* Input : appCallbacksṹָ +* Output : None +* Return : ִе״̬ +*******************************************************************************/ +bStatus_t OTAProfile_RegisterAppCBs( OTAProfileCBs_t *appCallbacks ); +/******************************************************************************* +* Function Name : OTAProfile_SendData +* Description : OTA Profileͨ +* Input : paramIDOTAͨѡ + p_dataָ + send_lenݳ +* Output : None +* Return : ִ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_SendData(unsigned char paramID ,unsigned char *p_data, unsigned char send_len ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/devinfoservice.h b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/devinfoservice.h new file mode 100644 index 0000000..a808937 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/devinfoservice.h @@ -0,0 +1,108 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef DEVINFOSERVICE_H +#define DEVINFOSERVICE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * 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 + +// 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 + +// System ID length +#define DEVINFO_SYSTEM_ID_LEN 8 + + // PnP ID length +#define DEVINFO_PNP_ID_LEN 7 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + + +/********************************************************************* + * API FUNCTIONS + */ + +/* + * DevInfo_AddService- Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + */ + +extern bStatus_t DevInfo_AddService( void ); + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ); + +/* + * 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). + */ +extern bStatus_t DevInfo_GetParameter( uint8 param, void *value ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif /* DEVINFOSERVICE_H */ diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/gattprofile.h b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/gattprofile.h new file mode 100644 index 0000000..ad9e613 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/Profile/include/gattprofile.h @@ -0,0 +1,127 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : GATTprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef GATTPROFILE_H +#define GATTPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// 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 + +// Simple Profile Service UUID +#define SIMPLEPROFILE_SERV_UUID 0xFFE0 + +// Key Pressed UUID +#define SIMPLEPROFILE_CHAR1_UUID 0xFFE1 +#define SIMPLEPROFILE_CHAR2_UUID 0xFFE2 +#define SIMPLEPROFILE_CHAR3_UUID 0xFFE3 +#define SIMPLEPROFILE_CHAR4_UUID 0xFFE4 +#define SIMPLEPROFILE_CHAR5_UUID 0xFFE5 + +// Simple Keys Profile Services bit fields +#define SIMPLEPROFILE_SERVICE 0x00000001 + +// Length of Characteristic 5 in bytes +#define SIMPLEPROFILE_CHAR4_LEN 8 +#define SIMPLEPROFILE_CHAR5_LEN 5 + +/********************************************************************* + * TYPEDEFS + */ + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// Callback when a characteristic value has changed +typedef void (*simpleProfileChange_t)( uint8 paramID ); + +typedef struct +{ + simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes +} simpleProfileCBs_t; + + + +/********************************************************************* + * API FUNCTIONS + */ + + +/* + * SimpleProfile_AddService- Initializes the Simple GATT 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. + */ + +extern bStatus_t SimpleProfile_AddService( uint32 services ); + +/* + * SimpleProfile_RegisterAppCBs - Registers the application callback function. + * Only call this function once. + * + * 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). + */ +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). + */ +extern bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ); + + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/BackupUpgrade_IAP/Project/BLE.uvprojx b/src/EXAM/BLE/BackupUpgrade_IAP/Project/BLE.uvprojx new file mode 100644 index 0000000..15a2585 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_IAP/Project/BLE.uvprojx @@ -0,0 +1,498 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + IAP + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x3c000 + 0x2800 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20004000 + 0x4000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG + + ..\APP\include;..\Profile\include;..\..\HAL\include;..\..\LIB;..\..\..\SRC\CMSIS\Include;..\..\..\SRC\StdPeriphDriver\inc + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + peripheral_main.c + 1 + ..\APP\peripheral_main.c + + + + + drive + + + startup_ARMCM0.s + 2 + ..\..\..\SRC\Startup\startup_ARMCM0.s + + + CH57x_clk.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_gpio.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_pwr.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_sys.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_uart1.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_int.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + 2 + 9 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_flash.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/APP/include/ota.h b/src/EXAM/BLE/BackupUpgrade_OTA/APP/include/ota.h new file mode 100644 index 0000000..d56102e --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/APP/include/ota.h @@ -0,0 +1,118 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : ota.h +* Author : WCH +* Version : V1.10 +* Date : 2018/12/14 +* Description : oadö +*******************************************************************************/ + + +/******************************************************************************/ +#ifndef __OTA_H +#define __OTA_H + + +/* ------------------------------------------------------------------------------------------------ + * OTA FLASH + * ------------------------------------------------------------------------------------------------ + */ + +/* ûcodeֳ飬120K120K10KֱimageAû룩imageB ݴ룩imageIAP*/ + +/* FLASH */ +#define FLASH_BLOCK_SIZE 512 +#define IMAGE_SIZE 120*1024 + +/* imageA */ +#define IMAGE_A_FLAG 0x01 +#define IMAGE_A_START_ADD 0 +#define IMAGE_A_SIZE IMAGE_SIZE +#define IMAGE_A_ENTRY_ADD (IMAGE_A_START_ADD + 4) + +/* imageB */ +#define IMAGE_B_FLAG 0x02 +#define IMAGE_B_START_ADD (IMAGE_A_START_ADD + IMAGE_SIZE) +#define IMAGE_B_SIZE IMAGE_SIZE +#define IMAGE_B_ENTRY_ADD (IMAGE_B_START_ADD + 4) + +/* imageIAP */ +#define IMAGE_IAP_FLAG 0x03 +#define IMAGE_IAP_START_ADD (IMAGE_B_START_ADD + IMAGE_SIZE) +#define IMAGE_IAP_SIZE 10*1024 +#define IMAGE_IAP_ENTRY_ADD (IMAGE_IAP_START_ADD + 4) + +/* IAP */ +/* ΪIAP */ +#define CMD_IAP_PROM 0x80 // IAP +#define CMD_IAP_ERASE 0x81 // IAP +#define CMD_IAP_VERIFY 0x82 // IAPУ +#define CMD_IAP_END 0x83 // IAP־ +#define CMD_IAP_INFO 0x84 // IAPȡ豸Ϣ + + +/* ֡ȶ */ +#define IAP_LEN 20 + +/* DataFlashַռλ */ +#define OTA_DATAFLASH_ADD 0x0003E800 + + +/* DataFlashOTAϢ */ +typedef struct +{ + unsigned char ImageFlag; //¼ĵǰimage־ + unsigned char Revd[3]; +}OTADataFlashInfo_t; + +/* OTA IAPͨѶЭ鶨 */ +/* ַʹ4ƫ */ +typedef union +{ + struct + { + unsigned char cmd; /* 0x81 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char block_num[2]; /* */ + + } erase; /* */ + struct + { + unsigned char cmd; /* 0x83 */ + unsigned char len; /* ݳ */ + unsigned char status[2]; /* ֽ״̬ */ + } end; /* */ + struct + { + unsigned char cmd; /* 0x82 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* Уַ */ + unsigned char buf[IAP_LEN-4]; /* У */ + } verify; /* У */ + struct + { + unsigned char cmd; /* 0x80 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char buf[IAP_LEN-4]; /* */ + } program; /* */ + struct + { + unsigned char cmd; /* 0x84 */ + unsigned char len; /* ݳ */ + unsigned char buf[IAP_LEN-2]; /* */ + } info; /* */ + struct + { + unsigned char buf[IAP_LEN]; /* ݰ*/ + } other; +} OTA_IAP_CMD_t; + + +/* ¼ǰImage */ +extern unsigned char CurrImageFlag; + + +#endif + +/******************************** endfile @ oad ******************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/APP/include/peripheral.h b/src/EXAM/BLE/BackupUpgrade_OTA/APP/include/peripheral.h new file mode 100644 index 0000000..86e442a --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/APP/include/peripheral.h @@ -0,0 +1,59 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef PERIPHERAL_H +#define PERIPHERAL_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + + +// Simple BLE Peripheral Task Events +#define SBP_START_DEVICE_EVT 0x0001 +#define SBP_PERIODIC_EVT 0x0002 +#define OTA_FLASH_ERASE_EVT 0x0004 //OTA Flash + + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * FUNCTIONS + */ + +/* + * Task Initialization for the BLE Application + */ +extern void Peripheral_Init( void ); + +/* + * Task Event Processor for the BLE Application + */ +extern uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/APP/peripheral.c b/src/EXAM/BLE/BackupUpgrade_OTA/APP/peripheral.c new file mode 100644 index 0000000..5425a77 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/APP/peripheral.c @@ -0,0 +1,822 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : Peripheral.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ӻӦó򣬳ʼ㲥ӲȻ㲥ֱͨԶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "devinfoservice.h" +#include "GATTprofile.h" +#include "Peripheral.h" +#include "OTA.h" +#include "OTAprofile.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// How often to perform periodic event +#define SBP_PERIODIC_EVT_PERIOD 1000 + +// What is the advertising interval when device is discoverable (units of 625us, 160=100ms) +#define DEFAULT_ADVERTISING_INTERVAL 160 + +// Limited discoverable mode advertises for 30.72s, and then stops +// General discoverable mode advertises indefinitely + +#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL + +// Minimum connection interval (units of 1.25ms, 80=100ms) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 6 + +// Maximum connection interval (units of 1.25ms, 800=1000ms) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 12 + +// Slave latency to use if automatic parameter update request is enabled +#define DEFAULT_DESIRED_SLAVE_LATENCY 0 + +// Supervision timeout value (units of 10ms, 1000=10s) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_CONN_TIMEOUT 1000 + +// Whether to enable automatic parameter update request when a connection is formed +#define DEFAULT_ENABLE_UPDATE_REQUEST TRUE + +// Connection Pause Peripheral time value (in seconds) +#define DEFAULT_CONN_PAUSE_PERIPHERAL 6 + +// Company Identifier: WCH +#define WCH_COMPANY_ID 0x07D7 + +#define INVALID_CONNHANDLE 0xFFFF + +// Length of bd addr as a string +#define B_ADDR_STR_LEN 15 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ +static uint8 Peripheral_TaskID=0xff; // Task ID for internal task/event processing + +// GAP - SCAN RSP data (max size = 31 bytes) +static uint8 scanRspData[31] = +{ + // complete name + 0x12, // length of this data + GAP_ADTYPE_LOCAL_NAME_COMPLETE, + 's','i','m','p','l','e',' ','P','e','r','i','p','h','e','r','a','l', + // connection interval range + 0x05, // length of this data + GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE, + LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), // 100ms + HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), + LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), // 1s + HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), + + // Tx power level + 0x02, // length of this data + GAP_ADTYPE_POWER_LEVEL, + 0 // 0dBm +}; + +// GAP - Advertisement data (max size = 31 bytes, though this is +// best kept short to conserve power while advertisting) +static uint8 advertData[] = +{ + // Flags; this sets the device to use limited discoverable + // mode (advertises for 30 seconds at a time) instead of general + // discoverable mode (advertises indefinitely) + 0x02, // length of this data + GAP_ADTYPE_FLAGS, + DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED, + + // service UUID, to notify central devices what services are included + // in this peripheral + 0x03, // length of this data + GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all + LO_UINT16( SIMPLEPROFILE_SERV_UUID ), + HI_UINT16( SIMPLEPROFILE_SERV_UUID ) + +}; + +// GAP GATT Attributes +static uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "Simple Peripheral"; + +// OTA IAP VARIABLES +/* OTAͨѶ֡ */ +OTA_IAP_CMD_t iap_rec_data; + +/* OTA */ +__align(8) UINT32 OpParaData[4]; +UINT32 OpParaDataLen = 0; +UINT32 OpAdd = 0; + +/* flashһʱ洢 */ +__align(8) uint8 vectors_block_buf[FLASH_BLOCK_SIZE]; + +/* dataflashʱ */ +__align(8) uint8 dataflash_block_buf[FLASH_BLOCK_SIZE]; + +/* Imageתַ */ +typedef int( *pImageTaskFn)( void ); +pImageTaskFn user_image_tasks; + +/* Flash */ +UINT32 EraseAdd = 0; //ַ +UINT32 EraseBlockNum = 0; //ҪĿ +UINT32 EraseBlockCnt = 0; //Ŀ + +/* FLASH У */ +UINT8 VerifyStatus = 0; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ); +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent ); +static void performPeriodicTask( void ); +static void simpleProfileChangeCB( uint8 paramID ); +void OTA_IAPReadDataComplete( unsigned char index ); +void OTA_IAPWriteData( unsigned char index, unsigned char *p_data, unsigned char w_len ); +void Rec_OTA_IAP_DataDeal(void); +void OTA_IAP_SendCMDDealSta(UINT8 deal_status); + +/********************************************************************* + * PROFILE CALLBACKS + */ + +// GAP Role Callbacks +static gapRolesCBs_t Peripheral_PeripheralCBs = +{ + peripheralStateNotificationCB, // Profile State Change Callbacks + NULL, // When a valid RSSI is read from controller (not used by application) + NULL +}; + +// GAP Bond Manager Callbacks +static gapBondCBs_t Peripheral_BondMgrCBs = +{ + NULL, // Passcode callback (not used by application) + NULL // Pairing / Bonding state Callback (not used by application) +}; + +// Simple GATT Profile Callbacks +static simpleProfileCBs_t Peripheral_SimpleProfileCBs = +{ + simpleProfileChangeCB // Charactersitic value change callback +}; + +// Simple GATT Profile Callbacks +static OTAProfileCBs_t Peripheral_OTA_IAPProfileCBs = +{ + OTA_IAPReadDataComplete, // Charactersitic value change callback + OTA_IAPWriteData +}; + + + +// Callback when the connection parameteres are updated. +void PeripheralParamUpdate(uint16 connInterval,uint16 connSlaveLatency, uint16 connTimeout); + +gapRolesParamUpdateCB_t PeripheralParamUpdate_t = NULL; + + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn Peripheral_Init + * + * @brief Initialization function for the 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 TMOS. This ID should be + * used to send messages and set timers. + * + * @return none + */ +void Peripheral_Init( ) +{ + Peripheral_TaskID = TMOS_ProcessEventRegister(Peripheral_ProcessEvent); + + // Setup the GAP Peripheral Role Profile + { + // For other hardware platforms, device starts advertising upon initialization + uint8 initial_advertising_enable = TRUE; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); + GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); + + //PeripheralParamUpdate_t = (gapRolesParamUpdateCB_t *)PeripheralParamUpdate; + + //PRINT( "PeripheralParamUpdate_t %08x \n",(int)PeripheralParamUpdate_t ); + + //GAPRole_PeripheralRegisterAppCBs( (gapRolesParamUpdateCB_t *)&PeripheralParamUpdate ); + } + + // Set the GAP Characteristics + GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); + + // Set advertising interval + { + uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; + + GAP_SetParamValue( TGAP_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_DISC_ADV_INT_MAX, advInt ); + } + + // Setup the GAP Bond Manager + { + uint32 passkey = 0; // passkey "000000" + uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; + uint8 mitm = TRUE; + uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; + uint8 bonding = TRUE; + GAPBondMgr_SetParameter( GAPBOND_PERI_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); + GAPBondMgr_SetParameter( GAPBOND_PERI_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); + GAPBondMgr_SetParameter( GAPBOND_PERI_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); + GAPBondMgr_SetParameter( GAPBOND_PERI_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); + GAPBondMgr_SetParameter( GAPBOND_PERI_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); + } + + // 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 + OTAProfile_AddService( GATT_ALL_SERVICES ); + + // Setup the SimpleProfile Characteristic Values + { + uint8 charValue1 = 1; + uint8 charValue2 = 2; + uint8 charValue3 = 3; + uint8 charValue4[SIMPLEPROFILE_CHAR4_LEN] = "01234567"; + uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 }; + + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, sizeof ( uint8 ), &charValue1 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, sizeof ( uint8 ), &charValue2 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 ); + + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, charValue4 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); + } + + // + { + //GAPRole_PeripheralRegisterAppCBs( (gapRolesParamUpdateCB_t *)PeripheralParamUpdate_t ); + + } + + // Register callback with SimpleGATTprofile + SimpleProfile_RegisterAppCBs( &Peripheral_SimpleProfileCBs ); + + // Register callback with OTAGATTprofile + OTAProfile_RegisterAppCBs( &Peripheral_OTA_IAPProfileCBs ); + + // Setup a delayed profile startup + tmos_set_event( Peripheral_TaskID, SBP_START_DEVICE_EVT ); + +} + +void PeripheralParamUpdate(uint16 connInterval,uint16 connSlaveLatency, uint16 connTimeout) +{ + PRINT( "update %d %d %d \n",connInterval,connSlaveLatency,connTimeout ); + +// GAPRole_SendUpdateParam( DEFAULT_DESIRED_MIN_CONN_INTERVAL, DEFAULT_DESIRED_MAX_CONN_INTERVAL, +// DEFAULT_DESIRED_SLAVE_LATENCY, DEFAULT_DESIRED_CONN_TIMEOUT, GAPROLE_NO_ACTION ); + +} + +/********************************************************************* + * @fn Peripheral_ProcessEvent + * + * @brief 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 TMOS assigned task ID. + * @param events - events to process. This is a bit map and can + * contain more than one event. + * + * @return events not processed + */ +uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ) +{ + +// VOID task_id; // TMOS required parameter that isn't used in this function + + if ( events & SYS_EVENT_MSG ){ + uint8 *pMsg; + + if ( (pMsg = tmos_msg_receive( Peripheral_TaskID )) != NULL ){ + Peripheral_ProcessTMOSMsg( (tmos_event_hdr_t *)pMsg ); + // Release the TMOS message + tmos_msg_deallocate( pMsg ); + } + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } + + if ( events & SBP_START_DEVICE_EVT ){ + // Start the Device + GAPRole_PeripheralStartDevice( Peripheral_TaskID, &Peripheral_BondMgrCBs, &Peripheral_PeripheralCBs ); + // Set timer for first periodic event + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + return ( events ^ SBP_START_DEVICE_EVT ); + } + + if ( events & SBP_PERIODIC_EVT ){ + // Restart timer + if ( SBP_PERIODIC_EVT_PERIOD ){ + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + } + // Perform periodic application task + performPeriodicTask(); + return (events ^ SBP_PERIODIC_EVT); + } + + //OTA_FLASH_ERASE_EVT + if ( events & OTA_FLASH_ERASE_EVT ) + { + UINT8 status; + + PRINT("ERASE:%08x num:%d\r\n",(int)(EraseAdd+EraseBlockCnt*FLASH_BLOCK_SIZE),(int)EraseBlockCnt); + status = FlashBlockErase(EraseAdd+EraseBlockCnt*FLASH_BLOCK_SIZE); + + /* ʧ */ + if(status != SUCCESS) + { + OTA_IAP_SendCMDDealSta(status); + return (events ^ OTA_FLASH_ERASE_EVT); + } + + EraseBlockCnt++; + + /* */ + if( EraseBlockCnt >= EraseBlockNum ) + { + PRINT("ERASE Complete\r\n"); + OTA_IAP_SendCMDDealSta(status); + return (events ^ OTA_FLASH_ERASE_EVT); + } + + return (events); + } + + // Discard unknown events + return 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessTMOSMsg + * + * @brief Process an incoming task message. + * + * @param pMsg - message to process + * + * @return none + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ) +{ + switch ( pMsg->event ){ + default: + break; + } +} + +/********************************************************************* + * @fn peripheralStateNotificationCB + * + * @brief Notification from the profile of a state change. + * + * @param newState - new state + * + * @return none + */ +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent ) +{ + switch ( newState ) + { + case GAPROLE_STARTED: + PRINT( "Initialized..\n" ); + break; + + case GAPROLE_ADVERTISING: + PRINT( "Advertising..\n" ); + break; + + case GAPROLE_CONNECTED: + { + gapEstLinkReqEvent_t *event = (gapEstLinkReqEvent_t *) pEvent; + uint16 conn_interval = 0; + + conn_interval = event->connInterval; + PRINT( "Connected.. \n" ); + + if( conn_interval > DEFAULT_DESIRED_MAX_CONN_INTERVAL) + { + PRINT("Send Update\r\n"); + GAPRole_PeripheralConnParamUpdateReq( event->connectionHandle, + DEFAULT_DESIRED_MIN_CONN_INTERVAL, + DEFAULT_DESIRED_MAX_CONN_INTERVAL, + DEFAULT_DESIRED_SLAVE_LATENCY, + DEFAULT_DESIRED_CONN_TIMEOUT, + Peripheral_TaskID ); + + } + break; + } + case GAPROLE_CONNECTED_ADV: + PRINT( "Connected Advertising..\n" ); + break; + case GAPROLE_WAITING: + { + uint8 initial_advertising_enable = TRUE; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + PRINT( "Disconnected..\n" ); + } + break; + + case GAPROLE_ERROR: + PRINT( "Error..\n" ); + break; + + default: + break; + + } +} + +/********************************************************************* + * @fn performPeriodicTask + * + * @brief Perform a periodic application task. This function gets + * called every five seconds as a result of the SBP_PERIODIC_EVT + * TMOS event. In this example, the value of the third + * characteristic in the SimpleGATTProfile service is retrieved + * from the profile, and then copied into the value of the + * the fourth characteristic. + * + * @param none + * + * @return none + */ +static void performPeriodicTask( void ) +{ + uint8 valueToCopy[SIMPLEPROFILE_CHAR4_LEN]; + uint8 stat; + + // Call to retrieve the value of the third characteristic in the profile + stat = SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR4, valueToCopy); + if( stat == SUCCESS ){ + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, valueToCopy); + } +} + +/********************************************************************* + * @fn simpleProfileChangeCB + * + * @brief Callback from Profile indicating a value change + * + * @param paramID - parameter ID of the value that was changed. + * + * @return none + */ +static void simpleProfileChangeCB( uint8 paramID ) +{ + uint8 newValue; + + switch( paramID ) + { + case SIMPLEPROFILE_CHAR1: + PRINT("profile ChangeCB CHAR1..\n"); + SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, &newValue ); + break; + + case SIMPLEPROFILE_CHAR3: + PRINT("profile ChangeCB CHAR3..\n"); + SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, &newValue ); + break; + + default: + // should not reach here! + break; + } +} + +/******************************************************************************* +* Function Name : OTA_IAP_SendData +* Description : OTA IAPݣʹʱ20ֽ +* Input : p_send_dataݵָ + send_lenݵij +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_SendData(UINT8 *p_send_data,UINT8 send_len) +{ + OTAProfile_SendData(OTAPROFILE_CHAR ,p_send_data, send_len ); +} + +/******************************************************************************* +* Function Name : OTA_IAP_SendCMDDealSta +* Description : OTA IAPִе״̬ +* Input : deal_statusص״̬ +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_SendCMDDealSta(UINT8 deal_status) +{ + UINT8 send_buf[2]; + + send_buf[0] = deal_status; + send_buf[1] = 0; + OTA_IAP_SendData(send_buf,2); +} + +/******************************************************************************* +* Function Name : OTA_IAP_CMDErrDeal +* Description : OTA IAP쳣봦 +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_CMDErrDeal(void) +{ + OTA_IAP_SendCMDDealSta(0xfe); +} + +/******************************************************************************* +* Function Name : SwitchImageFlag +* Description : лdataflashImageFlag +* Input : new_flagлImageFlag +* Output : none +* Return : none +*******************************************************************************/ +void SwitchImageFlag(UINT8 new_flag) +{ + UINT8 *p_flash; + UINT16 i; + UINT8 ver_flag; + + /* ȡһ */ + p_flash = (UINT8 *)OTA_DATAFLASH_ADD; + for(i=0; iICER[0] = 0xffffffff; + SysTick->CTRL = 0; //رSysTickж +} + +/******************************************************************************* +* Function Name : GotoResetVector +* Description : ȡתַת +* Input : entry_addResetַ +* Output : none +* Return : none +*******************************************************************************/ +void GotoResetVector(UINT32 entry_add) +{ + user_image_tasks = (pImageTaskFn)(*(UINT32 *)(entry_add)); + (user_image_tasks)(); +} + +/******************************************************************************* +* Function Name : Rec_OTA_IAP_DataDeal +* Description : յOTAݰ +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void Rec_OTA_IAP_DataDeal(void) +{ + switch(iap_rec_data.other.buf[0]) + { + /* */ + case CMD_IAP_PROM: + { + UINT32 i; + UINT8 status; + + OpParaDataLen = iap_rec_data.program.len; + + OpAdd = (UINT32)(iap_rec_data.program.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.program.addr[1]) << 8); + OpAdd = OpAdd * 4; + + OpAdd += IMAGE_B_START_ADD; + PRINT("IAP_PROM: %08x len:%d \r\n",(int)OpAdd,(int)OpParaDataLen); + + for(i=0; i<(OpParaDataLen/4); i++) + { + OpParaData[i] = (UINT32)(iap_rec_data.program.buf[0+4*i]); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[1+4*i]) << 8); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[2+4*i]) << 16); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[3+4*i]) << 24); + } + + status = FlashWriteBuf(OpAdd, OpParaData, (UINT16) OpParaDataLen); + + if( status ) OTA_IAP_SendCMDDealSta(status); + break; + } + /* -- */ + case CMD_IAP_ERASE: + { + OpAdd = (UINT32)(iap_rec_data.erase.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.erase.addr[1]) << 8); + OpAdd = OpAdd * 4; + + OpAdd += IMAGE_B_START_ADD; + EraseBlockNum = (UINT32)(iap_rec_data.erase.block_num[0]); + EraseBlockNum |= ((UINT32)(iap_rec_data.erase.block_num[1]) << 8); + EraseAdd = OpAdd; + EraseBlockCnt = 0; + + /* ͷڲ0 */ + VerifyStatus = 0; + + PRINT("IAP_ERASE start:%08x num:%d\r\n",(int)OpAdd,(int)EraseBlockNum); + + /* */ + tmos_set_event( Peripheral_TaskID, OTA_FLASH_ERASE_EVT ); + break; + } + /* У */ + case CMD_IAP_VERIFY: + { + UINT32 i; + UINT8 *p_flash; + UINT8 status = 0; + + OpParaDataLen = iap_rec_data.verify.len; + + OpAdd = (UINT32)(iap_rec_data.verify.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.verify.addr[1]) << 8); + OpAdd = OpAdd * 4; + + OpAdd += IMAGE_B_START_ADD; + PRINT("IAP_VERIFY: %08x len:%d \r\n",(int)OpAdd,(int)OpParaDataLen); + + p_flash = (UINT8 *)OpAdd; + + /* ǰImageAֱӶȡImageBУ */ + for(i=0; i>8) & 0xff); + send_buf[3] = (UINT8)((IMAGE_SIZE>>16) & 0xff); + send_buf[4] = (UINT8)((IMAGE_SIZE>>24) & 0xff); + + /* BLOCK SIZE */ + send_buf[5] = (UINT8)(FLASH_BLOCK_SIZE & 0xff); + send_buf[6] = (UINT8)((FLASH_BLOCK_SIZE>>8) & 0xff); + + /* Ҫ */ + + /* Ϣ */ + OTA_IAP_SendData(send_buf,20); + + break; + } + + default: + { + OTA_IAP_CMDErrDeal(); + break; + } + } +} + +/******************************************************************************* +* Function Name : OTA_IAPReadDataComplete +* Description : OTA ݶȡɴ +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAPReadDataComplete( unsigned char index ) +{ + PRINT("OTA Send Comp \r\n"); +} + +/******************************************************************************* +* Function Name : OTA_IAPWriteData +* Description : OTA ͨݽɴ +* Input : indexOTA ͨ + p_dataд + w_lenдij +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAPWriteData( unsigned char index, unsigned char *p_data, unsigned char w_len ) +{ + unsigned char rec_len; + unsigned char *rec_data; + + rec_len = w_len; + rec_data = p_data; + tmos_memcpy( (unsigned char *)&iap_rec_data, rec_data, rec_len ); + Rec_OTA_IAP_DataDeal(); +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/APP/peripheral_main.c b/src/EXAM/BLE/BackupUpgrade_OTA/APP/peripheral_main.c new file mode 100644 index 0000000..07d8187 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/APP/peripheral_main.c @@ -0,0 +1,123 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.1 +* Date : 2019/11/05 +* Description : ӻӦϵͳʼ +*******************************************************************************/ + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "GATTprofile.h" +#include "Peripheral.h" +#include "OTA.h" +#include "OTAprofile.h" + + +/* ¼ǰImage */ +unsigned char CurrImageFlag = 0xff; + +__align(8) unsigned char flash_buf[FLASH_BLOCK_SIZE]; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +#if (defined (BLE_MAC)) && (BLE_MAC == TRUE) +u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; +#endif + +/* ע⣺ڳflashIJִУκжϣֹжϺʧ */ +/******************************************************************************* +* Function Name : ReadImageFlag +* Description : ȡǰijImage־DataFlashΪգĬImageA +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +void ReadImageFlag(void) +{ + UINT8 *p_image_flash; + + p_image_flash = (UINT8 *)OTA_DATAFLASH_ADD; + CurrImageFlag = *p_image_flash; + + /* һִУûи¹ԺºڲDataFlash */ + if( CurrImageFlag != IMAGE_A_FLAG && CurrImageFlag != IMAGE_B_FLAG ) + { + CurrImageFlag = IMAGE_A_FLAG; + } + + PRINT("Image Flag %02x\n",CurrImageFlag); +} + +/******************************************************************************* +* Function Name : ImageVectorsCopy +* Description : ִжİƣImageAImageBʱִ +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +void ImageVectorsCopy(void) +{ + unsigned int vectors_entry; + + /* ȡǰijڵַ */ + vectors_entry = *(unsigned int *)IMAGE_A_ENTRY_ADD; + + /* ImageA->ImageBǰImageBImageAҪ */ + if( (CurrImageFlag == IMAGE_B_FLAG) && (vectors_entry < IMAGE_B_START_ADD) ) + { + unsigned int i; + unsigned char *p_flash; + + /* ȡImageBĴһ */ + p_flash = (UINT8 *)IMAGE_B_START_ADD; + for(i=0; itype.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch ( uuid ) + { + case OTAPROFILE_CHAR_UUID: + { + *pLen = 0; + if( OTAProfileReadLen ) + { + *pLen = OTAProfileReadLen; + tmos_memcpy( pValue, OTAProfileReadBuf, OTAProfileReadLen ); + OTAProfileReadLen = 0; + if( OTAProfile_AppCBs && OTAProfile_AppCBs->pfnOTAProfileRead ) + { + OTAProfile_AppCBs->pfnOTAProfileRead(OTAPROFILE_CHAR); + } + } + break; + } + default: + { + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn OTAProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t OTAProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + //uint8 notifyApp = 0xFF; + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch ( uuid ) + { + case OTAPROFILE_CHAR_UUID: + { + //Write the value + if ( status == SUCCESS ) + { + uint16 i; + uint8 *p_rec_buf; + + OTAProfileWriteLen = len; + p_rec_buf = pValue; + for(i=0; ipfnOTAProfileWrite) + { + OTAProfile_AppCBs->pfnOTAProfileWrite(OTAPROFILE_CHAR,OTAProfileWriteBuf,OTAProfileWriteLen); + OTAProfileWriteLen = 0; + } + + return ( status ); +} + +/******************************************************************************* +* Function Name : OTAProfile_SendData +* Description : OTA Profileͨ +* Input : paramIDOTAͨѡ + p_dataָ + send_lenݳ +* Output : None +* Return : ִ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_SendData(unsigned char paramID ,unsigned char *p_data, unsigned char send_len ) +{ + bStatus_t status = SUCCESS; + + /* ݳȳΧ */ + if( send_len > 20 ) return 0xfe; + + OTAProfileReadLen = send_len; + tmos_memcpy( OTAProfileReadBuf, p_data, OTAProfileReadLen ); + + return status; +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/Profile/devinfoservice.c b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/devinfoservice.c new file mode 100644 index 0000000..c63f6a7 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/devinfoservice.c @@ -0,0 +1,631 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.c +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : 豸Ϣ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "devinfoservice.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// Device information service +CONST uint8 devInfoServUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Model Number String +CONST uint8 devInfoModelNumberUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Firmware Revision String +CONST uint8 devInfoFirmwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Software Revision String +CONST uint8 devInfoSoftwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// 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) +}; + +// PnP ID +CONST uint8 devInfoPnpIdUUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(PNP_ID_UUID), HI_UINT16(PNP_ID_UUID) +}; + + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +/********************************************************************* + * Profile Attributes - variables + */ + +// Device Information Service attribute +static CONST gattAttrType_t devInfoService = { ATT_BT_UUID_SIZE, devInfoServUUID }; + +// System ID characteristic +static uint8 devInfoSystemIdProps = GATT_PROP_READ; +static uint8 devInfoSystemId[DEVINFO_SYSTEM_ID_LEN] = {0, 0, 0, 0, 0, 0, 0, 0}; + +// Model Number String characteristic +static uint8 devInfoModelNumberProps = GATT_PROP_READ; +static const uint8 devInfoModelNumber[] = "Model Number"; + +// Serial Number String characteristic +static uint8 devInfoSerialNumberProps = GATT_PROP_READ; +static const uint8 devInfoSerialNumber[] = "Serial Number"; + +// Firmware Revision String characteristic +static uint8 devInfoFirmwareRevProps = GATT_PROP_READ; +static const uint8 devInfoFirmwareRev[] = "Firmware Revision"; + +// Hardware Revision String characteristic +static uint8 devInfoHardwareRevProps = GATT_PROP_READ; +static const uint8 devInfoHardwareRev[] = "Hardware Revision"; + +// Software Revision String characteristic +static uint8 devInfoSoftwareRevProps = GATT_PROP_READ; +static const uint8 devInfoSoftwareRev[] = "Software Revision"; + +// Manufacturer Name String characteristic +static uint8 devInfoMfrNameProps = GATT_PROP_READ; +static const uint8 devInfoMfrName[] = "Manufacturer Name"; + +// IEEE 11073-20601 Regulatory Certification Data List characteristic +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: + 'e', 'x', 'p', 'e', 'r', 'i', 'm', 'e', 'n', 't', 'a', 'l' +}; + +// System ID characteristic +static uint8 devInfoPnpIdProps = GATT_PROP_READ; +static uint8 devInfoPnpId[DEVINFO_PNP_ID_LEN] = +{ + 1, // Vendor ID source (1=Bluetooth SIG) + LO_UINT16(0x07D7), HI_UINT16(0x07D7), // Vendor ID (WCH) + LO_UINT16(0x0000), HI_UINT16(0x0000), // Product ID (vendor-specific) + LO_UINT16(0x0110), HI_UINT16(0x0110) // Product version (JJ.M.N) +}; + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t devInfoAttrTbl[] = +{ + // Device Information Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&devInfoService /* pValue */ + }, + + // System ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSystemIdProps + }, + + // System ID Value + { + { ATT_BT_UUID_SIZE, devInfoSystemIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSystemId + }, + + // Model Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoModelNumberProps + }, + + // Model Number Value + { + { ATT_BT_UUID_SIZE, devInfoModelNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoModelNumber + }, + + // Serial Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSerialNumberProps + }, + + // Serial Number Value + { + { ATT_BT_UUID_SIZE, devInfoSerialNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSerialNumber + }, + + // Firmware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoFirmwareRevProps + }, + + // Firmware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoFirmwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoFirmwareRev + }, + + // Hardware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoHardwareRevProps + }, + + // Hardware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoHardwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoHardwareRev + }, + + // Software Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSoftwareRevProps + }, + + // Software Revision Value + { + { ATT_BT_UUID_SIZE, devInfoSoftwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSoftwareRev + }, + + // Manufacturer Name String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoMfrNameProps + }, + + // Manufacturer Name Value + { + { ATT_BT_UUID_SIZE, devInfoMfrNameUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoMfrName + }, + + // IEEE 11073-20601 Regulatory Certification Data List Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfo11073CertProps + }, + + // IEEE 11073-20601 Regulatory Certification Data List Value + { + { ATT_BT_UUID_SIZE, devInfo11073CertUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfo11073Cert + }, + + // PnP ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoPnpIdProps + }, + + // PnP ID Value + { + { ATT_BT_UUID_SIZE, devInfoPnpIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoPnpId + } +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Device Info Service Callbacks +gattServiceCBs_t devInfoCBs = +{ + devInfo_ReadAttrCB, // Read callback function pointer + NULL, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * NETWORK LAYER CALLBACKS + */ + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn DevInfo_AddService + * + * @brief Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + * @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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &devInfoCBs ); +} + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(devInfoSystemId, value, len); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn DevInfo_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(value, devInfoSystemId, sizeof(devInfoSystemId)); + break; + + case DEVINFO_MODEL_NUMBER: + tmos_memcpy(value, devInfoModelNumber, sizeof(devInfoModelNumber)); + break; + case DEVINFO_SERIAL_NUMBER: + tmos_memcpy(value, devInfoSerialNumber, sizeof(devInfoSerialNumber)); + break; + + case DEVINFO_FIRMWARE_REV: + tmos_memcpy(value, devInfoFirmwareRev, sizeof(devInfoFirmwareRev)); + break; + + case DEVINFO_HARDWARE_REV: + tmos_memcpy(value, devInfoHardwareRev, sizeof(devInfoHardwareRev)); + break; + + case DEVINFO_SOFTWARE_REV: + tmos_memcpy(value, devInfoSoftwareRev, sizeof(devInfoSoftwareRev)); + break; + + case DEVINFO_MANUFACTURER_NAME: + tmos_memcpy(value, devInfoMfrName, sizeof(devInfoMfrName)); + break; + + case DEVINFO_11073_CERT_DATA: + tmos_memcpy(value, devInfo11073Cert, sizeof(devInfo11073Cert)); + break; + + case DEVINFO_PNP_ID: + tmos_memcpy(value, devInfoPnpId, sizeof(devInfoPnpId)); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn devInfo_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch (uuid) + { + case SYSTEM_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoSystemId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoSystemId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSystemId[offset], *pLen); + } + break; + + case MODEL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoModelNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoModelNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoModelNumber[offset], *pLen); + } + break; + + case SERIAL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoSerialNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSerialNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSerialNumber[offset], *pLen); + } + break; + + case FIRMWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoFirmwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoFirmwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoFirmwareRev[offset], *pLen); + } + break; + + case HARDWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoHardwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoHardwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoHardwareRev[offset], *pLen); + } + break; + + case SOFTWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoSoftwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSoftwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSoftwareRev[offset], *pLen); + } + break; + + case MANUFACTURER_NAME_UUID: + // verify offset + if (offset >= (sizeof(devInfoMfrName) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoMfrName) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoMfrName[offset], *pLen); + } + break; + + case IEEE_11073_CERT_DATA_UUID: + // verify offset + if (offset >= sizeof(devInfo11073Cert)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfo11073Cert) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfo11073Cert[offset], *pLen); + } + break; + + case PNP_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoPnpId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoPnpId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoPnpId[offset], *pLen); + } + break; + + default: + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + + return ( status ); +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/Profile/gattprofile.c b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/gattprofile.c new file mode 100644 index 0000000..27c745c --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/gattprofile.c @@ -0,0 +1,702 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : GATTprofile.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ԶֲͬԵķ񣬰ɶд֪ͨɶдȫɶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "GATTprofile.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +#define SERVAPP_NUM_ATTR_SUPPORTED 17 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// 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: 0xFFF1 +CONST uint8 simpleProfilechar1UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR1_UUID), HI_UINT16(SIMPLEPROFILE_CHAR1_UUID) +}; + +// Characteristic 2 UUID: 0xFFF2 +CONST uint8 simpleProfilechar2UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR2_UUID), HI_UINT16(SIMPLEPROFILE_CHAR2_UUID) +}; + +// Characteristic 3 UUID: 0xFFF3 +CONST uint8 simpleProfilechar3UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR3_UUID), HI_UINT16(SIMPLEPROFILE_CHAR3_UUID) +}; + +// Characteristic 4 UUID: 0xFFF4 +CONST uint8 simpleProfilechar4UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR4_UUID), HI_UINT16(SIMPLEPROFILE_CHAR4_UUID) +}; + +// Characteristic 5 UUID: 0xFFF5 +CONST uint8 simpleProfilechar5UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR5_UUID), HI_UINT16(SIMPLEPROFILE_CHAR5_UUID) +}; + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +static simpleProfileCBs_t *simpleProfile_AppCBs = NULL; + +/********************************************************************* + * Profile Attributes - variables + */ + +// Simple Profile Service attribute +static CONST gattAttrType_t simpleProfileService = { ATT_BT_UUID_SIZE, simpleProfileServUUID }; + + +// Simple Profile Characteristic 1 Properties +static uint8 simpleProfileChar1Props = GATT_PROP_READ | GATT_PROP_WRITE; + +// Characteristic 1 Value +static uint8 simpleProfileChar1 = 0; + +// Simple Profile Characteristic 1 User Description +static uint8 simpleProfileChar1UserDesp[17] = "Characteristic 1\0"; + + +// Simple Profile Characteristic 2 Properties +static uint8 simpleProfileChar2Props = GATT_PROP_READ; + +// Characteristic 2 Value +static uint8 simpleProfileChar2 = 0; + +// Simple Profile Characteristic 2 User Description +static uint8 simpleProfileChar2UserDesp[17] = "Characteristic 2\0"; + + +// Simple Profile Characteristic 3 Properties +static uint8 simpleProfileChar3Props = GATT_PROP_WRITE; + +// Characteristic 3 Value +static uint8 simpleProfileChar3 = 0; + +// Simple Profile Characteristic 3 User Description +static uint8 simpleProfileChar3UserDesp[17] = "Characteristic 3\0"; + + +// Simple Profile Characteristic 4 Properties +static uint8 simpleProfileChar4Props = GATT_PROP_NOTIFY; + +// Characteristic 4 Value +static uint8 simpleProfileChar4 = 0; + +// Simple Profile Characteristic 4 Configuration Each client has its own +// instantiation of the Client Characteristic Configuration. Reads of the +// Client Characteristic Configuration only shows the configuration for +// that client and writes only affect the configuration of that client. +static gattCharCfg_t simpleProfileChar4Config[4]; + +// Simple Profile Characteristic 4 User Description +static uint8 simpleProfileChar4UserDesp[17] = "Characteristic 4\0"; + + +// Simple Profile Characteristic 5 Properties +static uint8 simpleProfileChar5Props = GATT_PROP_READ; + +// Characteristic 5 Value +static uint8 simpleProfileChar5[SIMPLEPROFILE_CHAR5_LEN] = { 0, 0, 0, 0, 0 }; + +// Simple Profile Characteristic 5 User Description +static uint8 simpleProfileChar5UserDesp[17] = "Characteristic 5\0"; + + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t simpleProfileAttrTbl[SERVAPP_NUM_ATTR_SUPPORTED] = +{ + // Simple Profile Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&simpleProfileService /* pValue */ + }, + + // Characteristic 1 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar1Props + }, + + // Characteristic Value 1 + { + { ATT_BT_UUID_SIZE, simpleProfilechar1UUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + &simpleProfileChar1 + }, + + // Characteristic 1 User Description + { + { 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, + 0, + &simpleProfileChar2 + }, + + // Characteristic 2 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar2UserDesp + }, + + // Characteristic 3 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar3Props + }, + + // Characteristic Value 3 + { + { ATT_BT_UUID_SIZE, simpleProfilechar3UUID }, + GATT_PERMIT_WRITE, + 0, + &simpleProfileChar3 + }, + + // Characteristic 3 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar3UserDesp + }, + + // Characteristic 4 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar4Props + }, + + // Characteristic Value 4 + { + { ATT_BT_UUID_SIZE, simpleProfilechar4UUID }, + 0, + 0, + &simpleProfileChar4 + }, + + // Characteristic 4 configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8 *)simpleProfileChar4Config + }, + + // Characteristic 4 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar4UserDesp + }, + + // Characteristic 5 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar5Props + }, + + // Characteristic Value 5 + { + { ATT_BT_UUID_SIZE, simpleProfilechar5UUID }, + GATT_PERMIT_AUTHEN_READ, + 0, + simpleProfileChar5 + }, + + // Characteristic 5 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar5UserDesp + }, + + +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ); + +static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); + + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Simple Profile Service Callbacks +gattServiceCBs_t simpleProfileCBs = +{ + simpleProfile_ReadAttrCB, // Read callback function pointer + simpleProfile_WriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn SimpleProfile_AddService + * + * @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. + * + * @return Success or Failure + */ +bStatus_t SimpleProfile_AddService( uint32 services ) +{ + uint8 status = SUCCESS; + + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar4Config ); + + // Register with Link DB to receive link status change callback + 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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &simpleProfileCBs ); + } + + return ( status ); +} + + +/********************************************************************* + * @fn SimpleProfile_RegisterAppCBs + * + * @brief Registers the application callback function. Only call + * this function once. + * + * @param callbacks - pointer to application callbacks. + * + * @return SUCCESS or bleAlreadyInRequestedMode + */ +bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) +{ + if ( appCallbacks ) + { + simpleProfile_AppCBs = appCallbacks; + + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } +} + + +/********************************************************************* + * @fn SimpleProfile_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar1 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR2: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar2 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR3: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar3 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR4: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar4 = *((uint8*)value); + + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR5: + if ( len == SIMPLEPROFILE_CHAR5_LEN ) + { + tmos_memcpy( simpleProfileChar5, value, SIMPLEPROFILE_CHAR5_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn SimpleProfile_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + *((uint8*)value) = simpleProfileChar1; + break; + + case SIMPLEPROFILE_CHAR2: + *((uint8*)value) = simpleProfileChar2; + break; + + case SIMPLEPROFILE_CHAR3: + *((uint8*)value) = simpleProfileChar3; + break; + + case SIMPLEPROFILE_CHAR4: + *((uint8*)value) = simpleProfileChar4; + break; + + case SIMPLEPROFILE_CHAR5: + tmos_memcpy( value, simpleProfileChar5, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn simpleProfile_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + + // If attribute permissions require authorization to read, return error + if ( gattPermitAuthorRead( pAttr->permissions ) ) + { + // 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 + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + // No need for "GATT_SERVICE_UUID" or "GATT_CLIENT_CHAR_CFG_UUID" cases; + // gattserverapp handles those reads + + // characteristics 1 and 2 have read permissions + // characteritisc 3 does not have read permissions; therefore it is not + // included here + // characteristic 4 does not have read permissions, but because it + // can be sent as a notification, it is included here + case SIMPLEPROFILE_CHAR1_UUID: + case SIMPLEPROFILE_CHAR2_UUID: + case SIMPLEPROFILE_CHAR4_UUID: + *pLen = 1; + pValue[0] = *pAttr->pValue; + break; + + case SIMPLEPROFILE_CHAR5_UUID: + *pLen = SIMPLEPROFILE_CHAR5_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint8 notifyApp = 0xFF; + + // If attribute permissions require authorization to write, return error + if ( gattPermitAuthorWrite( pAttr->permissions ) ) + { + // Insufficient authorization + return ( ATT_ERR_INSUFFICIENT_AUTHOR ); + } + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + case SIMPLEPROFILE_CHAR1_UUID: + case SIMPLEPROFILE_CHAR3_UUID: + + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len != 1 ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + uint8 *pCurValue = (uint8 *)pAttr->pValue; + *pCurValue = pValue[0]; + + if( pAttr->pValue == &simpleProfileChar1 ) + { + notifyApp = SIMPLEPROFILE_CHAR1; + } + else + { + notifyApp = SIMPLEPROFILE_CHAR3; + } + } + + break; + + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); + break; + + default: + // Should never get here! (characteristics 2 and 4 do not have write permissions) + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + status = ATT_ERR_INVALID_HANDLE; + } + + // 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 ); + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_HandleConnStatusCB + * + * @brief Simple Profile link status change handler function. + * + * @param connHandle - connection handle + * @param changeType - type of change + * + * @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 ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, simpleProfileChar4Config ); + } + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/OTAprofile.h b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/OTAprofile.h new file mode 100644 index 0000000..b786bd3 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/OTAprofile.h @@ -0,0 +1,98 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : OTAprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : +*******************************************************************************/ + +#ifndef OTAPROFILE_H +#define OTAPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// OTA ProfileͨIndex +#define OTAPROFILE_CHAR 0 + +// OTA UUID +#define OTAPROFILE_SERV_UUID 0xFEE0 + +// OTA ͨѶͨUUID +#define OTAPROFILE_CHAR_UUID 0xFEE1 + +// Simple Keys Profile Services bit fields +#define OTAPROFILE_SERVICE 0x00000001 + + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// дص +typedef void (*OTAProfileRead_t)( unsigned char paramID ); +typedef void (*OTAProfileWrite_t)( unsigned char paramID ,unsigned char *p_data, unsigned char w_len); + +typedef struct +{ + OTAProfileRead_t pfnOTAProfileRead; + OTAProfileWrite_t pfnOTAProfileWrite; +} OTAProfileCBs_t; + +/********************************************************************* + * API FUNCTIONS + */ + +/******************************************************************************* +* Function Name : OTAProfile_AddService +* Description : OTA Profileʼ +* Input : services +* Output : None +* Return : ʼ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_AddService( uint32 services ); +/******************************************************************************* +* Function Name : OTAProfile_RegisterAppCBs +* Description : OTA Profileдصע +* Input : appCallbacksṹָ +* Output : None +* Return : ִе״̬ +*******************************************************************************/ +bStatus_t OTAProfile_RegisterAppCBs( OTAProfileCBs_t *appCallbacks ); +/******************************************************************************* +* Function Name : OTAProfile_SendData +* Description : OTA Profileͨ +* Input : paramIDOTAͨѡ + p_dataָ + send_lenݳ +* Output : None +* Return : ִ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_SendData(unsigned char paramID ,unsigned char *p_data, unsigned char send_len ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/devinfoservice.h b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/devinfoservice.h new file mode 100644 index 0000000..a808937 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/devinfoservice.h @@ -0,0 +1,108 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef DEVINFOSERVICE_H +#define DEVINFOSERVICE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * 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 + +// 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 + +// System ID length +#define DEVINFO_SYSTEM_ID_LEN 8 + + // PnP ID length +#define DEVINFO_PNP_ID_LEN 7 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + + +/********************************************************************* + * API FUNCTIONS + */ + +/* + * DevInfo_AddService- Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + */ + +extern bStatus_t DevInfo_AddService( void ); + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ); + +/* + * 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). + */ +extern bStatus_t DevInfo_GetParameter( uint8 param, void *value ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif /* DEVINFOSERVICE_H */ diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/gattprofile.h b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/gattprofile.h new file mode 100644 index 0000000..ad9e613 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/Profile/include/gattprofile.h @@ -0,0 +1,127 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : GATTprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef GATTPROFILE_H +#define GATTPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// 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 + +// Simple Profile Service UUID +#define SIMPLEPROFILE_SERV_UUID 0xFFE0 + +// Key Pressed UUID +#define SIMPLEPROFILE_CHAR1_UUID 0xFFE1 +#define SIMPLEPROFILE_CHAR2_UUID 0xFFE2 +#define SIMPLEPROFILE_CHAR3_UUID 0xFFE3 +#define SIMPLEPROFILE_CHAR4_UUID 0xFFE4 +#define SIMPLEPROFILE_CHAR5_UUID 0xFFE5 + +// Simple Keys Profile Services bit fields +#define SIMPLEPROFILE_SERVICE 0x00000001 + +// Length of Characteristic 5 in bytes +#define SIMPLEPROFILE_CHAR4_LEN 8 +#define SIMPLEPROFILE_CHAR5_LEN 5 + +/********************************************************************* + * TYPEDEFS + */ + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// Callback when a characteristic value has changed +typedef void (*simpleProfileChange_t)( uint8 paramID ); + +typedef struct +{ + simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes +} simpleProfileCBs_t; + + + +/********************************************************************* + * API FUNCTIONS + */ + + +/* + * SimpleProfile_AddService- Initializes the Simple GATT 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. + */ + +extern bStatus_t SimpleProfile_AddService( uint32 services ); + +/* + * SimpleProfile_RegisterAppCBs - Registers the application callback function. + * Only call this function once. + * + * 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). + */ +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). + */ +extern bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ); + + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/BackupUpgrade_OTA/Project/BLE.uvprojx b/src/EXAM/BLE/BackupUpgrade_OTA/Project/BLE.uvprojx new file mode 100644 index 0000000..c4ab713 --- /dev/null +++ b/src/EXAM/BLE/BackupUpgrade_OTA/Project/BLE.uvprojx @@ -0,0 +1,568 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + OTA + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x1e000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20004000 + 0x4000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG + + ..\APP\include;..\Profile\include;..\..\HAL\include;..\..\LIB;..\..\..\SRC\CMSIS\Include;..\..\..\SRC\StdPeriphDriver\inc + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + peripheral.c + 1 + ..\APP\peripheral.c + + + peripheral_main.c + 1 + ..\APP\peripheral_main.c + + + + + profile + + + devinfoservice.c + 1 + ..\Profile\devinfoservice.c + + + gattprofile.c + 1 + ..\Profile\gattprofile.c + + + OTAprofile.c + 1 + ..\Profile\OTAprofile.c + + + + + drive + + + startup_ARMCM0.s + 2 + ..\..\..\SRC\Startup\startup_ARMCM0.s + + + CH57x_clk.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_gpio.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_pwr.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_sys.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_uart1.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_int.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + 2 + 9 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_flash.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + + + hal + + + MCU.c + 1 + ..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.LIB + 4 + ..\..\LIB\CH57xBLE.LIB + + + + + config + + + config.h + 5 + ..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/Broadcaster/APP/broadcaster_main.c b/src/EXAM/BLE/Broadcaster/APP/broadcaster_main.c index ca0cc5e..b44eabf 100644 --- a/src/EXAM/BLE/Broadcaster/APP/broadcaster_main.c +++ b/src/EXAM/BLE/Broadcaster/APP/broadcaster_main.c @@ -31,8 +31,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/Broadcaster/Project/BLE.uvprojx b/src/EXAM/BLE/Broadcaster/Project/BLE.uvprojx index 13510f1..81c07c5 100644 --- a/src/EXAM/BLE/Broadcaster/Project/BLE.uvprojx +++ b/src/EXAM/BLE/Broadcaster/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -498,6 +498,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + diff --git a/src/EXAM/BLE/CentPeri/APP/centPeri_main.c b/src/EXAM/BLE/CentPeri/APP/centPeri_main.c index 4cb7211..a85d855 100644 --- a/src/EXAM/BLE/CentPeri/APP/centPeri_main.c +++ b/src/EXAM/BLE/CentPeri/APP/centPeri_main.c @@ -33,8 +33,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/CentPeri/Project/BLE.uvprojx b/src/EXAM/BLE/CentPeri/Project/BLE.uvprojx index 5072f79..f379b57 100644 --- a/src/EXAM/BLE/CentPeri/Project/BLE.uvprojx +++ b/src/EXAM/BLE/CentPeri/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -508,6 +508,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + @@ -559,4 +564,10 @@ + + + + + + diff --git a/src/EXAM/BLE/Central/APP/central_main.c b/src/EXAM/BLE/Central/APP/central_main.c index b845757..a52e577 100644 --- a/src/EXAM/BLE/Central/APP/central_main.c +++ b/src/EXAM/BLE/Central/APP/central_main.c @@ -31,8 +31,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/Central/Project/BLE.uvprojx b/src/EXAM/BLE/Central/Project/BLE.uvprojx index e8b81cd..e9c1ff6 100644 --- a/src/EXAM/BLE/Central/Project/BLE.uvprojx +++ b/src/EXAM/BLE/Central/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -483,6 +483,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + diff --git a/src/EXAM/BLE/CyclingSensor/APP/cyclingsensor_main.c b/src/EXAM/BLE/CyclingSensor/APP/cyclingsensor_main.c index 374d238..444a4da 100644 --- a/src/EXAM/BLE/CyclingSensor/APP/cyclingsensor_main.c +++ b/src/EXAM/BLE/CyclingSensor/APP/cyclingsensor_main.c @@ -33,8 +33,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/CyclingSensor/Project/BLE.uvprojx b/src/EXAM/BLE/CyclingSensor/Project/BLE.uvprojx index 859d484..5a4d142 100644 --- a/src/EXAM/BLE/CyclingSensor/Project/BLE.uvprojx +++ b/src/EXAM/BLE/CyclingSensor/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -503,6 +503,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + @@ -549,4 +554,10 @@ + + + + + + diff --git a/src/EXAM/BLE/DirectTest/APP/directtest.c b/src/EXAM/BLE/DirectTest/APP/directtest.c index c5c8c17..798a723 100644 --- a/src/EXAM/BLE/DirectTest/APP/directtest.c +++ b/src/EXAM/BLE/DirectTest/APP/directtest.c @@ -22,6 +22,7 @@ static tmosTaskID testTaskID; static u8 TestEnalbe = FALSE; #endif +static u8 payload=0; /******************************************************************************* * @fn HAL_ProcessEvent @@ -41,36 +42,11 @@ static u8 TestEnalbe = FALSE; */ tmosEvents TEST_ProcessEvent( tmosTaskID task_id, tmosEvents events ) { - static u8 payload=0; uint8 * msgPtr; - keyChange_t *msgKeyPtr; if( events & SYS_EVENT_MSG ){ // HALϢtmos_msg_receiveȡϢɺɾϢ msgPtr = tmos_msg_receive(task_id); if( msgPtr ){ - switch( ((tmos_event_hdr_t*)msgPtr)->event){ - case KEY_CHANGE: - msgKeyPtr = (keyChange_t *)msgPtr; - if( msgKeyPtr->keys&HAL_KEY_SW_1 ){ - if( TestEnalbe == FALSE ){ - payload++; - TestEnalbe = TRUE; - HalLedBlink( HAL_LED_1, 0xff, 30 , 4000); - API_LE_TransmitterTestCmd( 0, 20, payload&7, 0x15|0x80 ); - PRINT("(key)test start ...\n"); - } - else{ - TestEnalbe = FALSE; - HalLedSet( HAL_LED_1, HAL_LED_MODE_OFF ); - API_LE_TestEndCmd( ); - PRINT(" (key)end!\n"); - } - tmos_stop_task( testTaskID, TEST_EVENT ); - } - break; - default: - break; - } /* De-allocate */ tmos_msg_deallocate( msgPtr ); } @@ -96,6 +72,41 @@ tmosEvents TEST_ProcessEvent( tmosTaskID task_id, tmosEvents events ) return 0; } +/******************************************************************************* + * @fn key_Change + * + * @brief ص + * + * input parameters + * + * @param keys. + * + * output parameters + * + * @param None. + * + * @return None. + */ +void key_Change( uint8 keys ) +{ + if( keys&HAL_KEY_SW_1 ){ + if( TestEnalbe == FALSE ){ + payload++; + TestEnalbe = TRUE; + HalLedBlink( HAL_LED_1, 0xff, 30 , 4000); + API_LE_TransmitterTestCmd( 0, 20, payload&7, 0x15|0x80 ); + PRINT("(key)test start ...\n"); + } + else{ + TestEnalbe = FALSE; + HalLedSet( HAL_LED_1, HAL_LED_MODE_OFF ); + API_LE_TestEndCmd( ); + PRINT(" (key)end!\n"); + } + tmos_stop_task( testTaskID, TEST_EVENT ); + } +} + /******************************************************************************* * @fn Hal_Init * @@ -115,7 +126,7 @@ tmosEvents TEST_ProcessEvent( tmosTaskID task_id, tmosEvents events ) { testTaskID = TMOS_ProcessEventRegister(TEST_ProcessEvent); #if (defined HAL_KEY) && (HAL_KEY == TRUE) - HAL_KEY_RegisterForKeys(testTaskID); + HalKeyConfig( key_Change ); #endif #if BLE_DIRECT_TEST tmos_start_task( testTaskID , TEST_EVENT ,1000 ); // һ diff --git a/src/EXAM/BLE/DirectTest/APP/directtest_main.c b/src/EXAM/BLE/DirectTest/APP/directtest_main.c index 110eb8d..9ba3f4e 100644 --- a/src/EXAM/BLE/DirectTest/APP/directtest_main.c +++ b/src/EXAM/BLE/DirectTest/APP/directtest_main.c @@ -31,8 +31,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/DirectTest/Project/BLE.uvprojx b/src/EXAM/BLE/DirectTest/Project/BLE.uvprojx index 726882a..58a4d27 100644 --- a/src/EXAM/BLE/DirectTest/Project/BLE.uvprojx +++ b/src/EXAM/BLE/DirectTest/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -483,6 +483,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + @@ -539,4 +544,10 @@ + + + + + + diff --git a/src/EXAM/BLE/HAL/KEY.c b/src/EXAM/BLE/HAL/KEY.c index 7939a06..2fc1018 100644 --- a/src/EXAM/BLE/HAL/KEY.c +++ b/src/EXAM/BLE/HAL/KEY.c @@ -18,12 +18,7 @@ * GLOBAL VARIABLES **************************************************************************************************/ -uint8 Hal_KeyIntEnable; /* interrupt enable/disable flag */ - -// Registered keys task ID, initialized to NOT USED. -static uint8 registeredKeysTaskID = TASK_NO_TASK; static uint8 halKeySavedKeys; /* ״̬ڲѯǷмֵ仯 */ -static uint8 KeyConfigFlag; /* Ƿñ־λ */ /************************************************************************************************** @@ -47,16 +42,10 @@ void HAL_KeyInit( void ) halKeySavedKeys = 0; /* Initialize callback function */ pHalKeyProcessFunction = NULL; - /* Start with key is not configured */ - KeyConfigFlag = FALSE; KEY1_DIR; KEY1_PU; - HalKeyConfig( HAL_KEY_INTERRUPT_DISABLE, HalKeyCallback ); -} - -void HAL_KEY_RegisterForKeys( tmosTaskID id ) -{ - registeredKeysTaskID = id; + KEY2_DIR; + KEY2_PU; } /************************************************************************************************** @@ -69,86 +58,13 @@ void HAL_KEY_RegisterForKeys( tmosTaskID id ) * * @return None **************************************************************************************************/ -void HalKeyConfig (uint8 interruptEnable, halKeyCBack_t cback) +void HalKeyConfig ( halKeyCBack_t cback) { - /* Enable/Disable Interrupt or */ - Hal_KeyIntEnable = interruptEnable; /* Register the callback fucntion */ pHalKeyProcessFunction = cback; - /* Determine if interrupt is enable or not */ - if (Hal_KeyIntEnable){ - /* Do this only after the hal_key is configured - to work with sleep stuff */ - if (KeyConfigFlag == TRUE){ - tmos_stop_task( halTaskID, HAL_KEY_EVENT ); /* Cancel polling if active */ - } - } - else{ /* Interrupts NOT enabled */ - tmos_start_task( halTaskID, HAL_KEY_EVENT, HAL_KEY_POLLING_VALUE); /* Kick off polling */ - } - /* Key now is configured */ - KeyConfigFlag = TRUE; -} - -/********************************************************************* - * @fn OnBoard_SendKeys - * - * @brief Send "Key Pressed" message to application. - * - * @param keys - keys that were pressed - * state - shifted - * - * @return status - *********************************************************************/ -uint8 OnBoard_SendKeys( uint8 keys, uint8 state ) -{ - keyChange_t *msgPtr; - - if ( registeredKeysTaskID != TASK_NO_TASK ){ - // Send the address to the task - msgPtr = (keyChange_t *)tmos_msg_allocate( sizeof(keyChange_t) ); - if ( msgPtr ){ - msgPtr->hdr.event = KEY_CHANGE; - msgPtr->state = state; - msgPtr->keys = keys; - tmos_msg_send( registeredKeysTaskID, (uint8 *)msgPtr ); - } - return ( SUCCESS ); - } - else{ - return ( FAILURE ); - } -} - -/********************************************************************* - * @fn OnBoard_KeyCallback - * - * @brief Callback service for keys - * - * @param keys - keys that were pressed - * state - shifted - * - * @return void - *********************************************************************/ -void HalKeyCallback ( uint8 keys, uint8 state ) -{ - (void)state; - if ( OnBoard_SendKeys( keys, state ) != SUCCESS ){ - // Process SW1 here - if ( keys & HAL_KEY_SW_1 ){ // Switch 1 - } - // Process SW2 here - if ( keys & HAL_KEY_SW_2 ){ // Switch 2 - } - // Process SW3 here - if ( keys & HAL_KEY_SW_3 ){ // Switch 3 - } - // Process SW4 here - if ( keys & HAL_KEY_SW_4 ){ // Switch 4 - } - } + tmos_start_task( halTaskID, HAL_KEY_EVENT, HAL_KEY_POLLING_VALUE); /* Kick off polling */ } - /************************************************************************************************** * @fn HalKeyRead * @@ -190,7 +106,6 @@ uint8 HalKeyRead ( void ) void HAL_KeyPoll (void) { uint8 keys = 0; - if( HAL_PUSH_BUTTON1() ){ keys |= HAL_KEY_SW_1; } @@ -203,15 +118,13 @@ void HAL_KeyPoll (void) if( HAL_PUSH_BUTTON4() ){ keys |= HAL_KEY_SW_4; } - if (!Hal_KeyIntEnable){ /* жδʹ */ - if(keys == halKeySavedKeys){ /* Exit - since no keys have changed */ - return; - } - halKeySavedKeys = keys; /* Store the current keys for comparation next time */ - } + if(keys == halKeySavedKeys){ /* Exit - since no keys have changed */ + return; + } + halKeySavedKeys = keys; /* Store the current keys for comparation next time */ /* Invoke Callback if new keys were depressed */ if (keys && (pHalKeyProcessFunction)){ - (pHalKeyProcessFunction) (keys, HAL_KEY_STATE_NORMAL); + (pHalKeyProcessFunction) (keys); } } diff --git a/src/EXAM/BLE/HAL/MCU.c b/src/EXAM/BLE/HAL/MCU.c index bf7c214..209a0c6 100644 --- a/src/EXAM/BLE/HAL/MCU.c +++ b/src/EXAM/BLE/HAL/MCU.c @@ -144,11 +144,9 @@ tmosEvents HAL_ProcessEvent( tmosTaskID task_id, tmosEvents events ) } if( events & HAL_KEY_EVENT ){ #if (defined HAL_KEY) && (HAL_KEY == TRUE) - HAL_KeyPoll(); /* Check for keys */ - if (!Hal_KeyIntEnable){ - tmos_start_task( halTaskID, HAL_KEY_EVENT, MS1_TO_SYSTEM_TIME(100) ); - } - return events ^ HAL_KEY_EVENT; + HAL_KeyPoll(); /* Check for keys */ + tmos_start_task( halTaskID, HAL_KEY_EVENT, MS1_TO_SYSTEM_TIME(100) ); + return events ^ HAL_KEY_EVENT; #endif } if( events & HAL_REG_INIT_EVENT ){ @@ -227,7 +225,7 @@ void LLE_IRQHandler(void) /******************************************************************************* * @fn HAL_GetInterTempValue * - * @brief None. + * @brief ʹADCжϲڴ˺ʱж. * * input parameters * @@ -241,22 +239,21 @@ void LLE_IRQHandler(void) */ uint16 HAL_GetInterTempValue( void ) { - uint8 sensor,channel,config; + uint8 sensor, channel, config; uint16 adc_data; - sensor = R8_TEM_SENSOR; + sensor = R8_TEM_SENSOR; channel = R8_ADC_CHANNEL; - config = R8_ADC_CFG; - R8_TEM_SENSOR |= RB_TEM_SEN_PWR_ON; - R8_ADC_CHANNEL = CH_INTE_VTEMP; - R8_ADC_CFG = RB_ADC_POWER_ON|( 2<<4 ) ; + config = R8_ADC_CFG; + ADC_InterTSSampInit(); R8_ADC_CONVERT |= RB_ADC_START; - while( R8_ADC_CONVERT & RB_ADC_START ); + while( R8_ADC_CONVERT & RB_ADC_START ) + ; adc_data = R16_ADC_DATA; - R8_TEM_SENSOR = sensor; + R8_TEM_SENSOR = sensor; R8_ADC_CHANNEL = channel; R8_ADC_CFG = config; - return( adc_data ); + return ( adc_data ); } /******************************** endfile @ mcu ******************************/ diff --git a/src/EXAM/BLE/HAL/RTC.c b/src/EXAM/BLE/HAL/RTC.c index 6e983cc..4d15785 100644 --- a/src/EXAM/BLE/HAL/RTC.c +++ b/src/EXAM/BLE/HAL/RTC.c @@ -75,6 +75,11 @@ void RTC_IRQHandler( void ) void HAL_TimeInit( void ) { #if( CLK_OSC32K ) + R8_SAFE_ACCESS_SIG = 0x57; + R8_SAFE_ACCESS_SIG = 0xa8; + R8_CK32K_CONFIG &= ~(RB_CLK_OSC32K_XT|RB_CLK_XT32K_PON); + R8_CK32K_CONFIG |= RB_CLK_INT32K_PON; + R8_SAFE_ACCESS_SIG = 0; Calibration_LSI(); #else R8_SAFE_ACCESS_SIG = 0x57; diff --git a/src/EXAM/BLE/HAL/SLEEP.c b/src/EXAM/BLE/HAL/SLEEP.c index 5ed0010..9894a78 100644 --- a/src/EXAM/BLE/HAL/SLEEP.c +++ b/src/EXAM/BLE/HAL/SLEEP.c @@ -47,9 +47,11 @@ u32 CH57X_LowPower( u32 time ) if( !RTCTigFlag ){ LowPower_Sleep(RB_PWR_RAM2K|RB_PWR_RAM14K|RB_PWR_EXTEND ); SetSysClock( CLK_SOURCE_HSI_32MHz ); - HSECFG_Current( HSE_RCur_100 ); // Ϊ(͹ĺHSEƫõ) - RTC_SetTignTime( time + 47 ); + time+=WAKE_UP_RTC_MAX_TIME; + if( time > 0xA8C00000 ) time -= 0xA8C00000; + RTC_SetTignTime( time ); LowPower_Idle(); + HSECFG_Current( HSE_RCur_100 ); // Ϊ(͹ĺHSEƫõ) SetSysClock( CLK_SOURCE_HSE_32MHz ); } else{ diff --git a/src/EXAM/BLE/HAL/include/KEY.h b/src/EXAM/BLE/HAL/include/KEY.h index d4fcbd2..0f2a9a7 100644 --- a/src/EXAM/BLE/HAL/include/KEY.h +++ b/src/EXAM/BLE/HAL/include/KEY.h @@ -23,60 +23,39 @@ extern "C" /************************************************************************************************** * MACROS **************************************************************************************************/ -#define KEY_CHANGE 0xC0 // Key message - -#define HAL_KEY_RISING_EDGE 0 -#define HAL_KEY_FALLING_EDGE 1 - -#define HAL_KEY_DEBOUNCE_VALUE 25 #define HAL_KEY_POLLING_VALUE 100 -/* Interrupt option - Enable or disable */ -#define HAL_KEY_INTERRUPT_DISABLE 0x00 -#define HAL_KEY_INTERRUPT_ENABLE 0x01 - -/* Key state - shift or nornal */ -#define HAL_KEY_STATE_NORMAL 0x00 -#define HAL_KEY_STATE_SHIFT 0x01 - /* Switches (keys) */ #define HAL_KEY_SW_1 0x01 // key1 #define HAL_KEY_SW_2 0x02 // key2 #define HAL_KEY_SW_3 0x04 // key3 #define HAL_KEY_SW_4 0x08 // key4 -#define HAL_KEY_SW_5 0x10 // key5 -/* Joystick */ -#define HAL_KEY_UP 0x01 // Joystick up -#define HAL_KEY_RIGHT 0x02 // Joystick right -#define HAL_KEY_CENTER 0x04 // Joystick center -#define HAL_KEY_LEFT 0x08 // Joystick left -#define HAL_KEY_DOWN 0x10 // Joystick down /* */ /* 1 - KEY */ #define KEY1_BV BV(22) - #define KEY2_BV + #define KEY2_BV BV(4) #define KEY3_BV #define KEY4_BV #define KEY1_PU (R32_PB_PU |= KEY1_BV) - #define KEY2_PU () + #define KEY2_PU (R32_PB_PU |= KEY2_BV) #define KEY3_PU () #define KEY4_PU () #define KEY1_DIR (R32_PB_DIR &= ~KEY1_BV) - #define KEY2_PU () - #define KEY3_PU () - #define KEY4_PU () + #define KEY2_DIR (R32_PB_DIR &= ~KEY2_BV) + #define KEY3_DIR () + #define KEY4_DIR () #define KEY1_IN (ACTIVE_LOW(R32_PB_PIN&KEY1_BV)) - #define KEY2_IN () + #define KEY2_IN (ACTIVE_LOW(R32_PB_PIN&KEY2_BV)) #define KEY3_IN () #define KEY4_IN () #define HAL_PUSH_BUTTON1() ( KEY1_IN ) //Զ尴 -#define HAL_PUSH_BUTTON2() ( 0 ) +#define HAL_PUSH_BUTTON2() ( KEY2_IN ) #define HAL_PUSH_BUTTON3() ( 0 ) #define HAL_PUSH_BUTTON4() ( 0 ) @@ -88,19 +67,16 @@ extern "C" /************************************************************************************************** * TYPEDEFS **************************************************************************************************/ -typedef void (*halKeyCBack_t) (uint8 keys, uint8 state); +typedef void (*halKeyCBack_t) (uint8 keys ); typedef struct { - tmos_event_hdr_t hdr; - uint8 state; // shift uint8 keys; // keys } keyChange_t; /************************************************************************************************** * GLOBAL VARIABLES **************************************************************************************************/ -extern uint8 Hal_KeyIntEnable; /********************************************************************* * FUNCTIONS @@ -116,20 +92,15 @@ void HAL_KeyInit( void ); */ void HAL_KeyPoll( void ); -/* - * Register the Key Service - */ -void HAL_KEY_RegisterForKeys( tmosTaskID id ); - /* * Configure the Key Service */ -void HalKeyConfig( uint8 interruptEnable, const halKeyCBack_t cback); +void HalKeyConfig( const halKeyCBack_t cback); /* * Read the Key callback */ -void HalKeyCallback ( uint8 keys, uint8 state ); +void HalKeyCallback ( uint8 keys ); /* * Read the Key status diff --git a/src/EXAM/BLE/HAL/include/config.h b/src/EXAM/BLE/HAL/include/config.h index 81b6184..d6c9560 100644 --- a/src/EXAM/BLE/HAL/include/config.h +++ b/src/EXAM/BLE/HAL/include/config.h @@ -27,9 +27,9 @@ SLEEP HAL_SLEEP - Ƿ˯߹ ( Ĭ:FALSE ) - WAKE_UP_RTC_MAX_TIME - ˯߻ʱ䣬ݲͬ˯ȡֵɷΪ˯ģʽ/µģʽ - 50(Ĭ) - ͣģʽ - 50 - ģʽ - 5 + WAKE_UP_RTC_MAX_TIME - ȴ32Mȶʱ䣬ݲͬ˯ȡֵɷΪ˯ģʽ/µģʽ - 45(Ĭ) + ͣģʽ - 45 + ģʽ - 5 TEMPERATION TEM_SAMPLE - Ƿ򿪸¶ȱ仯У׼ĹܣУ׼ʱС10ms( Ĭ:TRUE ) @@ -93,7 +93,7 @@ #define BLE_SNV_ADDR 0x3EC00 #endif #ifndef CLK_OSC32K -#define CLK_OSC32K 0 // ڹԤ޸ģɫʹⲿ32K +#define CLK_OSC32K 0 // ڴ޸ģڹԤ޸ģɫʹⲿ32K #endif #ifndef BLE_MEMHEAP_SIZE #define BLE_MEMHEAP_SIZE (1024*8) diff --git a/src/EXAM/BLE/HID_Consumer/APP/hidconsumer_main.c b/src/EXAM/BLE/HID_Consumer/APP/hidconsumer_main.c index 3f41196..d7d1e6b 100644 --- a/src/EXAM/BLE/HID_Consumer/APP/hidconsumer_main.c +++ b/src/EXAM/BLE/HID_Consumer/APP/hidconsumer_main.c @@ -32,8 +32,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/HID_Consumer/Profile/hiddev.c b/src/EXAM/BLE/HID_Consumer/Profile/hiddev.c index 7e4bb9f..d7ab212 100644 --- a/src/EXAM/BLE/HID_Consumer/Profile/hiddev.c +++ b/src/EXAM/BLE/HID_Consumer/Profile/hiddev.c @@ -47,34 +47,15 @@ // Heart Rate Task Events #define START_DEVICE_EVT 0x0001 #define BATT_PERIODIC_EVT 0x0002 -#define HID_IDLE_EVT 0x0004 -#define HID_SEND_REPORT_EVT 0x0008 - -#define reportQEmpty() ( firstQIdx == lastQIdx ) /********************************************************************* * CONSTANTS */ -#define HID_DEV_DATA_LEN 8 - -#ifdef HID_DEV_RPT_QUEUE_LEN - #define HID_DEV_REPORT_Q_SIZE (HID_DEV_RPT_QUEUE_LEN+1) -#else - #define HID_DEV_REPORT_Q_SIZE (10+1) -#endif - /********************************************************************* * TYPEDEFS */ -typedef struct -{ - uint8 id; - uint8 type; - uint8 len; - uint8 data[HID_DEV_DATA_LEN]; -} hidDevReport_t; /********************************************************************* * GLOBAL VARIABLES @@ -104,9 +85,6 @@ static uint8 hidDevConnSecure = FALSE; // GAP connection handle static uint16 gapConnHandle; -// TRUE if pairing in progress -static uint8 hidDevPairingStarted = TRUE; - // Status of last pairing static uint8 pairingStatus = SUCCESS; @@ -118,14 +96,6 @@ static hidDevCB_t *pHidDevCB; static hidDevCfg_t *pHidDevCfg; -// Pending reports -static uint8 firstQIdx = 0; -static uint8 lastQIdx = 0; -static hidDevReport_t hidDevReportQ[HID_DEV_REPORT_Q_SIZE]; - -// Last report sent out -//static attHandleValueNoti_t lastNoti = { 0 }; -static hidDevReport_t lastReport = { 0 }; /********************************************************************* * LOCAL FUNCTIONS */ @@ -145,17 +115,12 @@ static void hidDevBattPeriodicTask( void ); static hidRptMap_t *hidDevRptByHandle( uint16 handle ); static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ); static hidRptMap_t *hidDevRptByCccdHandle( uint16 handle ); -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); -static hidDevReport_t *hidDevDequeueReport( void ); -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); static void hidDevHighAdvertising( void ); static void hidDevLowAdvertising( void ); static void hidDevInitialAdvertising( void ); static uint8 hidDevBondCount( void ); -static void hidDevStartIdleTimer( void ); -static void hidDevStopIdleTimer( void ); static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData); -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len); /********************************************************************* * PROFILE CALLBACKS */ @@ -267,26 +232,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ START_DEVICE_EVT ); } - if ( events & HID_IDLE_EVT ) - { - if ( hidDevGapState == GAPROLE_CONNECTED ) - { - PRINT("hid idle event..\n"); - // if pairing in progress then restart timer - if ( hidDevPairingStarted ) - { - hidDevStartIdleTimer(); - } - // else disconnect - else - { - GAPRole_TerminateLink( gapConnHandle ); - } - } - - return ( events ^ HID_IDLE_EVT ); - } - if ( events & BATT_PERIODIC_EVT ) { // Perform periodic battery task @@ -295,25 +240,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ BATT_PERIODIC_EVT ); } - if ( events & HID_SEND_REPORT_EVT ) - { - // if connection is secure - if ( hidDevConnSecure ) - { - hidDevReport_t *pReport = hidDevDequeueReport(); - - if ( pReport != NULL ) - { - // Send report - hidDevSendReport( pReport->id, pReport->type, pReport->len, pReport->data ); - } - - return ( reportQEmpty() ? events ^ HID_SEND_REPORT_EVT : events ); - } - - return ( events ^ HID_SEND_REPORT_EVT ); - } - return 0; } @@ -361,7 +287,7 @@ void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ) * * @return None. */ -void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) +uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) { // if connected if ( hidDevGapState == GAPROLE_CONNECTED ) @@ -369,14 +295,8 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) // if connection is secure if ( hidDevConnSecure ) { - // Make sure there're no pending reports - if ( reportQEmpty() ) - { - // send report - hidDevSendReport( id, type, len, pData ); - - return; // we're done - } + // send report + return hidDevSendReport( id, type, len, pData ); } } // else if not already advertising @@ -395,9 +315,7 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) hidDevInitialAdvertising(); } } - - // hidDev task will send report when secure connection is established - hidDevEnqueueReport( id, type, len, pData ); + return bleNotReady; } /********************************************************************* @@ -447,33 +365,12 @@ bStatus_t HidDev_SetParameter( uint8 param, uint8 len, void *pValue ) case HIDDEV_ERASE_ALLBONDS: if ( len == 0 ) { - hidRptMap_t *pRpt; - if ((pRpt = hidDevRptById(lastReport.id, lastReport.type)) != NULL) - { - // See if the last report sent out wasn't a release key - if (HidDev_isbufset(lastReport.data, 0x00, lastReport.len) == FALSE) - { - // Send a release report before disconnecting, otherwise - // the last pressed key would get 'stuck' on the HID Host. - tmos_memset(lastReport.data, 0x00, lastReport.len); - - // Send report notification - HidDev_sendNoti(pRpt->handle, lastReport.len, lastReport.data); - } - - // Clear out last report - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); - } - // Drop connection if ( hidDevGapState == GAPROLE_CONNECTED ) { GAPRole_TerminateLink( gapConnHandle ); } - // Flush report queue - firstQIdx = lastQIdx = 0; - // Erase bonding info GAPBondMgr_SetParameter( GAPBOND_ERASE_ALLBONDS, 0, NULL ); } @@ -618,12 +515,6 @@ bStatus_t HidDev_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, tmos_memcpy( pValue, pAttr->pValue, HID_EXT_REPORT_REF_LEN ); } - // restart idle timer - if ( status == SUCCESS ) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -730,12 +621,6 @@ bStatus_t HidDev_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, } } - // restart idle timer - if (status == SUCCESS) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -820,9 +705,6 @@ static void hidDevHandleConnStatusCB( uint16 connHandle, uint8 changeType ) */ static void hidDevDisconnected( void ) { - // Stop idle timer - hidDevStopIdleTimer(); - // Reset client characteristic configuration descriptors Batt_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); ScanParam_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); @@ -831,11 +713,7 @@ static void hidDevDisconnected( void ) // Reset state variables hidDevConnSecure = FALSE; hidProtocolMode = HID_PROTOCOL_MODE_REPORT; - hidDevPairingStarted = FALSE; - // Reset last report sent out - //tmos_memset( &lastNoti, 0, sizeof( attHandleValueNoti_t ) ); - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); // if bonded and normally connectable start advertising if ( ( hidDevBondCount() > 0 ) && ( pHidDevCfg->hidFlags & HID_FLAGS_NORMALLY_CONNECTABLE ) ) @@ -871,8 +749,6 @@ static void hidDevGapStateCB( gapRole_States_t newState, gapRoleEvent_t * pEvent param = FALSE; GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), ¶m ); - // start idle timer - hidDevStartIdleTimer(); } // if disconnected else if ( hidDevGapState == GAPROLE_CONNECTED && @@ -931,14 +807,8 @@ static void hidDevParamUpdateCB( uint16 connHandle, uint16 connInterval, */ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) { - if ( state == GAPBOND_PAIRING_STATE_STARTED ) - { - hidDevPairingStarted = TRUE; - } - else if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) + if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) { - hidDevPairingStarted = FALSE; - if ( status == SUCCESS ) { hidDevConnSecure = TRUE; @@ -960,11 +830,6 @@ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) else if( state == GAPBOND_PAIRING_STATE_BOND_SAVED ) { } - if ( !reportQEmpty() && hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } } /********************************************************************* @@ -1139,11 +1004,12 @@ static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ) * * @return None. */ -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) { hidRptMap_t *pRpt; gattAttribute_t *pAttr; uint16 retHandle; + uint8 state = bleNoResources; // get att handle for report if ( (pRpt = hidDevRptById(id, type)) != NULL ) @@ -1157,20 +1023,11 @@ static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) if ( value & GATT_CLIENT_CFG_NOTIFY ) { // Send report notification - if (HidDev_sendNoti(pRpt->handle, len, pData) == SUCCESS) - { - // Save the report just sent out - lastReport.id = id; - lastReport.type = type; - lastReport.len = len; - tmos_memcpy(lastReport.data, pData, len); - } - - // start idle timer - hidDevStartIdleTimer(); + state = HidDev_sendNoti(pRpt->handle, len, pData); } } } + return state; } /********************************************************************* @@ -1211,71 +1068,6 @@ static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData) return status; } -/********************************************************************* - * @fn hidDevEnqueueReport - * - * @brief Enqueue a HID report to be sent later. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) -{ - // Enqueue only if bonded - if ( hidDevBondCount() > 0 ) - { - // Update last index - lastQIdx = ( lastQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - if ( lastQIdx == firstQIdx ) - { - // Queue overflow; discard oldest report - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - } - - // Save report - hidDevReportQ[lastQIdx].id = id; - hidDevReportQ[lastQIdx].type = type; - hidDevReportQ[lastQIdx].len = len; - tmos_memcpy( hidDevReportQ[lastQIdx].data, pData, len ); - - if ( hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } - } -} - -/********************************************************************* - * @fn hidDevDequeueReport - * - * @brief Dequeue a HID report to be sent out. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static hidDevReport_t *hidDevDequeueReport( void ) -{ - if ( reportQEmpty() ) - { - return NULL; - } - - // Update first index - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - return ( &(hidDevReportQ[firstQIdx]) ); -} - /********************************************************************* * @fn hidDevHighAdvertising * @@ -1355,69 +1147,5 @@ static uint8 hidDevBondCount( void ) return ( bondCnt ); } - -/********************************************************************* - * @fn HidDev_isbufset - * - * @brief Is all of the array elements set to a value? - * - * @param buf - buffer to check. - * @param val - value to check each array element for. - * @param len - length to check. - * - * @return TRUE if all "val". - * FALSE otherwise. - */ -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len) -{ - uint8 x; - - // Validate pointer and length of report - if ((buf == NULL) || (len > HID_DEV_DATA_LEN)) - { - return ( FALSE ); - } - - for ( x = 0; x < len; x++ ) - { - // Check for non-initialized value - if ( buf[x] != val ) - { - return ( FALSE ); - } - } - - return ( TRUE ); -} - - -/********************************************************************* - * @fn hidDevStartIdleTimer - * - * @brief Start the idle timer. - * - * @return None. - */ -static void hidDevStartIdleTimer( void ) -{ - if ( pHidDevCfg->idleTimeout > 0 ) - { -// tmos_start_task( hidDevTaskId, HID_IDLE_EVT, pHidDevCfg->idleTimeout ); - } -} - -/********************************************************************* - * @fn hidDevStopIdleTimer - * - * @brief Stop the idle timer. - * - * @return None. - */ -static void hidDevStopIdleTimer( void ) -{ - tmos_stop_task( hidDevTaskId, HID_IDLE_EVT ); -} - - /********************************************************************* *********************************************************************/ diff --git a/src/EXAM/BLE/HID_Consumer/Profile/include/hiddev.h b/src/EXAM/BLE/HID_Consumer/Profile/include/hiddev.h index 249b12f..6da7eb6 100644 --- a/src/EXAM/BLE/HID_Consumer/Profile/include/hiddev.h +++ b/src/EXAM/BLE/HID_Consumer/Profile/include/hiddev.h @@ -341,7 +341,7 @@ extern void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ); * * @return None. */ -extern void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); +extern uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); /********************************************************************* * @fn HidDev_Close diff --git a/src/EXAM/BLE/HID_Consumer/Project/BLE.uvprojx b/src/EXAM/BLE/HID_Consumer/Project/BLE.uvprojx index 3a42243..ccd1d6f 100644 --- a/src/EXAM/BLE/HID_Consumer/Project/BLE.uvprojx +++ b/src/EXAM/BLE/HID_Consumer/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -513,6 +513,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + diff --git a/src/EXAM/BLE/HID_Keyboard/APP/hidkbd_main.c b/src/EXAM/BLE/HID_Keyboard/APP/hidkbd_main.c index 4587780..e3aab52 100644 --- a/src/EXAM/BLE/HID_Keyboard/APP/hidkbd_main.c +++ b/src/EXAM/BLE/HID_Keyboard/APP/hidkbd_main.c @@ -32,8 +32,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/HID_Keyboard/Profile/hiddev.c b/src/EXAM/BLE/HID_Keyboard/Profile/hiddev.c index 9b9afc7..31b8e10 100644 --- a/src/EXAM/BLE/HID_Keyboard/Profile/hiddev.c +++ b/src/EXAM/BLE/HID_Keyboard/Profile/hiddev.c @@ -47,34 +47,15 @@ // Heart Rate Task Events #define START_DEVICE_EVT 0x0001 #define BATT_PERIODIC_EVT 0x0002 -#define HID_IDLE_EVT 0x0004 -#define HID_SEND_REPORT_EVT 0x0008 - -#define reportQEmpty() ( firstQIdx == lastQIdx ) /********************************************************************* * CONSTANTS */ -#define HID_DEV_DATA_LEN 8 - -#ifdef HID_DEV_RPT_QUEUE_LEN - #define HID_DEV_REPORT_Q_SIZE (HID_DEV_RPT_QUEUE_LEN+1) -#else - #define HID_DEV_REPORT_Q_SIZE (10+1) -#endif - /********************************************************************* * TYPEDEFS */ -typedef struct -{ - uint8 id; - uint8 type; - uint8 len; - uint8 data[HID_DEV_DATA_LEN]; -} hidDevReport_t; /********************************************************************* * GLOBAL VARIABLES @@ -104,9 +85,6 @@ static uint8 hidDevConnSecure = FALSE; // GAP connection handle static uint16 gapConnHandle; -// TRUE if pairing in progress -static uint8 hidDevPairingStarted = TRUE; - // Status of last pairing static uint8 pairingStatus = SUCCESS; @@ -118,14 +96,6 @@ static hidDevCB_t *pHidDevCB; static hidDevCfg_t *pHidDevCfg; -// Pending reports -static uint8 firstQIdx = 0; -static uint8 lastQIdx = 0; -static hidDevReport_t hidDevReportQ[HID_DEV_REPORT_Q_SIZE]; - -// Last report sent out -//static attHandleValueNoti_t lastNoti = { 0 }; -static hidDevReport_t lastReport = { 0 }; /********************************************************************* * LOCAL FUNCTIONS */ @@ -145,17 +115,12 @@ static void hidDevBattPeriodicTask( void ); static hidRptMap_t *hidDevRptByHandle( uint16 handle ); static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ); static hidRptMap_t *hidDevRptByCccdHandle( uint16 handle ); -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); -static hidDevReport_t *hidDevDequeueReport( void ); -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); static void hidDevHighAdvertising( void ); static void hidDevLowAdvertising( void ); static void hidDevInitialAdvertising( void ); static uint8 hidDevBondCount( void ); -static void hidDevStartIdleTimer( void ); -static void hidDevStopIdleTimer( void ); static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData); -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len); /********************************************************************* * PROFILE CALLBACKS */ @@ -267,26 +232,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ START_DEVICE_EVT ); } - if ( events & HID_IDLE_EVT ) - { - if ( hidDevGapState == GAPROLE_CONNECTED ) - { - PRINT("hid idle event..\n"); - // if pairing in progress then restart timer - if ( hidDevPairingStarted ) - { - hidDevStartIdleTimer(); - } - // else disconnect - else - { - GAPRole_TerminateLink( gapConnHandle ); - } - } - - return ( events ^ HID_IDLE_EVT ); - } - if ( events & BATT_PERIODIC_EVT ) { // Perform periodic battery task @@ -295,25 +240,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ BATT_PERIODIC_EVT ); } - if ( events & HID_SEND_REPORT_EVT ) - { - // if connection is secure - if ( hidDevConnSecure ) - { - hidDevReport_t *pReport = hidDevDequeueReport(); - - if ( pReport != NULL ) - { - // Send report - hidDevSendReport( pReport->id, pReport->type, pReport->len, pReport->data ); - } - - return ( reportQEmpty() ? events ^ HID_SEND_REPORT_EVT : events ); - } - - return ( events ^ HID_SEND_REPORT_EVT ); - } - return 0; } @@ -361,7 +287,7 @@ void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ) * * @return None. */ -void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) +uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) { // if connected if ( hidDevGapState == GAPROLE_CONNECTED ) @@ -369,14 +295,8 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) // if connection is secure if ( hidDevConnSecure ) { - // Make sure there're no pending reports - if ( reportQEmpty() ) - { - // send report - hidDevSendReport( id, type, len, pData ); - - return; // we're done - } + // send report + return hidDevSendReport( id, type, len, pData ); } } // else if not already advertising @@ -395,9 +315,7 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) hidDevInitialAdvertising(); } } - - // hidDev task will send report when secure connection is established - hidDevEnqueueReport( id, type, len, pData ); + return bleNotReady; } /********************************************************************* @@ -447,33 +365,12 @@ bStatus_t HidDev_SetParameter( uint8 param, uint8 len, void *pValue ) case HIDDEV_ERASE_ALLBONDS: if ( len == 0 ) { - hidRptMap_t *pRpt; - if ((pRpt = hidDevRptById(lastReport.id, lastReport.type)) != NULL) - { - // See if the last report sent out wasn't a release key - if (HidDev_isbufset(lastReport.data, 0x00, lastReport.len) == FALSE) - { - // Send a release report before disconnecting, otherwise - // the last pressed key would get 'stuck' on the HID Host. - tmos_memset(lastReport.data, 0x00, lastReport.len); - - // Send report notification - HidDev_sendNoti(pRpt->handle, lastReport.len, lastReport.data); - } - - // Clear out last report - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); - } - // Drop connection if ( hidDevGapState == GAPROLE_CONNECTED ) { GAPRole_TerminateLink( gapConnHandle ); } - // Flush report queue - firstQIdx = lastQIdx = 0; - // Erase bonding info GAPBondMgr_SetParameter( GAPBOND_ERASE_ALLBONDS, 0, NULL ); } @@ -618,12 +515,6 @@ bStatus_t HidDev_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, tmos_memcpy( pValue, pAttr->pValue, HID_EXT_REPORT_REF_LEN ); } - // restart idle timer - if ( status == SUCCESS ) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -730,12 +621,6 @@ bStatus_t HidDev_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, } } - // restart idle timer - if (status == SUCCESS) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -820,9 +705,6 @@ static void hidDevHandleConnStatusCB( uint16 connHandle, uint8 changeType ) */ static void hidDevDisconnected( void ) { - // Stop idle timer - hidDevStopIdleTimer(); - // Reset client characteristic configuration descriptors Batt_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); ScanParam_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); @@ -831,11 +713,7 @@ static void hidDevDisconnected( void ) // Reset state variables hidDevConnSecure = FALSE; hidProtocolMode = HID_PROTOCOL_MODE_REPORT; - hidDevPairingStarted = FALSE; - // Reset last report sent out - //tmos_memset( &lastNoti, 0, sizeof( attHandleValueNoti_t ) ); - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); // if bonded and normally connectable start advertising if ( ( hidDevBondCount() > 0 ) && ( pHidDevCfg->hidFlags & HID_FLAGS_NORMALLY_CONNECTABLE ) ) @@ -871,8 +749,6 @@ static void hidDevGapStateCB( gapRole_States_t newState, gapRoleEvent_t * pEvent param = FALSE; GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), ¶m ); - // start idle timer - hidDevStartIdleTimer(); } // if disconnected else if ( hidDevGapState == GAPROLE_CONNECTED && @@ -931,14 +807,8 @@ static void hidDevParamUpdateCB( uint16 connHandle, uint16 connInterval, */ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) { - if ( state == GAPBOND_PAIRING_STATE_STARTED ) - { - hidDevPairingStarted = TRUE; - } - else if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) + if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) { - hidDevPairingStarted = FALSE; - if ( status == SUCCESS ) { hidDevConnSecure = TRUE; @@ -960,11 +830,6 @@ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) else if( state == GAPBOND_PAIRING_STATE_BOND_SAVED ) { } - if ( !reportQEmpty() && hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } } /********************************************************************* @@ -1139,11 +1004,12 @@ static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ) * * @return None. */ -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) { hidRptMap_t *pRpt; gattAttribute_t *pAttr; uint16 retHandle; + uint8 state = bleNoResources; // get att handle for report if ( (pRpt = hidDevRptById(id, type)) != NULL ) @@ -1157,20 +1023,11 @@ static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) if ( value & GATT_CLIENT_CFG_NOTIFY ) { // Send report notification - if (HidDev_sendNoti(pRpt->handle, len, pData) == SUCCESS) - { - // Save the report just sent out - lastReport.id = id; - lastReport.type = type; - lastReport.len = len; - tmos_memcpy(lastReport.data, pData, len); - } - - // start idle timer - hidDevStartIdleTimer(); + state = HidDev_sendNoti(pRpt->handle, len, pData); } } } + return state; } /********************************************************************* @@ -1211,71 +1068,6 @@ static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData) return status; } -/********************************************************************* - * @fn hidDevEnqueueReport - * - * @brief Enqueue a HID report to be sent later. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) -{ - // Enqueue only if bonded - if ( hidDevBondCount() > 0 ) - { - // Update last index - lastQIdx = ( lastQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - if ( lastQIdx == firstQIdx ) - { - // Queue overflow; discard oldest report - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - } - - // Save report - hidDevReportQ[lastQIdx].id = id; - hidDevReportQ[lastQIdx].type = type; - hidDevReportQ[lastQIdx].len = len; - tmos_memcpy( hidDevReportQ[lastQIdx].data, pData, len ); - - if ( hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } - } -} - -/********************************************************************* - * @fn hidDevDequeueReport - * - * @brief Dequeue a HID report to be sent out. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static hidDevReport_t *hidDevDequeueReport( void ) -{ - if ( reportQEmpty() ) - { - return NULL; - } - - // Update first index - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - return ( &(hidDevReportQ[firstQIdx]) ); -} - /********************************************************************* * @fn hidDevHighAdvertising * @@ -1355,69 +1147,5 @@ static uint8 hidDevBondCount( void ) return ( bondCnt ); } - -/********************************************************************* - * @fn HidDev_isbufset - * - * @brief Is all of the array elements set to a value? - * - * @param buf - buffer to check. - * @param val - value to check each array element for. - * @param len - length to check. - * - * @return TRUE if all "val". - * FALSE otherwise. - */ -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len) -{ - uint8 x; - - // Validate pointer and length of report - if ((buf == NULL) || (len > HID_DEV_DATA_LEN)) - { - return ( FALSE ); - } - - for ( x = 0; x < len; x++ ) - { - // Check for non-initialized value - if ( buf[x] != val ) - { - return ( FALSE ); - } - } - - return ( TRUE ); -} - - -/********************************************************************* - * @fn hidDevStartIdleTimer - * - * @brief Start the idle timer. - * - * @return None. - */ -static void hidDevStartIdleTimer( void ) -{ - if ( pHidDevCfg->idleTimeout > 0 ) - { -// tmos_start_task( hidDevTaskId, HID_IDLE_EVT, pHidDevCfg->idleTimeout ); - } -} - -/********************************************************************* - * @fn hidDevStopIdleTimer - * - * @brief Stop the idle timer. - * - * @return None. - */ -static void hidDevStopIdleTimer( void ) -{ - tmos_stop_task( hidDevTaskId, HID_IDLE_EVT ); -} - - /********************************************************************* *********************************************************************/ diff --git a/src/EXAM/BLE/HID_Keyboard/Profile/include/hiddev.h b/src/EXAM/BLE/HID_Keyboard/Profile/include/hiddev.h index 249b12f..6da7eb6 100644 --- a/src/EXAM/BLE/HID_Keyboard/Profile/include/hiddev.h +++ b/src/EXAM/BLE/HID_Keyboard/Profile/include/hiddev.h @@ -341,7 +341,7 @@ extern void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ); * * @return None. */ -extern void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); +extern uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); /********************************************************************* * @fn HidDev_Close diff --git a/src/EXAM/BLE/HID_Keyboard/Project/BLE.uvprojx b/src/EXAM/BLE/HID_Keyboard/Project/BLE.uvprojx index f74ac74..ea1707f 100644 --- a/src/EXAM/BLE/HID_Keyboard/Project/BLE.uvprojx +++ b/src/EXAM/BLE/HID_Keyboard/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -513,6 +513,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + diff --git a/src/EXAM/BLE/HID_Mouse/APP/hidmouse_main.c b/src/EXAM/BLE/HID_Mouse/APP/hidmouse_main.c index 43eb760..e514421 100644 --- a/src/EXAM/BLE/HID_Mouse/APP/hidmouse_main.c +++ b/src/EXAM/BLE/HID_Mouse/APP/hidmouse_main.c @@ -32,8 +32,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/HID_Mouse/Profile/hiddev.c b/src/EXAM/BLE/HID_Mouse/Profile/hiddev.c index dae3d5c..079cfc3 100644 --- a/src/EXAM/BLE/HID_Mouse/Profile/hiddev.c +++ b/src/EXAM/BLE/HID_Mouse/Profile/hiddev.c @@ -47,34 +47,15 @@ // Heart Rate Task Events #define START_DEVICE_EVT 0x0001 #define BATT_PERIODIC_EVT 0x0002 -#define HID_IDLE_EVT 0x0004 -#define HID_SEND_REPORT_EVT 0x0008 - -#define reportQEmpty() ( firstQIdx == lastQIdx ) /********************************************************************* * CONSTANTS */ -#define HID_DEV_DATA_LEN 8 - -#ifdef HID_DEV_RPT_QUEUE_LEN - #define HID_DEV_REPORT_Q_SIZE (HID_DEV_RPT_QUEUE_LEN+1) -#else - #define HID_DEV_REPORT_Q_SIZE (10+1) -#endif - /********************************************************************* * TYPEDEFS */ -typedef struct -{ - uint8 id; - uint8 type; - uint8 len; - uint8 data[HID_DEV_DATA_LEN]; -} hidDevReport_t; /********************************************************************* * GLOBAL VARIABLES @@ -104,9 +85,6 @@ static uint8 hidDevConnSecure = FALSE; // GAP connection handle static uint16 gapConnHandle; -// TRUE if pairing in progress -static uint8 hidDevPairingStarted = TRUE; - // Status of last pairing static uint8 pairingStatus = SUCCESS; @@ -118,14 +96,6 @@ static hidDevCB_t *pHidDevCB; static hidDevCfg_t *pHidDevCfg; -// Pending reports -static uint8 firstQIdx = 0; -static uint8 lastQIdx = 0; -static hidDevReport_t hidDevReportQ[HID_DEV_REPORT_Q_SIZE]; - -// Last report sent out -//static attHandleValueNoti_t lastNoti = { 0 }; -static hidDevReport_t lastReport = { 0 }; /********************************************************************* * LOCAL FUNCTIONS */ @@ -145,17 +115,12 @@ static void hidDevBattPeriodicTask( void ); static hidRptMap_t *hidDevRptByHandle( uint16 handle ); static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ); static hidRptMap_t *hidDevRptByCccdHandle( uint16 handle ); -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); -static hidDevReport_t *hidDevDequeueReport( void ); -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); static void hidDevHighAdvertising( void ); static void hidDevLowAdvertising( void ); static void hidDevInitialAdvertising( void ); static uint8 hidDevBondCount( void ); -static void hidDevStartIdleTimer( void ); -static void hidDevStopIdleTimer( void ); static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData); -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len); /********************************************************************* * PROFILE CALLBACKS */ @@ -267,26 +232,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ START_DEVICE_EVT ); } - if ( events & HID_IDLE_EVT ) - { - if ( hidDevGapState == GAPROLE_CONNECTED ) - { - PRINT("hid idle event..\n"); - // if pairing in progress then restart timer - if ( hidDevPairingStarted ) - { - hidDevStartIdleTimer(); - } - // else disconnect - else - { - GAPRole_TerminateLink( gapConnHandle ); - } - } - - return ( events ^ HID_IDLE_EVT ); - } - if ( events & BATT_PERIODIC_EVT ) { // Perform periodic battery task @@ -295,25 +240,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ BATT_PERIODIC_EVT ); } - if ( events & HID_SEND_REPORT_EVT ) - { - // if connection is secure - if ( hidDevConnSecure ) - { - hidDevReport_t *pReport = hidDevDequeueReport(); - - if ( pReport != NULL ) - { - // Send report - hidDevSendReport( pReport->id, pReport->type, pReport->len, pReport->data ); - } - - return ( reportQEmpty() ? events ^ HID_SEND_REPORT_EVT : events ); - } - - return ( events ^ HID_SEND_REPORT_EVT ); - } - return 0; } @@ -361,7 +287,7 @@ void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ) * * @return None. */ -void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) +uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) { // if connected if ( hidDevGapState == GAPROLE_CONNECTED ) @@ -369,14 +295,8 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) // if connection is secure if ( hidDevConnSecure ) { - // Make sure there're no pending reports - if ( reportQEmpty() ) - { - // send report - hidDevSendReport( id, type, len, pData ); - - return; // we're done - } + // send report + return hidDevSendReport( id, type, len, pData ); } } // else if not already advertising @@ -395,9 +315,7 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) hidDevInitialAdvertising(); } } - - // hidDev task will send report when secure connection is established - hidDevEnqueueReport( id, type, len, pData ); + return bleNotReady; } /********************************************************************* @@ -447,33 +365,12 @@ bStatus_t HidDev_SetParameter( uint8 param, uint8 len, void *pValue ) case HIDDEV_ERASE_ALLBONDS: if ( len == 0 ) { - hidRptMap_t *pRpt; - if ((pRpt = hidDevRptById(lastReport.id, lastReport.type)) != NULL) - { - // See if the last report sent out wasn't a release key - if (HidDev_isbufset(lastReport.data, 0x00, lastReport.len) == FALSE) - { - // Send a release report before disconnecting, otherwise - // the last pressed key would get 'stuck' on the HID Host. - tmos_memset(lastReport.data, 0x00, lastReport.len); - - // Send report notification - HidDev_sendNoti(pRpt->handle, lastReport.len, lastReport.data); - } - - // Clear out last report - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); - } - // Drop connection if ( hidDevGapState == GAPROLE_CONNECTED ) { GAPRole_TerminateLink( gapConnHandle ); } - // Flush report queue - firstQIdx = lastQIdx = 0; - // Erase bonding info GAPBondMgr_SetParameter( GAPBOND_ERASE_ALLBONDS, 0, NULL ); } @@ -618,12 +515,6 @@ bStatus_t HidDev_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, tmos_memcpy( pValue, pAttr->pValue, HID_EXT_REPORT_REF_LEN ); } - // restart idle timer - if ( status == SUCCESS ) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -730,12 +621,6 @@ bStatus_t HidDev_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, } } - // restart idle timer - if (status == SUCCESS) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -820,9 +705,6 @@ static void hidDevHandleConnStatusCB( uint16 connHandle, uint8 changeType ) */ static void hidDevDisconnected( void ) { - // Stop idle timer - hidDevStopIdleTimer(); - // Reset client characteristic configuration descriptors Batt_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); ScanParam_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); @@ -831,11 +713,7 @@ static void hidDevDisconnected( void ) // Reset state variables hidDevConnSecure = FALSE; hidProtocolMode = HID_PROTOCOL_MODE_REPORT; - hidDevPairingStarted = FALSE; - // Reset last report sent out - //tmos_memset( &lastNoti, 0, sizeof( attHandleValueNoti_t ) ); - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); // if bonded and normally connectable start advertising if ( ( hidDevBondCount() > 0 ) && ( pHidDevCfg->hidFlags & HID_FLAGS_NORMALLY_CONNECTABLE ) ) @@ -871,8 +749,6 @@ static void hidDevGapStateCB( gapRole_States_t newState, gapRoleEvent_t * pEvent param = FALSE; GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), ¶m ); - // start idle timer - hidDevStartIdleTimer(); } // if disconnected else if ( hidDevGapState == GAPROLE_CONNECTED && @@ -931,14 +807,8 @@ static void hidDevParamUpdateCB( uint16 connHandle, uint16 connInterval, */ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) { - if ( state == GAPBOND_PAIRING_STATE_STARTED ) - { - hidDevPairingStarted = TRUE; - } - else if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) + if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) { - hidDevPairingStarted = FALSE; - if ( status == SUCCESS ) { hidDevConnSecure = TRUE; @@ -960,11 +830,6 @@ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) else if( state == GAPBOND_PAIRING_STATE_BOND_SAVED ) { } - if ( !reportQEmpty() && hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } } /********************************************************************* @@ -1139,11 +1004,12 @@ static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ) * * @return None. */ -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) { hidRptMap_t *pRpt; gattAttribute_t *pAttr; uint16 retHandle; + uint8 state = bleNoResources; // get att handle for report if ( (pRpt = hidDevRptById(id, type)) != NULL ) @@ -1157,20 +1023,11 @@ static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) if ( value & GATT_CLIENT_CFG_NOTIFY ) { // Send report notification - if (HidDev_sendNoti(pRpt->handle, len, pData) == SUCCESS) - { - // Save the report just sent out - lastReport.id = id; - lastReport.type = type; - lastReport.len = len; - tmos_memcpy(lastReport.data, pData, len); - } - - // start idle timer - hidDevStartIdleTimer(); + state = HidDev_sendNoti(pRpt->handle, len, pData); } } } + return state; } /********************************************************************* @@ -1211,71 +1068,6 @@ static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData) return status; } -/********************************************************************* - * @fn hidDevEnqueueReport - * - * @brief Enqueue a HID report to be sent later. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) -{ - // Enqueue only if bonded - if ( hidDevBondCount() > 0 ) - { - // Update last index - lastQIdx = ( lastQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - if ( lastQIdx == firstQIdx ) - { - // Queue overflow; discard oldest report - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - } - - // Save report - hidDevReportQ[lastQIdx].id = id; - hidDevReportQ[lastQIdx].type = type; - hidDevReportQ[lastQIdx].len = len; - tmos_memcpy( hidDevReportQ[lastQIdx].data, pData, len ); - - if ( hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } - } -} - -/********************************************************************* - * @fn hidDevDequeueReport - * - * @brief Dequeue a HID report to be sent out. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static hidDevReport_t *hidDevDequeueReport( void ) -{ - if ( reportQEmpty() ) - { - return NULL; - } - - // Update first index - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - return ( &(hidDevReportQ[firstQIdx]) ); -} - /********************************************************************* * @fn hidDevHighAdvertising * @@ -1355,69 +1147,5 @@ static uint8 hidDevBondCount( void ) return ( bondCnt ); } - -/********************************************************************* - * @fn HidDev_isbufset - * - * @brief Is all of the array elements set to a value? - * - * @param buf - buffer to check. - * @param val - value to check each array element for. - * @param len - length to check. - * - * @return TRUE if all "val". - * FALSE otherwise. - */ -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len) -{ - uint8 x; - - // Validate pointer and length of report - if ((buf == NULL) || (len > HID_DEV_DATA_LEN)) - { - return ( FALSE ); - } - - for ( x = 0; x < len; x++ ) - { - // Check for non-initialized value - if ( buf[x] != val ) - { - return ( FALSE ); - } - } - - return ( TRUE ); -} - - -/********************************************************************* - * @fn hidDevStartIdleTimer - * - * @brief Start the idle timer. - * - * @return None. - */ -static void hidDevStartIdleTimer( void ) -{ - if ( pHidDevCfg->idleTimeout > 0 ) - { -// tmos_start_task( hidDevTaskId, HID_IDLE_EVT, pHidDevCfg->idleTimeout ); - } -} - -/********************************************************************* - * @fn hidDevStopIdleTimer - * - * @brief Stop the idle timer. - * - * @return None. - */ -static void hidDevStopIdleTimer( void ) -{ - tmos_stop_task( hidDevTaskId, HID_IDLE_EVT ); -} - - /********************************************************************* *********************************************************************/ diff --git a/src/EXAM/BLE/HID_Mouse/Profile/include/hiddev.h b/src/EXAM/BLE/HID_Mouse/Profile/include/hiddev.h index 249b12f..6da7eb6 100644 --- a/src/EXAM/BLE/HID_Mouse/Profile/include/hiddev.h +++ b/src/EXAM/BLE/HID_Mouse/Profile/include/hiddev.h @@ -341,7 +341,7 @@ extern void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ); * * @return None. */ -extern void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); +extern uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); /********************************************************************* * @fn HidDev_Close diff --git a/src/EXAM/BLE/HID_Mouse/Project/BLE.uvprojx b/src/EXAM/BLE/HID_Mouse/Project/BLE.uvprojx index 7ca438d..c26a514 100644 --- a/src/EXAM/BLE/HID_Mouse/Project/BLE.uvprojx +++ b/src/EXAM/BLE/HID_Mouse/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -513,6 +513,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + diff --git a/src/EXAM/BLE/HID_Touch/APP/hidtouch_main.c b/src/EXAM/BLE/HID_Touch/APP/hidtouch_main.c index 655838b..ed134b2 100644 --- a/src/EXAM/BLE/HID_Touch/APP/hidtouch_main.c +++ b/src/EXAM/BLE/HID_Touch/APP/hidtouch_main.c @@ -32,8 +32,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/HID_Touch/Profile/hiddev.c b/src/EXAM/BLE/HID_Touch/Profile/hiddev.c index b0963b6..166bd1f 100644 --- a/src/EXAM/BLE/HID_Touch/Profile/hiddev.c +++ b/src/EXAM/BLE/HID_Touch/Profile/hiddev.c @@ -47,34 +47,15 @@ // Heart Rate Task Events #define START_DEVICE_EVT 0x0001 #define BATT_PERIODIC_EVT 0x0002 -#define HID_IDLE_EVT 0x0004 -#define HID_SEND_REPORT_EVT 0x0008 - -#define reportQEmpty() ( firstQIdx == lastQIdx ) /********************************************************************* * CONSTANTS */ -#define HID_DEV_DATA_LEN 8 - -#ifdef HID_DEV_RPT_QUEUE_LEN - #define HID_DEV_REPORT_Q_SIZE (HID_DEV_RPT_QUEUE_LEN+1) -#else - #define HID_DEV_REPORT_Q_SIZE (10+1) -#endif - /********************************************************************* * TYPEDEFS */ -typedef struct -{ - uint8 id; - uint8 type; - uint8 len; - uint8 data[HID_DEV_DATA_LEN]; -} hidDevReport_t; /********************************************************************* * GLOBAL VARIABLES @@ -104,9 +85,6 @@ static uint8 hidDevConnSecure = FALSE; // GAP connection handle static uint16 gapConnHandle; -// TRUE if pairing in progress -static uint8 hidDevPairingStarted = TRUE; - // Status of last pairing static uint8 pairingStatus = SUCCESS; @@ -118,14 +96,6 @@ static hidDevCB_t *pHidDevCB; static hidDevCfg_t *pHidDevCfg; -// Pending reports -static uint8 firstQIdx = 0; -static uint8 lastQIdx = 0; -static hidDevReport_t hidDevReportQ[HID_DEV_REPORT_Q_SIZE]; - -// Last report sent out -//static attHandleValueNoti_t lastNoti = { 0 }; -static hidDevReport_t lastReport = { 0 }; /********************************************************************* * LOCAL FUNCTIONS */ @@ -145,17 +115,12 @@ static void hidDevBattPeriodicTask( void ); static hidRptMap_t *hidDevRptByHandle( uint16 handle ); static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ); static hidRptMap_t *hidDevRptByCccdHandle( uint16 handle ); -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); -static hidDevReport_t *hidDevDequeueReport( void ); -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ); static void hidDevHighAdvertising( void ); static void hidDevLowAdvertising( void ); static void hidDevInitialAdvertising( void ); static uint8 hidDevBondCount( void ); -static void hidDevStartIdleTimer( void ); -static void hidDevStopIdleTimer( void ); static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData); -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len); /********************************************************************* * PROFILE CALLBACKS */ @@ -267,26 +232,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ START_DEVICE_EVT ); } - if ( events & HID_IDLE_EVT ) - { - if ( hidDevGapState == GAPROLE_CONNECTED ) - { - PRINT("hid idle event..\n"); - // if pairing in progress then restart timer - if ( hidDevPairingStarted ) - { - hidDevStartIdleTimer(); - } - // else disconnect - else - { - GAPRole_TerminateLink( gapConnHandle ); - } - } - - return ( events ^ HID_IDLE_EVT ); - } - if ( events & BATT_PERIODIC_EVT ) { // Perform periodic battery task @@ -295,25 +240,6 @@ uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events ) return ( events ^ BATT_PERIODIC_EVT ); } - if ( events & HID_SEND_REPORT_EVT ) - { - // if connection is secure - if ( hidDevConnSecure ) - { - hidDevReport_t *pReport = hidDevDequeueReport(); - - if ( pReport != NULL ) - { - // Send report - hidDevSendReport( pReport->id, pReport->type, pReport->len, pReport->data ); - } - - return ( reportQEmpty() ? events ^ HID_SEND_REPORT_EVT : events ); - } - - return ( events ^ HID_SEND_REPORT_EVT ); - } - return 0; } @@ -361,7 +287,7 @@ void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ) * * @return None. */ -void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) +uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) { // if connected if ( hidDevGapState == GAPROLE_CONNECTED ) @@ -369,14 +295,8 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) // if connection is secure if ( hidDevConnSecure ) { - // Make sure there're no pending reports - if ( reportQEmpty() ) - { - // send report - hidDevSendReport( id, type, len, pData ); - - return; // we're done - } + // send report + return hidDevSendReport( id, type, len, pData ); } } // else if not already advertising @@ -395,9 +315,7 @@ void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8*pData ) hidDevInitialAdvertising(); } } - - // hidDev task will send report when secure connection is established - hidDevEnqueueReport( id, type, len, pData ); + return bleNotReady; } /********************************************************************* @@ -447,33 +365,12 @@ bStatus_t HidDev_SetParameter( uint8 param, uint8 len, void *pValue ) case HIDDEV_ERASE_ALLBONDS: if ( len == 0 ) { - hidRptMap_t *pRpt; - if ((pRpt = hidDevRptById(lastReport.id, lastReport.type)) != NULL) - { - // See if the last report sent out wasn't a release key - if (HidDev_isbufset(lastReport.data, 0x00, lastReport.len) == FALSE) - { - // Send a release report before disconnecting, otherwise - // the last pressed key would get 'stuck' on the HID Host. - tmos_memset(lastReport.data, 0x00, lastReport.len); - - // Send report notification - HidDev_sendNoti(pRpt->handle, lastReport.len, lastReport.data); - } - - // Clear out last report - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); - } - // Drop connection if ( hidDevGapState == GAPROLE_CONNECTED ) { GAPRole_TerminateLink( gapConnHandle ); } - // Flush report queue - firstQIdx = lastQIdx = 0; - // Erase bonding info GAPBondMgr_SetParameter( GAPBOND_ERASE_ALLBONDS, 0, NULL ); } @@ -618,12 +515,6 @@ bStatus_t HidDev_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, tmos_memcpy( pValue, pAttr->pValue, HID_EXT_REPORT_REF_LEN ); } - // restart idle timer - if ( status == SUCCESS ) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -730,12 +621,6 @@ bStatus_t HidDev_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, } } - // restart idle timer - if (status == SUCCESS) - { - hidDevStartIdleTimer(); - } - return ( status ); } @@ -820,9 +705,6 @@ static void hidDevHandleConnStatusCB( uint16 connHandle, uint8 changeType ) */ static void hidDevDisconnected( void ) { - // Stop idle timer - hidDevStopIdleTimer(); - // Reset client characteristic configuration descriptors Batt_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); ScanParam_HandleConnStatusCB( gapConnHandle, LINKDB_STATUS_UPDATE_REMOVED ); @@ -831,11 +713,7 @@ static void hidDevDisconnected( void ) // Reset state variables hidDevConnSecure = FALSE; hidProtocolMode = HID_PROTOCOL_MODE_REPORT; - hidDevPairingStarted = FALSE; - // Reset last report sent out - //tmos_memset( &lastNoti, 0, sizeof( attHandleValueNoti_t ) ); - tmos_memset(&lastReport, 0, sizeof(hidDevReport_t)); // if bonded and normally connectable start advertising if ( ( hidDevBondCount() > 0 ) && ( pHidDevCfg->hidFlags & HID_FLAGS_NORMALLY_CONNECTABLE ) ) @@ -871,8 +749,6 @@ static void hidDevGapStateCB( gapRole_States_t newState, gapRoleEvent_t * pEvent param = FALSE; GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), ¶m ); - // start idle timer - hidDevStartIdleTimer(); } // if disconnected else if ( hidDevGapState == GAPROLE_CONNECTED && @@ -931,14 +807,8 @@ static void hidDevParamUpdateCB( uint16 connHandle, uint16 connInterval, */ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) { - if ( state == GAPBOND_PAIRING_STATE_STARTED ) - { - hidDevPairingStarted = TRUE; - } - else if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) + if ( state == GAPBOND_PAIRING_STATE_COMPLETE ) { - hidDevPairingStarted = FALSE; - if ( status == SUCCESS ) { hidDevConnSecure = TRUE; @@ -960,11 +830,6 @@ static void hidDevPairStateCB( uint16 connHandle, uint8 state, uint8 status ) else if( state == GAPBOND_PAIRING_STATE_BOND_SAVED ) { } - if ( !reportQEmpty() && hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } } /********************************************************************* @@ -1139,11 +1004,12 @@ static hidRptMap_t *hidDevRptById( uint8 id, uint8 type ) * * @return None. */ -static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) +static uint8 hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) { hidRptMap_t *pRpt; gattAttribute_t *pAttr; uint16 retHandle; + uint8 state = bleNoResources; // get att handle for report if ( (pRpt = hidDevRptById(id, type)) != NULL ) @@ -1157,20 +1023,11 @@ static void hidDevSendReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) if ( value & GATT_CLIENT_CFG_NOTIFY ) { // Send report notification - if (HidDev_sendNoti(pRpt->handle, len, pData) == SUCCESS) - { - // Save the report just sent out - lastReport.id = id; - lastReport.type = type; - lastReport.len = len; - tmos_memcpy(lastReport.data, pData, len); - } - - // start idle timer - hidDevStartIdleTimer(); + state = HidDev_sendNoti(pRpt->handle, len, pData); } } } + return state; } /********************************************************************* @@ -1211,71 +1068,6 @@ static uint8 HidDev_sendNoti(uint16 handle, uint8 len, uint8 *pData) return status; } -/********************************************************************* - * @fn hidDevEnqueueReport - * - * @brief Enqueue a HID report to be sent later. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static void hidDevEnqueueReport( uint8 id, uint8 type, uint8 len, uint8 *pData ) -{ - // Enqueue only if bonded - if ( hidDevBondCount() > 0 ) - { - // Update last index - lastQIdx = ( lastQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - if ( lastQIdx == firstQIdx ) - { - // Queue overflow; discard oldest report - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - } - - // Save report - hidDevReportQ[lastQIdx].id = id; - hidDevReportQ[lastQIdx].type = type; - hidDevReportQ[lastQIdx].len = len; - tmos_memcpy( hidDevReportQ[lastQIdx].data, pData, len ); - - if ( hidDevConnSecure ) - { - // Notify our task to send out pending reports - tmos_set_event( hidDevTaskId, HID_SEND_REPORT_EVT ); - } - } -} - -/********************************************************************* - * @fn hidDevDequeueReport - * - * @brief Dequeue a HID report to be sent out. - * - * @param id - HID report ID. - * @param type - HID report type. - * @param len - Length of report. - * @param pData - Report data. - * - * @return None. - */ -static hidDevReport_t *hidDevDequeueReport( void ) -{ - if ( reportQEmpty() ) - { - return NULL; - } - - // Update first index - firstQIdx = ( firstQIdx + 1 ) % HID_DEV_REPORT_Q_SIZE; - - return ( &(hidDevReportQ[firstQIdx]) ); -} - /********************************************************************* * @fn hidDevHighAdvertising * @@ -1355,69 +1147,5 @@ static uint8 hidDevBondCount( void ) return ( bondCnt ); } - -/********************************************************************* - * @fn HidDev_isbufset - * - * @brief Is all of the array elements set to a value? - * - * @param buf - buffer to check. - * @param val - value to check each array element for. - * @param len - length to check. - * - * @return TRUE if all "val". - * FALSE otherwise. - */ -static uint8 HidDev_isbufset(uint8 *buf, uint8 val, uint8 len) -{ - uint8 x; - - // Validate pointer and length of report - if ((buf == NULL) || (len > HID_DEV_DATA_LEN)) - { - return ( FALSE ); - } - - for ( x = 0; x < len; x++ ) - { - // Check for non-initialized value - if ( buf[x] != val ) - { - return ( FALSE ); - } - } - - return ( TRUE ); -} - - -/********************************************************************* - * @fn hidDevStartIdleTimer - * - * @brief Start the idle timer. - * - * @return None. - */ -static void hidDevStartIdleTimer( void ) -{ - if ( pHidDevCfg->idleTimeout > 0 ) - { -// tmos_start_task( hidDevTaskId, HID_IDLE_EVT, pHidDevCfg->idleTimeout ); - } -} - -/********************************************************************* - * @fn hidDevStopIdleTimer - * - * @brief Stop the idle timer. - * - * @return None. - */ -static void hidDevStopIdleTimer( void ) -{ - tmos_stop_task( hidDevTaskId, HID_IDLE_EVT ); -} - - /********************************************************************* *********************************************************************/ diff --git a/src/EXAM/BLE/HID_Touch/Profile/include/hiddev.h b/src/EXAM/BLE/HID_Touch/Profile/include/hiddev.h index 249b12f..6da7eb6 100644 --- a/src/EXAM/BLE/HID_Touch/Profile/include/hiddev.h +++ b/src/EXAM/BLE/HID_Touch/Profile/include/hiddev.h @@ -341,7 +341,7 @@ extern void HidDev_RegisterReports( uint8 numReports, hidRptMap_t *pRpt ); * * @return None. */ -extern void HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); +extern uint8 HidDev_Report( uint8 id, uint8 type, uint8 len, uint8 *pData ); /********************************************************************* * @fn HidDev_Close diff --git a/src/EXAM/BLE/HID_Touch/Project/BLE.uvprojx b/src/EXAM/BLE/HID_Touch/Project/BLE.uvprojx index a591832..67bd56e 100644 --- a/src/EXAM/BLE/HID_Touch/Project/BLE.uvprojx +++ b/src/EXAM/BLE/HID_Touch/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -513,6 +513,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + @@ -559,4 +564,10 @@ + + + + + + diff --git a/src/EXAM/BLE/HeartRate/APP/heartrate.c b/src/EXAM/BLE/HeartRate/APP/heartrate.c index 998ad31..d4305c0 100644 --- a/src/EXAM/BLE/HeartRate/APP/heartrate.c +++ b/src/EXAM/BLE/HeartRate/APP/heartrate.c @@ -44,10 +44,10 @@ #define DEFAULT_HEARTRATE_PERIOD 2000 // Minimum connection interval (units of 1.25ms) -#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 200 +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 20 // Maximum connection interval (units of 1.25ms) -#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 1600 +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 160 // Slave latency to use if parameter update request #define DEFAULT_DESIRED_SLAVE_LATENCY 1 diff --git a/src/EXAM/BLE/HeartRate/APP/heartrate_main.c b/src/EXAM/BLE/HeartRate/APP/heartrate_main.c index 3e51337..32f5919 100644 --- a/src/EXAM/BLE/HeartRate/APP/heartrate_main.c +++ b/src/EXAM/BLE/HeartRate/APP/heartrate_main.c @@ -31,8 +31,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/HeartRate/Project/BLE.uvprojx b/src/EXAM/BLE/HeartRate/Project/BLE.uvprojx index 532cf58..b200e2e 100644 --- a/src/EXAM/BLE/HeartRate/Project/BLE.uvprojx +++ b/src/EXAM/BLE/HeartRate/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -503,6 +503,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + diff --git a/src/EXAM/BLE/LIB/CH57xBLE.lib b/src/EXAM/BLE/LIB/CH57xBLE.lib index 88eee70..29229c8 100644 Binary files a/src/EXAM/BLE/LIB/CH57xBLE.lib and b/src/EXAM/BLE/LIB/CH57xBLE.lib differ diff --git a/src/EXAM/BLE/LIB/CH57xBLE_LIB.H b/src/EXAM/BLE/LIB/CH57xBLE_LIB.H index 877d46c..7e366d7 100644 --- a/src/EXAM/BLE/LIB/CH57xBLE_LIB.H +++ b/src/EXAM/BLE/LIB/CH57xBLE_LIB.H @@ -1,8 +1,8 @@ /********************************** (C) COPYRIGHT ****************************** * File Name : CH57xBLE_LIB.H * Author : WCH -* Version : V1.70 -* Date : 2022/01/21 +* Version : V1.80 +* Date : 2021/06/29 * Description : head file *******************************************************************************/ @@ -158,7 +158,7 @@ typedef struct /********************************************************************* * GLOBAL MACROS */ -#define VER_FILE "CH57x_BLE_LIB_V1.7" +#define VER_FILE "CH57x_BLE_LIB_V1.8" extern const u8 VER_LIB[]; // LIB version #define SYSTEM_TIME_MICROSEN 625 // unit of process event timer is 625us #define MS1_TO_SYSTEM_TIME(x) ((x)*1000/SYSTEM_TIME_MICROSEN) // transform unit in ms to unit in 625us ( attentional bias ) @@ -484,14 +484,14 @@ extern const u8 VER_LIB[]; // LIB version #define GATT_UNIT_TIME_MONTH_UUID 0x27B4 // /************************************************ Messages IDs *************************************************************/ -// GATT - Messages IDs (0xB0 - 0xBF) +// GATT - Messages IDs #define GATT_MSG_EVENT 0xB0 //!< Incoming GATT message -#define GATT_SERV_MSG_EVENT 0xB1 //!< Incoming GATT Serv App message -// GAP - Messages IDs (0xD0 - 0xDF) +#define GATT_SERV_MSG_EVENT 0xB1 //!< Incoming GATT ServApp message +// GAP - Messages IDs #define GAP_MSG_EVENT 0xD0 //!< Incoming GAP message /************************************************ ATT *************************************************************/ -#define ATT_MTU_SIZE L2CAP_MTU_SIZE //!< Minimum ATT MTU size -#define ATT_MAX_MTU_SIZE 517 //!< Maximum ATT MTU size +#define ATT_MTU_SIZE 23 //!< Minimum ATT MTU size +#define ATT_MAX_MTU_SIZE 247 //!< Maximum ATT MTU size // ATT Methods #define ATT_ERROR_RSP 0x01 //!< ATT Error Response #define ATT_EXCHANGE_MTU_REQ 0x02 //!< ATT Exchange MTU Request @@ -524,17 +524,17 @@ extern const u8 VER_LIB[]; // LIB version #define ATT_SIGNED_WRITE_CMD 0xD2 //!< ATT Signed Write Command // ATT Error Codes -#define ATT_ERR_INVALID_HANDLE 0x01 //!< Attribute handle value given was not valid on this attribute server -#define ATT_ERR_READ_NOT_PERMITTED 0x02 //!< Attribute cannot be read -#define ATT_ERR_WRITE_NOT_PERMITTED 0x03 //!< Attribute cannot be written +#define ATT_ERR_INVALID_HANDLE 0x01 //!< The attribute handle given was not valid on this server +#define ATT_ERR_READ_NOT_PERMITTED 0x02 //!< The attribute cannot be read +#define ATT_ERR_WRITE_NOT_PERMITTED 0x03 //!< The attribute cannot be written #define ATT_ERR_INVALID_PDU 0x04 //!< The attribute PDU was invalid #define ATT_ERR_INSUFFICIENT_AUTHEN 0x05 //!< The attribute requires authentication before it can be read or written -#define ATT_ERR_UNSUPPORTED_REQ 0x06 //!< Attribute server doesn't support the request received from the attribute client +#define ATT_ERR_UNSUPPORTED_REQ 0x06 //!< Attribute server does not support the request received from the client #define ATT_ERR_INVALID_OFFSET 0x07 //!< Offset specified was past the end of the attribute -#define ATT_ERR_INSUFFICIENT_AUTHOR 0x08 //!< The attribute requires an authorization before it can be read or written +#define ATT_ERR_INSUFFICIENT_AUTHOR 0x08 //!< The attribute requires authorization before it can be read or written #define ATT_ERR_PREPARE_QUEUE_FULL 0x09 //!< Too many prepare writes have been queued #define ATT_ERR_ATTR_NOT_FOUND 0x0a //!< No attribute found within the given attribute handle range -#define ATT_ERR_ATTR_NOT_LONG 0x0b //!< Attribute cannot be read or written using the Read Blob Request or Prepare Write Request +#define ATT_ERR_ATTR_NOT_LONG 0x0b //!< The attribute cannot be read using the Read Blob Request #define ATT_ERR_INSUFFICIENT_KEY_SIZE 0x0c //!< The Encryption Key Size used for encrypting this link is insufficient #define ATT_ERR_INVALID_VALUE_SIZE 0x0d //!< The attribute value length is invalid for the operation #define ATT_ERR_UNLIKELY 0x0e //!< The attribute request that was requested has encountered an error that was very unlikely, and therefore could not be completed as requested @@ -584,8 +584,8 @@ extern const u8 VER_LIB[]; // LIB version #define GATT_PROP_READ 0x02 //!< Permits reads of the Characteristic Value #define GATT_PROP_WRITE_NO_RSP 0x04 //!< Permits writes of the Characteristic Value without response #define GATT_PROP_WRITE 0x08 //!< Permits writes of the Characteristic Value with response -#define GATT_PROP_NOTIFY 0x10 //!< Permits notifications of a Characteristic Value without acknowledgement -#define GATT_PROP_INDICATE 0x20 //!< Permits indications of a Characteristic Value with acknowledgement +#define GATT_PROP_NOTIFY 0x10 //!< Permits notifications of a Characteristic Value without acknowledgment +#define GATT_PROP_INDICATE 0x20 //!< Permits indications of a Characteristic Value with acknowledgment #define GATT_PROP_AUTHEN 0x40 //!< Permits signed writes to the Characteristic Value #define GATT_PROP_EXTENDED 0x80 //!< Additional characteristic properties are defined in the Characteristic Extended Properties Descriptor @@ -711,42 +711,44 @@ extern const u8 VER_LIB[]; // LIB version // GAP_PARAMETER_ID_DEFINES GAP Parameter IDs // Timers -#define TGAP_GEN_DISC_ADV_MIN 0 //!< Minimum time to remain advertising, when in Discoverable mode (0.625 mSec). Setting this parameter to 0 turns off the timeout (default). -#define TGAP_LIM_ADV_TIMEOUT 1 //!< Maximum time to remain advertising, when in Limited Discoverable mode. In seconds (default 180 seconds) -#define TGAP_DISC_SCAN 2 //!< Minimum time to perform scanning, when performing General Discovery proc (0.625 mSec) - -// Constants -#define TGAP_DISC_ADV_INT_MIN 3 //!< Minimum advertising interval, when in General discoverable mode (n * 0.625 mSec) -#define TGAP_DISC_ADV_INT_MAX 4 //!< Maximum advertising interval, when in General discoverable mode (n * 0.625 mSec) -#define TGAP_DISC_SCAN_INT 5 //!< Scan interval used during Link Layer Scanning state, when in General Discovery proc (n * 0.625 mSec) -#define TGAP_DISC_SCAN_WIND 6 //!< Scan window used during Link Layer Scanning state, when in General Discovery proc (n * 0.625 mSec) -#define TGAP_CONN_EST_INT_MIN 7 //!< Minimum Link Layer connection interval, when using Connection Establishment proc (n * 1.25 mSec) -#define TGAP_CONN_EST_INT_MAX 8 //!< Maximum Link Layer connection interval, when using Connection Establishment proc (n * 1.25 mSec) -#define TGAP_CONN_EST_SCAN_INT 9 //!< Scan interval used during Link Layer Initiating state, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_CONN_EST_SCAN_WIND 10 //!< Scan window used during Link Layer Initiating state, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_CONN_EST_HIGH_SCAN_INT 11 //!< Scan interval used during Link Layer Initiating state, when in Connectable mode, high duty scan cycle scan parameters (n * 0.625 mSec) -#define TGAP_CONN_EST_HIGH_SCAN_WIND 12 //!< Scan window used during Link Layer Initiating state, when in Connectable mode, high duty scan cycle scan parameters (n * 0.625 mSec) -#define TGAP_CONN_EST_SUPERV_TIMEOUT 13 //!< Link Layer connection supervision timeout, when using Connection Establishment proc (n * 10 mSec) -#define TGAP_CONN_EST_LATENCY 14 //!< Link Layer connection slave latency, when using Connection Establishment proc (in number of connection events) -#define TGAP_CONN_EST_MIN_CE_LEN 15 //!< Local informational parameter about min len of connection needed, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_CONN_EST_MAX_CE_LEN 16 //!< Local informational parameter about max len of connection needed, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_PRIVATE_ADDR_INT 17 //!< Minimum Time Interval between private (resolvable) address changes. In minutes (default 15 minutes) +#define TGAP_GEN_DISC_ADV_MIN 0 //!< Minimum time to remain advertising, when in Discoverable mode.Default 0-turns off the timeout. (n * 0.625 mSec). +#define TGAP_LIM_ADV_TIMEOUT 1 //!< Maximum time to remain advertising, when in Limited Discoverable mode.Default 180 seconds. (n * 1 seconds) +#define TGAP_DISC_SCAN 2 //!< Minimum time to perform scanning,Setting this parameter to 0 turns off the timeout.Default 10.24seconds. (n * 0.625 mSec) + +// when in General Discovery process +#define TGAP_DISC_ADV_INT_MIN 3 //!< Minimum advertising interval.Default 160. (n * 0.625 mSec) +#define TGAP_DISC_ADV_INT_MAX 4 //!< Maximum advertising interval.Default 160. (n * 0.625 mSec) +#define TGAP_DISC_SCAN_INT 5 //!< Scan interval used during Link Layer Scanning state.Default 16. (n * 0.625 mSec) +#define TGAP_DISC_SCAN_WIND 6 //!< Scan window used during Link Layer Scanning state.Default 16. (n * 0.625 mSec) + +// when in Connection Establishment process(1M PHY) +#define TGAP_CONN_EST_INT_MIN 7 //!< Minimum Link Layer connection interval.Default 80. (n * 1.25 mSec) +#define TGAP_CONN_EST_INT_MAX 8 //!< Maximum Link Layer connection interval.Default 80. (n * 1.25 mSec) +#define TGAP_CONN_EST_SCAN_INT 9 //!< Scan interval used during Link Layer Initiating state.Default 16. (n * 0.625 mSec) +#define TGAP_CONN_EST_SCAN_WIND 10 //!< Scan window used during Link Layer Initiating state.Default 16. (n * 0.625 mSec) +#define TGAP_CONN_EST_HIGH_SCAN_INT 11 //!< Scan interval used during Link Layer Initiating state, high duty scan cycle scan parameters (n * 0.625 mSec) +#define TGAP_CONN_EST_HIGH_SCAN_WIND 12 //!< Scan window used during Link Layer Initiating state, high duty scan cycle scan parameters (n * 0.625 mSec) +#define TGAP_CONN_EST_SUPERV_TIMEOUT 13 //!< Link Layer connection supervision timeout.Default 2000. (n * 10 mSec) +#define TGAP_CONN_EST_LATENCY 14 //!< Link Layer connection slave latency.Default 0. (in number of connection events) +#define TGAP_CONN_EST_MIN_CE_LEN 15 //!< Local informational parameter about minimum length of connection needed.Default 0. (n * 0.625 mSec) +#define TGAP_CONN_EST_MAX_CE_LEN 16 //!< Local informational parameter about maximum length of connection needed.Default 0. (n * 0.625 mSec) // Proprietary -#define TGAP_SM_TIMEOUT 18 //!< SM Message Timeout (milliseconds). Default 30 seconds. -#define TGAP_SM_MIN_KEY_LEN 19 //!< SM Minimum Key Length supported. Default 7. -#define TGAP_SM_MAX_KEY_LEN 20 //!< SM Maximum Key Length supported. Default 16. -#define TGAP_FILTER_ADV_REPORTS 21 //!< Filter duplicate advertising reports. Default TRUE. -#define TGAP_SCAN_RSP_RSSI_MIN 22 //!< Minimum RSSI required for scan responses to be reported to the app. Default -127. -#define TGAP_REJECT_CONN_PARAMS 23 //!< Whether or not to reject Connection Parameter Update Request received on Central device. Default FALSE. -#define TGAP_AUTH_TASK_ID 24 //!< Task ID override for Task Authentication control (for stack internal use only) +#define TGAP_PRIVATE_ADDR_INT 17 //!< Minimum Time Interval between private (resolvable) address changes.Default 15. (n * 1 minute) +#define TGAP_SM_TIMEOUT 18 //!< SM Message Timeout (milliseconds). Default 30 seconds. +#define TGAP_SM_MIN_KEY_LEN 19 //!< SM Minimum Key Length supported. Default 7. +#define TGAP_SM_MAX_KEY_LEN 20 //!< SM Maximum Key Length supported. Default 16. +#define TGAP_FILTER_ADV_REPORTS 21 //!< Filter duplicate advertising reports. Default TRUE. +#define TGAP_SCAN_RSP_RSSI_MIN 22 //!< Minimum RSSI required for scan responses to be reported to the app. Default -127. +#define TGAP_REJECT_CONN_PARAMS 23 //!< Whether or not to reject Connection Parameter Update Request received on Central device. Default FALSE. +#define TGAP_AUTH_TASK_ID 24 //!< Task ID override for Task Authentication control (for stack internal use only) #define TGAP_PARAMID_MAX 25 //!< ID MAX-valid Parameter ID // GAP_DEVDISC_MODE_DEFINES GAP Device Discovery Modes -#define DEVDISC_MODE_NONDISCOVERABLE 0x00 //!< No discoverable setting -#define DEVDISC_MODE_GENERAL 0x01 //!< General Discoverable devices -#define DEVDISC_MODE_LIMITED 0x02 //!< Limited Discoverable devices -#define DEVDISC_MODE_ALL 0x03 //!< Not filtered +#define DEVDISC_MODE_NONDISCOVERABLE 0x00 //!< No discoverable setting +#define DEVDISC_MODE_GENERAL 0x01 //!< General Discoverable devices +#define DEVDISC_MODE_LIMITED 0x02 //!< Limited Discoverable devices +#define DEVDISC_MODE_ALL 0x03 //!< Not filtered // GAP_ADDR_TYPE_DEFINES GAP Address Types #define ADDRTYPE_PUBLIC 0x00 //!< Use the BD_ADDR @@ -755,11 +757,11 @@ extern const u8 VER_LIB[]; // LIB version #define ADDRTYPE_PRIVATE_RESOLVE 0x03 //!< Generate Resolvable Private Address // GAP_ADVERTISEMENT_TYPE_DEFINES GAP Advertising Event Types -#define GAP_ADTYPE_ADV_IND 0x00 //!< Connectable undirected advertisement -#define GAP_ADTYPE_ADV_HDC_DIRECT_IND 0x01 //!< Connectable high duty cycle directed advertisement -#define GAP_ADTYPE_ADV_SCAN_IND 0x02 //!< Scannable undirected advertisement -#define GAP_ADTYPE_ADV_NONCONN_IND 0x03 //!< Non-Connectable undirected advertisement -#define GAP_ADTYPE_ADV_LDC_DIRECT_IND 0x04 //!< Connectable low duty cycle directed advertisement +#define GAP_ADTYPE_ADV_IND 0x00 //!< Connectable undirected event typet +#define GAP_ADTYPE_ADV_HDC_DIRECT_IND 0x01 //!< Connectable high duty cycle directed event type +#define GAP_ADTYPE_ADV_SCAN_IND 0x02 //!< Scannable undirected event type +#define GAP_ADTYPE_ADV_NONCONN_IND 0x03 //!< Non-Connectable undirected event type +#define GAP_ADTYPE_ADV_LDC_DIRECT_IND 0x04 //!< Connectable low duty cycle directed event type // GAP_ADVERTISEMENT_REPORT_TYPE_DEFINES GAP Advertising Report Event Types #define GAP_ADRPT_ADV_IND 0x00 //!< Connectable undirected advertisement @@ -798,7 +800,7 @@ extern const u8 VER_LIB[]; // LIB version #define GAP_ADTYPE_128BIT_COMPLETE 0x07 //!< Service: Complete list of 128-bit UUIDs #define GAP_ADTYPE_LOCAL_NAME_SHORT 0x08 //!< Shortened local name #define GAP_ADTYPE_LOCAL_NAME_COMPLETE 0x09 //!< Complete local name -#define GAP_ADTYPE_POWER_LEVEL 0x0A //!< TX Power Level: 0xXX: -127 to +127 dBm +#define GAP_ADTYPE_POWER_LEVEL 0x0A //!< TX Power Level: -127 to +127 dBm #define GAP_ADTYPE_OOB_CLASS_OF_DEVICE 0x0D //!< Simple Pairing OOB Tag: Class of device (3 octets) #define GAP_ADTYPE_OOB_SIMPLE_PAIRING_HASHC 0x0E //!< Simple Pairing OOB Tag: Simple Pairing Hash C (16 octets) #define GAP_ADTYPE_OOB_SIMPLE_PAIRING_RANDR 0x0F //!< Simple Pairing OOB Tag: Simple Pairing Randomizer R (16 octets) @@ -857,14 +859,16 @@ extern const u8 VER_LIB[]; // LIB version #define GAP_APPEARE_HID_DIGITAL_CARDREADER 0x03C6 //!< HID Card Reader #define GAP_APPEARE_HID_DIGITAL_PEN 0x03C7 //!< HID Digital Pen #define GAP_APPEARE_HID_BARCODE_SCANNER 0x03C8 //!< HID Barcode Scanner + /*********************************************gapRole*********************************************************/ +// GAPROLE_PROFILE_PARAMETERS GAP Role Manager 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_DATA 0x306 //!< 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_ADVERT_DATA 0x306 //!< Advertisement Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Defaults to all 0. #define GAPROLE_SCAN_RSP_DATA 0x307 //!< Scan Response Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Defaults to all 0. #define GAPROLE_ADV_EVENT_TYPE 0x308 //!< Advertisement Type. Read/Write. Size is uint8. Default is GAP_ADTYPE_ADV_IND. #define GAPROLE_ADV_DIRECT_TYPE 0x309 //!< Direct Advertisement Address Type. Read/Write. Size is uint8. Default is ADDRTYPE_PUBLIC. @@ -875,8 +879,8 @@ extern const u8 VER_LIB[]; // LIB version #define GAPROLE_MAX_SCAN_RES 0x30E //!< Maximum number of discover scan results to receive. Default is 0 = unlimited. #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). -/*****************************************************GAPBOND*****************************************************************/ +/*****************************************************GAPBOND*****************************************************************/ // GAPBOND_PROFILE_PARAMETERS GAP Bond Manager Parameters #define GAPBOND_PERI_PAIRING_MODE 0x400 //!< Pairing Mode: @ref GAPBOND_PAIRING_MODE_DEFINES. Read/Write. Size is uint8. Default is GAPBOND_PAIRING_MODE_WAIT_FOR_REQ. #define GAPBOND_PERI_MITM_PROTECTION 0x401 //!< Man-In-The-Middle (MITM) basically turns on Passkey protection in the pairing algorithm. Read/Write. Size is uint8. Default is 0(disabled). @@ -962,7 +966,6 @@ extern const u8 VER_LIB[]; // LIB version #define GAP_BOND_DEV_IRK_OFFSET 3 //!< NV ID for the bonding records' device IRK #define GAP_BOND_DEV_CSRK_OFFSET 4 //!< NV ID for the bonding records' device CSRK #define GAP_BOND_DEV_SIGN_COUNTER_OFFSET 5 //!< NV ID for the bonding records' device Sign Counter - #define GAP_BOND_REC_IDS 6 // Bonding NV Items - START 0x20 @@ -989,7 +992,7 @@ extern const u8 VER_LIB[]; // LIB version typedef struct { uint8 LTK[KEYLEN]; // Long Term Key (LTK) - uint16 div; //lint -e754 // LTK eDiv + uint16 div; // LTK eDiv uint8 rand[B_RANDOM_NUM_SIZE]; // LTK random number uint8 keySize; // LTK key size } gapBondLTK_t; @@ -1644,14 +1647,14 @@ typedef struct */ typedef struct { - tmos_event_hdr_t hdr; //!< GAP_MSG_EVENT and status - uint8 opcode; //!< GAP_DEVICE_INFO_EVENT - uint8 eventType; //!< Advertisement Type: @ref GAP_ADVERTISEMENT_REPORT_TYPE_DEFINES - uint8 addrType; //!< address type: @ref GAP_ADDR_TYPE_DEFINES - uint8 addr[B_ADDR_LEN]; //!< Address of the advertisement or SCAN_RSP - int8 rssi; //!< Advertisement or SCAN_RSP RSSI - uint8 dataLen; //!< Length (in bytes) of the data field (evtData) - uint8 *pEvtData; //!< Data field of advertisement or SCAN_RSP + tmos_event_hdr_t hdr; //!< GAP_MSG_EVENT and status + uint8 opcode; //!< GAP_DEVICE_INFO_EVENT + uint8 eventType; //!< Advertisement Type: @ref GAP_ADVERTISEMENT_REPORT_TYPE_DEFINES + uint8 addrType; //!< address type: @ref GAP_ADDR_TYPE_DEFINES + uint8 addr[B_ADDR_LEN]; //!< Address of the advertisement or SCAN_RSP + int8 rssi; //!< Advertisement or SCAN_RSP RSSI + uint8 dataLen; //!< Length (in bytes) of the data field (evtData) + uint8 *pEvtData; //!< Data field of advertisement or SCAN_RSP } gapDeviceInfoEvent_t; /** @@ -1905,7 +1908,7 @@ typedef struct { gapRolesStateNotify_t pfnStateChange; //!< Whenever the device changes state gapRolesRssiRead_t pfnRssiRead; //!< When a valid RSSI is read from controller - gapRolesParamUpdateCB_t pfnParamUpdate; + gapRolesParamUpdateCB_t pfnParamUpdate; //!< When the connection parameteres are updated } gapRolesCBs_t; /** @@ -1935,50 +1938,58 @@ typedef struct /* RF-PHY define */ /* - * pfnRFStatusCB_t state defined + * RF_ROLE_STATUS_TYPE pfnRFStatusCB_t state defined */ // TX_MODE call RF_Tx -#define TX_MODE_TX_FINISH 0x01 // basic or auto tx mode sends data successfully - // if it is in basic mode,it will enter idle state; - // if it is in auto mode,it will wait for receiving -#define TX_MODE_TX_FAIL 0x11 // basic or auto tx mode fail to send data and enter idle state -#define TX_MODE_TX_TIMEOUT TX_MODE_TX_FAIL // timeout = time of data transmission(1bit = 1us) -#define TX_MODE_RX_DATA 0x02 // auto tx mode receive data(ack) and enter idle state -#define TX_MODE_RX_TIMEOUT 0x12 // auto tx mode receive timeout(3ms) and enter idle state +#define TX_MODE_TX_FINISH 0x01 //!< basic or auto tx mode sends data successfully + //!< if it is in basic mode,it will enter idle state; + //!< if it is in auto mode,it will wait for receiving +#define TX_MODE_TX_FAIL 0x11 //!< basic or auto tx mode fail to send data and enter idle state +#define TX_MODE_TX_TIMEOUT TX_MODE_TX_FAIL //!< time of data transmission +#define TX_MODE_RX_DATA 0x02 //!< auto tx mode receive data(ack) and enter idle state +#define TX_MODE_RX_TIMEOUT 0x12 //!< auto tx mode receive timeout and enter idle state #define TX_MODE_HOP_SHUT 0x22 // RX_MODE call RF_Rx -#define RX_MODE_RX_DATA 0x03 // basic or auto rx mode receive data - // if it is in basic mode,it will enter idle state; - // if it is in auto mode,it will judge whether the type matches; - // if it matches,it will send data(ack),otherwise(rsr=2), it will restart receiving -#define RX_MODE_TX_FINISH 0x04 // auto rx mode sends data(ack) successfully and enters idle state -#define RX_MODE_TX_FAIL 0x14 // auto rx mode fail to send data and enter idle state -#define RX_MODE_TX_TIMEOUT RX_MODE_TX_FAIL // timeout = time of data transmission(1bit = 1us) +#define RX_MODE_RX_DATA 0x03 //!< basic or auto rx mode receive data + //!< if it is in basic mode,it will enter idle state; + //!< if it is in auto mode,it will judge whether the type matches; + //!< if it matches,it will send data(ack),otherwise(rsr=2), it will restart receiving +#define RX_MODE_TX_FINISH 0x04 //!< auto rx mode sends data(ack) successfully and enters idle state +#define RX_MODE_TX_FAIL 0x14 //!< auto rx mode fail to send data and enter idle state +#define RX_MODE_TX_TIMEOUT RX_MODE_TX_FAIL //!< time of data transmission #define RX_MODE_HOP_SHUT 0x24 +// LLE_MODE_TYPE +#define LLE_MODE_BASIC (0) //!< basic mode, enter idle state after sending or receive +#define LLE_MODE_AUTO (1) //!< auto mode, auto swtich to the receiving status after sending and the sending status after receiving +#define LLE_MODE_NON_RSSI (1<<7) -// LLE_MODE -#define LLE_MODE_BASIC (0) // basic mode, enter idle state after sending or receive -#define LLE_MODE_AUTO (1) // auto mode, auto swtich to the receiving status after sending and the sending status after receiving - -// status call back define +/** + * RFRole Event Callback Function + */ typedef void ( *pfnRFStatusCB_t)( u8 sta , u8 rsr, u8 *rxBuf ); -// sta - current status -// rsr - receive status reprots: bit0- crc check result,bit1- type matching result +// sta - current status@ref RF_ROLE_STATUS_TYPE +// rsr - receive status: bit0- crc check result,bit1- type matching result // rxBuf - receive data buffer typedef struct tag_rf_config { u8 LLEMode; // BIT0 0=LLE_MODE_BASIC, 1=LLE_MODE_AUTO - // BIT7 0=the first byte of the receive buffer is rssi - // 1=the first byte of the receive buffer is package type + // BIT7 0=the first byte of the receive buffer is rssi + // 1=the first byte of the receive buffer is package type u8 Channel; // rf channel(0-39) u32 TxAccessAddress; // tx access address,32bit phy tx address u32 RxAccessAddress; // rx access address,32bit phy matching address u32 TxCRCInit; // tx crc initial value u32 RxCRCInit; // rx crc initial value pfnRFStatusCB_t rfStatusCB; // status call back + u32 ChannelMap; // indicating Used and Unused data channels.Every channel is represented with a + // bit positioned as per the data channel index,The LSB represents data channel index 0 + u8 Resv; + u8 HeartPeriod; // The heart package interval shall be an integer multiple of 100ms + u8 HopPeriod; // hop period( T=32n*RTC clock ),default is 8 + u8 HopIndex; // indicate the hopIncrement used in the data channel selection algorithm,default is 17 }rfConfig_t; /* end define@RF-PHY */ @@ -3514,7 +3525,6 @@ extern bStatus_t GATTServApp_ProcessCCCWriteReq( uint16 connHandle, gattAttribut uint8 *pValue, uint16 len, uint16 offset, uint16 validCfg ); - /** * @brief Set a GAP GATT Server parameter. * @@ -3680,9 +3690,7 @@ extern bStatus_t GAP_UpdateAdvertisingData( u8 taskID,u8 adType,u8 dataLen,u8 *p * @brief Set a GAP Bond Manager 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". + * GAP Parameter. * * @param param - Profile parameter ID: @ref GAPBOND_PROFILE_PARAMETERS * @param len - length of data to write @@ -3699,8 +3707,7 @@ extern bStatus_t GAPBondMgr_SetParameter( uint16 param, uint8 len, void *pValue * @brief Get a GAP Bond Manager 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". + * GAP Parameter. * * @param param - Profile parameter ID: @ref GAPBOND_PROFILE_PARAMETERS * @param pValue - pointer to location to get the value. This is dependent on @@ -3728,14 +3735,28 @@ extern bStatus_t GAPBondMgr_PasscodeRsp( uint16 connectionHandle, uint8 status, /*------------------------------------------------------------------- * FUNCTIONS - GAPRole API */ +/** + * @brief Set a GAP Role parameter. + * + * NOTE: You can call this function with a GAP Parameter ID and it will set a + * GAP Parameter. + * + * @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) + */ extern bStatus_t GAPRole_SetParameter( uint16 param, uint8 len, void *pValue ); /** * @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". + * GAP Parameter. * * @param param - Profile parameter ID: @ref GAPROLE_PROFILE_PARAMETERS * @param pValue - pointer to location to get the value. This is dependent on @@ -3777,8 +3798,8 @@ extern bStatus_t GAPRole_ReadRssiCmd( uint16 connHandle ); * bleIncorrectMode: No connection to update.
*/ extern bStatus_t GAPRole_UpdateLink( uint16 connHandle, uint16 connIntervalMin, - uint16 connIntervalMax, uint16 connLatency, - uint16 connTimeout ); + uint16 connIntervalMax, uint16 connLatency, uint16 connTimeout ); + /*------------------------------------------------------------------- * FUNCTIONS - BROADCASTER_PROFILE_API Broadcaster Profile API @@ -3892,7 +3913,8 @@ extern bStatus_t GAPRole_PeripheralStartDevice( uint8 taskid, gapBondCBs_t *pCB, * @brief Update the parameters of an existing connection * * @param connHandle - the connection Handle - * @param connInterval - the new connection interval + * @param connIntervalMin - minimum connection interval in 1.25ms units + * @param connIntervalMax - maximum connection interval in 1.25ms units * @param latency - the new slave latency * @param connTimeout - the new timeout value * @param taskId - taskID will recv L2CAP_SIGNAL_EVENT message @@ -3900,7 +3922,7 @@ extern bStatus_t GAPRole_PeripheralStartDevice( uint8 taskid, gapBondCBs_t *pCB, * @return SUCCESS, bleNotConnected or bleInvalidRange */ extern bStatus_t GAPRole_PeripheralConnParamUpdateReq( uint16 connHandle, - uint16 minConnInterval, uint16 maxConnInterval, + uint16 connIntervalMin, uint16 connIntervalMax, uint16 latency, uint16 connTimeout,uint8 taskId); /*------------------------------------------------------------------- @@ -3954,7 +3976,7 @@ extern bStatus_t GAPRole_CentralCancelDiscovery( void ); * @brief Establish a link to a peer device. * * @param highDutyCycle - TRUE to high duty cycle scan, FALSE if not - * @param whiteList - determines use of the white list: @ref GAP_WHITELIST_DEFINES + * @param whiteList - determines use of the white list: TRUE-enable * @param addrTypePeer - address type of the peer device: @ref GAP_ADDR_TYPE_DEFINES * @param peerAddr - peer device address * @@ -4132,7 +4154,7 @@ extern u8 RF_FrequencyHoppingTx( u8 resendCount ); * * @param None. * - * @return 0 - success. + * @return 0 - success.1-fail.2-LLEMode error(shall AUTO) */ extern u8 RF_FrequencyHoppingRx( u32 timeoutMS ); diff --git a/src/EXAM/BLE/LIB/CH57xBLE_ROM.H b/src/EXAM/BLE/LIB/CH57xBLE_ROM.H index 394d7cc..9a7e4d0 100644 --- a/src/EXAM/BLE/LIB/CH57xBLE_ROM.H +++ b/src/EXAM/BLE/LIB/CH57xBLE_ROM.H @@ -1,18 +1,18 @@ /********************************** (C) COPYRIGHT ****************************** * File Name : CH57xBLE_ROM.H * Author : WCH -* Version : V1.30 -* Date : 2021/01/21 +* Version : V1.80 +* Date : 2021/06/29 * Description : head file * Address Space CH579 * CODE: 00025800H - 0003E7FFH 100K -* DATA: 20003800H - +* DATA: 20003800H - 200047FFH 4k * Address Space CH578 * CODE: 0000F000H - 00027FFFH 100K -* DATA: 20003800H - +* DATA: 20003800H - 200047FFH 4k * Address Space CH577 * CODE: 00007000H - 0001FFFFH 100K -* DATA: 20004000H - +* DATA: 20004000H - 20004FFFH 4k *******************************************************************************/ @@ -167,7 +167,7 @@ typedef struct /********************************************************************* * GLOBAL MACROS */ -#define VER_FILE "CH57x_BLE_LIB_V1.7" +#define VER_FILE "CH57x_BLE_LIB_V1.8" extern const u8 VER_LIB[]; // LIB version #define SYSTEM_TIME_MICROSEN 625 // unit of process event timer is 625us #define MS1_TO_SYSTEM_TIME(x) ((x)*1000/SYSTEM_TIME_MICROSEN) // transform unit in ms to unit in 625us ( attentional bias ) @@ -493,14 +493,14 @@ extern const u8 VER_LIB[]; // LIB version #define GATT_UNIT_TIME_MONTH_UUID 0x27B4 // /************************************************ Messages IDs *************************************************************/ -// GATT - Messages IDs (0xB0 - 0xBF) +// GATT - Messages IDs #define GATT_MSG_EVENT 0xB0 //!< Incoming GATT message -#define GATT_SERV_MSG_EVENT 0xB1 //!< Incoming GATT Serv App message -// GAP - Messages IDs (0xD0 - 0xDF) +#define GATT_SERV_MSG_EVENT 0xB1 //!< Incoming GATT ServApp message +// GAP - Messages IDs #define GAP_MSG_EVENT 0xD0 //!< Incoming GAP message /************************************************ ATT *************************************************************/ -#define ATT_MTU_SIZE L2CAP_MTU_SIZE //!< Minimum ATT MTU size -#define ATT_MAX_MTU_SIZE 517 //!< Maximum ATT MTU size +#define ATT_MTU_SIZE 23 //!< Minimum ATT MTU size +#define ATT_MAX_MTU_SIZE 247 //!< Maximum ATT MTU size // ATT Methods #define ATT_ERROR_RSP 0x01 //!< ATT Error Response #define ATT_EXCHANGE_MTU_REQ 0x02 //!< ATT Exchange MTU Request @@ -533,17 +533,17 @@ extern const u8 VER_LIB[]; // LIB version #define ATT_SIGNED_WRITE_CMD 0xD2 //!< ATT Signed Write Command // ATT Error Codes -#define ATT_ERR_INVALID_HANDLE 0x01 //!< Attribute handle value given was not valid on this attribute server -#define ATT_ERR_READ_NOT_PERMITTED 0x02 //!< Attribute cannot be read -#define ATT_ERR_WRITE_NOT_PERMITTED 0x03 //!< Attribute cannot be written +#define ATT_ERR_INVALID_HANDLE 0x01 //!< The attribute handle given was not valid on this server +#define ATT_ERR_READ_NOT_PERMITTED 0x02 //!< The attribute cannot be read +#define ATT_ERR_WRITE_NOT_PERMITTED 0x03 //!< The attribute cannot be written #define ATT_ERR_INVALID_PDU 0x04 //!< The attribute PDU was invalid #define ATT_ERR_INSUFFICIENT_AUTHEN 0x05 //!< The attribute requires authentication before it can be read or written -#define ATT_ERR_UNSUPPORTED_REQ 0x06 //!< Attribute server doesn't support the request received from the attribute client +#define ATT_ERR_UNSUPPORTED_REQ 0x06 //!< Attribute server does not support the request received from the client #define ATT_ERR_INVALID_OFFSET 0x07 //!< Offset specified was past the end of the attribute -#define ATT_ERR_INSUFFICIENT_AUTHOR 0x08 //!< The attribute requires an authorization before it can be read or written +#define ATT_ERR_INSUFFICIENT_AUTHOR 0x08 //!< The attribute requires authorization before it can be read or written #define ATT_ERR_PREPARE_QUEUE_FULL 0x09 //!< Too many prepare writes have been queued #define ATT_ERR_ATTR_NOT_FOUND 0x0a //!< No attribute found within the given attribute handle range -#define ATT_ERR_ATTR_NOT_LONG 0x0b //!< Attribute cannot be read or written using the Read Blob Request or Prepare Write Request +#define ATT_ERR_ATTR_NOT_LONG 0x0b //!< The attribute cannot be read using the Read Blob Request #define ATT_ERR_INSUFFICIENT_KEY_SIZE 0x0c //!< The Encryption Key Size used for encrypting this link is insufficient #define ATT_ERR_INVALID_VALUE_SIZE 0x0d //!< The attribute value length is invalid for the operation #define ATT_ERR_UNLIKELY 0x0e //!< The attribute request that was requested has encountered an error that was very unlikely, and therefore could not be completed as requested @@ -593,8 +593,8 @@ extern const u8 VER_LIB[]; // LIB version #define GATT_PROP_READ 0x02 //!< Permits reads of the Characteristic Value #define GATT_PROP_WRITE_NO_RSP 0x04 //!< Permits writes of the Characteristic Value without response #define GATT_PROP_WRITE 0x08 //!< Permits writes of the Characteristic Value with response -#define GATT_PROP_NOTIFY 0x10 //!< Permits notifications of a Characteristic Value without acknowledgement -#define GATT_PROP_INDICATE 0x20 //!< Permits indications of a Characteristic Value with acknowledgement +#define GATT_PROP_NOTIFY 0x10 //!< Permits notifications of a Characteristic Value without acknowledgment +#define GATT_PROP_INDICATE 0x20 //!< Permits indications of a Characteristic Value with acknowledgment #define GATT_PROP_AUTHEN 0x40 //!< Permits signed writes to the Characteristic Value #define GATT_PROP_EXTENDED 0x80 //!< Additional characteristic properties are defined in the Characteristic Extended Properties Descriptor @@ -720,42 +720,44 @@ extern const u8 VER_LIB[]; // LIB version // GAP_PARAMETER_ID_DEFINES GAP Parameter IDs // Timers -#define TGAP_GEN_DISC_ADV_MIN 0 //!< Minimum time to remain advertising, when in Discoverable mode (0.625 mSec). Setting this parameter to 0 turns off the timeout (default). -#define TGAP_LIM_ADV_TIMEOUT 1 //!< Maximum time to remain advertising, when in Limited Discoverable mode. In seconds (default 180 seconds) -#define TGAP_DISC_SCAN 2 //!< Minimum time to perform scanning, when performing General Discovery proc (0.625 mSec) - -// Constants -#define TGAP_DISC_ADV_INT_MIN 3 //!< Minimum advertising interval, when in General discoverable mode (n * 0.625 mSec) -#define TGAP_DISC_ADV_INT_MAX 4 //!< Maximum advertising interval, when in General discoverable mode (n * 0.625 mSec) -#define TGAP_DISC_SCAN_INT 5 //!< Scan interval used during Link Layer Scanning state, when in General Discovery proc (n * 0.625 mSec) -#define TGAP_DISC_SCAN_WIND 6 //!< Scan window used during Link Layer Scanning state, when in General Discovery proc (n * 0.625 mSec) -#define TGAP_CONN_EST_INT_MIN 7 //!< Minimum Link Layer connection interval, when using Connection Establishment proc (n * 1.25 mSec) -#define TGAP_CONN_EST_INT_MAX 8 //!< Maximum Link Layer connection interval, when using Connection Establishment proc (n * 1.25 mSec) -#define TGAP_CONN_EST_SCAN_INT 9 //!< Scan interval used during Link Layer Initiating state, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_CONN_EST_SCAN_WIND 10 //!< Scan window used during Link Layer Initiating state, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_CONN_EST_HIGH_SCAN_INT 11 //!< Scan interval used during Link Layer Initiating state, when in Connectable mode, high duty scan cycle scan parameters (n * 0.625 mSec) -#define TGAP_CONN_EST_HIGH_SCAN_WIND 12 //!< Scan window used during Link Layer Initiating state, when in Connectable mode, high duty scan cycle scan parameters (n * 0.625 mSec) -#define TGAP_CONN_EST_SUPERV_TIMEOUT 13 //!< Link Layer connection supervision timeout, when using Connection Establishment proc (n * 10 mSec) -#define TGAP_CONN_EST_LATENCY 14 //!< Link Layer connection slave latency, when using Connection Establishment proc (in number of connection events) -#define TGAP_CONN_EST_MIN_CE_LEN 15 //!< Local informational parameter about min len of connection needed, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_CONN_EST_MAX_CE_LEN 16 //!< Local informational parameter about max len of connection needed, when using Connection Establishment proc (n * 0.625 mSec) -#define TGAP_PRIVATE_ADDR_INT 17 //!< Minimum Time Interval between private (resolvable) address changes. In minutes (default 15 minutes) +#define TGAP_GEN_DISC_ADV_MIN 0 //!< Minimum time to remain advertising, when in Discoverable mode.Default 0-turns off the timeout. (n * 0.625 mSec). +#define TGAP_LIM_ADV_TIMEOUT 1 //!< Maximum time to remain advertising, when in Limited Discoverable mode.Default 180 seconds. (n * 1 seconds) +#define TGAP_DISC_SCAN 2 //!< Minimum time to perform scanning,Setting this parameter to 0 turns off the timeout.Default 10.24seconds. (n * 0.625 mSec) + +// when in General Discovery process +#define TGAP_DISC_ADV_INT_MIN 3 //!< Minimum advertising interval.Default 160. (n * 0.625 mSec) +#define TGAP_DISC_ADV_INT_MAX 4 //!< Maximum advertising interval.Default 160. (n * 0.625 mSec) +#define TGAP_DISC_SCAN_INT 5 //!< Scan interval used during Link Layer Scanning state.Default 16. (n * 0.625 mSec) +#define TGAP_DISC_SCAN_WIND 6 //!< Scan window used during Link Layer Scanning state.Default 16. (n * 0.625 mSec) + +// when in Connection Establishment process(1M PHY) +#define TGAP_CONN_EST_INT_MIN 7 //!< Minimum Link Layer connection interval.Default 80. (n * 1.25 mSec) +#define TGAP_CONN_EST_INT_MAX 8 //!< Maximum Link Layer connection interval.Default 80. (n * 1.25 mSec) +#define TGAP_CONN_EST_SCAN_INT 9 //!< Scan interval used during Link Layer Initiating state.Default 16. (n * 0.625 mSec) +#define TGAP_CONN_EST_SCAN_WIND 10 //!< Scan window used during Link Layer Initiating state.Default 16. (n * 0.625 mSec) +#define TGAP_CONN_EST_HIGH_SCAN_INT 11 //!< Scan interval used during Link Layer Initiating state, high duty scan cycle scan parameters (n * 0.625 mSec) +#define TGAP_CONN_EST_HIGH_SCAN_WIND 12 //!< Scan window used during Link Layer Initiating state, high duty scan cycle scan parameters (n * 0.625 mSec) +#define TGAP_CONN_EST_SUPERV_TIMEOUT 13 //!< Link Layer connection supervision timeout.Default 2000. (n * 10 mSec) +#define TGAP_CONN_EST_LATENCY 14 //!< Link Layer connection slave latency.Default 0. (in number of connection events) +#define TGAP_CONN_EST_MIN_CE_LEN 15 //!< Local informational parameter about minimum length of connection needed.Default 0. (n * 0.625 mSec) +#define TGAP_CONN_EST_MAX_CE_LEN 16 //!< Local informational parameter about maximum length of connection needed.Default 0. (n * 0.625 mSec) // Proprietary -#define TGAP_SM_TIMEOUT 18 //!< SM Message Timeout (milliseconds). Default 30 seconds. -#define TGAP_SM_MIN_KEY_LEN 19 //!< SM Minimum Key Length supported. Default 7. -#define TGAP_SM_MAX_KEY_LEN 20 //!< SM Maximum Key Length supported. Default 16. -#define TGAP_FILTER_ADV_REPORTS 21 //!< Filter duplicate advertising reports. Default TRUE. -#define TGAP_SCAN_RSP_RSSI_MIN 22 //!< Minimum RSSI required for scan responses to be reported to the app. Default -127. -#define TGAP_REJECT_CONN_PARAMS 23 //!< Whether or not to reject Connection Parameter Update Request received on Central device. Default FALSE. -#define TGAP_AUTH_TASK_ID 24 //!< Task ID override for Task Authentication control (for stack internal use only) +#define TGAP_PRIVATE_ADDR_INT 17 //!< Minimum Time Interval between private (resolvable) address changes.Default 15. (n * 1 minute) +#define TGAP_SM_TIMEOUT 18 //!< SM Message Timeout (milliseconds). Default 30 seconds. +#define TGAP_SM_MIN_KEY_LEN 19 //!< SM Minimum Key Length supported. Default 7. +#define TGAP_SM_MAX_KEY_LEN 20 //!< SM Maximum Key Length supported. Default 16. +#define TGAP_FILTER_ADV_REPORTS 21 //!< Filter duplicate advertising reports. Default TRUE. +#define TGAP_SCAN_RSP_RSSI_MIN 22 //!< Minimum RSSI required for scan responses to be reported to the app. Default -127. +#define TGAP_REJECT_CONN_PARAMS 23 //!< Whether or not to reject Connection Parameter Update Request received on Central device. Default FALSE. +#define TGAP_AUTH_TASK_ID 24 //!< Task ID override for Task Authentication control (for stack internal use only) #define TGAP_PARAMID_MAX 25 //!< ID MAX-valid Parameter ID // GAP_DEVDISC_MODE_DEFINES GAP Device Discovery Modes -#define DEVDISC_MODE_NONDISCOVERABLE 0x00 //!< No discoverable setting -#define DEVDISC_MODE_GENERAL 0x01 //!< General Discoverable devices -#define DEVDISC_MODE_LIMITED 0x02 //!< Limited Discoverable devices -#define DEVDISC_MODE_ALL 0x03 //!< Not filtered +#define DEVDISC_MODE_NONDISCOVERABLE 0x00 //!< No discoverable setting +#define DEVDISC_MODE_GENERAL 0x01 //!< General Discoverable devices +#define DEVDISC_MODE_LIMITED 0x02 //!< Limited Discoverable devices +#define DEVDISC_MODE_ALL 0x03 //!< Not filtered // GAP_ADDR_TYPE_DEFINES GAP Address Types #define ADDRTYPE_PUBLIC 0x00 //!< Use the BD_ADDR @@ -764,11 +766,11 @@ extern const u8 VER_LIB[]; // LIB version #define ADDRTYPE_PRIVATE_RESOLVE 0x03 //!< Generate Resolvable Private Address // GAP_ADVERTISEMENT_TYPE_DEFINES GAP Advertising Event Types -#define GAP_ADTYPE_ADV_IND 0x00 //!< Connectable undirected advertisement -#define GAP_ADTYPE_ADV_HDC_DIRECT_IND 0x01 //!< Connectable high duty cycle directed advertisement -#define GAP_ADTYPE_ADV_SCAN_IND 0x02 //!< Scannable undirected advertisement -#define GAP_ADTYPE_ADV_NONCONN_IND 0x03 //!< Non-Connectable undirected advertisement -#define GAP_ADTYPE_ADV_LDC_DIRECT_IND 0x04 //!< Connectable low duty cycle directed advertisement +#define GAP_ADTYPE_ADV_IND 0x00 //!< Connectable undirected event typet +#define GAP_ADTYPE_ADV_HDC_DIRECT_IND 0x01 //!< Connectable high duty cycle directed event type +#define GAP_ADTYPE_ADV_SCAN_IND 0x02 //!< Scannable undirected event type +#define GAP_ADTYPE_ADV_NONCONN_IND 0x03 //!< Non-Connectable undirected event type +#define GAP_ADTYPE_ADV_LDC_DIRECT_IND 0x04 //!< Connectable low duty cycle directed event type // GAP_ADVERTISEMENT_REPORT_TYPE_DEFINES GAP Advertising Report Event Types #define GAP_ADRPT_ADV_IND 0x00 //!< Connectable undirected advertisement @@ -807,7 +809,7 @@ extern const u8 VER_LIB[]; // LIB version #define GAP_ADTYPE_128BIT_COMPLETE 0x07 //!< Service: Complete list of 128-bit UUIDs #define GAP_ADTYPE_LOCAL_NAME_SHORT 0x08 //!< Shortened local name #define GAP_ADTYPE_LOCAL_NAME_COMPLETE 0x09 //!< Complete local name -#define GAP_ADTYPE_POWER_LEVEL 0x0A //!< TX Power Level: 0xXX: -127 to +127 dBm +#define GAP_ADTYPE_POWER_LEVEL 0x0A //!< TX Power Level: -127 to +127 dBm #define GAP_ADTYPE_OOB_CLASS_OF_DEVICE 0x0D //!< Simple Pairing OOB Tag: Class of device (3 octets) #define GAP_ADTYPE_OOB_SIMPLE_PAIRING_HASHC 0x0E //!< Simple Pairing OOB Tag: Simple Pairing Hash C (16 octets) #define GAP_ADTYPE_OOB_SIMPLE_PAIRING_RANDR 0x0F //!< Simple Pairing OOB Tag: Simple Pairing Randomizer R (16 octets) @@ -866,14 +868,16 @@ extern const u8 VER_LIB[]; // LIB version #define GAP_APPEARE_HID_DIGITAL_CARDREADER 0x03C6 //!< HID Card Reader #define GAP_APPEARE_HID_DIGITAL_PEN 0x03C7 //!< HID Digital Pen #define GAP_APPEARE_HID_BARCODE_SCANNER 0x03C8 //!< HID Barcode Scanner + /*********************************************gapRole*********************************************************/ +// GAPROLE_PROFILE_PARAMETERS GAP Role Manager 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_DATA 0x306 //!< 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_ADVERT_DATA 0x306 //!< Advertisement Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Defaults to all 0. #define GAPROLE_SCAN_RSP_DATA 0x307 //!< Scan Response Data. Read/Write. Max size is uint8[B_MAX_ADV_LEN]. Defaults to all 0. #define GAPROLE_ADV_EVENT_TYPE 0x308 //!< Advertisement Type. Read/Write. Size is uint8. Default is GAP_ADTYPE_ADV_IND. #define GAPROLE_ADV_DIRECT_TYPE 0x309 //!< Direct Advertisement Address Type. Read/Write. Size is uint8. Default is ADDRTYPE_PUBLIC. @@ -884,8 +888,8 @@ extern const u8 VER_LIB[]; // LIB version #define GAPROLE_MAX_SCAN_RES 0x30E //!< Maximum number of discover scan results to receive. Default is 0 = unlimited. #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). -/*****************************************************GAPBOND*****************************************************************/ +/*****************************************************GAPBOND*****************************************************************/ // GAPBOND_PROFILE_PARAMETERS GAP Bond Manager Parameters #define GAPBOND_PERI_PAIRING_MODE 0x400 //!< Pairing Mode: @ref GAPBOND_PAIRING_MODE_DEFINES. Read/Write. Size is uint8. Default is GAPBOND_PAIRING_MODE_WAIT_FOR_REQ. #define GAPBOND_PERI_MITM_PROTECTION 0x401 //!< Man-In-The-Middle (MITM) basically turns on Passkey protection in the pairing algorithm. Read/Write. Size is uint8. Default is 0(disabled). @@ -971,7 +975,6 @@ extern const u8 VER_LIB[]; // LIB version #define GAP_BOND_DEV_IRK_OFFSET 3 //!< NV ID for the bonding records' device IRK #define GAP_BOND_DEV_CSRK_OFFSET 4 //!< NV ID for the bonding records' device CSRK #define GAP_BOND_DEV_SIGN_COUNTER_OFFSET 5 //!< NV ID for the bonding records' device Sign Counter - #define GAP_BOND_REC_IDS 6 // Bonding NV Items - START 0x20 @@ -998,7 +1001,7 @@ extern const u8 VER_LIB[]; // LIB version typedef struct { uint8 LTK[KEYLEN]; // Long Term Key (LTK) - uint16 div; //lint -e754 // LTK eDiv + uint16 div; // LTK eDiv uint8 rand[B_RANDOM_NUM_SIZE]; // LTK random number uint8 keySize; // LTK key size } gapBondLTK_t; @@ -1653,14 +1656,14 @@ typedef struct */ typedef struct { - tmos_event_hdr_t hdr; //!< GAP_MSG_EVENT and status - uint8 opcode; //!< GAP_DEVICE_INFO_EVENT - uint8 eventType; //!< Advertisement Type: @ref GAP_ADVERTISEMENT_REPORT_TYPE_DEFINES - uint8 addrType; //!< address type: @ref GAP_ADDR_TYPE_DEFINES - uint8 addr[B_ADDR_LEN]; //!< Address of the advertisement or SCAN_RSP - int8 rssi; //!< Advertisement or SCAN_RSP RSSI - uint8 dataLen; //!< Length (in bytes) of the data field (evtData) - uint8 *pEvtData; //!< Data field of advertisement or SCAN_RSP + tmos_event_hdr_t hdr; //!< GAP_MSG_EVENT and status + uint8 opcode; //!< GAP_DEVICE_INFO_EVENT + uint8 eventType; //!< Advertisement Type: @ref GAP_ADVERTISEMENT_REPORT_TYPE_DEFINES + uint8 addrType; //!< address type: @ref GAP_ADDR_TYPE_DEFINES + uint8 addr[B_ADDR_LEN]; //!< Address of the advertisement or SCAN_RSP + int8 rssi; //!< Advertisement or SCAN_RSP RSSI + uint8 dataLen; //!< Length (in bytes) of the data field (evtData) + uint8 *pEvtData; //!< Data field of advertisement or SCAN_RSP } gapDeviceInfoEvent_t; /** @@ -1914,7 +1917,7 @@ typedef struct { gapRolesStateNotify_t pfnStateChange; //!< Whenever the device changes state gapRolesRssiRead_t pfnRssiRead; //!< When a valid RSSI is read from controller - gapRolesParamUpdateCB_t pfnParamUpdate; + gapRolesParamUpdateCB_t pfnParamUpdate; //!< When the connection parameteres are updated } gapRolesCBs_t; /** @@ -1944,49 +1947,58 @@ typedef struct /* RF-PHY define */ /* - * pfnRFStatusCB_t state defined + * RF_ROLE_STATUS_TYPE pfnRFStatusCB_t state defined */ // TX_MODE call RF_Tx -#define TX_MODE_TX_FINISH 0x01 // basic or auto tx mode sends data successfully - // if it is in basic mode,it will enter idle state; - // if it is in auto mode,it will wait for receiving -#define TX_MODE_TX_FAIL 0x11 // basic or auto tx mode fail to send data and enter idle state -#define TX_MODE_TX_TIMEOUT TX_MODE_TX_FAIL // timeout = time of data transmission(1bit = 1us) -#define TX_MODE_RX_DATA 0x02 // auto tx mode receive data(ack) and enter idle state -#define TX_MODE_RX_TIMEOUT 0x12 // auto tx mode receive timeout(3ms) and enter idle state +#define TX_MODE_TX_FINISH 0x01 //!< basic or auto tx mode sends data successfully + //!< if it is in basic mode,it will enter idle state; + //!< if it is in auto mode,it will wait for receiving +#define TX_MODE_TX_FAIL 0x11 //!< basic or auto tx mode fail to send data and enter idle state +#define TX_MODE_TX_TIMEOUT TX_MODE_TX_FAIL //!< time of data transmission +#define TX_MODE_RX_DATA 0x02 //!< auto tx mode receive data(ack) and enter idle state +#define TX_MODE_RX_TIMEOUT 0x12 //!< auto tx mode receive timeout and enter idle state #define TX_MODE_HOP_SHUT 0x22 // RX_MODE call RF_Rx -#define RX_MODE_RX_DATA 0x03 // basic or auto rx mode receive data - // if it is in basic mode,it will enter idle state; - // if it is in auto mode,it will judge whether the type matches; - // if it matches,it will send data(ack),otherwise(rsr=2), it will restart receiving -#define RX_MODE_TX_FINISH 0x04 // auto rx mode sends data(ack) successfully and enters idle state -#define RX_MODE_TX_FAIL 0x14 // auto rx mode fail to send data and enter idle state -#define RX_MODE_TX_TIMEOUT RX_MODE_TX_FAIL // timeout = time of data transmission(1bit = 1us) +#define RX_MODE_RX_DATA 0x03 //!< basic or auto rx mode receive data + //!< if it is in basic mode,it will enter idle state; + //!< if it is in auto mode,it will judge whether the type matches; + //!< if it matches,it will send data(ack),otherwise(rsr=2), it will restart receiving +#define RX_MODE_TX_FINISH 0x04 //!< auto rx mode sends data(ack) successfully and enters idle state +#define RX_MODE_TX_FAIL 0x14 //!< auto rx mode fail to send data and enter idle state +#define RX_MODE_TX_TIMEOUT RX_MODE_TX_FAIL //!< time of data transmission #define RX_MODE_HOP_SHUT 0x24 -// LLE_MODE -#define LLE_MODE_BASIC (0) // basic mode, enter idle state after sending or receive -#define LLE_MODE_AUTO (1) // auto mode, auto swtich to the receiving status after sending and the sending status after receiving +// LLE_MODE_TYPE +#define LLE_MODE_BASIC (0) //!< basic mode, enter idle state after sending or receive +#define LLE_MODE_AUTO (1) //!< auto mode, auto swtich to the receiving status after sending and the sending status after receiving +#define LLE_MODE_NON_RSSI (1<<7) -// status call back define +/** + * RFRole Event Callback Function + */ typedef void ( *pfnRFStatusCB_t)( u8 sta , u8 rsr, u8 *rxBuf ); -// sta - current status -// rsr - receive status reprots: bit0- crc check result,bit1- type matching result +// sta - current status@ref RF_ROLE_STATUS_TYPE +// rsr - receive status: bit0- crc check result,bit1- type matching result // rxBuf - receive data buffer typedef struct tag_rf_config { u8 LLEMode; // BIT0 0=LLE_MODE_BASIC, 1=LLE_MODE_AUTO - // BIT7 0=the first byte of the receive buffer is rssi - // 1=the first byte of the receive buffer is package type + // BIT7 0=the first byte of the receive buffer is rssi + // 1=the first byte of the receive buffer is package type u8 Channel; // rf channel(0-39) u32 TxAccessAddress; // tx access address,32bit phy tx address u32 RxAccessAddress; // rx access address,32bit phy matching address u32 TxCRCInit; // tx crc initial value u32 RxCRCInit; // rx crc initial value pfnRFStatusCB_t rfStatusCB; // status call back + u32 ChannelMap; // indicating Used and Unused data channels.Every channel is represented with a + // bit positioned as per the data channel index,The LSB represents data channel index 0 + u8 Resv; + u8 HeartPeriod; // The heart package interval shall be an integer multiple of 100ms + u8 HopPeriod; // hop period( T=32n*RTC clock ),default is 8 + u8 HopIndex; // indicate the hopIncrement used in the data channel selection algorithm,default is 17 }rfConfig_t; /* end define@RF-PHY */ @@ -2247,7 +2259,7 @@ typedef struct tag_rf_config * @return SUCCESS if successful, NV_OPER_FAILED if failed. */ #define tmos_snv_read (( bStatus_t (*) ( u8 id, u8 len, void *pBuf)) BLE_LIB_JT(107) ) - + /******************************************************************************* * @fn TMOS_TimerInit * @@ -2480,7 +2492,7 @@ typedef struct tag_rf_config * @return the value of rssi. */ #define BLE_ReadRssi (( s8 (*) ( void )) BLE_LIB_JT(108) ) - + /******************************************************************************* * @fn BLE_ReadCfo * @@ -2516,7 +2528,7 @@ typedef struct tag_rf_config * @return Command Status. */ #define BLE_PAControlInit (( void (*) ( blePaControlConfig_t *paControl )) BLE_LIB_JT(109) ) - + /******************************************************************************* * @fn BLE_RegInit * @@ -2533,7 +2545,7 @@ typedef struct tag_rf_config * @return None. */ #define BLE_RegInit (( void (*) ( void )) BLE_LIB_JT(110) ) - + /******************************************************************************* * @fn BLE_LibInit * @@ -3711,9 +3723,7 @@ typedef struct tag_rf_config * @brief Set a GAP Bond Manager 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". + * GAP Parameter. * * @param param - Profile parameter ID: @ref GAPBOND_PROFILE_PARAMETERS * @param len - length of data to write @@ -3730,8 +3740,7 @@ typedef struct tag_rf_config * @brief Get a GAP Bond Manager 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". + * GAP Parameter. * * @param param - Profile parameter ID: @ref GAPBOND_PROFILE_PARAMETERS * @param pValue - pointer to location to get the value. This is dependent on @@ -3759,14 +3768,28 @@ typedef struct tag_rf_config /*------------------------------------------------------------------- * FUNCTIONS - GAPRole API */ +/** + * @brief Set a GAP Role parameter. + * + * NOTE: You can call this function with a GAP Parameter ID and it will set a + * GAP Parameter. + * + * @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) + */ #define GAPRole_SetParameter (( bStatus_t (*) ( uint16 param, uint8 len, void *pValue )) BLE_LIB_JT(80) ) /** * @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". + * GAP Parameter. * * @param param - Profile parameter ID: @ref GAPROLE_PROFILE_PARAMETERS * @param pValue - pointer to location to get the value. This is dependent on @@ -3921,14 +3944,15 @@ typedef struct tag_rf_config * @brief Update the parameters of an existing connection * * @param connHandle - the connection Handle - * @param connInterval - the new connection interval + * @param connIntervalMin - minimum connection interval in 1.25ms units + * @param connIntervalMax - maximum connection interval in 1.25ms units * @param latency - the new slave latency * @param connTimeout - the new timeout value * @param taskId - taskID will recv L2CAP_SIGNAL_EVENT message * * @return SUCCESS, bleNotConnected or bleInvalidRange */ -#define GAPRole_PeripheralConnParamUpdateReq (( bStatus_t (*) ( uint16 connHandle, uint16 minConnInterval, uint16 maxConnInterval,uint16 latency, uint16 connTimeout,uint8 taskId )) BLE_LIB_JT(93) ) +#define GAPRole_PeripheralConnParamUpdateReq (( bStatus_t (*) ( uint16 connHandle, uint16 connIntervalMin, uint16 connIntervalMax,uint16 latency, uint16 connTimeout,uint8 taskId )) BLE_LIB_JT(93) ) /*------------------------------------------------------------------- * FUNCTIONS - CENTRAL_PROFILE_API Central Profile API @@ -3981,7 +4005,7 @@ typedef struct tag_rf_config * @brief Establish a link to a peer device. * * @param highDutyCycle - TRUE to high duty cycle scan, FALSE if not - * @param whiteList - determines use of the white list: @ref GAP_WHITELIST_DEFINES + * @param whiteList - determines use of the white list: TRUE-enable * @param addrTypePeer - address type of the peer device: @ref GAP_ADDR_TYPE_DEFINES * @param peerAddr - peer device address * @@ -4012,6 +4036,7 @@ typedef struct tag_rf_config * @return 0 - success. */ #define RF_RoleInit (( bStatus_t (*) ( void ) BLE_LIB_JT(99) ) + /******************************************************************************* * @fn RF_Config * @@ -4158,7 +4183,7 @@ typedef struct tag_rf_config * * @param None. * - * @return 0 - success. + * @return 0 - success.1-fail.2-LLEMode error(shall AUTO) */ #define RF_FrequencyHoppingRx (( bStatus_t (*) ( u32 timeoutMS )) BLE_LIB_JT(118) ) diff --git a/src/EXAM/BLE/MESH/MESH_LIB/MESH_LIB.h b/src/EXAM/BLE/MESH/MESH_LIB/MESH_LIB.h new file mode 100644 index 0000000..61b122d --- /dev/null +++ b/src/EXAM/BLE/MESH/MESH_LIB/MESH_LIB.h @@ -0,0 +1,2188 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : mesh_lib.h +* Author : WCH +* Version : V1.1 +* Date : 2021/06/04 +* Description : +*******************************************************************************/ + +#ifndef mesh_lib_H +#define mesh_lib_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#pragma anon_unions + +#include "stdint.h" +#include "stdio.h" +#include "stddef.h" +#include "string.h" +#include "app_mesh_config.h" + +/******************************************************************************/ + +#ifndef int8 +typedef signed char int8; +#endif +#ifndef int16 +typedef short int16; +#endif +#ifndef BOOL +typedef unsigned char BOOL; +#endif +#ifndef s8 +typedef signed char s8; +#endif +#ifndef s16 +typedef signed short s16; +#endif +#ifndef s32 +typedef signed long s32; +#endif +#ifndef u8 +typedef unsigned char u8; +#endif +#ifndef u16 +typedef unsigned short u16; +#endif +#ifndef u32 +typedef unsigned long u32; +#endif +#ifndef u64 +typedef unsigned long long u64; +#endif +#ifndef u8C +typedef const unsigned char u8C; +#endif +#ifndef u32V +typedef unsigned long volatile u32V; +#endif +#ifndef uint8 +typedef unsigned char uint8; +#endif +#ifndef uint16 +typedef unsigned short uint16; +#endif +#ifndef uint32 +typedef unsigned long uint32; +#endif +#ifndef s8_t +typedef signed char s8_t; +#endif +#ifndef s16_t +typedef signed short s16_t; +#endif +#ifndef s32_t +typedef int s32_t; +#endif +#ifndef s64_t +typedef signed long long s64_t; +#endif +#ifndef u8_t +typedef unsigned char u8_t; +#endif +#ifndef u16_t +typedef unsigned short u16_t; +#endif +#ifndef u32_t +typedef unsigned int u32_t; +#endif +#ifndef u64_t +typedef unsigned long long u64_t; +#endif +#ifndef bt_mesh_atomic_t +typedef unsigned int bt_mesh_atomic_t; +#endif +#ifndef ssize_t +typedef signed int ssize_t; +#endif + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif +#ifndef NULL +#define NULL 0 +#endif +#ifndef VOID +#define VOID (void) +#endif +#ifndef CONST +#define CONST const +#endif + +/******************************************************************************/ +#define VER_MESH_FILE "MESH_LIB_V1.1" +extern const uint8 VER_MESH_LIB[]; + +// Global_Error_Code +#define MESH_ERROR_BASE_NUM (0x0) ///< Global error base + +#define NOERR (MESH_ERROR_BASE_NUM + 0) +#define EINVAL (MESH_ERROR_BASE_NUM + 1) +#define EALREADY (MESH_ERROR_BASE_NUM + 2) +#define ESRCH (MESH_ERROR_BASE_NUM + 3) +#define EBUSY (MESH_ERROR_BASE_NUM + 4) +#define ENOTCONN (MESH_ERROR_BASE_NUM + 5) +#define EAGAIN (MESH_ERROR_BASE_NUM + 6) +#define ENOBUFS (MESH_ERROR_BASE_NUM + 7) +#define ENOENT (MESH_ERROR_BASE_NUM + 8) +#define ENOMEM (MESH_ERROR_BASE_NUM + 9) +#define EEXIST (MESH_ERROR_BASE_NUM + 10) +#define EIO (MESH_ERROR_BASE_NUM + 11) +#define EDEADLK (MESH_ERROR_BASE_NUM + 12) +#define ESPIPE (MESH_ERROR_BASE_NUM + 13) +#define EACCES (MESH_ERROR_BASE_NUM + 14) +#define ENXIO (MESH_ERROR_BASE_NUM + 15) +#define ENOSPC (MESH_ERROR_BASE_NUM + 16) +#define EBADMSG (MESH_ERROR_BASE_NUM + 17) +#define E2BIG (MESH_ERROR_BASE_NUM + 18) +#define ENOTSUP (MESH_ERROR_BASE_NUM + 19) +#define EADDRINUSE (MESH_ERROR_BASE_NUM + 20) +#define EMSGSIZE (MESH_ERROR_BASE_NUM + 21) +#define ECANCELED (MESH_ERROR_BASE_NUM + 22) +#define ETIMEDOUT (MESH_ERROR_BASE_NUM + 23) +#define EADDRNOTAVAIL (MESH_ERROR_BASE_NUM + 24) + + +/* Primary Network Key index */ +#define BLE_MESH_NET_PRIMARY 0x000 + +#define BLE_MESH_RELAY_DISABLED 0x00 +#define BLE_MESH_RELAY_ENABLED 0x01 +#define BLE_MESH_RELAY_NOT_SUPPORTED 0x02 + +#define BLE_MESH_BEACON_DISABLED 0x00 +#define BLE_MESH_BEACON_ENABLED 0x01 + +#define BLE_MESH_GATT_PROXY_DISABLED 0x00 +#define BLE_MESH_GATT_PROXY_ENABLED 0x01 +#define BLE_MESH_GATT_PROXY_NOT_SUPPORTED 0x02 + +#define BLE_MESH_FRIEND_DISABLED 0x00 +#define BLE_MESH_FRIEND_ENABLED 0x01 +#define BLE_MESH_FRIEND_NOT_SUPPORTED 0x02 + +#define BLE_MESH_NODE_IDENTITY_STOPPED 0x00 +#define BLE_MESH_NODE_IDENTITY_RUNNING 0x01 +#define BLE_MESH_NODE_IDENTITY_NOT_SUPPORTED 0x02 + +/* Features */ +#define BLE_MESH_FEAT_RELAY BIT(0) +#define BLE_MESH_FEAT_PROXY BIT(1) +#define BLE_MESH_FEAT_FRIEND BIT(2) +#define BLE_MESH_FEAT_LOW_POWER BIT(3) +#define BLE_MESH_FEAT_SUPPORTED (BLE_MESH_FEAT_RELAY | \ + BLE_MESH_FEAT_PROXY | \ + BLE_MESH_FEAT_FRIEND | \ + BLE_MESH_FEAT_LOW_POWER) + +#define BLE_MESH_SDU_UNSEG_MAX 11 // ְʱûĬϿͳΪֵ47ֽ +#define BLE_MESH_CTL_SEG_SDU_MAX 8 +#define BLE_MESH_APP_SEG_SDU_MAX 12 +#define BLE_MESH_TX_SDU_MAX (32 * BLE_MESH_APP_SEG_SDU_MAX) // ְʱûܳΪֵ8 +#define BLE_MESH_RX_SDU_MAX (32 * BLE_MESH_APP_SEG_SDU_MAX) +#define BLE_MESH_RX_CTL_MAX (32 * BLE_MESH_CTL_SEG_SDU_MAX) + +// ɴ洢ģԿ +#define CONFIG_BLE_MESH_MOD_KEY_COUNT 3 +// ɴ洢ģͶ +#define CONFIG_BLE_MESH_MOD_GROUP_COUNT 6 + +#define BLE_MESH_KEY_PRIMARY 0x0000 +#define BLE_MESH_KEY_ANY 0xffff + +#define BLE_MESH_ADDR_IS_UNICAST(addr) ((addr) && (addr) < 0x8000) +#define BLE_MESH_ADDR_IS_GROUP(addr) ((addr) >= 0xc000 && (addr) <= 0xff00) +#define BLE_MESH_ADDR_IS_VIRTUAL(addr) ((addr) >= 0x8000 && (addr) < 0xc000) +#define BLE_MESH_ADDR_IS_RFU(addr) ((addr) >= 0xff00 && (addr) <= 0xfffb) + +/**************************************ACCESS****************************************/ + +#define BLE_MESH_ADDR_UNASSIGNED 0x0000 +#define BLE_MESH_ADDR_ALL_NODES 0xffff +#define BLE_MESH_ADDR_PROXIES 0xfffc +#define BLE_MESH_ADDR_FRIENDS 0xfffd +#define BLE_MESH_ADDR_RELAYS 0xfffe + +#define BLE_MESH_KEY_UNUSED 0xffff +#define BLE_MESH_KEY_DEV 0xfffe +#define BLE_MESH_KEY_DEV_LOCAL BLE_MESH_KEY_DEV +#define BLE_MESH_KEY_DEV_REMOTE 0xfffd +#define BLE_MESH_KEY_DEV_ANY 0xfffc + +#define BLE_MESH_IS_DEV_KEY(key) (key == BLE_MESH_KEY_DEV_LOCAL || \ + key == BLE_MESH_KEY_DEV_REMOTE) + +/**************************************k_timer****************************************/ +#define MSEC_PER_SEC 1000U +#define K_NO_WAIT 0 +#define K_MSEC(ms) (ms) +#define K_SECONDS(s) K_MSEC((s) * MSEC_PER_SEC) +#define K_MINUTES(m) K_SECONDS((m) * 60) +#define K_HOURS(h) K_MINUTES((h) * 60) +#define K_FOREVER (-1) + + +/**************************************MODEL****************************************/ + +// BLE_MESH_MODEL_OP +#define OP_APP_KEY_ADD BLE_MESH_MODEL_OP_1(0x00) +#define OP_APP_KEY_UPDATE BLE_MESH_MODEL_OP_1(0x01) +#define OP_DEV_COMP_DATA_STATUS BLE_MESH_MODEL_OP_1(0x02) +#define OP_MOD_PUB_SET BLE_MESH_MODEL_OP_1(0x03) +#define OP_HEALTH_CURRENT_STATUS BLE_MESH_MODEL_OP_1(0x04) +#define OP_HEALTH_FAULT_STATUS BLE_MESH_MODEL_OP_1(0x05) +#define OP_HEARTBEAT_PUB_STATUS BLE_MESH_MODEL_OP_1(0x06) +#define OP_APP_KEY_DEL BLE_MESH_MODEL_OP_2(0x80, 0x00) +#define OP_APP_KEY_GET BLE_MESH_MODEL_OP_2(0x80, 0x01) +#define OP_APP_KEY_LIST BLE_MESH_MODEL_OP_2(0x80, 0x02) +#define OP_APP_KEY_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x03) +#define OP_ATTENTION_GET BLE_MESH_MODEL_OP_2(0x80, 0x04) +#define OP_ATTENTION_SET BLE_MESH_MODEL_OP_2(0x80, 0x05) +#define OP_ATTENTION_SET_UNREL BLE_MESH_MODEL_OP_2(0x80, 0x06) +#define OP_ATTENTION_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x07) +#define OP_DEV_COMP_DATA_GET BLE_MESH_MODEL_OP_2(0x80, 0x08) +#define OP_BEACON_GET BLE_MESH_MODEL_OP_2(0x80, 0x09) +#define OP_BEACON_SET BLE_MESH_MODEL_OP_2(0x80, 0x0a) +#define OP_BEACON_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x0b) +#define OP_DEFAULT_TTL_GET BLE_MESH_MODEL_OP_2(0x80, 0x0c) +#define OP_DEFAULT_TTL_SET BLE_MESH_MODEL_OP_2(0x80, 0x0d) +#define OP_DEFAULT_TTL_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x0e) +#define OP_FRIEND_GET BLE_MESH_MODEL_OP_2(0x80, 0x0f) +#define OP_FRIEND_SET BLE_MESH_MODEL_OP_2(0x80, 0x10) +#define OP_FRIEND_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x11) +#define OP_GATT_PROXY_GET BLE_MESH_MODEL_OP_2(0x80, 0x12) +#define OP_GATT_PROXY_SET BLE_MESH_MODEL_OP_2(0x80, 0x13) +#define OP_GATT_PROXY_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x14) +#define OP_KRP_GET BLE_MESH_MODEL_OP_2(0x80, 0x15) +#define OP_KRP_SET BLE_MESH_MODEL_OP_2(0x80, 0x16) +#define OP_KRP_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x17) +#define OP_MOD_PUB_GET BLE_MESH_MODEL_OP_2(0x80, 0x18) +#define OP_MOD_PUB_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x19) +#define OP_MOD_PUB_VA_SET BLE_MESH_MODEL_OP_2(0x80, 0x1a) +#define OP_MOD_SUB_ADD BLE_MESH_MODEL_OP_2(0x80, 0x1b) +#define OP_MOD_SUB_DEL BLE_MESH_MODEL_OP_2(0x80, 0x1c) +#define OP_MOD_SUB_DEL_ALL BLE_MESH_MODEL_OP_2(0x80, 0x1d) +#define OP_MOD_SUB_OVERWRITE BLE_MESH_MODEL_OP_2(0x80, 0x1e) +#define OP_MOD_SUB_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x1f) +#define OP_MOD_SUB_VA_ADD BLE_MESH_MODEL_OP_2(0x80, 0x20) +#define OP_MOD_SUB_VA_DEL BLE_MESH_MODEL_OP_2(0x80, 0x21) +#define OP_MOD_SUB_VA_OVERWRITE BLE_MESH_MODEL_OP_2(0x80, 0x22) +#define OP_NET_TRANSMIT_GET BLE_MESH_MODEL_OP_2(0x80, 0x23) +#define OP_NET_TRANSMIT_SET BLE_MESH_MODEL_OP_2(0x80, 0x24) +#define OP_NET_TRANSMIT_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x25) +#define OP_RELAY_GET BLE_MESH_MODEL_OP_2(0x80, 0x26) +#define OP_RELAY_SET BLE_MESH_MODEL_OP_2(0x80, 0x27) +#define OP_RELAY_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x28) +#define OP_MOD_SUB_GET BLE_MESH_MODEL_OP_2(0x80, 0x29) +#define OP_MOD_SUB_LIST BLE_MESH_MODEL_OP_2(0x80, 0x2a) +#define OP_MOD_SUB_GET_VND BLE_MESH_MODEL_OP_2(0x80, 0x2b) +#define OP_MOD_SUB_LIST_VND BLE_MESH_MODEL_OP_2(0x80, 0x2c) +#define OP_LPN_TIMEOUT_GET BLE_MESH_MODEL_OP_2(0x80, 0x2d) +#define OP_LPN_TIMEOUT_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x2e) +#define OP_HEALTH_FAULT_CLEAR BLE_MESH_MODEL_OP_2(0x80, 0x2f) +#define OP_HEALTH_FAULT_CLEAR_UNREL BLE_MESH_MODEL_OP_2(0x80, 0x30) +#define OP_HEALTH_FAULT_GET BLE_MESH_MODEL_OP_2(0x80, 0x31) +#define OP_HEALTH_FAULT_TEST BLE_MESH_MODEL_OP_2(0x80, 0x32) +#define OP_HEALTH_FAULT_TEST_UNREL BLE_MESH_MODEL_OP_2(0x80, 0x33) +#define OP_HEALTH_PERIOD_GET BLE_MESH_MODEL_OP_2(0x80, 0x34) +#define OP_HEALTH_PERIOD_SET BLE_MESH_MODEL_OP_2(0x80, 0x35) +#define OP_HEALTH_PERIOD_SET_UNREL BLE_MESH_MODEL_OP_2(0x80, 0x36) +#define OP_HEALTH_PERIOD_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x37) +#define OP_HEARTBEAT_PUB_GET BLE_MESH_MODEL_OP_2(0x80, 0x38) +#define OP_HEARTBEAT_PUB_SET BLE_MESH_MODEL_OP_2(0x80, 0x39) +#define OP_HEARTBEAT_SUB_GET BLE_MESH_MODEL_OP_2(0x80, 0x3a) +#define OP_HEARTBEAT_SUB_SET BLE_MESH_MODEL_OP_2(0x80, 0x3b) +#define OP_HEARTBEAT_SUB_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x3c) +#define OP_MOD_APP_BIND BLE_MESH_MODEL_OP_2(0x80, 0x3d) +#define OP_MOD_APP_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x3e) +#define OP_MOD_APP_UNBIND BLE_MESH_MODEL_OP_2(0x80, 0x3f) +#define OP_NET_KEY_ADD BLE_MESH_MODEL_OP_2(0x80, 0x40) +#define OP_NET_KEY_DEL BLE_MESH_MODEL_OP_2(0x80, 0x41) +#define OP_NET_KEY_GET BLE_MESH_MODEL_OP_2(0x80, 0x42) +#define OP_NET_KEY_LIST BLE_MESH_MODEL_OP_2(0x80, 0x43) +#define OP_NET_KEY_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x44) +#define OP_NET_KEY_UPDATE BLE_MESH_MODEL_OP_2(0x80, 0x45) +#define OP_NODE_IDENTITY_GET BLE_MESH_MODEL_OP_2(0x80, 0x46) +#define OP_NODE_IDENTITY_SET BLE_MESH_MODEL_OP_2(0x80, 0x47) +#define OP_NODE_IDENTITY_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x48) +#define OP_NODE_RESET BLE_MESH_MODEL_OP_2(0x80, 0x49) +#define OP_NODE_RESET_STATUS BLE_MESH_MODEL_OP_2(0x80, 0x4a) +#define OP_SIG_MOD_APP_GET BLE_MESH_MODEL_OP_2(0x80, 0x4b) +#define OP_SIG_MOD_APP_LIST BLE_MESH_MODEL_OP_2(0x80, 0x4c) +#define OP_VND_MOD_APP_GET BLE_MESH_MODEL_OP_2(0x80, 0x4d) +#define OP_VND_MOD_APP_LIST BLE_MESH_MODEL_OP_2(0x80, 0x4e) + +/* Generic OnOff Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_ONOFF_GET BLE_MESH_MODEL_OP_2(0x82, 0x01) +#define BLE_MESH_MODEL_OP_GEN_ONOFF_SET BLE_MESH_MODEL_OP_2(0x82, 0x02) +#define BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x03) +#define BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x04) + +/* Generic Level Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_LEVEL_GET BLE_MESH_MODEL_OP_2(0x82, 0x05) +#define BLE_MESH_MODEL_OP_GEN_LEVEL_SET BLE_MESH_MODEL_OP_2(0x82, 0x06) +#define BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x07) +#define BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x08) +#define BLE_MESH_MODEL_OP_GEN_DELTA_SET BLE_MESH_MODEL_OP_2(0x82, 0x09) +#define BLE_MESH_MODEL_OP_GEN_DELTA_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x0A) +#define BLE_MESH_MODEL_OP_GEN_MOVE_SET BLE_MESH_MODEL_OP_2(0x82, 0x0B) +#define BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x0C) + +/* Generic Default Transition Time Message Opcode*/ +#define BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_GET BLE_MESH_MODEL_OP_2(0x82, 0x0D) +#define BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET BLE_MESH_MODEL_OP_2(0x82, 0x0E) +#define BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x0F) +#define BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x10) + +/* Generic Power OnOff Message Opcode*/ +#define BLE_MESH_MODEL_OP_GEN_ONPOWERUP_GET BLE_MESH_MODEL_OP_2(0x82, 0x11) +#define BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x12) + +/* Generic Power OnOff Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET BLE_MESH_MODEL_OP_2(0x82, 0x13) +#define BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x14) + +/* Generic Power Level Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_GET BLE_MESH_MODEL_OP_2(0x82, 0x15) +#define BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET BLE_MESH_MODEL_OP_2(0x82, 0x16) +#define BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x17) +#define BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x18) +#define BLE_MESH_MODEL_OP_GEN_POWER_LAST_GET BLE_MESH_MODEL_OP_2(0x82, 0x19) +#define BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x1A) +#define BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_GET BLE_MESH_MODEL_OP_2(0x82, 0x1B) +#define BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x1C) +#define BLE_MESH_MODEL_OP_GEN_POWER_RANGE_GET BLE_MESH_MODEL_OP_2(0x82, 0x1D) +#define BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x1E) + +/* Generic Power Level Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET BLE_MESH_MODEL_OP_2(0x82, 0x1F) +#define BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x20) +#define BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET BLE_MESH_MODEL_OP_2(0x82, 0x21) +#define BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x22) + +/* Generic Battery Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_BATTERY_GET BLE_MESH_MODEL_OP_2(0x82, 0x23) +#define BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x24) + +/* Generic Location Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_GET BLE_MESH_MODEL_OP_2(0x82, 0x25) +#define BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS BLE_MESH_MODEL_OP_1(0x40) +#define BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_GET BLE_MESH_MODEL_OP_2(0x82, 0x26) +#define BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x27) + +/* Generic Location Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET BLE_MESH_MODEL_OP_1(0x41) +#define BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK BLE_MESH_MODEL_OP_1(0x42) +#define BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET BLE_MESH_MODEL_OP_2(0x82, 0x28) +#define BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x29) + +/* Generic Manufacturer Property Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_MANU_PROPERTIES_GET BLE_MESH_MODEL_OP_2(0x82, 0x2A) +#define BLE_MESH_MODEL_OP_GEN_MANU_PROPERTIES_STATUS BLE_MESH_MODEL_OP_1(0x43) +#define BLE_MESH_MODEL_OP_GEN_MANU_PROPERTY_GET BLE_MESH_MODEL_OP_2(0x82, 0x2B) +#define BLE_MESH_MODEL_OP_GEN_MANU_PROPERTY_SET BLE_MESH_MODEL_OP_1(0x44) +#define BLE_MESH_MODEL_OP_GEN_MANU_PROPERTY_SET_UNACK BLE_MESH_MODEL_OP_1(0x45) +#define BLE_MESH_MODEL_OP_GEN_MANU_PROPERTY_STATUS BLE_MESH_MODEL_OP_1(0x46) + +/* Generic Admin Property Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_GET BLE_MESH_MODEL_OP_2(0x82, 0x2C) +#define BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS BLE_MESH_MODEL_OP_1(0x47) +#define BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET BLE_MESH_MODEL_OP_2(0x82, 0x2D) +#define BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET BLE_MESH_MODEL_OP_1(0x48) +#define BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK BLE_MESH_MODEL_OP_1(0x49) +#define BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS BLE_MESH_MODEL_OP_1(0x4A) + +/* Generic User Property Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_GET BLE_MESH_MODEL_OP_2(0x82, 0x2E) +#define BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS BLE_MESH_MODEL_OP_1(0x4B) +#define BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET BLE_MESH_MODEL_OP_2(0x82, 0x2F) +#define BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET BLE_MESH_MODEL_OP_1(0x4C) +#define BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK BLE_MESH_MODEL_OP_1(0x4D) +#define BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS BLE_MESH_MODEL_OP_1(0x4E) + +/* Generic Client Property Message Opcode */ +#define BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET BLE_MESH_MODEL_OP_1(0x4F) +#define BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS BLE_MESH_MODEL_OP_1(0x50) + +/* Sensor Message Opcode */ +#define BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET BLE_MESH_MODEL_OP_2(0x82, 0x30) +#define BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS BLE_MESH_MODEL_OP_1(0x51) +#define BLE_MESH_MODEL_OP_SENSOR_GET BLE_MESH_MODEL_OP_2(0x82, 0x31) +#define BLE_MESH_MODEL_OP_SENSOR_STATUS BLE_MESH_MODEL_OP_1(0x52) +#define BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET BLE_MESH_MODEL_OP_2(0x82, 0x32) +#define BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS BLE_MESH_MODEL_OP_1(0x53) +#define BLE_MESH_MODEL_OP_SENSOR_SERIES_GET BLE_MESH_MODEL_OP_2(0x82, 0x33) +#define BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS BLE_MESH_MODEL_OP_1(0x54) + +/* Sensor Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET BLE_MESH_MODEL_OP_2(0x82, 0x34) +#define BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET BLE_MESH_MODEL_OP_1(0x55) +#define BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK BLE_MESH_MODEL_OP_1(0x56) +#define BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS BLE_MESH_MODEL_OP_1(0x57) +#define BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET BLE_MESH_MODEL_OP_2(0x82, 0x35) +#define BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS BLE_MESH_MODEL_OP_1(0x58) +#define BLE_MESH_MODEL_OP_SENSOR_SETTING_GET BLE_MESH_MODEL_OP_2(0x82, 0x36) +#define BLE_MESH_MODEL_OP_SENSOR_SETTING_SET BLE_MESH_MODEL_OP_1(0x59) +#define BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK BLE_MESH_MODEL_OP_1(0x5A) +#define BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS BLE_MESH_MODEL_OP_1(0x5B) + +/* Time Message Opcode */ +#define BLE_MESH_MODEL_OP_TIME_GET BLE_MESH_MODEL_OP_2(0x82, 0x37) +#define BLE_MESH_MODEL_OP_TIME_SET BLE_MESH_MODEL_OP_1(0x5C) +#define BLE_MESH_MODEL_OP_TIME_STATUS BLE_MESH_MODEL_OP_1(0x5D) +#define BLE_MESH_MODEL_OP_TIME_ROLE_GET BLE_MESH_MODEL_OP_2(0x82, 0x38) +#define BLE_MESH_MODEL_OP_TIME_ROLE_SET BLE_MESH_MODEL_OP_2(0x82, 0x39) +#define BLE_MESH_MODEL_OP_TIME_ROLE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x3A) +#define BLE_MESH_MODEL_OP_TIME_ZONE_GET BLE_MESH_MODEL_OP_2(0x82, 0x3B) +#define BLE_MESH_MODEL_OP_TIME_ZONE_SET BLE_MESH_MODEL_OP_2(0x82, 0x3C) +#define BLE_MESH_MODEL_OP_TIME_ZONE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x3D) +#define BLE_MESH_MODEL_OP_TAI_UTC_DELTA_GET BLE_MESH_MODEL_OP_2(0x82, 0x3E) +#define BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET BLE_MESH_MODEL_OP_2(0x82, 0x3F) +#define BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x40) + +/* Scene Message Opcode */ +#define BLE_MESH_MODEL_OP_SCENE_GET BLE_MESH_MODEL_OP_2(0x82, 0x41) +#define BLE_MESH_MODEL_OP_SCENE_RECALL BLE_MESH_MODEL_OP_2(0x82, 0x42) +#define BLE_MESH_MODEL_OP_SCENE_RECALL_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x43) +#define BLE_MESH_MODEL_OP_SCENE_STATUS BLE_MESH_MODEL_OP_1(0x5E) +#define BLE_MESH_MODEL_OP_SCENE_REGISTER_GET BLE_MESH_MODEL_OP_2(0x82, 0x44) +#define BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x45) + +/* Scene Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_SCENE_STORE BLE_MESH_MODEL_OP_2(0x82, 0x46) +#define BLE_MESH_MODEL_OP_SCENE_STORE_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x47) +#define BLE_MESH_MODEL_OP_SCENE_DELETE BLE_MESH_MODEL_OP_2(0x82, 0x9E) +#define BLE_MESH_MODEL_OP_SCENE_DELETE_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x9F) + +/* Scheduler Message Opcode */ +#define BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET BLE_MESH_MODEL_OP_2(0x82, 0x48) +#define BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS BLE_MESH_MODEL_OP_1(0x5F) +#define BLE_MESH_MODEL_OP_SCHEDULER_GET BLE_MESH_MODEL_OP_2(0x82, 0x49) +#define BLE_MESH_MODEL_OP_SCHEDULER_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x4A) + +/* Scheduler Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET BLE_MESH_MODEL_OP_1(0x60) +#define BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK BLE_MESH_MODEL_OP_1(0x61) + +/* Light Lightness Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET BLE_MESH_MODEL_OP_2(0x82, 0x4B) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET BLE_MESH_MODEL_OP_2(0x82, 0x4C) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x4D) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x4E) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_GET BLE_MESH_MODEL_OP_2(0x82, 0x4F) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET BLE_MESH_MODEL_OP_2(0x82, 0x50) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x51) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x52) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_GET BLE_MESH_MODEL_OP_2(0x82, 0x53) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x54) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_GET BLE_MESH_MODEL_OP_2(0x82, 0x55) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x56) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_GET BLE_MESH_MODEL_OP_2(0x82, 0x57) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x58) + +/* Light Lightness Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET BLE_MESH_MODEL_OP_2(0x82, 0x59) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x5A) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET BLE_MESH_MODEL_OP_2(0x82, 0x5B) +#define BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x5C) + +/* Light CTL Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_CTL_GET BLE_MESH_MODEL_OP_2(0x82, 0x5D) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_SET BLE_MESH_MODEL_OP_2(0x82, 0x5E) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x5F) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x60) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_GET BLE_MESH_MODEL_OP_2(0x82, 0x61) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_GET BLE_MESH_MODEL_OP_2(0x82, 0x62) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x63) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET BLE_MESH_MODEL_OP_2(0x82, 0x64) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x65) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x66) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_GET BLE_MESH_MODEL_OP_2(0x82, 0x67) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x68) + +/* Light CTL Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET BLE_MESH_MODEL_OP_2(0x82, 0x69) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x6A) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET BLE_MESH_MODEL_OP_2(0x82, 0x6B) +#define BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x6C) + +/* Light HSL Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_HSL_GET BLE_MESH_MODEL_OP_2(0x82, 0x6D) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_GET BLE_MESH_MODEL_OP_2(0x82, 0x6E) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET BLE_MESH_MODEL_OP_2(0x82, 0x6F) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x70) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x71) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_GET BLE_MESH_MODEL_OP_2(0x82, 0x72) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET BLE_MESH_MODEL_OP_2(0x82, 0x73) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x74) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x75) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_SET BLE_MESH_MODEL_OP_2(0x82, 0x76) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x77) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x78) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_GET BLE_MESH_MODEL_OP_2(0x82, 0x79) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x7A) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_GET BLE_MESH_MODEL_OP_2(0x82, 0x7B) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x7C) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_GET BLE_MESH_MODEL_OP_2(0x82, 0x7D) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x7E) + +/* Light HSL Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET BLE_MESH_MODEL_OP_2(0x82, 0x7F) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x80) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET BLE_MESH_MODEL_OP_2(0x82, 0x81) +#define BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x82) /* Model spec is wrong */ + +/* Light xyL Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_XYL_GET BLE_MESH_MODEL_OP_2(0x82, 0x83) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_SET BLE_MESH_MODEL_OP_2(0x82, 0x84) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x85) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x86) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_GET BLE_MESH_MODEL_OP_2(0x82, 0x87) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x88) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_GET BLE_MESH_MODEL_OP_2(0x82, 0x89) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x8A) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_GET BLE_MESH_MODEL_OP_2(0x82, 0x8B) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x8C) + +/* Light xyL Setup Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET BLE_MESH_MODEL_OP_2(0x82, 0x8D) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x8E) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET BLE_MESH_MODEL_OP_2(0x82, 0x8F) +#define BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x90) + +/* Light Control Message Opcode */ +#define BLE_MESH_MODEL_OP_LIGHT_LC_MODE_GET BLE_MESH_MODEL_OP_2(0x82, 0x91) +#define BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET BLE_MESH_MODEL_OP_2(0x82, 0x92) +#define BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x93) +#define BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x94) +#define BLE_MESH_MODEL_OP_LIGHT_LC_OM_GET BLE_MESH_MODEL_OP_2(0x82, 0x95) +#define BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET BLE_MESH_MODEL_OP_2(0x82, 0x96) +#define BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x97) +#define BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x98) +#define BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_GET BLE_MESH_MODEL_OP_2(0x82, 0x99) +#define BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET BLE_MESH_MODEL_OP_2(0x82, 0x9A) +#define BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK BLE_MESH_MODEL_OP_2(0x82, 0x9B) +#define BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS BLE_MESH_MODEL_OP_2(0x82, 0x9C) +#define BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET BLE_MESH_MODEL_OP_2(0x82, 0x9D) +#define BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET BLE_MESH_MODEL_OP_1(0x62) +#define BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK BLE_MESH_MODEL_OP_1(0x63) +#define BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS BLE_MESH_MODEL_OP_1(0x64) + + +#define STATUS_SUCCESS 0x00 +#define STATUS_INVALID_ADDRESS 0x01 +#define STATUS_INVALID_MODEL 0x02 +#define STATUS_INVALID_APPKEY 0x03 +#define STATUS_INVALID_NETKEY 0x04 +#define STATUS_INSUFF_RESOURCES 0x05 +#define STATUS_IDX_ALREADY_STORED 0x06 +#define STATUS_NVAL_PUB_PARAM 0x07 +#define STATUS_NOT_SUB_MOD 0x08 +#define STATUS_STORAGE_FAIL 0x09 +#define STATUS_FEAT_NOT_SUPP 0x0a +#define STATUS_CANNOT_UPDATE 0x0b +#define STATUS_CANNOT_REMOVE 0x0c +#define STATUS_CANNOT_BIND 0x0d +#define STATUS_TEMP_STATE_CHG_FAIL 0x0e +#define STATUS_CANNOT_SET 0x0f +#define STATUS_UNSPECIFIED 0x10 +#define STATUS_INVALID_BINDING 0x11 + +/* Foundation Models */ +#define BLE_MESH_MODEL_ID_CFG_SRV 0x0000 +#define BLE_MESH_MODEL_ID_CFG_CLI 0x0001 +#define BLE_MESH_MODEL_ID_HEALTH_SRV 0x0002 +#define BLE_MESH_MODEL_ID_HEALTH_CLI 0x0003 + +/* Models from the Mesh Model Specification */ +#define BLE_MESH_MODEL_ID_GEN_ONOFF_SRV 0x1000 +#define BLE_MESH_MODEL_ID_GEN_ONOFF_CLI 0x1001 +#define BLE_MESH_MODEL_ID_GEN_LEVEL_SRV 0x1002 +#define BLE_MESH_MODEL_ID_GEN_LEVEL_CLI 0x1003 +#define BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV 0x1004 +#define BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI 0x1005 +#define BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV 0x1006 +#define BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV 0x1007 +#define BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_CLI 0x1008 +#define BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SRV 0x1009 +#define BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SETUP_SRV 0x100a +#define BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_CLI 0x100b +#define BLE_MESH_MODEL_ID_GEN_BATTERY_SRV 0x100c +#define BLE_MESH_MODEL_ID_GEN_BATTERY_CLI 0x100d +#define BLE_MESH_MODEL_ID_GEN_LOCATION_SRV 0x100e +#define BLE_MESH_MODEL_ID_GEN_LOCATION_SETUPSRV 0x100f +#define BLE_MESH_MODEL_ID_GEN_LOCATION_CLI 0x1010 +#define BLE_MESH_MODEL_ID_GEN_ADMIN_PROP_SRV 0x1011 +#define BLE_MESH_MODEL_ID_GEN_MANUFACTURER_PROP_SRV 0x1012 +#define BLE_MESH_MODEL_ID_GEN_USER_PROP_SRV 0x1013 +#define BLE_MESH_MODEL_ID_GEN_CLIENT_PROP_SRV 0x1014 +#define BLE_MESH_MODEL_ID_GEN_PROP_CLI 0x1015 +#define BLE_MESH_MODEL_ID_SENSOR_SRV 0x1100 +#define BLE_MESH_MODEL_ID_SENSOR_SETUP_SRV 0x1101 +#define BLE_MESH_MODEL_ID_SENSOR_CLI 0x1102 +#define BLE_MESH_MODEL_ID_TIME_SRV 0x1200 +#define BLE_MESH_MODEL_ID_TIME_SETUP_SRV 0x1201 +#define BLE_MESH_MODEL_ID_TIME_CLI 0x1202 +#define BLE_MESH_MODEL_ID_SCENE_SRV 0x1203 +#define BLE_MESH_MODEL_ID_SCENE_SETUP_SRV 0x1204 +#define BLE_MESH_MODEL_ID_SCENE_CLI 0x1205 +#define BLE_MESH_MODEL_ID_SCHEDULER_SRV 0x1206 +#define BLE_MESH_MODEL_ID_SCHEDULER_SETUP_SRV 0x1207 +#define BLE_MESH_MODEL_ID_SCHEDULER_CLI 0x1208 +#define BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV 0x1300 +#define BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV 0x1301 +#define BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI 0x1302 +#define BLE_MESH_MODEL_ID_LIGHT_CTL_SRV 0x1303 +#define BLE_MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV 0x1304 +#define BLE_MESH_MODEL_ID_LIGHT_CTL_CLI 0x1305 +#define BLE_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV 0x1306 +#define BLE_MESH_MODEL_ID_LIGHT_HSL_SRV 0x1307 +#define BLE_MESH_MODEL_ID_LIGHT_HSL_SETUP_SRV 0x1308 +#define BLE_MESH_MODEL_ID_LIGHT_HSL_CLI 0x1309 +#define BLE_MESH_MODEL_ID_LIGHT_HSL_HUE_SRV 0x130a +#define BLE_MESH_MODEL_ID_LIGHT_HSL_SAT_SRV 0x130b +#define BLE_MESH_MODEL_ID_LIGHT_XYL_SRV 0x130c +#define BLE_MESH_MODEL_ID_LIGHT_XYL_SETUP_SRV 0x130d +#define BLE_MESH_MODEL_ID_LIGHT_XYL_CLI 0x130e +#define BLE_MESH_MODEL_ID_LIGHT_LC_SRV 0x130f +#define BLE_MESH_MODEL_ID_LIGHT_LC_SETUPSRV 0x1310 +#define BLE_MESH_MODEL_ID_LIGHT_LC_CLI 0x1311 + +// link close reason +#define CLOSE_REASON_SUCCESS 0x00 +#define CLOSE_REASON_NVAL_PDU 0x01 +#define CLOSE_REASON_NVAL_FMT 0x02 +#define CLOSE_REASON_UNEXP_PDU 0x03 +#define CLOSE_REASON_CFM_FAILED 0x04 +#define CLOSE_REASON_RESOURCES 0x05 +#define CLOSE_REASON_DECRYPT 0x06 +#define CLOSE_REASON_UNEXP_ERR 0x07 +#define CLOSE_REASON_ADDR 0x08 +#define CLOSE_REASON_TIMEOUT 0x09 + + +/** Special TTL value to request using configured default TTL */ +#define BLE_MESH_TTL_DEFAULT 0xff + +/** Maximum allowed TTL value */ +#define BLE_MESH_TTL_MAX 0x7f + +/** @def BLE_MESH_MODEL_CB + * + * @brief Composition data SIG model entry with callback functions. + * + * @param _id Model ID. + * @param _op Array of model opcode handlers. + * @param _pub Model publish parameters. + * @param _user_data User data for the model. + * @param _cb Callback structure, or NULL to keep no callbacks. + */ +#define BLE_MESH_MODEL_CB(_id, _op, _pub, _user_data, _cb) \ +{ \ + .id = (_id), \ + .op = _op, \ + .keys = { BLE_MESH_KEY_UNUSED }, \ + .pub = _pub, \ + .groups = { BLE_MESH_ADDR_UNASSIGNED }, \ + .user_data = _user_data, \ + .cb = _cb, \ +} + +/** @def BLE_MESH_MODEL_VND_CB + * + * @brief Composition data vendor model entry with callback functions. + * + * @param _company Company ID. + * @param _id Model ID. + * @param _op Array of model opcode handlers. + * @param _pub Model publish parameters. + * @param _user_data User data for the model. + * @param _cb Callback structure, or NULL to keep no callbacks. + */ +#define BLE_MESH_MODEL_VND_CB(_company, _id, _op, _pub, _user_data, _cb) \ +{ \ + .vnd.company = (_company), \ + .vnd.id = (_id), \ + .op = _op, \ + .pub = _pub, \ + .keys = { BLE_MESH_KEY_UNUSED }, \ + .groups = { BLE_MESH_ADDR_UNASSIGNED }, \ + .user_data = _user_data, \ + .cb = _cb, \ +} + +/** @def BLE_MESH_MODEL + * + * @brief Composition data SIG model entry. + * + * @param _id Model ID. + * @param _op Array of model opcode handlers. + * @param _pub Model publish parameters. + * @param _user_data User data for the model. + */ +#define BLE_MESH_MODEL(_id, _op, _pub, _user_data) \ + BLE_MESH_MODEL_CB(_id, _op, _pub, _user_data, NULL) + +/** @def BLE_MESH_MODEL_VND + * + * @brief Composition data vendor model entry. + * + * @param _company Company ID. + * @param _id Model ID. + * @param _op Array of model opcode handlers. + * @param _pub Model publish parameters. + * @param _user_data User data for the model. + */ +#define BLE_MESH_MODEL_VND(_company, _id, _op, _pub, _user_data) \ + BLE_MESH_MODEL_VND_CB(_company, _id, _op, _pub, _user_data, NULL) + +/** @def BLE_MESH_TRANSMIT + * + * @brief Encode transmission count & interval steps. + * + * @param count Number of retransmissions (first transmission is excluded). + * @param int_ms Interval steps in milliseconds. Must be greater than 0 + * and a multiple of 10. + * + * @return Mesh transmit value that can be used e.g. for the default + * values of the configuration model data. + */ +#define BLE_MESH_TRANSMIT(count, int_ms) ((count) | (((int_ms / 10) - 1) << 3)) + +/** @def BLE_MESH_TRANSMIT_COUNT + * + * @brief Decode transmit count from a transmit value. + * + * @param transmit Encoded transmit count & interval value. + * + * @return Transmission count (actual transmissions is N + 1). + */ +#define BLE_MESH_TRANSMIT_COUNT(transmit) (((transmit) & (u8_t)BIT_MASK(3))) + +/** @def BLE_MESH_TRANSMIT_INT + * + * @brief Decode transmit interval from a transmit value. + * + * @param transmit Encoded transmit count & interval value. + * + * @return Transmission interval in milliseconds. + */ +#define BLE_MESH_TRANSMIT_INT(transmit) ((((transmit) >> 3) + 1) * 10) + +/** @def BLE_MESH_PUB_TRANSMIT + * + * @brief Encode Publish Retransmit count & interval steps. + * + * @param count Number of retransmissions (first transmission is excluded). + * @param int_ms Interval steps in milliseconds. Must be greater than 0 + * and a multiple of 50. + * + * @return Mesh transmit value that can be used e.g. for the default + * values of the configuration model data. + */ +#define BLE_MESH_PUB_TRANSMIT(count, int_ms) BLE_MESH_TRANSMIT(count, (int_ms) / 5) + +/** @def BLE_MESH_PUB_TRANSMIT_COUNT + * + * @brief Decode Pubhlish Retransmit count from a given value. + * + * @param transmit Encoded Publish Retransmit count & interval value. + * + * @return Retransmission count (actual transmissions is N + 1). + */ +#define BLE_MESH_PUB_TRANSMIT_COUNT(transmit) BLE_MESH_TRANSMIT_COUNT(transmit) + +/** @def BLE_MESH_PUB_TRANSMIT_INT + * + * @brief Decode Publish Retransmit interval from a given value. + * + * @param transmit Encoded Publish Retransmit count & interval value. + * + * @return Transmission interval in milliseconds. + */ +#define BLE_MESH_PUB_TRANSMIT_INT(transmit) ((((transmit) >> 3) + 1) * 50) + + + +/**************************************foundation****************************************/ + +#ifndef BIT +#define BIT(n) (1UL << (n)) +#endif + +#ifndef BIT_MASK +#define BIT_MASK(n) (BIT(n) - 1) +#endif + +#define ARRAY_SIZE(array) \ + ((unsigned long)((sizeof(array) / sizeof((array)[0])))) + +#define ALIGN_TYPE(_type) ((size_t) & ((struct {uint8_t _1; _type _2; } *)NULL)->_2) + +/**************************************MODEL****************************************/ + +#define BLE_MESH_MODEL_OP_1(b0) (b0) +#define BLE_MESH_MODEL_OP_2(b0, b1) (((b0) << 8) | (b1)) +#define BLE_MESH_MODEL_OP_3(b0, cid) ((((b0) << 16) | 0xc00000) | (cid)) + +#define BLE_MESH_MODEL_OP_END { 0, 0, NULL } +#define BLE_MESH_MODEL_NO_OPS ((struct bt_mesh_model_op []) \ + { BLE_MESH_MODEL_OP_END }) + +/**************************************SHA256****************************************/ + +#define TC_SHA256_BLOCK_SIZE (64) +#define TC_SHA256_DIGEST_SIZE (32) +#define TC_SHA256_STATE_BLOCKS (TC_SHA256_DIGEST_SIZE/4) + +#define TC_CRYPTO_SUCCESS 1 +#define TC_CRYPTO_FAIL 0 + + +struct tc_sha256_state_struct { + unsigned int iv[TC_SHA256_STATE_BLOCKS]; + uint64_t bits_hashed; + uint8_t leftover[TC_SHA256_BLOCK_SIZE]; + size_t leftover_offset; +}; + +typedef struct tc_sha256_state_struct *TCSha256State_t; + +int tc_sha256_init(TCSha256State_t s); + +int tc_sha256_update (TCSha256State_t s, const uint8_t *data, size_t datalen); + +int tc_sha256_final(uint8_t *digest, TCSha256State_t s); + + +/******************************************************************************/ + + +// mesh Эջʹõڴ +typedef struct +{ + u8_t * base_addr; + u32_t mem_len; +}mem_info_t; + +typedef struct +{ + u8_t adv_buf_count; + u8_t rpl_count; + u8_t ivu_divider; + u8_t allow_same_addr; +} ble_mesh_common_cfg_t; + +typedef struct +{ + u8_t pxyfilter_count; +} ble_mesh_proxy_cfg_t; + +typedef struct +{ + u8_t msgcache_count; + + u8_t subnet_count; + u8_t appkey_count; + + u8_t unseg_length; + u8_t txseg_max; + u8_t txseg_count; + + u8_t rxseg_count; + u16_t rxsdu_max; + + u8_t label_count; +} ble_mesh_net_cfg_t; + +typedef struct +{ + u16_t seq_store_rate; + u16_t rpl_store_rate; + u16_t store_rate; +} ble_mesh_store_cfg_t; + +typedef struct +{ + u8_t frndseg_rx; + u8_t frndsub_size; + u8_t frndlpn_count; + u8_t frndqueue_size; + u16_t frndrecv_win; +} ble_mesh_friend_cfg_t; + +typedef struct +{ + u8_t lpnmin_size; + u8_t lpnrssi_factor; + u8_t lpnrecv_factor; + u16_t lpnpoll_timeout; + u16_t lpnrecv_delay; + u16_t lpnretry_timeout; +} ble_mesh_lpn_cfg_t; + +typedef struct +{ + u8_t node_count; +} ble_mesh_prov_cfg_t; + +typedef struct +{ + const u32_t rf_accessAddress; + const u8_t rf_channel_37; + const u8_t rf_channel_38; + const u8_t rf_channel_39; +} ble_mesh_rf_cfg_t; + +// mesh عܵ +typedef struct +{ + ble_mesh_common_cfg_t common_cfg; + ble_mesh_proxy_cfg_t proxy_cfg; + ble_mesh_net_cfg_t net_cfg; + ble_mesh_store_cfg_t store_cfg; + ble_mesh_friend_cfg_t friend_cfg; + ble_mesh_lpn_cfg_t lpn_cfg; + ble_mesh_prov_cfg_t prov_cfg; + ble_mesh_rf_cfg_t rf_cfg; +} ble_mesh_cfg_t; + +/************************************k_work******************************************/ + +struct k_work; +typedef void (*k_work_handler_t)(struct k_work *work); + +struct _snode { + struct _snode *next; +}; +typedef struct _snode sys_snode_t; + +// workṹ +struct k_work { + sys_snode_t node; + k_work_handler_t handler; + bt_mesh_atomic_t flags[1]; +}; + +struct _dnode { + union { + struct _dnode *head; /* ptr to head of list (sys_dlist_t) */ + struct _dnode *next; /* ptr to next node (sys_dnode_t) */ + }; + union { + struct _dnode *tail; /* ptr to tail of list (sys_dlist_t) */ + struct _dnode *prev; /* ptr to previous node (sys_dnode_t) */ + }; +}; + +typedef struct _dnode sys_dlist_t; +typedef struct _dnode sys_dnode_t; + +// ʱб ṹ +struct _timeout { + sys_dnode_t node; + s32_t dticks; +}; + +// ӳٲбworkṹ +struct k_delayed_work { + struct k_work work; + struct _timeout timeout; + struct k_work_q *work_q; +}; + +/************************************model******************************************/ + +struct bt_mesh_model; + +/** Model publication context. */ +struct bt_mesh_model_pub { + /** The model the context belongs to. Initialized by the stack. */ + struct bt_mesh_model *mod; + + u16_t addr; /**< Publish Address. */ + u16_t key:12, /**< Publish AppKey Index. */ + cred:1, /**< Friendship Credentials Flag. */ + send_rel:1; /**< Force reliable sending (segment acks) */ + + u8_t ttl; /**< Publish Time to Live. */ + u8_t retransmit; /**< Retransmit Count & Interval Steps. */ + u8_t period; /**< Publish Period. */ + u16_t period_div: 4, /**< Divisor for the Period. */ + fast_period: 1, /**< Use FastPeriodDivisor */ + count: 3; /**< Retransmissions left. */ + + u32_t period_start; /**< Start of the current period. */ + + /** @brief Publication buffer, containing the publication message. + * + * This will get correctly created when the publication context + * has been defined using the BLE_MESH_MODEL_PUB_DEFINE macro. + * + * BLE_MESH_MODEL_PUB_DEFINE(name, update, size); + */ + struct net_buf_simple *msg; + + /** @brief Callback for updating the publication buffer. + * + * When set to NULL, the model is assumed not to support + * periodic publishing. When set to non-NULL the callback + * will be called periodically and is expected to update + * @ref bt_mesh_model_pub.msg with a valid publication + * message. + * + * @param mod The Model the Publication Context belogs to. + * + * @return Zero on success or (negative) error code otherwise. + */ + int (*update)(struct bt_mesh_model *mod); + + /** Publish Period Timer. Only for stack-internal use. */ + struct k_delayed_work timer; +}; + +/** Message sending context. */ +struct bt_mesh_msg_ctx { + /** NetKey Index of the subnet to send the message on. */ + u16_t net_idx; + + /** AppKey Index to encrypt the message with. */ + u16_t app_idx; + + /** Remote address. */ + u16_t addr; + + /** Destination address of a received message. Not used for sending. */ + u16_t recv_dst; + + /** RSSI of received packet. Not used for sending. */ + s8_t recv_rssi; + + /** Received TTL value. Not used for sending. */ + u8_t recv_ttl: 7; + + /** Force sending reliably by using segment acknowledgement */ + u8_t send_rel: 1; + + /** TTL, or BLE_MESH_TTL_DEFAULT for default TTL. */ + u8_t send_ttl; +}; + +struct bt_mesh_model_op { + /* OpCode encoded using the BLE_MESH_MODEL_OP_* macros */ + const u32_t opcode; + + /* Minimum required message length */ + const size_t min_len; + + /* Message handler for the opcode */ + void (*const func)(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf); +}; + + +typedef ssize_t (*settings_read_cb)(void *cb_arg, void *data, size_t len); + +/** Model callback functions. */ +struct bt_mesh_model_cb { + /** @brief Set value handler of user data tied to the model. + * + * @sa settings_handler::h_set + * + * @param model Model to set the persistent data of. + * @param len_rd The size of the data found in the backend. + * @param read_cb Function provided to read the data from the backend. + * @param cb_arg Arguments for the read function provided by the + * backend. + * + * @return 0 on success, error otherwise. + */ + int (*const settings_set)(struct bt_mesh_model *model, + size_t len_rd, settings_read_cb read_cb, + void *cb_arg); + + /** @brief Callback called when the mesh is started. + * + * This handler gets called after the node has been provisioned, or + * after all mesh data has been loaded from persistent storage. + * + * When this callback fires, the mesh model may start its behavior, + * and all Access APIs are ready for use. + * + * @param model Model this callback belongs to. + * @param first_time Flag indicating whether this is the first time the + * node is started. If false, provisioning data was + * loaded from persistent storage. + */ + int (*const start)(struct bt_mesh_model *model, BOOL first_time); + + /** @brief Model init callback. + * + * Called on every model instance during mesh initialization. + * + * @param model Model to be initialized. + * + * @return 0 on success, error otherwise. + */ + int (*const init)(struct bt_mesh_model *model); + + /** @brief Model reset callback. + * + * Called when the mesh node is reset. All model data is deleted on + * reset, and the model should clear its state. + * + * @param model Model this callback belongs to. + */ + void (*const reset)(struct bt_mesh_model *model); +}; + +/** Abstraction that describes a Mesh Model instance */ +struct bt_mesh_model { + union { + const u16_t id; + struct { + u16_t id; + u16_t company; + } vnd; + }; + + /* Internal information, mainly for persistent storage */ + u8_t elem_idx; /* Belongs to Nth element */ + u8_t model_idx; /* Is the Nth model in the element */ + u16_t flags; /* Information about what has changed */ + + /* Model Publication */ + struct bt_mesh_model_pub *const pub; + + /* AppKey List */ + u16_t keys[CONFIG_BLE_MESH_MOD_KEY_COUNT]; + + /* Subscription List (group or virtual addresses) */ + u16_t groups[CONFIG_BLE_MESH_MOD_GROUP_COUNT]; + + const struct bt_mesh_model_op * op; + + /* Model callback structure. */ + const struct bt_mesh_model_cb * cb; + + /* Model-specific user data */ + void *user_data; +}; + +/************************************elem******************************************/ + +/** Abstraction that describes a Mesh Element */ +struct bt_mesh_elem { + /* Unicast Address. Set at runtime during provisioning. */ + u16_t addr; + + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + const u16_t loc; + + const u8_t model_count; + const u8_t vnd_model_count; + + struct bt_mesh_model *const models; + struct bt_mesh_model *const vnd_models; +}; + +/** Node Composition */ +struct bt_mesh_comp { + u16_t cid; + u16_t pid; + u16_t vid; + + size_t elem_count; + struct bt_mesh_elem *elem; +}; + + + + +typedef enum +{ + BLE_MESH_PROV_OOB_OTHER = BIT(0), + BLE_MESH_PROV_OOB_URI = BIT(1), + BLE_MESH_PROV_OOB_2D_CODE = BIT(2), + BLE_MESH_PROV_OOB_BAR_CODE = BIT(3), + BLE_MESH_PROV_OOB_NFC = BIT(4), + BLE_MESH_PROV_OOB_NUMBER = BIT(5), + BLE_MESH_PROV_OOB_STRING = BIT(6), + /* 7 - 10 are reserved */ + BLE_MESH_PROV_OOB_ON_BOX = BIT(11), + BLE_MESH_PROV_OOB_IN_BOX = BIT(12), + BLE_MESH_PROV_OOB_ON_PAPER = BIT(13), + BLE_MESH_PROV_OOB_IN_MANUAL = BIT(14), + BLE_MESH_PROV_OOB_ON_DEV = BIT(15), +} bt_mesh_prov_oob_info_t; + +typedef enum +{ + BLE_MESH_NO_OUTPUT = 0, + BLE_MESH_BLINK = BIT(0), + BLE_MESH_BEEP = BIT(1), + BLE_MESH_VIBRATE = BIT(2), + BLE_MESH_DISPLAY_NUMBER = BIT(3), + BLE_MESH_DISPLAY_STRING = BIT(4), +} bt_mesh_output_action_t; + +typedef enum +{ + BLE_MESH_NO_INPUT = 0, + BLE_MESH_PUSH = BIT(0), + BLE_MESH_TWIST = BIT(1), + BLE_MESH_ENTER_NUMBER = BIT(2), + BLE_MESH_ENTER_STRING = BIT(3), +} bt_mesh_input_action_t; + +typedef enum +{ + BLE_MESH_PROV_ADV = BIT(0), + BLE_MESH_PROV_GATT = BIT(1), +} bt_mesh_prov_bearer_t; + +typedef struct { + u8_t type; + u8_t val[6]; +} bt_mesh_addr_t; + +typedef union { + struct pb_adv + { + const u32_t *uri_hash; + } adv; + + struct pb_gatt + { + const bt_mesh_addr_t *addr; + } gatt; +} unprivison_info_t; + + +/** Provisioning properties & capabilities. */ +struct bt_mesh_prov +{ + /** The UUID that's used when advertising as unprovisioned */ + const u8_t *uuid; + + /** Optional URI. This will be advertised separately from the + * unprovisioned beacon, however the unprovisioned beacon will + * contain a hash of it so the two can be associated by the + * provisioner. + */ + const char *uri; + + /** Out of Band information field. */ + bt_mesh_prov_oob_info_t oob_info; + + /** Flag indicates whether unprovisioned devices support OOB public key */ + BOOL oob_pub_key; + + /** @brief Set device OOB public key. + * + * This callback notifies the application to + * set OOB public key & private key pair. + */ + void (*oob_pub_key_cb)(void); + + /** Static OOB value */ + const u8_t *static_val; + /** Static OOB value length */ + u8_t static_val_len; + + /** Maximum size of Output OOB supported */ + u8_t output_size; + /** Supported Output OOB Actions */ + u16_t output_actions; + + /* Maximum size of Input OOB supported */ + u8_t input_size; + /** Supported Input OOB Actions */ + u16_t input_actions; + + /** @brief Output of a number is requested. + * + * This callback notifies the application to + * output the given number using the given action. + * + * @param act Action for outputting the number. + * @param num Number to be out-put. + * + * @return Zero on success or negative error code otherwise + */ + int (*output_number)(bt_mesh_output_action_t act, u32_t num); + + /** @brief Output of a string is requested. + * + * This callback notifies the application to + * display the given string to the user. + * + * @param str String to be displayed. + * + * @return Zero on success or negative error code otherwise + */ + int (*output_string)(const char *str); + + /** @brief Input is requested. + * + * This callback notifies the application to request + * input from the user using the given action. The + * requested input will either be a string or a number, and + * the application needs to consequently call the + * bt_mesh_input_string() or bt_mesh_input_number() functions + * once the data has been acquired from the user. + * + * @param act Action for inputting data. + * @param num Maximum size of the in-put data. + * + * @return Zero on success or negative error code otherwise + */ + int (*input)(bt_mesh_input_action_t act, u8_t size); + + /** @brief Unprovisioned beacon has been received. + * + * This callback notifies the application that an unprovisioned + * beacon has been received. + * + * @param uuid UUID + * @param oob_info OOB Information + * @param uri_hash Pointer to URI Hash value. NULL if no hash was + * present in the beacon. + */ + void (*unprovisioned_beacon)(bt_mesh_prov_bearer_t bearer, + const u8_t uuid[16], bt_mesh_prov_oob_info_t oob_info, + const unprivison_info_t *info); + + void (*pear_oob_pub_key)(void); + + /** @brief Provisioning link has been opened. + * + * This callback notifies the application that a provisioning + * link has been opened on the given provisioning bearer. + * + * @param bearer Provisioning bearer. + */ + void (*link_open)(bt_mesh_prov_bearer_t bearer); + + /** @brief Provisioning link has been closed. + * + * This callback notifies the application that a provisioning + * link has been closed on the given provisioning bearer. + * + * @param bearer Provisioning bearer. + */ + void (*link_close)(bt_mesh_prov_bearer_t bearer, u8_t reason); + + /** @brief Provisioning is complete. + * + * This callback notifies the application that provisioning has + * been successfully completed, and that the local node has been + * assigned the specified NetKeyIndex and primary element address. + * + * @param net_idx NetKeyIndex given during provisioning. + * @param addr Primary element address. + * @param flags Key Refresh & IV Update flags + * @param iv_index IV Index. + */ + void (*complete)(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); + + /** @brief A new node has been added to the provisioning database. + * + * This callback notifies the application that provisioning has + * been successfully completed, and that a node has been assigned + * the specified NetKeyIndex and primary element address. + * + * @param net_idx NetKeyIndex given during provisioning. + * @param addr Primary element address. + * @param num_elem Number of elements that this node has. + */ + void (*node_added)(u16_t net_idx, u16_t addr, u8_t num_elem); + + /** @brief Node has been reset. + * + * This callback notifies the application that the local node + * has been reset and needs to be reprovisioned. The node will + * not automatically advertise as unprovisioned, rather the + * bt_mesh_prov_enable() API needs to be called to enable + * unprovisioned advertising on one or more provisioning bearers. + */ + void (*reset)(void); +}; + + +struct bt_mesh_conn { + u16_t handle; + bt_mesh_atomic_t ref; +}; + +/** Proxy Client. */ +struct bt_mesh_proxy_cli +{ + void (*connected)(struct bt_mesh_conn *conn); + + void (*disconnected)(struct bt_mesh_conn *conn, u8_t reason); + + void (*net_id_recv)(const bt_mesh_addr_t *addr, u16_t net_idx); + + void (*node_id_recv)(const bt_mesh_addr_t *bt_addr, u16_t net_idx, u16_t addr); +}; + +extern const struct bt_mesh_model_op bt_mesh_cfg_srv_op[]; +extern const struct bt_mesh_model_cb bt_mesh_cfg_srv_cb; + +#define BLE_MESH_MODEL_CFG_SRV(srv_data) \ + BLE_MESH_MODEL_CB(BLE_MESH_MODEL_ID_CFG_SRV, bt_mesh_cfg_srv_op, NULL, \ + srv_data, &bt_mesh_cfg_srv_cb) +#define BLE_MESH_MODEL_CFG_CLI(cli_data) \ + BLE_MESH_MODEL_CB(BLE_MESH_MODEL_ID_CFG_CLI, NULL, NULL, cli_data, NULL) + +extern const struct bt_mesh_model_op bt_mesh_health_srv_op[]; +extern const struct bt_mesh_model_cb bt_mesh_health_mod_srv_cb; + +#define BLE_MESH_MODEL_HEALTH_SRV(srv, pub) \ + BLE_MESH_MODEL_CB(BLE_MESH_MODEL_ID_HEALTH_SRV, bt_mesh_health_srv_op, \ + pub, srv, &bt_mesh_health_mod_srv_cb) +/*****************************************buf*************************************/ + +#define BLE_MESH_NET_BUF_USER_DATA_SIZE 1 + +// +// Сbufṹ +// +struct net_buf_simple { + /** Pointer to the start of data in the buffer. */ + u8_t *data; + + /** Length of the data behind the data pointer. */ + u16_t len; + + /** Amount of data that this buffer can store. */ + u16_t size; + + /** Start of the data storage. Not to be accessed directly + * (the data pointer should be used instead). + */ + u8_t *__buf; +}; + +// +// һbufbufϢô־ԼϼĿ¼ָ룩СbufΪbuf +// +struct net_buf { + union { + /** Allow placing the buffer into sys_slist_t */ + sys_snode_t node; + + /** Fragments associated with this buffer. */ + struct net_buf *frags; + }; + + /** Reference count. */ + u8_t ref; + + /** Bit-field of buffer flags. */ + u8_t flags; + + /** Where the buffer should go when freed up. */ + struct net_buf_pool *pool; + + /* Union for convenience access to the net_buf_simple members, also + * preserving the old API. + */ + union { + /* The ABI of this struct must match net_buf_simple */ + struct { + /** Pointer to the start of data in the buffer. */ + u8_t *data; + + /** Length of the data behind the data pointer. */ + u16_t len; + + /** Amount of data that this buffer can store. */ + u16_t size; + + /** Start of the data storage. Not to be accessed + * directly (the data pointer should be used + * instead). + */ + u8_t *__buf; + }; + + struct net_buf_simple b; + }; + + /** System metadata for this buffer. */ + u32_t user_data[BLE_MESH_NET_BUF_USER_DATA_SIZE]; +}; + + +// Define a net_buf_simple stack variable. +#define NET_BUF_SIMPLE_DEFINE(_name, _size) \ + u8_t net_buf_data_##_name[_size]; \ + struct net_buf_simple _name = { \ + .data = net_buf_data_##_name, \ + .len = 0, \ + .size = _size, \ + .__buf = net_buf_data_##_name, \ + } + +// Define a static net_buf_simple variable. +#define NET_BUF_SIMPLE_DEFINE_STATIC(_name, _size) \ + static u8_t net_buf_data_##_name[_size]; \ + static struct net_buf_simple _name = { \ + .data = net_buf_data_##_name, \ + .len = 0, \ + .size = _size, \ + .__buf = net_buf_data_##_name, \ + } + +// Define a model publication context. +#define BLE_MESH_MODEL_PUB_DEFINE(_name, _update, _msg_len) \ + NET_BUF_SIMPLE_DEFINE_STATIC(bt_mesh_pub_msg_##_name, _msg_len); \ + static struct bt_mesh_model_pub _name = { \ + .update = _update, \ + .msg = &bt_mesh_pub_msg_##_name, \ + } + +// A helper to define a health publication context +#define BLE_MESH_HEALTH_PUB_DEFINE(_name, _max_faults) \ + BLE_MESH_MODEL_PUB_DEFINE(_name, NULL, (1 + 3 + (_max_faults))) + +// ϼṹָ +#define CONTAINER_OF(ptr, type, field) \ + ((type *)(((char *)(ptr)) - offsetof(type, field))) + + +void *net_buf_simple_add(struct net_buf_simple *buf, size_t len); +#define net_buf_add(buf, len) net_buf_simple_add(&(buf)->b, len) + +void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem, + size_t len); +#define net_buf_add_mem(buf, mem, len) net_buf_simple_add_mem(&(buf)->b, mem, len) + +u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val); +#define net_buf_add_u8(buf, val) net_buf_simple_add_u8(&(buf)->b, val) + +void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val); +#define net_buf_add_le16(buf, val) net_buf_simple_add_le16(&(buf)->b, val) + +void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val); +#define net_buf_add_be16(buf, val) net_buf_simple_add_be16(&(buf)->b, val) + +void net_buf_simple_add_le32(struct net_buf_simple *buf, u32_t val); +#define net_buf_add_le32(buf, val) net_buf_simple_add_le32(&(buf)->b, val) + +void net_buf_simple_add_be32(struct net_buf_simple *buf, u32_t val); +#define net_buf_add_be32(buf, val) net_buf_simple_add_be32(&(buf)->b, val) + +void *net_buf_simple_push(struct net_buf_simple *buf, size_t len); +#define net_buf_push(buf, len) net_buf_simple_push(&(buf)->b, len) + +void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val); +#define net_buf_push_le16(buf, val) net_buf_simple_push_le16(&(buf)->b, val) + +void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val); +#define net_buf_push_be16(buf, val) net_buf_simple_push_be16(&(buf)->b, val) + +void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val); +#define net_buf_push_u8(buf, val) net_buf_simple_push_u8(&(buf)->b, val) + +void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len); +#define net_buf_pull(buf, len) net_buf_simple_pull(&(buf)->b, len) + +void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len); +#define net_buf_pull_mem(buf, len) net_buf_simple_pull_mem(&(buf)->b, len) + +u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf); +#define net_buf_pull_u8(buf) net_buf_simple_pull_u8(&(buf)->b) + +u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf); +#define net_buf_pull_le16(buf) net_buf_simple_pull_le16(&(buf)->b) + +u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf); +#define net_buf_pull_be16(buf) net_buf_simple_pull_be16(&(buf)->b) + +u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf); +#define net_buf_pull_le32(buf) net_buf_simple_pull_le32(&(buf)->b) + +u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf); +#define net_buf_pull_be32(buf) net_buf_simple_pull_be32(&(buf)->b) + +size_t net_buf_simple_tailroom(struct net_buf_simple *buf); +#define net_buf_tailroom(buf) net_buf_simple_tailroom(&(buf)->b) + +size_t net_buf_simple_headroom(struct net_buf_simple *buf); +#define net_buf_headroom(buf) net_buf_simple_headroom(&(buf)->b) + +void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve); +#define net_buf_reserve(buf, reserve) net_buf_simple_reserve(&(buf)->b, reserve); + +void net_buf_unref(struct net_buf *buf); + + +/*****************************************list*************************************/ +typedef struct{ + sys_snode_t *head; + sys_snode_t *tail; +}sys_slist_t; + + +/*****************************************NVS*************************************/ + +typedef int (*flash_api_read)(int offset, void *data, unsigned int len); +typedef int (*flash_api_write)(int offset, const void *data, unsigned int len); +typedef int (*flash_api_erase)(int offset, unsigned int len); +typedef int (*flash_api_write_protection)(BOOL enable); + +struct flash_config_info { + u8_t nvs_sector_cnt; + u8_t nvs_write_size; + u16_t nvs_sector_size; + u32_t nvs_store_baddr; +}; + +struct flash_driver_api { + flash_api_read read; + flash_api_write write; + flash_api_erase erase; + flash_api_write_protection write_protection; +}; + +struct device +{ + struct flash_driver_api api; + struct flash_config_info info; +}; + + +int settings_load(void); + +void bt_mesh_settings_init(void); + +/*****************************************beacon*************************************/ +void bt_mesh_beacon_init(void); + +/*****************************************health_srv*************************************/ + +/** Mesh Health Server Model Callback */ +struct bt_mesh_health_srv_cb +{ + /* Fetch current faults */ + int (*fault_get_cur)(struct bt_mesh_model *model, u8_t *test_id, + u16_t *company_id, u8_t *faults, + u8_t *fault_count); + + /* Fetch registered faults */ + int (*fault_get_reg)(struct bt_mesh_model *model, u16_t company_id, + u8_t *test_id, u8_t *faults, + u8_t *fault_count); + + /* Clear registered faults */ + int (*fault_clear)(struct bt_mesh_model *model, u16_t company_id); + + /* Run a specific test */ + int (*fault_test)(struct bt_mesh_model *model, u8_t test_id, + u16_t company_id); + + /* Attention on */ + void (*attn_on)(struct bt_mesh_model *model); + + /* Attention off */ + void (*attn_off)(struct bt_mesh_model *model); +}; + +/** Mesh Health Server Model Context */ +struct bt_mesh_health_srv +{ + struct bt_mesh_model *model; + + /* Optional callback struct */ + const struct bt_mesh_health_srv_cb *cb; + + /* Attention Timer state */ + struct k_delayed_work attn_timer; +}; + +/* Heartbeat Publication */ +struct bt_mesh_hb_pub { + struct k_delayed_work timer; + + u16_t dst; + u16_t count; + u8_t period; + u8_t ttl; + u16_t feat; + u16_t net_idx; +}; + +/* Heartbeat Subscription */ +struct bt_mesh_hb_sub { + s64_t expiry; + + u16_t src; + u16_t dst; + u16_t count; + u8_t min_hops; + u8_t max_hops; + + /* Optional subscription tracking function */ + void (*func)(u8_t hops, u16_t feat); +}; + +/*****************************************cfg_srv*************************************/ + +/** Mesh Configuration Server Model Context */ +struct bt_mesh_cfg_srv +{ + struct bt_mesh_model *model; + + u8_t net_transmit; /* Network Transmit state */ + u8_t relay; /* Relay Mode state */ + u8_t relay_retransmit; /* Relay Retransmit state */ + u8_t beacon; /* Secure Network Beacon state */ + u8_t gatt_proxy; /* GATT Proxy state */ + u8_t frnd; /* Friend state */ + u8_t default_ttl; /* Default TTL */ + + struct bt_mesh_hb_pub hb_pub; + + struct bt_mesh_hb_sub hb_sub; +}; + +void bt_mesh_relay_init(void); + +u8_t bt_mesh_net_transmit_get(void); +u8_t bt_mesh_relay_get(void); +u8_t bt_mesh_friend_get(void); +u8_t bt_mesh_relay_retransmit_get(void); +u8_t bt_mesh_beacon_get(void); +u8_t bt_mesh_gatt_proxy_get(void); +u8_t bt_mesh_default_ttl_get(void); +u8_t *bt_mesh_label_uuid_get(u16_t addr); + + +/*****************************************cfg_cli*************************************/ + +struct bt_mesh_cfg_comp_data +{ + struct net_buf_simple *buf; +}; + +struct bt_mesh_cfg_relay +{ + u8_t transmit; +}; + +struct bt_mesh_cfg_mod_pub { + u16_t addr; + u16_t app_idx; + BOOL cred_flag; + u8_t ttl; + u8_t period; + u8_t transmit; +}; + +struct bt_mesh_cfg_mod_pub_va { + u16_t addr[16]; + u16_t app_idx; + BOOL cred_flag; + u8_t ttl; + u8_t period; + u8_t transmit; +}; + +struct bt_mesh_cfg_hb_sub { + u16_t src; + u16_t dst; + u8_t period; + u8_t count; + u8_t min; + u8_t max; +}; + +struct bt_mesh_cfg_hb_pub { + u16_t dst; + u8_t count; + u8_t period; + u8_t ttl; + u16_t feat; + u16_t net_idx; +}; + +struct bt_mesh_cfg_lpn_timeout +{ + u16_t addr; + u32_t polltimeout; +}; + +struct bt_mesh_cfg_net_transmit +{ + u8_t transmit; +}; + +struct bt_mesh_node_id +{ + u8_t identity; + u16_t net_idx; +}; + +struct bt_mesh_krp +{ + u8_t phase; + u16_t net_idx; +}; + +struct bt_mesh_cfg_app_list +{ + u16_t elem_addr; + u16_t mod_id; + u16_t cid; + const u16_t *app_lists; +}; + +struct bt_mesh_app_key_list +{ + u16_t net_idx; + const u16_t *app_key_lists; +}; + +struct bt_mesh_sub_list +{ + u16_t elem_addr; + u16_t cid; + u16_t mod_id; + const u16_t *addr; +}; + +struct cfgEventHdr +{ + u8_t status; + u32_t opcode; +}; + +union cfgEvent_t +{ + struct bt_mesh_cfg_comp_data comp; + struct bt_mesh_cfg_relay relay; + struct bt_mesh_cfg_mod_pub m_pub; + struct bt_mesh_cfg_hb_pub h_pub; + struct bt_mesh_cfg_hb_sub sub; + struct bt_mesh_cfg_lpn_timeout lpn; + struct bt_mesh_cfg_net_transmit transmit; + struct bt_mesh_node_id id; + struct bt_mesh_krp krp; + struct bt_mesh_cfg_app_list aplist; + struct bt_mesh_app_key_list apklist; + struct bt_mesh_sub_list sublist; +}; + +typedef struct +{ + struct cfgEventHdr cfgHdr; + union cfgEvent_t cfgEvent; +}cfg_cli_status_t; + +typedef void (*cfg_cli_rsp_handler_t)(const cfg_cli_status_t *val); + + +/** Mesh Configuration Client Model Context */ +struct bt_mesh_cfg_cli { + struct bt_mesh_model *model; + + cfg_cli_rsp_handler_t handler; + + u32_t op_req; + u32_t op_pending; + + struct k_delayed_work op_sync; +}; + +int bt_mesh_cfg_comp_data_get(u16_t net_idx, u16_t addr, u8_t page); +int bt_mesh_cfg_beacon_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_beacon_set(u16_t net_idx, u16_t addr, u8_t val); +int bt_mesh_cfg_ttl_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_ttl_set(u16_t net_idx, u16_t addr, u8_t val); +int bt_mesh_cfg_friend_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_friend_set(u16_t net_idx, u16_t addr, u8_t val); +int bt_mesh_cfg_gatt_proxy_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_gatt_proxy_set(u16_t net_idx, u16_t addr, u8_t val); +int bt_mesh_cfg_relay_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_relay_set(u16_t net_idx, u16_t addr, u8_t new_relay, + u8_t new_transmit); +int bt_mesh_cfg_net_key_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_net_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, + const u8_t net_key[16]); +int bt_mesh_cfg_net_key_update(u16_t net_idx, u16_t addr, u16_t key_net_idx, + const u8_t net_key[16]); +int bt_mesh_cfg_net_key_delete(u16_t net_idx, u16_t addr, u16_t key_net_idx); +int bt_mesh_cfg_app_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, + u16_t key_app_idx, const u8_t app_key[16]); +int bt_mesh_cfg_app_key_update(u16_t net_idx, u16_t addr, u16_t key_net_idx, + u16_t key_app_idx, const u8_t app_key[16]); +int bt_mesh_cfg_app_key_delete(u16_t net_idx, u16_t addr, u16_t key_net_idx, + u16_t key_app_idx); +int bt_mesh_cfg_mod_app_bind(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_app_idx, u16_t mod_id); +int bt_mesh_cfg_mod_app_bind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_app_idx, u16_t mod_id, u16_t cid); +int bt_mesh_cfg_mod_app_unbind(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_app_idx, u16_t mod_id); +int bt_mesh_cfg_mod_app_unbind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_app_idx, u16_t mod_id, u16_t cid); +int bt_mesh_cfg_mod_pub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id); +int bt_mesh_cfg_mod_pub_get_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id, u16_t cid); +int bt_mesh_cfg_mod_pub_set(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id, const struct bt_mesh_cfg_mod_pub *pub); +int bt_mesh_cfg_mod_pub_set_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id, u16_t cid, const struct bt_mesh_cfg_mod_pub *pub); +int bt_mesh_cfg_mod_pub_va_set(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id, const struct bt_mesh_cfg_mod_pub_va *pub); +int bt_mesh_cfg_mod_pub_va_set_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id, u16_t cid, const struct bt_mesh_cfg_mod_pub_va *pub); +int bt_mesh_cfg_mod_sub_add(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t sub_addr, u16_t mod_id); +int bt_mesh_cfg_mod_sub_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t sub_addr, u16_t mod_id, u16_t cid); +int bt_mesh_cfg_mod_sub_del(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t sub_addr, u16_t mod_id); +int bt_mesh_cfg_mod_sub_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t sub_addr, u16_t mod_id, u16_t cid); +int bt_mesh_cfg_mod_sub_del_all(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id); +int bt_mesh_cfg_mod_sub_delall_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id, u16_t cid); +int bt_mesh_cfg_mod_sub_overwrite(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t sub_addr, u16_t mod_id); +int bt_mesh_cfg_mod_sub_overwrite_vnd(u16_t net_idx, u16_t addr, + u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u16_t cid); +int bt_mesh_cfg_mod_sub_va_add(u16_t net_idx, u16_t addr, u16_t elem_addr, + const u8_t label[16], u16_t mod_id, u16_t virt_addr); +int bt_mesh_cfg_mod_sub_va_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + const u8_t label[16], u16_t mod_id, u16_t cid, u16_t virt_addr); +int bt_mesh_cfg_mod_sub_va_del(u16_t net_idx, u16_t addr, u16_t elem_addr, + const u8_t label[16], u16_t mod_id, u16_t virt_addr); +int bt_mesh_cfg_mod_sub_va_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + const u8_t label[16], u16_t mod_id, u16_t cid, u16_t virt_addr); +int bt_mesh_cfg_mod_sub_va_overwrite(u16_t net_idx, u16_t addr, + u16_t elem_addr, const u8_t label[16], + u16_t mod_id, u16_t virt_addr); +int bt_mesh_cfg_mod_sub_va_overwrite_vnd(u16_t net_idx, u16_t addr, + u16_t elem_addr, const u8_t label[16], + u16_t mod_id, u16_t cid, u16_t virt_addr); +int bt_mesh_cfg_hb_pub_set(u16_t net_idx, u16_t addr, + const struct bt_mesh_cfg_hb_pub *param); +int bt_mesh_cfg_hb_pub_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_lpn_polltimeout_get(u16_t net_idx, u16_t addr, u16_t lpn_addr); +int bt_mesh_cfg_net_transmit_get(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_net_transmit_set(u16_t net_idx, u16_t addr, u8_t val); +int bt_mesh_cfg_node_reset(u16_t net_idx, u16_t addr); +int bt_mesh_cfg_node_id_get(u16_t net_idx, u16_t addr, u16_t id_net_idx); +int bt_mesh_cfg_node_id_set(u16_t net_idx, u16_t addr, u16_t id_net_idx, u8_t val); +int bt_mesh_cfg_krp_get(u16_t net_idx, u16_t addr, u16_t krp_net_idx); +int bt_mesh_cfg_krp_set(u16_t net_idx, u16_t addr, u16_t krp_net_idx, u8_t val); +int bt_mesh_cfg_mod_app_get_sig(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id); +int bt_mesh_cfg_mod_app_get_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, u16_t cid); +int bt_mesh_cfg_app_key_get(u16_t net_idx, u16_t addr, u16_t key_net_idx); +int bt_mesh_cfg_mod_sub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id); +int bt_mesh_cfg_mod_sub_get_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, + u16_t mod_id, u16_t cid); +s32_t bt_mesh_cfg_cli_timeout_get(void); +void bt_mesh_cfg_cli_timeout_set(s32_t timeout); + +/******************************************************************************/ + +extern u8_t bt_mesh_lib_init(void); + +BOOL bt_mesh_is_provisioned(void); + +u8_t bt_mesh_lib_init(void); + +int bt_mesh_cfg_set(ble_mesh_cfg_t const *p_cfg, void const *p_dev, + u8_t const * p_mac, mem_info_t *info); + +int bt_mesh_init(const struct bt_mesh_prov *prov, + const struct bt_mesh_comp *comp, + const struct bt_mesh_proxy_cli *cli); + +int bt_mesh_prov_enable( u8_t bearers); + +int bt_mesh_provision(const u8_t net_key[16], u16_t net_idx, + u8_t flags, u32_t iv_index, u16_t addr, + const u8_t dev_key[16]); + +int bt_mesh_provision_adv(const u8_t uuid[16], u16_t net_idx, u16_t addr, + u8_t attention_duration); + + +/*****************************************adapt*************************************/ +typedef int (*gatts_notify_cb_t)(struct bt_mesh_conn *conn, const void *data, u16_t len); + +void bt_mesh_proxy_cli_adapt_init(void); + +void bt_mesh_adapt_init(void); + +void bt_mesh_adv_init(void); + +void bt_mesh_conn_adv_init(void); + +void gatts_notify_register( gatts_notify_cb_t cb); + +int bt_mesh_scan_enable(void); +int bt_mesh_scan_disable(void); + +void bt_mesh_beacon_enable(void); +void bt_mesh_beacon_disable(void); + +int bt_mesh_proxy_prov_enable(void); +int bt_mesh_proxy_prov_disable(BOOL disconnect); + +/*****************************************proxy*************************************/ + +typedef void (*proxy_beacon_init_cb_t) ( void *client ); +typedef int (*proxy_prov_enable_cb_t)(void); +typedef int (*proxy_gatt_enable_cb_t)(void); + + + +void bt_mesh_proxy_beacon_init( void *client ); +int bt_mesh_gatts_notify(struct bt_mesh_conn *conn, const void *data, u16_t len); +int bt_mesh_proxy_gatt_enable(void); + +void bt_mesh_proxy_beacon_init_register( void *cb ); +void proxy_prov_enable_register( proxy_prov_enable_cb_t cb ); +void proxy_gatt_enable_register(proxy_gatt_enable_cb_t cb ); + +int bt_mesh_proxy_init(void); + +/*****************************************prov*************************************/ + +void adv_link_rx_buf_register( struct net_buf_simple *buf); + +int bt_mesh_provisioner_enable(bt_mesh_prov_bearer_t bearers); +int bt_mesh_provisioner_disable(bt_mesh_prov_bearer_t bearers, BOOL force); + +void bt_mesh_prov_retransmit_init(void); + +int bt_mesh_prov_init(const struct bt_mesh_prov *prov_info); + +/*****************************************tran*************************************/ +void bt_mesh_trans_init(void); + +/*****************************************friend*************************************/ +#define FRIEND_FRIENDSHIP_ESTABLISHED 0x01 +#define FRIEND_FRIENDSHIP_TERMINATED 0x02 + +typedef int (*friend_init_cb_t)(void); +typedef void (*friend_state_cb_t)(u16_t lpn_addr, u8_t state); + +void friend_init_register(friend_init_cb_t cb, friend_state_cb_t state_cb); +int bt_mesh_friend_init(void); + +/*****************************************lpn*************************************/ +#define LPN_FRIENDSHIP_ESTABLISHED 0x01 +#define LPN_FRIENDSHIP_TERMINATED 0x02 + +typedef int (*lpn_init_cb_t)(void); +typedef void (*lpn_state_cb_t)(u8_t state); + +void lpn_init_register(lpn_init_cb_t cb, lpn_state_cb_t state_cb); +int bt_mesh_lpn_init(void); +int bt_mesh_lpn_set(BOOL enable); + +/*****************************************net*************************************/ +void bt_mesh_net_init(void); + +// APP key +struct bt_mesh_app_key { + u16_t net_idx; + u16_t app_idx; + BOOL updated; + struct bt_mesh_app_keys { + u8_t id; + u8_t val[16]; + } keys[2]; +}; + + +struct bt_mesh_app_key *bt_mesh_app_keys_get(u16_t net_idx); +struct bt_mesh_app_key *bt_mesh_app_key_find(u16_t app_idx); + +/*****************************************NVS*************************************/ +void bt_mesh_store_mod_bind(struct bt_mesh_model *mod); +void bt_mesh_store_mod_sub(struct bt_mesh_model *mod); + +/*****************************************access*************************************/ + + // ÷͵Ļصһʼʱһʱ +struct bt_mesh_send_cb { + void (*start)(u16_t duration, int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + +void bt_mesh_mod_init( void ); + +int bt_mesh_comp_register(const struct bt_mesh_comp *comp); + +u8_t bt_mesh_elem_count(void); + +u16_t bt_mesh_primary_addr(void); + +void bt_mesh_model_msg_init(struct net_buf_simple *msg, u32_t opcode); + +int bt_mesh_model_send(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *msg, + const struct bt_mesh_send_cb *cb, void *cb_data); + +/*****************************************t_timer*************************************/ +void MeshTimer_Init(void); + +void MeshDeamon_Init(void); + +/*****************************************rf*************************************/ + +typedef void ( *pfnAppRFStatusCB_t)( u8 sta , u8 rsr, u8 *rxBuf ); +// sta - current status@ref RF_ROLE_STATUS_TYPE +// rsr - receive status: bit0- crc check result,bit1- type matching result +// rxBuf - receive data buffer + +typedef struct app_tag_rf_config +{ + u8 LLEMode; // BIT0 0=LLE_MODE_BASIC + // BIT6 0=data channel(0-39) + // 1=rf frequency (2400000kHz-2483500kHz) + // BIT7 0=the first byte of the receive buffer is rssi + // 1=the first byte of the receive buffer is package type + u8 Channel; // rf channel(0-39) + u32 Frequency; // rf frequency (2400000kHz-2483500kHz) + u32 accessAddress; // access address,32bit PHY address + u32 CRCInit; // crc initial value + pfnAppRFStatusCB_t rfStatusCB; // status call back +}app_rfConfig_t; + +void hal_rf_init(void); +void app_rf_config( app_rfConfig_t *app_rfConfig ); +int app_rf_tx( u8 *txBuf, u8 txLen, u8 pktTxType ); +int app_rf_rx( u8 pktRxType ); +void app_rf_stop( void ); + +/*****************************************api*************************************/ +void bt_mesh_reset(void); + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/MESH_LIB/MESH_LIB.lib b/src/EXAM/BLE/MESH/MESH_LIB/MESH_LIB.lib new file mode 100644 index 0000000..b0c532b Binary files /dev/null and b/src/EXAM/BLE/MESH/MESH_LIB/MESH_LIB.lib differ diff --git a/src/EXAM/BLE/MESH/adv_ali_light/APP/app.c b/src/EXAM/BLE/MESH/adv_ali_light/APP/app.c new file mode 100644 index 0000000..7ff55c9 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light/APP/app.c @@ -0,0 +1,570 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" +#include "app.h" +#include "HAL.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void prov_reset(void); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +static struct bt_mesh_health_srv health_srv; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), + BLE_MESH_MODEL(BLE_MESH_MODEL_ID_GEN_ONOFF_SRV, gen_onoff_op, NULL, NULL), +}; + +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = tm_uuid, + .static_val_len = ARRAY_SIZE(static_key), + .static_val = static_key, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .reset = prov_reset, +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : silen_adv_set +* Description : þĬ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void silen_adv_set(u8_t flag) +{ + tm_uuid[13] &= ~BIT(0); + tm_uuid[13] |= (BIT_MASK(1) & flag); +} + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + silen_adv_set(SELENCE_ADV_OF); + + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } + + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, ADV_TIMEOUT); +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkصֹͣ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(" "); + + tmos_stop_task(App_TaskID, APP_SILENT_ADV_EVT); +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : None +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + prov_enable(); + } + else + { + /*è鲻·Config_model_app_bindConfig_Model_Subscrption_AddϢ + IOT豸ҪиElementmodel·AppKeyݲƷΪ + modelӦ鲥ַƷ鲥ַĸƷ淶Mesh豸 + ҪϢϱϱϢ豸ֵ֧Ŀϱԡ*/ + + /* For Light Subscription group address */ + root_models[2].groups[0] = (u16_t)0xC000; + root_models[2].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&root_models[2]); + + root_models[2].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&root_models[2]); + + /* For Light Subscription group address */ + vnd_models[0].groups[0] = (u16_t)0xC000; + vnd_models[0].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&vnd_models[0]); + + vnd_models[0].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&vnd_models[0]); + } +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص¿ʼ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + /* 豸ϵҲҪ1~10sϱֵ֧״̬ */ + tmosTimer rand_timer; + APP_DBG(" "); + + rand_timer = K_SECONDS(5) + (tmos_rand() % K_SECONDS(6)); + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, rand_timer); +} + +/******************************************************************************* +* Function Name : prov_reset +* Description : λܻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_reset(void) +{ + APP_DBG(""); + + prov_enable(); +} + +/******************************************************************************* +* Function Name : ind_end_cb +* Description : ͸λ¼ɻص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_end_cb(int err, void *cb_data) +{ + APP_DBG(" bt_mesh_reset "); + bt_mesh_reset(); +} + +static const struct bt_adv_ind_send_cb reset_cb = { + .end = ind_end_cb, +}; + +/******************************************************************************* +* Function Name : send_support_attr +* Description : ֵ֧ĿϱԸè,Ϣèж豸֧Щ +* Input : None +* Return : None +*******************************************************************************/ +void senf_support_attr(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 32 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + // ӿ + { + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + } +// // ѡݰõIJƷԹӶӦ ( BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET ) +// // ο,ҪӶӦopcode,ӷʽοԵ gen_onoff_op ṹ +// { +// /* Add brightness attrbute opcode */ +// net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_BRIGHTNESS); + +// /* Add brightness status (655~65535Ӧè1~100) */ +// net_buf_simple_add_le16(&(ind->buf->b), 65535); +// } + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : send_led_state +* Description : ͵ǰƵ״̬è +* Input : None +* Return : None +*******************************************************************************/ +void send_led_state(void) +{ + APP_DBG(""); + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .send_ttl = BLE_MESH_TTL_DEFAULT, + .tid = als_avail_tid_get(), + }; + + toggle_led_state(MSG_PIN); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + send_led_indicate(¶m); +} + +/******************************************************************************* +* Function Name : send_reset_indicate +* Description : ͸λ¼è飬ɺ״̬mesh +* Input : None +* Return : None +*******************************************************************************/ +void send_reset_indicate(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.cb = &reset_cb; + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + /* Add event report opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_EVENT_TRIGGER); + + /* Add reset event */ + net_buf_simple_add_u8(&(ind->buf->b), ALI_GEN_ATTR_TYPE_HARDWARE_RESET); + + bt_mesh_indicate_send(ind); +} + +#define HAL_KEY_SEND_MSG BIT(0) +#define HAL_KEY_RESET BIT(1) + +/******************************************************************************* +* Function Name : keyPress +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void keyPress(uint8 keys) +{ + APP_DBG("keys : %d ",keys); + + switch (keys) + { + case HAL_KEY_SEND_MSG: + send_led_state(); + break; + case HAL_KEY_RESET: + send_reset_indicate(); + break; + } +} + +/******************************************************************************* +* Function Name : app_silent_adv +* Description : ʱδɹ뾲Ĭ㲥ģʽ,ֵ֧Ըè +* Input : None +* Return : None +*******************************************************************************/ +static void app_silent_adv(void) +{ + APP_DBG(""); + if (bt_mesh_is_provisioned()) + { + senf_support_attr(); + return; + } + + silen_adv_set(SELENCE_ADV_ON); + + /* Disable Scanner not response Provisioner message */ + bt_mesh_scan_disable(); +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + APP_DBG("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MacAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress ); + set_led_state(MSG_PIN, 0); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_SILENT_ADV_EVT ) + { + app_silent_adv(); + return ( events ^ APP_SILENT_ADV_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light/APP/app_generic_onoff_model.c b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_generic_onoff_model.c new file mode 100644 index 0000000..c6e350b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_generic_onoff_model.c @@ -0,0 +1,187 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_generic_onoff_model.h" +#include "app_vendor_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +#define ALI_DEF_TTL (10) + +/******************************************************************************* +* Function Name : read_led_state +* Description : ȡǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : õǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : תǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + + +/******************************************************************************* +* Function Name : gen_onoff_status +* Description : ظè鿪״̬ +* Input : model: ģͲ +* ctxݲ +* Return : None +*******************************************************************************/ +static void gen_onoff_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx) +{ + NET_BUF_SIMPLE_DEFINE(msg, 32); + int err; + + bt_mesh_model_msg_init(&msg, BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS); + net_buf_simple_add_u8(&msg, read_led_state(MSG_PIN)); + + APP_DBG("ttl: 0x%02x dst: 0x%04x", ctx->recv_ttl, ctx->recv_dst); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + ctx->send_ttl = BLE_MESH_TTL_DEFAULT; + } + else + { + ctx->send_ttl = 0; + } + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : gen_onoff_get +* Description : è·Ļȡ״̬ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + + gen_onoff_status(model, ctx); +} + + +/******************************************************************************* +* Function Name : gen_onoff_set +* Description : è·ÿ״̬ + 뵱ǰ״̬ͬ,Ҫindè +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .rand = (tmos_rand() % 50), + .tid = als_avail_tid_get(), + }; + + APP_DBG("ttl: 0x%02x dst: 0x%04x rssi: %d", + ctx->recv_ttl, ctx->recv_dst, ctx->recv_rssi); + + set_led_state(MSG_PIN, buf->data[0]); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + param.send_ttl = BLE_MESH_TTL_DEFAULT; + } + + /* Overwrite default configuration */ + if (BLE_MESH_ADDR_IS_UNICAST(ctx->recv_dst)) + { + param.rand = 0; + param.send_ttl = BLE_MESH_TTL_DEFAULT; + param.period = K_MSEC(100); + } + + send_led_indicate(¶m); + + gen_onoff_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_onoff_set_unack +* Description : è·ÿ״̬(Ӧ) +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t status; + + APP_DBG(" "); + + status = read_led_state(MSG_PIN); + if (status != buf->data[0]) + { + set_led_state(MSG_PIN, buf->data[0]); + } +} + +const struct bt_mesh_model_op gen_onoff_op[] = { + {BLE_MESH_MODEL_OP_GEN_ONOFF_GET, 0, gen_onoff_get}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET, 2, gen_onoff_set}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK, 2, gen_onoff_set_unack}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light/APP/app_main.c b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light/APP/app_vendor_model.c b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_vendor_model.c new file mode 100644 index 0000000..1d703f3 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light/APP/app_vendor_model.c @@ -0,0 +1,532 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "CONFIG.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +///* Mac Address Light1 */ +//#define PID 7049884 +//#define MAC_ADDR {0x18,0x14,0x6c,0x49,0x54,0x98} +//#define ALI_SECRET {0x35,0x06,0xa0,0xe9,0x60,0xde,0xbd,0x59,0xcf,0xcc,0xce,0x11,0x2c,0x91,0xbf,0x3f} +/* Mac Address Light2 */ +#define PID 9701 +#define MAC_ADDR {0xf8,0xa7,0x63,0x6a,0xec,0x3f} +#define ALI_SECRET {0x6b,0xfa,0x68,0x6f,0x9d,0x1b,0x37,0x00,0x01,0xd1,0xfd,0xb8,0x27,0x7d,0xc0,0x81} + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +u8_t tm_uuid[16]; +u8_t static_key[16]; +u8C MacAddr[6] = MAC_ADDR; + +static const struct bt_als_cfg cfg = +{ + .mac = MAC_ADDR, + .secret = ALI_SECRET, + .pid = PID, + .cid = 0x01a8, + .version = 0x00060000, +}; + +static uint8 als_vendor_model_TaskID = 0; // Task ID for internal task/event processing + +static u8_t als_tid=0; + +static struct net_buf ind_buf[CONFIG_INDICATE_NUM]={0}; +static struct bt_mesh_indicate indicate[CONFIG_INDICATE_NUM]={0}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +static void ind_reset(struct bt_mesh_indicate *ind, int err); +static uint16 als_vendor_model_ProcessEvent( uint8 task_id, uint16 events ); + +static void tm_attr_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +/******************************************************************************* +* Function Name : tm_attr_confirm +* Description : յè鷢confirm - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_confirm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if (indicate[i].param.tid == recv_tid) + { + ind_reset(&indicate[i], 0); + tmos_stop_task(als_vendor_model_TaskID, indicate[i].event); + continue; + } + } +} + +/******************************************************************************* +* Function Name : tm_attr_trans +* Description : ϢMesh豸è֮͸ +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +// opcode ӦĴ +static const struct bt_mesh_model_op vnd_model_op[] = { + {OP_VENDOR_MESSAGE_ATTR_GET, 0, tm_attr_get}, + {OP_VENDOR_MESSAGE_ATTR_SET, 0, tm_attr_set}, + {OP_VENDOR_MESSAGE_ATTR_SET_UNACK, 0, tm_attr_set_unack}, + {OP_VENDOR_MESSAGE_ATTR_STATUS, 0, tm_attr_status}, + {OP_VENDOR_MESSAGE_ATTR_CONFIRMATION, 1, tm_attr_confirm}, + {OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG, 0, tm_attr_trans}, + BLE_MESH_MODEL_OP_END, +}; + +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_ALI_GENIE, 0x0000, vnd_model_op, NULL, NULL, &bt_mesh_als_vendor_model_cb), +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : als_avail_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t als_avail_tid_get(void) +{ + return als_tid++; +} + +/******************************************************************************* +* Function Name : uuid_generate +* Description : ɰ淶UUID +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void uuid_generate(struct bt_als_cfg const *cfg) +{ + /* Company ID */ + tm_uuid[0] = cfg->cid; + tm_uuid[1] = cfg->cid >> 8; + + /* bit30 㲥汾ţĿǰ0x01 + bit4Ϊ1һһ + bit5Ϊ1֧OTA + bit76Э汾 + 00BLE4.0 + 01BLE4.2 + 10BLE5.0 + 11BLE5.0 */ + /* Advertising Verison */ + tm_uuid[2] = BIT(0) | /* adv version */ + BIT(4) | /* secret */ + BIT(5) | /* ota */ + BIT(7); /* ble verison */ + + /* Product Id */ + tm_uuid[2 + 1] = cfg->pid; + tm_uuid[2 + 2] = cfg->pid >> 8; + tm_uuid[2 + 3] = cfg->pid >> 16; + tm_uuid[2 + 4] = cfg->pid >> 24; + + /* Device Mac Address */ + for(int i=0;i<6;i++) tm_uuid[2 + 1 + 4 + i] = cfg->mac[5-i]; + + /* UUID Verison */ + tm_uuid[2 + 1 + 4 + 6] = BIT(1); + + /* RFU */ + tm_uuid[2 + 1 + 4 + 6 + 1] = 0x00; + tm_uuid[2 + 1 + 4 + 6 + 2] = 0x00; +} + +/******************************************************************************* +* Function Name : num_to_str +* Description : תַ +* Input : +* Return : None +*******************************************************************************/ +static void num_to_str(u8_t *out, const u8_t *in, u16_t in_len) +{ + u16_t i; + static const char hex[] = "0123456789abcdef"; + + for (i = 0; i < in_len; i++) + { + out[i * 2] = hex[in[i] >> 4]; + out[i * 2 + 1] = hex[in[i] & 0xf]; + } +} + +/******************************************************************************* +* Function Name : oob_key_generate +* Description : OOB key +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void oob_key_generate(struct bt_als_cfg const *cfg) +{ + int err; + u32_t pid; + u8_t out[8 + 1 + 12 + 1 + 32], dig[32]; + struct tc_sha256_state_struct s; + + tc_sha256_init(&s); + + /** pid value */ + pid = ((u32_t)((((cfg->pid) >> 24) & 0xff) | \ + (((cfg->pid) >> 8) & 0xff00) | \ + (((cfg->pid)&0xff00) << 8) | \ + (((cfg->pid)&0xff) << 24))); + num_to_str(out, (void *)&pid, 4); + + /** Separator */ + strcpy((void *)(out + 8), ","); + /** mac value */ + num_to_str(out + 8 + 1, (void *)cfg->mac, 6); + + /** Separator */ + strcpy((void *)(out + 8 + 1 + 12), ","); + /** secret value */ + num_to_str(out + 8 + 1 + 12 + 1, (void *)cfg->secret, 16); + + err = tc_sha256_update(&s, out, sizeof(out)); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Update Sha256"); + return; + } + + err = tc_sha256_final(dig, &s); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Generate sha256 value"); + return; + } + + memcpy(static_key, dig, 16); +} + +/******************************************************************************* +* Function Name : ind_reset +* Description : Ƴб÷ɻصͷŻ +* Input : indҪõ֪ͨ + err +* Return : None +*******************************************************************************/ +static void ind_reset(struct bt_mesh_indicate *ind, int err) +{ + if (ind->param.cb && ind->param.cb->end) + { + ind->param.cb->end(err, ind->param.cb_data); + } + + tmos_msg_deallocate(ind->buf->__buf); + ind->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_reset +* Description : ͷδ͵֪ͨ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_reset(void) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf != NULL ) + { + ind_reset(&indicate[i], -ECANCELED); + } + } +} + +/******************************************************************************* +* Function Name : ind_start +* Description : indicate ʼص +* Input : durationηͽҪʱ + err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(als_vendor_model_TaskID, ind->event, K_MSEC(100) ); + return; + } +} + +/******************************************************************************* +* Function Name : ind_end +* Description : indicate ص +* Input : err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_end(int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.period ); +} + +// indicate صṹ +const struct bt_mesh_send_cb ind_cb = +{ + .start = ind_start, + .end = ind_end, +}; + +/******************************************************************************* +* Function Name : adv_ind_send +* Description : indicate +* Input : indҪ͵֪ͨ +* Return : None +*******************************************************************************/ +static void adv_ind_send(struct bt_mesh_indicate *ind) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, 32); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = vnd_models[0].keys[0], + .addr = ALI_TM_SUB_ADDRESS, + }; + + if (ind->buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (ind->param.trans_cnt == 0) + { + ind_reset(ind, -ETIMEDOUT); + return; + } + + ind->param.trans_cnt --; + + ctx.send_ttl = ind->param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, ind->buf->data, ind->buf->len); + + err = bt_mesh_model_send(vnd_models, &ctx, &msg, &ind_cb, ind); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + ind_reset(ind, -EIO); + return; + } +} + +/******************************************************************************* +* Function Name : bt_mesh_ind_allocһյ +* Description : һյindicateڴ +* Input : buf: Ҫ +* Return : indicateṹָ +*******************************************************************************/ +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf == NULL ) + break; + } + if( i == CONFIG_INDICATE_NUM ) + return NULL; + + indicate[i].buf->__buf = tmos_msg_allocate(len); + indicate[i].buf->size = len; + + if( indicate[i].buf->__buf == NULL ) + return NULL; + + return &indicate[i]; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_send +* Description : ֪ͨ¼ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ) +{ + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.rand ); +} + +/******************************************************************************* +* Function Name : send_led_indicate +* Description : ͵ǰLED״̬LED״̬ʱҪô˺ +* Input : param ֪ͨķͲ +* Return : None +*******************************************************************************/ +void send_led_indicate(struct indicate_param *param) +{ + struct bt_mesh_indicate *ind; + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + memcpy(&(ind->param), param, sizeof(struct indicate_param)); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), param->tid); + + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : als_vendor_init +* Description : ģ ʼ +* Input : model: صģͲ +* Return : None +*******************************************************************************/ +static int als_vendor_init(struct bt_mesh_model *model) +{ + u32_t ran; + + uuid_generate(&cfg); + oob_key_generate(&cfg); + + /** Random Local TID Value + * @Caution Don't use single octer only. + */ + ran = tmos_rand(); + als_tid += ((u8_t *)&ran)[0]; + als_tid += ((u8_t *)&ran)[1]; + als_tid += ((u8_t *)&ran)[2]; + als_tid += ((u8_t *)&ran)[3]; + + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + indicate[i].buf = &ind_buf[i]; + indicate[i].event = (1< ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light/APP/include/app_vendor_model.h b/src/EXAM/BLE/MESH/adv_ali_light/APP/include/app_vendor_model.h new file mode 100644 index 0000000..3d6fc85 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light/APP/include/app_vendor_model.h @@ -0,0 +1,134 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_H +#define app_vendor_model_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/******************************************************************************/ + +#include "MESH_LIB.h" + +/******************************************************************************/ + +#define CID_ALI_GENIE 0x01A8 + +#define OP_VENDOR_MESSAGE_ATTR_GET BLE_MESH_MODEL_OP_3(0xD0, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET BLE_MESH_MODEL_OP_3(0xD1, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET_UNACK BLE_MESH_MODEL_OP_3(0xD2, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_STATUS BLE_MESH_MODEL_OP_3(0xD3, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_INDICATION BLE_MESH_MODEL_OP_3(0xD4, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_CONFIRMATION BLE_MESH_MODEL_OP_3(0xD5, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_ALI_GENIE) + +#define ALI_SYS_ATTR_TYPE_ERROR 0x0000 +#define ALI_SYS_ATTR_TYPE_VERSION 0xFF01 +#define ALI_SYS_ATTR_TYPE_DEV_FEATURE 0xFF02 +#define ALI_SYS_ATTR_TYPE_TOTAL_FLASH_SIZE 0xFF03 +#define ALI_SYS_ATTR_TYPE_USED_FLASH_SIZE 0xFF04 +#define ALI_SYS_ATTR_TYPE_FREE_FLASH_SIZE 0xFF05 +#define ALI_SYS_ATTR_TYPE_ENGINEER_MODE 0xFF06 + +#define ALI_GEN_ATTR_TYPE_WORK_STATUS 0xF001 +#define ALI_GEN_ATTR_TYPE_USER_ID 0xF002 +#define ALI_GEN_ATTR_TYPE_DEVICE_NAME 0xF003 +#define ALI_GEN_ATTR_TYPE_MODE_NUMBER 0xF004 +#define ALI_GEN_ATTR_TYPE_ONOFF_PLAN 0xF008 +#define ALI_GEN_ATTR_TYPE_EVENT_TRIGGER 0xF009 +#define ALI_GEN_ATTR_TYPE_EVENT_CLEAR 0xF019 +#define ALI_GEN_ATTR_TYPE_SIGNAL_INTENSITY 0xF00A +#define ALI_GEN_ATTR_TYPE_DELTA_VALUE 0xF00B +#define ALI_GEN_ATTR_TYPE_ELEMENT_COUNT 0xF00C +#define ALI_GEN_ATTR_TYPE_ATTR_SWITCH 0xF00D +#define ALI_GEN_ATTR_TYPE_REMOTE_ADDRESS 0xF00E +#define ALI_GEN_ATTR_TYPE_NEARBY_SIGNAL_INTEN 0xF00F +#define ALI_GEN_ATTR_TYPE_SET_VALUE_TIMING 0xF010 +#define ALI_GEN_ATTR_TYPE_SET_VALUE_PERIODIC 0xF011 +#define ALI_GEN_ATTR_TYPE_DEL_TIMING 0xF012 +#define ALI_GEN_ATTR_TYPE_REQ_UPDATE_TIMING 0xF013 +#define ALI_GEN_ATTR_TYPE_SETTING_TIMING 0xF01D +#define ALI_GEN_ATTR_TYPE_TIME_ZONE 0xF01E +#define ALI_GEN_ATTR_TYPE_UNIX_TIMER 0xF01F +#define ALI_GEN_ATTR_TYPE_POWERDOWN_MEM 0xF021 +#define ALI_GEN_ATTR_TYPE_CALORIES 0x06D5 +#define ALI_GEN_ATTR_TYPE_SPORTCOUNT 0x0212 +#define ALI_GEN_ATTR_TYPE_POWER_STATE 0x0100 +#define ALI_GEN_ATTR_TYPE_BRIGHTNESS 0x0121 +#define ALI_GEN_ATTR_TYPE_HARDWARE_RESET 0x0023 + +#define ALI_TM_SUB_ADDRESS 0xF000 + +/** Default number of Indication */ +#define CONFIG_INDICATE_NUM (3) + +/******************************************************************************/ + +struct bt_adv_ind_send_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + +struct indicate_param +{ + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_ind_send_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct indicate_param param; + struct net_buf *buf; + uint8 event; +}; + +struct bt_als_cfg +{ + /** Company Identify */ + u16_t cid; + + /** Product Identify */ + u32_t pid; + + /** Mac Address */ + u8_t mac[6]; + + /** Secret Information */ + u8_t secret[16]; + + /** Currently Library Version */ + u32_t version; +}; + +extern struct bt_mesh_model vnd_models[1]; +extern u8_t static_key[16]; +extern u8_t tm_uuid[16]; +extern const struct bt_mesh_model_cb bt_mesh_als_vendor_model_cb; +/******************************************************************************/ +u8_t als_avail_tid_get(void); +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ); +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ); +void send_led_indicate(struct indicate_param *param); +void bt_mesh_indicate_reset(void); + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_ali_light/Project/BLE.uvprojx new file mode 100644 index 0000000..5134157 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light/Project/BLE.uvprojx @@ -0,0 +1,582 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model.c + 1 + ..\APP\app_vendor_model.c + + + app_generic_onoff_model.c + 1 + ..\APP\app_generic_onoff_model.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app.c b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app.c new file mode 100644 index 0000000..42f10c2 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app.c @@ -0,0 +1,580 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" +#include "app_generic_lightness_model.h" +#include "app.h" +#include "HAL.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void prov_reset(void); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +static struct bt_mesh_health_srv health_srv; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), + BLE_MESH_MODEL(BLE_MESH_MODEL_ID_GEN_ONOFF_SRV, gen_onoff_op, NULL, NULL), + BLE_MESH_MODEL(BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV, gen_lightness_op, NULL, NULL), +}; + +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = tm_uuid, + .static_val_len = ARRAY_SIZE(static_key), + .static_val = static_key, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .reset = prov_reset, +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : silen_adv_set +* Description : þĬ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void silen_adv_set(u8_t flag) +{ + tm_uuid[13] &= ~BIT(0); + tm_uuid[13] |= (BIT_MASK(1) & flag); +} + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + silen_adv_set(SELENCE_ADV_OF); + + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } + + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, ADV_TIMEOUT); +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkصֹͣ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(" "); + + tmos_stop_task(App_TaskID, APP_SILENT_ADV_EVT); +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : None +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + prov_enable(); + } + else + { + /*è鲻·Config_model_app_bindConfig_Model_Subscrption_AddϢ + IOT豸ҪиElementmodel·AppKeyݲƷΪ + modelӦ鲥ַƷ鲥ַĸƷ淶Mesh豸 + ҪϢϱϱϢ豸ֵ֧Ŀϱԡ*/ + + /* For Light Subscription group address */ + root_models[2].groups[0] = (u16_t)0xC000; + root_models[2].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&root_models[2]); + + root_models[2].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&root_models[2]); + + /* For Light Subscription group address */ + root_models[3].groups[0] = (u16_t)0xC000; + root_models[3].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&root_models[3]); + + root_models[3].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&root_models[3]); + + /* For Light Subscription group address */ + vnd_models[0].groups[0] = (u16_t)0xC000; + vnd_models[0].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&vnd_models[0]); + + vnd_models[0].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&vnd_models[0]); + } +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص¿ʼ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + /* 豸ϵҲҪ1~10sϱֵ֧״̬ */ + tmosTimer rand_timer; + APP_DBG(" "); + + rand_timer = K_SECONDS(5) + (tmos_rand() % K_SECONDS(6)); + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, rand_timer); +} + +/******************************************************************************* +* Function Name : prov_reset +* Description : λܻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_reset(void) +{ + APP_DBG(""); + + prov_enable(); +} + +/******************************************************************************* +* Function Name : ind_end_cb +* Description : ͸λ¼ɻص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_end_cb(int err, void *cb_data) +{ + APP_DBG(" bt_mesh_reset "); + bt_mesh_reset(); +} + +static const struct bt_adv_ind_send_cb reset_cb = { + .end = ind_end_cb, +}; + +/******************************************************************************* +* Function Name : send_support_attr +* Description : ֵ֧ĿϱԸè,Ϣèж豸֧Щ +* Input : None +* Return : None +*******************************************************************************/ +void senf_support_attr(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 32 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + // ӿ + { + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + } + // ѡݰõIJƷԹӶӦ ( BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET ) + // ο,ҪӶӦopcode,ӷʽοԵ gen_onoff_op ṹ + { + /* Add brightness attrbute opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_BRIGHTNESS); + + /* Add brightness status (655~65535Ӧè1~100) */ + net_buf_simple_add_le16(&(ind->buf->b), 65535); + } + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : send_led_state +* Description : ͵ǰƵ״̬è +* Input : None +* Return : None +*******************************************************************************/ +void send_led_state(void) +{ + APP_DBG(""); + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .send_ttl = BLE_MESH_TTL_DEFAULT, + .tid = als_avail_tid_get(), + }; + + toggle_led_state(MSG_PIN); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + send_led_indicate(¶m); +} + +/******************************************************************************* +* Function Name : send_reset_indicate +* Description : ͸λ¼è飬ɺ״̬mesh +* Input : None +* Return : None +*******************************************************************************/ +void send_reset_indicate(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.cb = &reset_cb; + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + /* Add event report opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_EVENT_TRIGGER); + + /* Add reset event */ + net_buf_simple_add_u8(&(ind->buf->b), ALI_GEN_ATTR_TYPE_HARDWARE_RESET); + + bt_mesh_indicate_send(ind); +} + +#define HAL_KEY_SEND_MSG BIT(0) +#define HAL_KEY_RESET BIT(1) + +/******************************************************************************* +* Function Name : keyPress +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void keyPress(uint8 keys) +{ + APP_DBG("keys : %d ",keys); + + switch (keys) + { + case HAL_KEY_SEND_MSG: + send_led_state(); + break; + case HAL_KEY_RESET: + send_reset_indicate(); + break; + } +} + +/******************************************************************************* +* Function Name : app_silent_adv +* Description : ʱδɹ뾲Ĭ㲥ģʽ,ֵ֧Ըè +* Input : None +* Return : None +*******************************************************************************/ +static void app_silent_adv(void) +{ + APP_DBG(""); + if (bt_mesh_is_provisioned()) + { + senf_support_attr(); + return; + } + + silen_adv_set(SELENCE_ADV_ON); + + /* Disable Scanner not response Provisioner message */ + bt_mesh_scan_disable(); +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + APP_DBG("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MacAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress ); + set_led_state(MSG_PIN, 0); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_SILENT_ADV_EVT ) + { + app_silent_adv(); + return ( events ^ APP_SILENT_ADV_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_generic_lightness_model.c b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_generic_lightness_model.c new file mode 100644 index 0000000..dce624b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_generic_lightness_model.c @@ -0,0 +1,177 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_generic_lightness_model.h" +#include "app_vendor_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +#define ALI_DEF_TTL (10) + +// ģֵ +u16_t led_lightness = 100; + +/******************************************************************************* +* Function Name : read_led_lightness +* Description : ȡǰ +* Input : None +* Return : None +*******************************************************************************/ +u16_t read_led_lightness(u32_t led_pin) +{ + APP_DBG("led_lightness: %d ",led_lightness); + return led_lightness; +} + +/******************************************************************************* +* Function Name : set_led_lightness +* Description : õǰ +* Input : None +* Return : None +*******************************************************************************/ +void set_led_lightness(u32_t led_pin, u16_t lightness) +{ + led_lightness = lightness; +} + +/******************************************************************************* +* Function Name : gen_lightness_status +* Description : ظè +* Input : model: ģͲ +* ctxݲ +* Return : None +*******************************************************************************/ +static void gen_lightness_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx) +{ + NET_BUF_SIMPLE_DEFINE(msg, 32); + int err; + + bt_mesh_model_msg_init(&msg, BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS); + net_buf_simple_add_le16(&msg, read_led_lightness(MSG_PIN)); + + APP_DBG("ttl: 0x%02x dst: 0x%04x", ctx->recv_ttl, ctx->recv_dst); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + ctx->send_ttl = BLE_MESH_TTL_DEFAULT; + } + else + { + ctx->send_ttl = 0; + } + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : gen_onoff_get +* Description : è·Ļȡ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_lightness_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + + gen_lightness_status(model, ctx); +} + + +/******************************************************************************* +* Function Name : gen_lightness_set +* Description : è· + 뵱ǰȲͬ,Ҫindè +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_lightness_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .rand = (tmos_rand() % 50), + .tid = als_avail_tid_get(), + }; + + APP_DBG("ttl: 0x%02x dst: 0x%04x rssi: %d lightness: %d", + ctx->recv_ttl, ctx->recv_dst, ctx->recv_rssi, buf->data[0]|(buf->data[1]<<8)); + + set_led_lightness(MSG_PIN, buf->data[0]|(buf->data[1]<<8)); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + param.send_ttl = BLE_MESH_TTL_DEFAULT; + } + + /* Overwrite default configuration */ + if (BLE_MESH_ADDR_IS_UNICAST(ctx->recv_dst)) + { + param.rand = 0; + param.send_ttl = BLE_MESH_TTL_DEFAULT; + param.period = K_MSEC(100); + } + + send_lightness_indicate(¶m); + + gen_lightness_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_lightness_set_unack +* Description : è·(Ӧ) +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_lightness_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u16_t lightness; + + APP_DBG(" "); + + lightness = read_led_lightness(MSG_PIN); + if (lightness != (buf->data[0]|(buf->data[1]<<8))) + { + set_led_lightness(MSG_PIN, buf->data[0]|(buf->data[1]<<8)); + } +} + +const struct bt_mesh_model_op gen_lightness_op[] = { + {BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET, 0, gen_lightness_get}, + {BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET, 3, gen_lightness_set}, + {BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK, 3, gen_lightness_set_unack}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_generic_onoff_model.c b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_generic_onoff_model.c new file mode 100644 index 0000000..c6e350b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_generic_onoff_model.c @@ -0,0 +1,187 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_generic_onoff_model.h" +#include "app_vendor_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +#define ALI_DEF_TTL (10) + +/******************************************************************************* +* Function Name : read_led_state +* Description : ȡǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : õǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : תǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + + +/******************************************************************************* +* Function Name : gen_onoff_status +* Description : ظè鿪״̬ +* Input : model: ģͲ +* ctxݲ +* Return : None +*******************************************************************************/ +static void gen_onoff_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx) +{ + NET_BUF_SIMPLE_DEFINE(msg, 32); + int err; + + bt_mesh_model_msg_init(&msg, BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS); + net_buf_simple_add_u8(&msg, read_led_state(MSG_PIN)); + + APP_DBG("ttl: 0x%02x dst: 0x%04x", ctx->recv_ttl, ctx->recv_dst); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + ctx->send_ttl = BLE_MESH_TTL_DEFAULT; + } + else + { + ctx->send_ttl = 0; + } + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : gen_onoff_get +* Description : è·Ļȡ״̬ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + + gen_onoff_status(model, ctx); +} + + +/******************************************************************************* +* Function Name : gen_onoff_set +* Description : è·ÿ״̬ + 뵱ǰ״̬ͬ,Ҫindè +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .rand = (tmos_rand() % 50), + .tid = als_avail_tid_get(), + }; + + APP_DBG("ttl: 0x%02x dst: 0x%04x rssi: %d", + ctx->recv_ttl, ctx->recv_dst, ctx->recv_rssi); + + set_led_state(MSG_PIN, buf->data[0]); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + param.send_ttl = BLE_MESH_TTL_DEFAULT; + } + + /* Overwrite default configuration */ + if (BLE_MESH_ADDR_IS_UNICAST(ctx->recv_dst)) + { + param.rand = 0; + param.send_ttl = BLE_MESH_TTL_DEFAULT; + param.period = K_MSEC(100); + } + + send_led_indicate(¶m); + + gen_onoff_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_onoff_set_unack +* Description : è·ÿ״̬(Ӧ) +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t status; + + APP_DBG(" "); + + status = read_led_state(MSG_PIN); + if (status != buf->data[0]) + { + set_led_state(MSG_PIN, buf->data[0]); + } +} + +const struct bt_mesh_model_op gen_onoff_op[] = { + {BLE_MESH_MODEL_OP_GEN_ONOFF_GET, 0, gen_onoff_get}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET, 2, gen_onoff_set}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK, 2, gen_onoff_set_unack}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_main.c b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_vendor_model.c b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_vendor_model.c new file mode 100644 index 0000000..cb6a02c --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/app_vendor_model.c @@ -0,0 +1,566 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "CONFIG.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" +#include "app_generic_lightness_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +/* Mac Address Light1 */ +#define PID 7049884 +#define MAC_ADDR {0x18,0x14,0x6c,0x49,0x54,0x98} +#define ALI_SECRET {0x35,0x06,0xa0,0xe9,0x60,0xde,0xbd,0x59,0xcf,0xcc,0xce,0x11,0x2c,0x91,0xbf,0x3f} +///* Mac Address Light2 */ +//#define PID 9701 +//#define MAC_ADDR {0xf8,0xa7,0x63,0x6a,0xec,0x3f} +//#define ALI_SECRET {0x6b,0xfa,0x68,0x6f,0x9d,0x1b,0x37,0x00,0x01,0xd1,0xfd,0xb8,0x27,0x7d,0xc0,0x81} + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +u8_t tm_uuid[16]; +u8_t static_key[16]; +u8C MacAddr[6] = MAC_ADDR; + +static const struct bt_als_cfg cfg = +{ + .mac = MAC_ADDR, + .secret = ALI_SECRET, + .pid = PID, + .cid = 0x01a8, + .version = 0x00060000, +}; + +static uint8 als_vendor_model_TaskID = 0; // Task ID for internal task/event processing + +static u8_t als_tid=0; + +static struct net_buf ind_buf[CONFIG_INDICATE_NUM]={0}; +static struct bt_mesh_indicate indicate[CONFIG_INDICATE_NUM]={0}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +static void ind_reset(struct bt_mesh_indicate *ind, int err); +static uint16 als_vendor_model_ProcessEvent( uint8 task_id, uint16 events ); + +static void tm_attr_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +/******************************************************************************* +* Function Name : tm_attr_confirm +* Description : յè鷢confirm - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_confirm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if (indicate[i].param.tid == recv_tid) + { + ind_reset(&indicate[i], 0); + tmos_stop_task(als_vendor_model_TaskID, indicate[i].event); + continue; + } + } +} + +/******************************************************************************* +* Function Name : tm_attr_trans +* Description : ϢMesh豸è֮͸ +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +// opcode ӦĴ +static const struct bt_mesh_model_op vnd_model_op[] = { + {OP_VENDOR_MESSAGE_ATTR_GET, 0, tm_attr_get}, + {OP_VENDOR_MESSAGE_ATTR_SET, 0, tm_attr_set}, + {OP_VENDOR_MESSAGE_ATTR_SET_UNACK, 0, tm_attr_set_unack}, + {OP_VENDOR_MESSAGE_ATTR_STATUS, 0, tm_attr_status}, + {OP_VENDOR_MESSAGE_ATTR_CONFIRMATION, 1, tm_attr_confirm}, + {OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG, 0, tm_attr_trans}, + BLE_MESH_MODEL_OP_END, +}; + +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_ALI_GENIE, 0x0000, vnd_model_op, NULL, NULL, &bt_mesh_als_vendor_model_cb), +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : als_avail_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t als_avail_tid_get(void) +{ + return als_tid++; +} + +/******************************************************************************* +* Function Name : uuid_generate +* Description : ɰ淶UUID +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void uuid_generate(struct bt_als_cfg const *cfg) +{ + /* Company ID */ + tm_uuid[0] = cfg->cid; + tm_uuid[1] = cfg->cid >> 8; + + /* bit30 㲥汾ţĿǰ0x01 + bit4Ϊ1һһ + bit5Ϊ1֧OTA + bit76Э汾 + 00BLE4.0 + 01BLE4.2 + 10BLE5.0 + 11BLE5.0 */ + /* Advertising Verison */ + tm_uuid[2] = BIT(0) | /* adv version */ + BIT(4) | /* secret */ + BIT(5) | /* ota */ + BIT(7); /* ble verison */ + + /* Product Id */ + tm_uuid[2 + 1] = cfg->pid; + tm_uuid[2 + 2] = cfg->pid >> 8; + tm_uuid[2 + 3] = cfg->pid >> 16; + tm_uuid[2 + 4] = cfg->pid >> 24; + + /* Device Mac Address */ + for(int i=0;i<6;i++) tm_uuid[2 + 1 + 4 + i] = cfg->mac[5-i]; + + /* UUID Verison */ + tm_uuid[2 + 1 + 4 + 6] = BIT(1); + + /* RFU */ + tm_uuid[2 + 1 + 4 + 6 + 1] = 0x00; + tm_uuid[2 + 1 + 4 + 6 + 2] = 0x00; +} + +/******************************************************************************* +* Function Name : num_to_str +* Description : תַ +* Input : +* Return : None +*******************************************************************************/ +static void num_to_str(u8_t *out, const u8_t *in, u16_t in_len) +{ + u16_t i; + static const char hex[] = "0123456789abcdef"; + + for (i = 0; i < in_len; i++) + { + out[i * 2] = hex[in[i] >> 4]; + out[i * 2 + 1] = hex[in[i] & 0xf]; + } +} + +/******************************************************************************* +* Function Name : oob_key_generate +* Description : OOB key +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void oob_key_generate(struct bt_als_cfg const *cfg) +{ + int err; + u32_t pid; + u8_t out[8 + 1 + 12 + 1 + 32], dig[32]; + struct tc_sha256_state_struct s; + + tc_sha256_init(&s); + + /** pid value */ + pid = ((u32_t)((((cfg->pid) >> 24) & 0xff) | \ + (((cfg->pid) >> 8) & 0xff00) | \ + (((cfg->pid)&0xff00) << 8) | \ + (((cfg->pid)&0xff) << 24))); + num_to_str(out, (void *)&pid, 4); + + /** Separator */ + strcpy((void *)(out + 8), ","); + /** mac value */ + num_to_str(out + 8 + 1, (void *)cfg->mac, 6); + + /** Separator */ + strcpy((void *)(out + 8 + 1 + 12), ","); + /** secret value */ + num_to_str(out + 8 + 1 + 12 + 1, (void *)cfg->secret, 16); + + err = tc_sha256_update(&s, out, sizeof(out)); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Update Sha256"); + return; + } + + err = tc_sha256_final(dig, &s); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Generate sha256 value"); + return; + } + + memcpy(static_key, dig, 16); +} + +/******************************************************************************* +* Function Name : ind_reset +* Description : Ƴб÷ɻصͷŻ +* Input : indҪõ֪ͨ + err +* Return : None +*******************************************************************************/ +static void ind_reset(struct bt_mesh_indicate *ind, int err) +{ + if (ind->param.cb && ind->param.cb->end) + { + ind->param.cb->end(err, ind->param.cb_data); + } + + tmos_msg_deallocate(ind->buf->__buf); + ind->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_reset +* Description : ͷδ͵֪ͨ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_reset(void) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf != NULL ) + { + ind_reset(&indicate[i], -ECANCELED); + } + } +} + +/******************************************************************************* +* Function Name : ind_start +* Description : indicate ʼص +* Input : durationηͽҪʱ + err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(als_vendor_model_TaskID, ind->event, K_MSEC(100) ); + return; + } +} + +/******************************************************************************* +* Function Name : ind_end +* Description : indicate ص +* Input : err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_end(int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.period ); +} + +// indicate صṹ +const struct bt_mesh_send_cb ind_cb = +{ + .start = ind_start, + .end = ind_end, +}; + +/******************************************************************************* +* Function Name : adv_ind_send +* Description : indicate +* Input : indҪ͵֪ͨ +* Return : None +*******************************************************************************/ +static void adv_ind_send(struct bt_mesh_indicate *ind) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, 32); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = vnd_models[0].keys[0], + .addr = ALI_TM_SUB_ADDRESS, + }; + + if (ind->buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (ind->param.trans_cnt == 0) + { + ind_reset(ind, -ETIMEDOUT); + return; + } + + ind->param.trans_cnt --; + + ctx.send_ttl = ind->param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, ind->buf->data, ind->buf->len); + + err = bt_mesh_model_send(vnd_models, &ctx, &msg, &ind_cb, ind); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + ind_reset(ind, -EIO); + return; + } +} + +/******************************************************************************* +* Function Name : bt_mesh_ind_allocһյ +* Description : һյindicateڴ +* Input : buf: Ҫ +* Return : indicateṹָ +*******************************************************************************/ +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf == NULL ) + break; + } + if( i == CONFIG_INDICATE_NUM ) + return NULL; + + indicate[i].buf->__buf = tmos_msg_allocate(len); + indicate[i].buf->size = len; + + if( indicate[i].buf->__buf == NULL ) + return NULL; + + return &indicate[i]; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_send +* Description : ֪ͨ¼ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ) +{ + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.rand ); +} + +/******************************************************************************* +* Function Name : send_led_indicate +* Description : ͵ǰLED״̬LED״̬ʱҪô˺ +* Input : param ֪ͨķͲ +* Return : None +*******************************************************************************/ +void send_led_indicate(struct indicate_param *param) +{ + struct bt_mesh_indicate *ind; + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + memcpy(&(ind->param), param, sizeof(struct indicate_param)); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), param->tid); + + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : send_lightness_indicate +* Description : ͵ǰLEDȣLEDȸʱҪô˺ +* Input : param ֪ͨķͲ +* Return : None +*******************************************************************************/ +void send_lightness_indicate(struct indicate_param *param) +{ + struct bt_mesh_indicate *ind; + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + memcpy(&(ind->param), param, sizeof(struct indicate_param)); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), param->tid); + + /* Add brightness attrbute opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_BRIGHTNESS); + + /* Add brightness status (655~65535Ӧè1~100) */ + net_buf_simple_add_le16(&(ind->buf->b), read_led_lightness(MSG_PIN)); + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : als_vendor_init +* Description : ģ ʼ +* Input : model: صģͲ +* Return : None +*******************************************************************************/ +static int als_vendor_init(struct bt_mesh_model *model) +{ + u32_t ran; + + uuid_generate(&cfg); + oob_key_generate(&cfg); + + /** Random Local TID Value + * @Caution Don't use single octer only. + */ + ran = tmos_rand(); + als_tid += ((u8_t *)&ran)[0]; + als_tid += ((u8_t *)&ran)[1]; + als_tid += ((u8_t *)&ran)[2]; + als_tid += ((u8_t *)&ran)[3]; + + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + indicate[i].buf = &ind_buf[i]; + indicate[i].event = (1< ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/include/app_vendor_model.h b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/include/app_vendor_model.h new file mode 100644 index 0000000..925791a --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/APP/include/app_vendor_model.h @@ -0,0 +1,136 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_H +#define app_vendor_model_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/******************************************************************************/ + +#include "MESH_LIB.h" + +/******************************************************************************/ + +#define CID_ALI_GENIE 0x01A8 + +#define OP_VENDOR_MESSAGE_ATTR_GET BLE_MESH_MODEL_OP_3(0xD0, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET BLE_MESH_MODEL_OP_3(0xD1, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET_UNACK BLE_MESH_MODEL_OP_3(0xD2, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_STATUS BLE_MESH_MODEL_OP_3(0xD3, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_INDICATION BLE_MESH_MODEL_OP_3(0xD4, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_CONFIRMATION BLE_MESH_MODEL_OP_3(0xD5, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_ALI_GENIE) + +#define ALI_SYS_ATTR_TYPE_ERROR 0x0000 +#define ALI_SYS_ATTR_TYPE_VERSION 0xFF01 +#define ALI_SYS_ATTR_TYPE_DEV_FEATURE 0xFF02 +#define ALI_SYS_ATTR_TYPE_TOTAL_FLASH_SIZE 0xFF03 +#define ALI_SYS_ATTR_TYPE_USED_FLASH_SIZE 0xFF04 +#define ALI_SYS_ATTR_TYPE_FREE_FLASH_SIZE 0xFF05 +#define ALI_SYS_ATTR_TYPE_ENGINEER_MODE 0xFF06 + +#define ALI_GEN_ATTR_TYPE_WORK_STATUS 0xF001 +#define ALI_GEN_ATTR_TYPE_USER_ID 0xF002 +#define ALI_GEN_ATTR_TYPE_DEVICE_NAME 0xF003 +#define ALI_GEN_ATTR_TYPE_MODE_NUMBER 0xF004 +#define ALI_GEN_ATTR_TYPE_ONOFF_PLAN 0xF008 +#define ALI_GEN_ATTR_TYPE_EVENT_TRIGGER 0xF009 +#define ALI_GEN_ATTR_TYPE_EVENT_CLEAR 0xF019 +#define ALI_GEN_ATTR_TYPE_SIGNAL_INTENSITY 0xF00A +#define ALI_GEN_ATTR_TYPE_DELTA_VALUE 0xF00B +#define ALI_GEN_ATTR_TYPE_ELEMENT_COUNT 0xF00C +#define ALI_GEN_ATTR_TYPE_ATTR_SWITCH 0xF00D +#define ALI_GEN_ATTR_TYPE_REMOTE_ADDRESS 0xF00E +#define ALI_GEN_ATTR_TYPE_NEARBY_SIGNAL_INTEN 0xF00F +#define ALI_GEN_ATTR_TYPE_SET_VALUE_TIMING 0xF010 +#define ALI_GEN_ATTR_TYPE_SET_VALUE_PERIODIC 0xF011 +#define ALI_GEN_ATTR_TYPE_DEL_TIMING 0xF012 +#define ALI_GEN_ATTR_TYPE_REQ_UPDATE_TIMING 0xF013 +#define ALI_GEN_ATTR_TYPE_SETTING_TIMING 0xF01D +#define ALI_GEN_ATTR_TYPE_TIME_ZONE 0xF01E +#define ALI_GEN_ATTR_TYPE_UNIX_TIMER 0xF01F +#define ALI_GEN_ATTR_TYPE_POWERDOWN_MEM 0xF021 +#define ALI_GEN_ATTR_TYPE_CALORIES 0x06D5 +#define ALI_GEN_ATTR_TYPE_SPORTCOUNT 0x0212 +#define ALI_GEN_ATTR_TYPE_POWER_STATE 0x0100 +#define ALI_GEN_ATTR_TYPE_BRIGHTNESS 0x0121 +#define ALI_GEN_ATTR_TYPE_HARDWARE_RESET 0x0023 + +#define ALI_TM_SUB_ADDRESS 0xF000 + +/** Default number of Indication */ +#define CONFIG_INDICATE_NUM (3) + +/******************************************************************************/ + +struct bt_adv_ind_send_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + +struct indicate_param +{ + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_ind_send_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct indicate_param param; + struct net_buf *buf; + uint8 event; +}; + +struct bt_als_cfg +{ + /** Company Identify */ + u16_t cid; + + /** Product Identify */ + u32_t pid; + + /** Mac Address */ + u8_t mac[6]; + + /** Secret Information */ + u8_t secret[16]; + + /** Currently Library Version */ + u32_t version; +}; + +extern struct bt_mesh_model vnd_models[1]; +extern u8_t static_key[16]; +extern u8_t tm_uuid[16]; +extern const struct bt_mesh_model_cb bt_mesh_als_vendor_model_cb; +/******************************************************************************/ +u8_t als_avail_tid_get(void); +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ); +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ); +void send_led_indicate(struct indicate_param *param); +void send_lightness_indicate(struct indicate_param *param); + +void bt_mesh_indicate_reset(void); + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/Project/BLE.uvprojx new file mode 100644 index 0000000..c0f6644 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_lightness/Project/BLE.uvprojx @@ -0,0 +1,587 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model.c + 1 + ..\APP\app_vendor_model.c + + + app_generic_onoff_model.c + 1 + ..\APP\app_generic_onoff_model.c + + + app_generic_lightness_model.c + 1 + ..\APP\app_generic_lightness_model.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app.c b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app.c new file mode 100644 index 0000000..2692b00 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app.c @@ -0,0 +1,570 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" +#include "app_als_windspeed_attr.h" +#include "app.h" +#include "HAL.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void prov_reset(void); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +static struct bt_mesh_health_srv health_srv; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), + BLE_MESH_MODEL(BLE_MESH_MODEL_ID_GEN_ONOFF_SRV, gen_onoff_op, NULL, NULL), +}; + +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = tm_uuid, + .static_val_len = ARRAY_SIZE(static_key), + .static_val = static_key, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .reset = prov_reset, +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : silen_adv_set +* Description : þĬ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void silen_adv_set(u8_t flag) +{ + tm_uuid[13] &= ~BIT(0); + tm_uuid[13] |= (BIT_MASK(1) & flag); +} + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + silen_adv_set(SELENCE_ADV_OF); + + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } + + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, ADV_TIMEOUT); +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkصֹͣ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(" "); + + tmos_stop_task(App_TaskID, APP_SILENT_ADV_EVT); +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : None +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + prov_enable(); + } + else + { + /*è鲻·Config_model_app_bindConfig_Model_Subscrption_AddϢ + IOT豸ҪиElementmodel·AppKeyݲƷΪ + modelӦ鲥ַƷ鲥ַĸƷ淶Mesh豸 + ҪϢϱϱϢ豸ֵ֧Ŀϱԡ*/ + + /* For Light Subscription group address */ + root_models[2].groups[0] = (u16_t)0xC000; + root_models[2].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&root_models[2]); + + root_models[2].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&root_models[2]); + + /* For Light Subscription group address */ + vnd_models[0].groups[0] = (u16_t)0xC000; + vnd_models[0].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&vnd_models[0]); + + vnd_models[0].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&vnd_models[0]); + } +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص¿ʼ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + /* 豸ϵҲҪ1~10sϱֵ֧״̬ */ + tmosTimer rand_timer; + APP_DBG(" "); + + rand_timer = K_SECONDS(5) + (tmos_rand() % K_SECONDS(6)); + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, rand_timer); +} + +/******************************************************************************* +* Function Name : prov_reset +* Description : λܻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_reset(void) +{ + APP_DBG(""); + + prov_enable(); +} + +/******************************************************************************* +* Function Name : ind_end_cb +* Description : ͸λ¼ɻص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_end_cb(int err, void *cb_data) +{ + APP_DBG(" bt_mesh_reset "); + bt_mesh_reset(); +} + +static const struct bt_adv_ind_send_cb reset_cb = { + .end = ind_end_cb, +}; + +/******************************************************************************* +* Function Name : send_support_attr +* Description : ֵ֧ĿϱԸè,Ϣèж豸֧Щ +* Input : None +* Return : None +*******************************************************************************/ +void senf_support_attr(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 32 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + // ӿ + { + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + } + // windspeed + { + /* Add windspeed attrbute opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_WINDSPEED); + + /* Add windspeed status */ + net_buf_simple_add_u8(&(ind->buf->b), read_windspeed()); + } + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : send_led_state +* Description : ͵ǰƵ״̬è +* Input : None +* Return : None +*******************************************************************************/ +void send_led_state(void) +{ + APP_DBG(""); + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .send_ttl = BLE_MESH_TTL_DEFAULT, + .tid = als_avail_tid_get(), + }; + + toggle_led_state(MSG_PIN); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + send_led_indicate(¶m); +} + +/******************************************************************************* +* Function Name : send_reset_indicate +* Description : ͸λ¼è飬ɺ״̬mesh +* Input : None +* Return : None +*******************************************************************************/ +void send_reset_indicate(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.cb = &reset_cb; + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + /* Add event report opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_EVENT_TRIGGER); + + /* Add reset event */ + net_buf_simple_add_u8(&(ind->buf->b), ALI_GEN_ATTR_TYPE_HARDWARE_RESET); + + bt_mesh_indicate_send(ind); +} + +#define HAL_KEY_SEND_MSG BIT(0) +#define HAL_KEY_RESET BIT(1) + +/******************************************************************************* +* Function Name : keyPress +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void keyPress(uint8 keys) +{ + APP_DBG("keys : %d ",keys); + + switch (keys) + { + case HAL_KEY_SEND_MSG: + send_led_state(); + break; + case HAL_KEY_RESET: + send_reset_indicate(); + break; + } +} + +/******************************************************************************* +* Function Name : app_silent_adv +* Description : ʱδɹ뾲Ĭ㲥ģʽ,ֵ֧Ըè +* Input : None +* Return : None +*******************************************************************************/ +static void app_silent_adv(void) +{ + APP_DBG(""); + if (bt_mesh_is_provisioned()) + { + senf_support_attr(); + return; + } + + silen_adv_set(SELENCE_ADV_ON); + + /* Disable Scanner not response Provisioner message */ + bt_mesh_scan_disable(); +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + APP_DBG("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MacAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress ); + set_led_state(MSG_PIN, 0); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_SILENT_ADV_EVT ) + { + app_silent_adv(); + return ( events ^ APP_SILENT_ADV_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_als_windspeed_attr.c b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_als_windspeed_attr.c new file mode 100644 index 0000000..8a99a9a --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_als_windspeed_attr.c @@ -0,0 +1,201 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_als_windspeed_attr.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_als_windspeed_attr.h" +#include "app_vendor_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +#define ALI_DEF_TTL (10) + +// ģwindspeedֵ +u8_t device_windspeed = 1; + +/******************************************************************************* +* Function Name : read_windspeed +* Description : ȡǰwindspeed +* Input : None +* Return : None +*******************************************************************************/ +u8_t read_windspeed( void ) +{ + APP_DBG("device_windspeed: %d ",device_windspeed); + return device_windspeed; +} + +/******************************************************************************* +* Function Name : set_windspeeds +* Description : õǰwindspeed +* Input : None +* Return : None +*******************************************************************************/ +void set_windspeed( u8_t windspeed ) +{ + device_windspeed = windspeed; +} + +/******************************************************************************* +* Function Name : gen_windspeed_status +* Description : ظèwindspeed +* Input : model: ģͲ +* ctxݲ +* Return : None +*******************************************************************************/ +static void gen_windspeed_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx) +{ + NET_BUF_SIMPLE_DEFINE(msg, 32); + int err; + + //////////////////////////////////////////////////////////////////////// + // 0xD3 0xA8 0x01 | 0x## | 0x0a 0x01 | 0x## 0x## // + // Opcode | TID | Attribute Type | Attribute Value // + //////////////////////////////////////////////////////////////////////// + bt_mesh_model_msg_init(&msg, OP_VENDOR_MESSAGE_ATTR_STATUS); + net_buf_simple_add_u8(&msg, als_avail_tid_get()); + net_buf_simple_add_le16(&msg, ALI_GEN_ATTR_TYPE_WINDSPEED); + net_buf_simple_add_le16(&msg, read_windspeed()); + + APP_DBG("ttl: 0x%02x dst: 0x%04x", ctx->recv_ttl, ctx->recv_dst); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + ctx->send_ttl = BLE_MESH_TTL_DEFAULT; + } + else + { + ctx->send_ttl = 0; + } + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : gen_windspeed_get +* Description : è·Ļȡwindspeed +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +void gen_windspeed_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + gen_windspeed_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_windspeed_set +* Description : è·windspeed + 뵱ǰwindspeedͬ,Ҫindè +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +void gen_windspeed_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .rand = (tmos_rand() % 50), + .tid = als_avail_tid_get(), + }; + + APP_DBG("ttl: 0x%02x dst: 0x%04x rssi: %d ", + ctx->recv_ttl, ctx->recv_dst, ctx->recv_rssi); + + if( (buf->data[1]|(buf->data[2]<<8)) < ALI_GEN_ATTR_TYPE_WORK_STATUS ) + { + // Ϊ趨ֵ + set_windspeed( buf->data[3] ); + } + else + { + switch( buf->data[1]|(buf->data[2]<<8) ) + { + // Ϊ趨仯 + case ALI_GEN_ATTR_TYPE_DELTA_VALUE: + { + char delta = (char) buf->data[5]; + set_windspeed( read_windspeed()+delta ); + } + } + } + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + param.send_ttl = BLE_MESH_TTL_DEFAULT; + } + + /* Overwrite default configuration */ + if (BLE_MESH_ADDR_IS_UNICAST(ctx->recv_dst)) + { + param.rand = 0; + param.send_ttl = BLE_MESH_TTL_DEFAULT; + param.period = K_MSEC(100); + } + + send_windspeed_indicate(¶m); + + gen_windspeed_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_windspeed_set_unack +* Description : è·windspeed(Ӧ) +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +void gen_windspeed_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + + if( (buf->data[1]|(buf->data[2]<<8)) < ALI_GEN_ATTR_TYPE_WORK_STATUS ) + { + // Ϊ趨ֵ + set_windspeed( buf->data[3] ); + } + else + { + switch( buf->data[1]|(buf->data[2]<<8) ) + { + // Ϊ趨仯 + case ALI_GEN_ATTR_TYPE_DELTA_VALUE: + { + char delta = (char) buf->data[5]; + set_windspeed( read_windspeed()+delta ); + } + } + } +} + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_generic_onoff_model.c b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_generic_onoff_model.c new file mode 100644 index 0000000..c6e350b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_generic_onoff_model.c @@ -0,0 +1,187 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_generic_onoff_model.h" +#include "app_vendor_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +#define ALI_DEF_TTL (10) + +/******************************************************************************* +* Function Name : read_led_state +* Description : ȡǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : õǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : תǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + + +/******************************************************************************* +* Function Name : gen_onoff_status +* Description : ظè鿪״̬ +* Input : model: ģͲ +* ctxݲ +* Return : None +*******************************************************************************/ +static void gen_onoff_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx) +{ + NET_BUF_SIMPLE_DEFINE(msg, 32); + int err; + + bt_mesh_model_msg_init(&msg, BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS); + net_buf_simple_add_u8(&msg, read_led_state(MSG_PIN)); + + APP_DBG("ttl: 0x%02x dst: 0x%04x", ctx->recv_ttl, ctx->recv_dst); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + ctx->send_ttl = BLE_MESH_TTL_DEFAULT; + } + else + { + ctx->send_ttl = 0; + } + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : gen_onoff_get +* Description : è·Ļȡ״̬ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + + gen_onoff_status(model, ctx); +} + + +/******************************************************************************* +* Function Name : gen_onoff_set +* Description : è·ÿ״̬ + 뵱ǰ״̬ͬ,Ҫindè +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .rand = (tmos_rand() % 50), + .tid = als_avail_tid_get(), + }; + + APP_DBG("ttl: 0x%02x dst: 0x%04x rssi: %d", + ctx->recv_ttl, ctx->recv_dst, ctx->recv_rssi); + + set_led_state(MSG_PIN, buf->data[0]); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + param.send_ttl = BLE_MESH_TTL_DEFAULT; + } + + /* Overwrite default configuration */ + if (BLE_MESH_ADDR_IS_UNICAST(ctx->recv_dst)) + { + param.rand = 0; + param.send_ttl = BLE_MESH_TTL_DEFAULT; + param.period = K_MSEC(100); + } + + send_led_indicate(¶m); + + gen_onoff_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_onoff_set_unack +* Description : è·ÿ״̬(Ӧ) +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t status; + + APP_DBG(" "); + + status = read_led_state(MSG_PIN); + if (status != buf->data[0]) + { + set_led_state(MSG_PIN, buf->data[0]); + } +} + +const struct bt_mesh_model_op gen_onoff_op[] = { + {BLE_MESH_MODEL_OP_GEN_ONOFF_GET, 0, gen_onoff_get}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET, 2, gen_onoff_set}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK, 2, gen_onoff_set_unack}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_main.c b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_vendor_model.c b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_vendor_model.c new file mode 100644 index 0000000..931d6cf --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/app_vendor_model.c @@ -0,0 +1,647 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "CONFIG.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" +#include "app_als_windspeed_attr.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +///* Mac Address Light1 */ +//#define PID 7049884 +//#define MAC_ADDR {0x18,0x14,0x6c,0x49,0x54,0x98} +//#define ALI_SECRET {0x35,0x06,0xa0,0xe9,0x60,0xde,0xbd,0x59,0xcf,0xcc,0xce,0x11,0x2c,0x91,0xbf,0x3f} +///* Mac Address Light2 */ +//#define PID 9701 +//#define MAC_ADDR {0xf8,0xa7,0x63,0x6a,0xec,0x3f} +//#define ALI_SECRET {0x6b,0xfa,0x68,0x6f,0x9d,0x1b,0x37,0x00,0x01,0xd1,0xfd,0xb8,0x27,0x7d,0xc0,0x81} +/* Mac Address Fan */ +#define PID 7969121 +#define MAC_ADDR {0x18,0x14,0x6c,0x8b,0x65,0x20} +#define ALI_SECRET {0x7a,0x60,0x0a,0xe8,0x1e,0xeb,0xd5,0x1a,0xe5,0x38,0xec,0xe9,0xe2,0x55,0x42,0x17} + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +u8_t tm_uuid[16]; +u8_t static_key[16]; +u8C MacAddr[6] = MAC_ADDR; + +static const struct bt_als_cfg cfg = +{ + .mac = MAC_ADDR, + .secret = ALI_SECRET, + .pid = PID, + .cid = 0x01a8, + .version = 0x00060000, +}; + +static uint8 als_vendor_model_TaskID = 0; // Task ID for internal task/event processing + +static u8_t als_tid=0; + +static struct net_buf ind_buf[CONFIG_INDICATE_NUM]={0}; +static struct bt_mesh_indicate indicate[CONFIG_INDICATE_NUM]={0}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +static void ind_reset(struct bt_mesh_indicate *ind, int err); +static uint16 als_vendor_model_ProcessEvent( uint8 task_id, uint16 events ); + +/******************************************************************************* +* Function Name : tm_attr_get +* Description : յè鷢Ļȡֵ +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u16_t attr_type; + if( (buf->data[1]|(buf->data[2]<<8)) < ALI_GEN_ATTR_TYPE_WORK_STATUS ) + { + attr_type = buf->data[1]|(buf->data[2]<<8); + } + else + { + attr_type = buf->data[3]|(buf->data[4]<<8); + } + + APP_DBG("attr_type0x%04x ",attr_type); + + switch( attr_type ) + { + case ALI_GEN_ATTR_TYPE_WINDSPEED: + { + gen_windspeed_get(model, ctx, buf); + } + + default: + break; + } +} + +/******************************************************************************* +* Function Name : tm_attr_set +* Description : յè鷢ֵ +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u16_t attr_type; + + + if( (buf->data[1]|(buf->data[2]<<8)) < ALI_GEN_ATTR_TYPE_WORK_STATUS ) + { + attr_type = buf->data[1]|(buf->data[2]<<8); + } + else + { + attr_type = buf->data[3]|(buf->data[4]<<8); + } + + APP_DBG("attr_type0x%04x ",attr_type); + + switch( attr_type ) + { + case ALI_GEN_ATTR_TYPE_WINDSPEED: + { + gen_windspeed_set(model, ctx, buf); + } + + default: + break; + } +} + +/******************************************************************************* +* Function Name : tm_attr_set_unack +* Description : յè鷢ֵӦ +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u16_t attr_type; + if( (buf->data[1]|(buf->data[2]<<8)) < ALI_GEN_ATTR_TYPE_WORK_STATUS ) + { + attr_type = buf->data[1]|(buf->data[2]<<8); + } + else + { + attr_type = buf->data[3]|(buf->data[4]<<8); + } + + APP_DBG("attr_type0x%04x ",attr_type); + + switch( attr_type ) + { + case ALI_GEN_ATTR_TYPE_WINDSPEED: + { + gen_windspeed_set_unack(model, ctx, buf); + } + + default: + break; + } + APP_DBG(" "); +} + +/******************************************************************************* +* Function Name : tm_attr_confirm +* Description : յè鷢confirm - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_confirm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if (indicate[i].param.tid == recv_tid) + { + ind_reset(&indicate[i], 0); + tmos_stop_task(als_vendor_model_TaskID, indicate[i].event); + continue; + } + } +} + +/******************************************************************************* +* Function Name : tm_attr_trans +* Description : ϢMesh豸è֮͸ +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +// opcode ӦĴ +static const struct bt_mesh_model_op vnd_model_op[] = { + {OP_VENDOR_MESSAGE_ATTR_GET, 0, tm_attr_get}, + {OP_VENDOR_MESSAGE_ATTR_SET, 0, tm_attr_set}, + {OP_VENDOR_MESSAGE_ATTR_SET_UNACK, 0, tm_attr_set_unack}, + {OP_VENDOR_MESSAGE_ATTR_CONFIRMATION, 1, tm_attr_confirm}, + {OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG, 0, tm_attr_trans}, + BLE_MESH_MODEL_OP_END, +}; + +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_ALI_GENIE, 0x0000, vnd_model_op, NULL, NULL, &bt_mesh_als_vendor_model_cb), +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : als_avail_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t als_avail_tid_get(void) +{ + return als_tid++; +} + +/******************************************************************************* +* Function Name : uuid_generate +* Description : ɰ淶UUID +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void uuid_generate(struct bt_als_cfg const *cfg) +{ + /* Company ID */ + tm_uuid[0] = cfg->cid; + tm_uuid[1] = cfg->cid >> 8; + + /* bit30 㲥汾ţĿǰ0x01 + bit4Ϊ1һһ + bit5Ϊ1֧OTA + bit76Э汾 + 00BLE4.0 + 01BLE4.2 + 10BLE5.0 + 11BLE5.0 */ + /* Advertising Verison */ + tm_uuid[2] = BIT(0) | /* adv version */ + BIT(4) | /* secret */ + BIT(5) | /* ota */ + BIT(7); /* ble verison */ + + /* Product Id */ + tm_uuid[2 + 1] = cfg->pid; + tm_uuid[2 + 2] = cfg->pid >> 8; + tm_uuid[2 + 3] = cfg->pid >> 16; + tm_uuid[2 + 4] = cfg->pid >> 24; + + /* Device Mac Address */ + for(int i=0;i<6;i++) tm_uuid[2 + 1 + 4 + i] = cfg->mac[5-i]; + + /* UUID Verison */ + tm_uuid[2 + 1 + 4 + 6] = BIT(1); + + /* RFU */ + tm_uuid[2 + 1 + 4 + 6 + 1] = 0x00; + tm_uuid[2 + 1 + 4 + 6 + 2] = 0x00; +} + +/******************************************************************************* +* Function Name : num_to_str +* Description : תַ +* Input : +* Return : None +*******************************************************************************/ +static void num_to_str(u8_t *out, const u8_t *in, u16_t in_len) +{ + u16_t i; + static const char hex[] = "0123456789abcdef"; + + for (i = 0; i < in_len; i++) + { + out[i * 2] = hex[in[i] >> 4]; + out[i * 2 + 1] = hex[in[i] & 0xf]; + } +} + +/******************************************************************************* +* Function Name : oob_key_generate +* Description : OOB key +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void oob_key_generate(struct bt_als_cfg const *cfg) +{ + int err; + u32_t pid; + u8_t out[8 + 1 + 12 + 1 + 32], dig[32]; + struct tc_sha256_state_struct s; + + tc_sha256_init(&s); + + /** pid value */ + pid = ((u32_t)((((cfg->pid) >> 24) & 0xff) | \ + (((cfg->pid) >> 8) & 0xff00) | \ + (((cfg->pid)&0xff00) << 8) | \ + (((cfg->pid)&0xff) << 24))); + num_to_str(out, (void *)&pid, 4); + + /** Separator */ + strcpy((void *)(out + 8), ","); + /** mac value */ + num_to_str(out + 8 + 1, (void *)cfg->mac, 6); + + /** Separator */ + strcpy((void *)(out + 8 + 1 + 12), ","); + /** secret value */ + num_to_str(out + 8 + 1 + 12 + 1, (void *)cfg->secret, 16); + + err = tc_sha256_update(&s, out, sizeof(out)); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Update Sha256"); + return; + } + + err = tc_sha256_final(dig, &s); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Generate sha256 value"); + return; + } + + memcpy(static_key, dig, 16); +} + +/******************************************************************************* +* Function Name : ind_reset +* Description : Ƴб÷ɻصͷŻ +* Input : indҪõ֪ͨ + err +* Return : None +*******************************************************************************/ +static void ind_reset(struct bt_mesh_indicate *ind, int err) +{ + if (ind->param.cb && ind->param.cb->end) + { + ind->param.cb->end(err, ind->param.cb_data); + } + + tmos_msg_deallocate(ind->buf->__buf); + ind->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_reset +* Description : ͷδ͵֪ͨ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_reset(void) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf != NULL ) + { + ind_reset(&indicate[i], -ECANCELED); + } + } +} + +/******************************************************************************* +* Function Name : ind_start +* Description : indicate ʼص +* Input : durationηͽҪʱ + err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(als_vendor_model_TaskID, ind->event, K_MSEC(100) ); + return; + } +} + +/******************************************************************************* +* Function Name : ind_end +* Description : indicate ص +* Input : err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_end(int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.period ); +} + +// indicate صṹ +const struct bt_mesh_send_cb ind_cb = +{ + .start = ind_start, + .end = ind_end, +}; + +/******************************************************************************* +* Function Name : adv_ind_send +* Description : indicate +* Input : indҪ͵֪ͨ +* Return : None +*******************************************************************************/ +static void adv_ind_send(struct bt_mesh_indicate *ind) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, 32); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = vnd_models[0].keys[0], + .addr = ALI_TM_SUB_ADDRESS, + }; + + if (ind->buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (ind->param.trans_cnt == 0) + { + ind_reset(ind, -ETIMEDOUT); + return; + } + + ind->param.trans_cnt --; + + ctx.send_ttl = ind->param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, ind->buf->data, ind->buf->len); + + err = bt_mesh_model_send(vnd_models, &ctx, &msg, &ind_cb, ind); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + ind_reset(ind, -EIO); + return; + } +} + +/******************************************************************************* +* Function Name : bt_mesh_ind_allocһյ +* Description : һյindicateڴ +* Input : buf: Ҫ +* Return : indicateṹָ +*******************************************************************************/ +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf == NULL ) + break; + } + if( i == CONFIG_INDICATE_NUM ) + return NULL; + + indicate[i].buf->__buf = tmos_msg_allocate(len); + indicate[i].buf->size = len; + + if( indicate[i].buf->__buf == NULL ) + return NULL; + + return &indicate[i]; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_send +* Description : ֪ͨ¼ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ) +{ + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.rand ); +} + +/******************************************************************************* +* Function Name : send_led_indicate +* Description : ͵ǰLED״̬LED״̬ʱҪô˺ +* Input : param ֪ͨķͲ +* Return : None +*******************************************************************************/ +void send_led_indicate(struct indicate_param *param) +{ + struct bt_mesh_indicate *ind; + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + memcpy(&(ind->param), param, sizeof(struct indicate_param)); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), param->tid); + + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : send_windspeed_indicate +* Description : ͵ǰwindspeedwindspeedʱҪô˺ +* Input : param ֪ͨķͲ +* Return : None +*******************************************************************************/ +void send_windspeed_indicate(struct indicate_param *param) +{ + struct bt_mesh_indicate *ind; + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + memcpy(&(ind->param), param, sizeof(struct indicate_param)); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), param->tid); + + /* Add windspeed attrbute opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_WINDSPEED); + + /* Add windspeed status */ + net_buf_simple_add_u8(&(ind->buf->b), read_windspeed()); + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : als_vendor_init +* Description : ģ ʼ +* Input : model: صģͲ +* Return : None +*******************************************************************************/ +static int als_vendor_init(struct bt_mesh_model *model) +{ + u32_t ran; + + uuid_generate(&cfg); + oob_key_generate(&cfg); + + /** Random Local TID Value + * @Caution Don't use single octer only. + */ + ran = tmos_rand(); + als_tid += ((u8_t *)&ran)[0]; + als_tid += ((u8_t *)&ran)[1]; + als_tid += ((u8_t *)&ran)[2]; + als_tid += ((u8_t *)&ran)[3]; + + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + indicate[i].buf = &ind_buf[i]; + indicate[i].event = (1< ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/include/app_vendor_model.h b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/include/app_vendor_model.h new file mode 100644 index 0000000..c14492d --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/include/app_vendor_model.h @@ -0,0 +1,138 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_H +#define app_vendor_model_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/******************************************************************************/ + +#include "MESH_LIB.h" + +/******************************************************************************/ + +#define CID_ALI_GENIE 0x01A8 + +#define OP_VENDOR_MESSAGE_ATTR_GET BLE_MESH_MODEL_OP_3(0xD0, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET BLE_MESH_MODEL_OP_3(0xD1, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET_UNACK BLE_MESH_MODEL_OP_3(0xD2, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_STATUS BLE_MESH_MODEL_OP_3(0xD3, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_INDICATION BLE_MESH_MODEL_OP_3(0xD4, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_CONFIRMATION BLE_MESH_MODEL_OP_3(0xD5, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_ALI_GENIE) + +#define ALI_SYS_ATTR_TYPE_ERROR 0x0000 +#define ALI_SYS_ATTR_TYPE_VERSION 0xFF01 +#define ALI_SYS_ATTR_TYPE_DEV_FEATURE 0xFF02 +#define ALI_SYS_ATTR_TYPE_TOTAL_FLASH_SIZE 0xFF03 +#define ALI_SYS_ATTR_TYPE_USED_FLASH_SIZE 0xFF04 +#define ALI_SYS_ATTR_TYPE_FREE_FLASH_SIZE 0xFF05 +#define ALI_SYS_ATTR_TYPE_ENGINEER_MODE 0xFF06 + +#define ALI_GEN_ATTR_TYPE_WORK_STATUS 0xF001 +#define ALI_GEN_ATTR_TYPE_USER_ID 0xF002 +#define ALI_GEN_ATTR_TYPE_DEVICE_NAME 0xF003 +#define ALI_GEN_ATTR_TYPE_MODE_NUMBER 0xF004 +#define ALI_GEN_ATTR_TYPE_ONOFF_PLAN 0xF008 +#define ALI_GEN_ATTR_TYPE_EVENT_TRIGGER 0xF009 +#define ALI_GEN_ATTR_TYPE_EVENT_CLEAR 0xF019 +#define ALI_GEN_ATTR_TYPE_SIGNAL_INTENSITY 0xF00A +#define ALI_GEN_ATTR_TYPE_DELTA_VALUE 0xF00B +#define ALI_GEN_ATTR_TYPE_ELEMENT_COUNT 0xF00C +#define ALI_GEN_ATTR_TYPE_ATTR_SWITCH 0xF00D +#define ALI_GEN_ATTR_TYPE_REMOTE_ADDRESS 0xF00E +#define ALI_GEN_ATTR_TYPE_NEARBY_SIGNAL_INTEN 0xF00F +#define ALI_GEN_ATTR_TYPE_SET_VALUE_TIMING 0xF010 +#define ALI_GEN_ATTR_TYPE_SET_VALUE_PERIODIC 0xF011 +#define ALI_GEN_ATTR_TYPE_DEL_TIMING 0xF012 +#define ALI_GEN_ATTR_TYPE_REQ_UPDATE_TIMING 0xF013 +#define ALI_GEN_ATTR_TYPE_SETTING_TIMING 0xF01D +#define ALI_GEN_ATTR_TYPE_TIME_ZONE 0xF01E +#define ALI_GEN_ATTR_TYPE_UNIX_TIMER 0xF01F +#define ALI_GEN_ATTR_TYPE_POWERDOWN_MEM 0xF021 + +#define ALI_GEN_ATTR_TYPE_CALORIES 0x06D5 +#define ALI_GEN_ATTR_TYPE_SPORTCOUNT 0x0212 +#define ALI_GEN_ATTR_TYPE_POWER_STATE 0x0100 +#define ALI_GEN_ATTR_TYPE_BRIGHTNESS 0x0121 +#define ALI_GEN_ATTR_TYPE_HARDWARE_RESET 0x0023 +#define ALI_GEN_ATTR_TYPE_WINDSPEED 0x010A + +#define ALI_TM_SUB_ADDRESS 0xF000 + +/** Default number of Indication */ +#define CONFIG_INDICATE_NUM (3) + +/******************************************************************************/ + +struct bt_adv_ind_send_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + +struct indicate_param +{ + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_ind_send_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct indicate_param param; + struct net_buf *buf; + uint8 event; +}; + +struct bt_als_cfg +{ + /** Company Identify */ + u16_t cid; + + /** Product Identify */ + u32_t pid; + + /** Mac Address */ + u8_t mac[6]; + + /** Secret Information */ + u8_t secret[16]; + + /** Currently Library Version */ + u32_t version; +}; + +extern struct bt_mesh_model vnd_models[1]; +extern u8_t static_key[16]; +extern u8_t tm_uuid[16]; +extern const struct bt_mesh_model_cb bt_mesh_als_vendor_model_cb; +/******************************************************************************/ +u8_t als_avail_tid_get(void); +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ); +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ); +void send_led_indicate(struct indicate_param *param); +void send_windspeed_indicate(struct indicate_param *param); + +void bt_mesh_indicate_reset(void); + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/include/mesh_debug.h b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/include/mesh_debug.h new file mode 100644 index 0000000..0dbd7e5 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/APP/include/mesh_debug.h @@ -0,0 +1,183 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : mesh_debug.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef mesh_debug_H +#define mesh_debug_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/******************************************************************************/ + +#include "stdio.h" +/******************************************************************************/ + +#define BT_DBG_ENABLED 1 + +#define BT_DBG(X...) \ + if (0) \ + { \ + printf("DEBUG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +#define BT_ERR(X...) \ + if (BT_DBG_ENABLED) \ + { \ + printf("ERROR %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +#define BT_WARN(X...) \ + if (BT_DBG_ENABLED) \ + { \ + printf("WARNNING %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_PRT(X...) \ + if (0) \ + { \ + printf("PRINT %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_CRYPTO(X...) \ + if (0) \ + { \ + printf("CRYPTO %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_BUF(X...) \ + if (0) \ + { \ + printf("BUF %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_NET(X...) \ + if (0) \ + { \ + printf("NET %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_TRANS(X...) \ + if (0) \ + { \ + printf("TRANS %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_PROXY(X...) \ + if (0) \ + { \ + printf("PROXY %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_INFO(X...) \ + if (0) \ + { \ + printf("INFO %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define NET_BUF_SIMPLE_DBG(X...) \ + if (0) \ + { \ + printf("NET_BUF_SIMPLE_DBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define NET_BUF_DBG(X...) \ + if (0) \ + { \ + printf("NET_BUF_DBG "X); \ + printf("\n"); \ + } \ + + +#define BT_WORK_DBG(X...) \ + if (0) \ + { \ + printf("WKDBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_TEST(X...) \ + if (BT_DBG_ENABLED) \ + { \ + printf("TEST %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +#define LOG_DBG(X...) \ + if (0) \ + { \ + printf("NV DEBUG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +#define LOG_ERR(X...) \ + if (BT_DBG_ENABLED) \ + { \ + printf("NV ERROR %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define LOG_INF(X...) \ + if (0) \ + { \ + printf("NV INFO %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +#define BT_RF(X...) \ + if (0) \ + { \ + printf("RF %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + +const char *bt_hex(const void *buf, size_t len); + +/******************************************************************************/ + + + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/Project/BLE.uvprojx new file mode 100644 index 0000000..7db17ce --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_add_windspeed/Project/BLE.uvprojx @@ -0,0 +1,587 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model.c + 1 + ..\APP\app_vendor_model.c + + + app_als_windspeed_attr.c + 1 + ..\APP\app_als_windspeed_attr.c + + + app_generic_onoff_model.c + 1 + ..\APP\app_generic_onoff_model.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app.c b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app.c new file mode 100644 index 0000000..388059d --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app.c @@ -0,0 +1,573 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" +#include "app.h" +#include "HAL.h" +#include "peripheral.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void prov_reset(void); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +static struct bt_mesh_health_srv health_srv; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), + BLE_MESH_MODEL(BLE_MESH_MODEL_ID_GEN_ONOFF_SRV, gen_onoff_op, NULL, NULL), +}; + +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = tm_uuid, + .static_val_len = ARRAY_SIZE(static_key), + .static_val = static_key, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .reset = prov_reset, +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : silen_adv_set +* Description : þĬ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void silen_adv_set(u8_t flag) +{ + tm_uuid[13] &= ~BIT(0); + tm_uuid[13] |= (BIT_MASK(1) & flag); +} + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + silen_adv_set(SELENCE_ADV_OF); + + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } + + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, ADV_TIMEOUT); +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkصֹͣ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(" "); + + tmos_stop_task(App_TaskID, APP_SILENT_ADV_EVT); +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : None +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + prov_enable(); + } + else + { + /*è鲻·Config_model_app_bindConfig_Model_Subscrption_AddϢ + IOT豸ҪиElementmodel·AppKeyݲƷΪ + modelӦ鲥ַƷ鲥ַĸƷ淶Mesh豸 + ҪϢϱϱϢ豸ֵ֧Ŀϱԡ*/ + + /* For Light Subscription group address */ + root_models[2].groups[0] = (u16_t)0xC000; + root_models[2].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&root_models[2]); + + root_models[2].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&root_models[2]); + + /* For Light Subscription group address */ + vnd_models[0].groups[0] = (u16_t)0xC000; + vnd_models[0].groups[1] = (u16_t)0xCFFF; + bt_mesh_store_mod_sub(&vnd_models[0]); + + vnd_models[0].keys[0] = (u16_t)0x0000; + bt_mesh_store_mod_bind(&vnd_models[0]); + } +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص¿ʼ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + /* 豸ϵҲҪ1~10sϱֵ֧״̬ */ + tmosTimer rand_timer; + APP_DBG(" "); + + rand_timer = K_SECONDS(5) + (tmos_rand() % K_SECONDS(6)); + tmos_start_task(App_TaskID, APP_SILENT_ADV_EVT, rand_timer); +} + +/******************************************************************************* +* Function Name : prov_reset +* Description : λܻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_reset(void) +{ + APP_DBG(""); + + prov_enable(); +} + +/******************************************************************************* +* Function Name : ind_end_cb +* Description : ͸λ¼ɻص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_end_cb(int err, void *cb_data) +{ + APP_DBG(" bt_mesh_reset "); + bt_mesh_reset(); +} + +static const struct bt_adv_ind_send_cb reset_cb = { + .end = ind_end_cb, +}; + +/******************************************************************************* +* Function Name : send_support_attr +* Description : ֵ֧ĿϱԸè,Ϣèж豸֧Щ +* Input : None +* Return : None +*******************************************************************************/ +void senf_support_attr(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 32 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + // ӿ + { + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + } +// // ѡݰõIJƷԹӶӦ ( BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET ) +// // ο,ҪӶӦopcode,ӷʽοԵ gen_onoff_op ṹ +// { +// /* Add brightness attrbute opcode */ +// net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_BRIGHTNESS); + +// /* Add brightness status (1~100) */ +// net_buf_simple_add_le16(&(ind->buf->b), 100); +// } + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : send_led_state +* Description : ͵ǰƵ״̬è +* Input : None +* Return : None +*******************************************************************************/ +void send_led_state(void) +{ + APP_DBG(""); + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .send_ttl = BLE_MESH_TTL_DEFAULT, + .tid = als_avail_tid_get(), + }; + + toggle_led_state(MSG_PIN); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + send_led_indicate(¶m); +} + +/******************************************************************************* +* Function Name : send_reset_indicate +* Description : ͸λ¼è飬ɺ״̬mesh +* Input : None +* Return : None +*******************************************************************************/ +void send_reset_indicate(void) +{ + struct bt_mesh_indicate *ind; + APP_DBG(""); + + if (!bt_mesh_is_provisioned()) + { + APP_DBG("Local Dev Unprovisioned"); + return; + } + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + ind->param.trans_cnt = 0x09; + ind->param.period = K_MSEC(300); + ind->param.cb = &reset_cb; + ind->param.send_ttl = BLE_MESH_TTL_DEFAULT; + ind->param.tid = als_avail_tid_get(); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), ind->param.tid); + + /* Add event report opcode */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_EVENT_TRIGGER); + + /* Add reset event */ + net_buf_simple_add_u8(&(ind->buf->b), ALI_GEN_ATTR_TYPE_HARDWARE_RESET); + + bt_mesh_indicate_send(ind); +} + +#define HAL_KEY_SEND_MSG BIT(0) +#define HAL_KEY_RESET BIT(1) + +/******************************************************************************* +* Function Name : keyPress +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void keyPress(uint8 keys) +{ + APP_DBG("keys : %d ",keys); + + switch (keys) + { + case HAL_KEY_SEND_MSG: + send_led_state(); + break; + case HAL_KEY_RESET: + send_reset_indicate(); + break; + } +} + +/******************************************************************************* +* Function Name : app_silent_adv +* Description : ʱδɹ뾲Ĭ㲥ģʽ,ֵ֧Ըè +* Input : None +* Return : None +*******************************************************************************/ +static void app_silent_adv(void) +{ + APP_DBG(""); + if (bt_mesh_is_provisioned()) + { + senf_support_attr(); + return; + } + + silen_adv_set(SELENCE_ADV_ON); + + /* Disable Scanner not response Provisioner message */ + bt_mesh_scan_disable(); +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + APP_DBG("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MacAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + GAPRole_PeripheralInit(); + Peripheral_Init(); + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress ); + set_led_state(MSG_PIN, 0); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_SILENT_ADV_EVT ) + { + app_silent_adv(); + return ( events ^ APP_SILENT_ADV_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_generic_onoff_model.c b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_generic_onoff_model.c new file mode 100644 index 0000000..c6e350b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_generic_onoff_model.c @@ -0,0 +1,187 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_generic_onoff_model.h" +#include "app_vendor_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +#define ALI_DEF_TTL (10) + +/******************************************************************************* +* Function Name : read_led_state +* Description : ȡǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : õǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : תǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + + +/******************************************************************************* +* Function Name : gen_onoff_status +* Description : ظè鿪״̬ +* Input : model: ģͲ +* ctxݲ +* Return : None +*******************************************************************************/ +static void gen_onoff_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx) +{ + NET_BUF_SIMPLE_DEFINE(msg, 32); + int err; + + bt_mesh_model_msg_init(&msg, BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS); + net_buf_simple_add_u8(&msg, read_led_state(MSG_PIN)); + + APP_DBG("ttl: 0x%02x dst: 0x%04x", ctx->recv_ttl, ctx->recv_dst); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + ctx->send_ttl = BLE_MESH_TTL_DEFAULT; + } + else + { + ctx->send_ttl = 0; + } + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : gen_onoff_get +* Description : è·Ļȡ״̬ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + + gen_onoff_status(model, ctx); +} + + +/******************************************************************************* +* Function Name : gen_onoff_set +* Description : è·ÿ״̬ + 뵱ǰ״̬ͬ,Ҫindè +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + struct indicate_param param = { + .trans_cnt = 0x09, + .period = K_MSEC(300), + .rand = (tmos_rand() % 50), + .tid = als_avail_tid_get(), + }; + + APP_DBG("ttl: 0x%02x dst: 0x%04x rssi: %d", + ctx->recv_ttl, ctx->recv_dst, ctx->recv_rssi); + + set_led_state(MSG_PIN, buf->data[0]); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + param.send_ttl = BLE_MESH_TTL_DEFAULT; + } + + /* Overwrite default configuration */ + if (BLE_MESH_ADDR_IS_UNICAST(ctx->recv_dst)) + { + param.rand = 0; + param.send_ttl = BLE_MESH_TTL_DEFAULT; + param.period = K_MSEC(100); + } + + send_led_indicate(¶m); + + gen_onoff_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_onoff_set_unack +* Description : è·ÿ״̬(Ӧ) +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t status; + + APP_DBG(" "); + + status = read_led_state(MSG_PIN); + if (status != buf->data[0]) + { + set_led_state(MSG_PIN, buf->data[0]); + } +} + +const struct bt_mesh_model_op gen_onoff_op[] = { + {BLE_MESH_MODEL_OP_GEN_ONOFF_GET, 0, gen_onoff_get}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET, 2, gen_onoff_set}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK, 2, gen_onoff_set_unack}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_main.c b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_vendor_model.c b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_vendor_model.c new file mode 100644 index 0000000..1d703f3 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/app_vendor_model.c @@ -0,0 +1,532 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "CONFIG.h" +#include "app_vendor_model.h" +#include "app_generic_onoff_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +///* Mac Address Light1 */ +//#define PID 7049884 +//#define MAC_ADDR {0x18,0x14,0x6c,0x49,0x54,0x98} +//#define ALI_SECRET {0x35,0x06,0xa0,0xe9,0x60,0xde,0xbd,0x59,0xcf,0xcc,0xce,0x11,0x2c,0x91,0xbf,0x3f} +/* Mac Address Light2 */ +#define PID 9701 +#define MAC_ADDR {0xf8,0xa7,0x63,0x6a,0xec,0x3f} +#define ALI_SECRET {0x6b,0xfa,0x68,0x6f,0x9d,0x1b,0x37,0x00,0x01,0xd1,0xfd,0xb8,0x27,0x7d,0xc0,0x81} + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +u8_t tm_uuid[16]; +u8_t static_key[16]; +u8C MacAddr[6] = MAC_ADDR; + +static const struct bt_als_cfg cfg = +{ + .mac = MAC_ADDR, + .secret = ALI_SECRET, + .pid = PID, + .cid = 0x01a8, + .version = 0x00060000, +}; + +static uint8 als_vendor_model_TaskID = 0; // Task ID for internal task/event processing + +static u8_t als_tid=0; + +static struct net_buf ind_buf[CONFIG_INDICATE_NUM]={0}; +static struct bt_mesh_indicate indicate[CONFIG_INDICATE_NUM]={0}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +static void ind_reset(struct bt_mesh_indicate *ind, int err); +static uint16 als_vendor_model_ProcessEvent( uint8 task_id, uint16 events ); + +static void tm_attr_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +static void tm_attr_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +/******************************************************************************* +* Function Name : tm_attr_confirm +* Description : յè鷢confirm - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_confirm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if (indicate[i].param.tid == recv_tid) + { + ind_reset(&indicate[i], 0); + tmos_stop_task(als_vendor_model_TaskID, indicate[i].event); + continue; + } + } +} + +/******************************************************************************* +* Function Name : tm_attr_trans +* Description : ϢMesh豸è֮͸ +* Input : None +* Return : None +*******************************************************************************/ +static void tm_attr_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); +} + +// opcode ӦĴ +static const struct bt_mesh_model_op vnd_model_op[] = { + {OP_VENDOR_MESSAGE_ATTR_GET, 0, tm_attr_get}, + {OP_VENDOR_MESSAGE_ATTR_SET, 0, tm_attr_set}, + {OP_VENDOR_MESSAGE_ATTR_SET_UNACK, 0, tm_attr_set_unack}, + {OP_VENDOR_MESSAGE_ATTR_STATUS, 0, tm_attr_status}, + {OP_VENDOR_MESSAGE_ATTR_CONFIRMATION, 1, tm_attr_confirm}, + {OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG, 0, tm_attr_trans}, + BLE_MESH_MODEL_OP_END, +}; + +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_ALI_GENIE, 0x0000, vnd_model_op, NULL, NULL, &bt_mesh_als_vendor_model_cb), +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : als_avail_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t als_avail_tid_get(void) +{ + return als_tid++; +} + +/******************************************************************************* +* Function Name : uuid_generate +* Description : ɰ淶UUID +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void uuid_generate(struct bt_als_cfg const *cfg) +{ + /* Company ID */ + tm_uuid[0] = cfg->cid; + tm_uuid[1] = cfg->cid >> 8; + + /* bit30 㲥汾ţĿǰ0x01 + bit4Ϊ1һһ + bit5Ϊ1֧OTA + bit76Э汾 + 00BLE4.0 + 01BLE4.2 + 10BLE5.0 + 11BLE5.0 */ + /* Advertising Verison */ + tm_uuid[2] = BIT(0) | /* adv version */ + BIT(4) | /* secret */ + BIT(5) | /* ota */ + BIT(7); /* ble verison */ + + /* Product Id */ + tm_uuid[2 + 1] = cfg->pid; + tm_uuid[2 + 2] = cfg->pid >> 8; + tm_uuid[2 + 3] = cfg->pid >> 16; + tm_uuid[2 + 4] = cfg->pid >> 24; + + /* Device Mac Address */ + for(int i=0;i<6;i++) tm_uuid[2 + 1 + 4 + i] = cfg->mac[5-i]; + + /* UUID Verison */ + tm_uuid[2 + 1 + 4 + 6] = BIT(1); + + /* RFU */ + tm_uuid[2 + 1 + 4 + 6 + 1] = 0x00; + tm_uuid[2 + 1 + 4 + 6 + 2] = 0x00; +} + +/******************************************************************************* +* Function Name : num_to_str +* Description : תַ +* Input : +* Return : None +*******************************************************************************/ +static void num_to_str(u8_t *out, const u8_t *in, u16_t in_len) +{ + u16_t i; + static const char hex[] = "0123456789abcdef"; + + for (i = 0; i < in_len; i++) + { + out[i * 2] = hex[in[i] >> 4]; + out[i * 2 + 1] = hex[in[i] & 0xf]; + } +} + +/******************************************************************************* +* Function Name : oob_key_generate +* Description : OOB key +* Input : cfgϢ +* Return : None +*******************************************************************************/ +static void oob_key_generate(struct bt_als_cfg const *cfg) +{ + int err; + u32_t pid; + u8_t out[8 + 1 + 12 + 1 + 32], dig[32]; + struct tc_sha256_state_struct s; + + tc_sha256_init(&s); + + /** pid value */ + pid = ((u32_t)((((cfg->pid) >> 24) & 0xff) | \ + (((cfg->pid) >> 8) & 0xff00) | \ + (((cfg->pid)&0xff00) << 8) | \ + (((cfg->pid)&0xff) << 24))); + num_to_str(out, (void *)&pid, 4); + + /** Separator */ + strcpy((void *)(out + 8), ","); + /** mac value */ + num_to_str(out + 8 + 1, (void *)cfg->mac, 6); + + /** Separator */ + strcpy((void *)(out + 8 + 1 + 12), ","); + /** secret value */ + num_to_str(out + 8 + 1 + 12 + 1, (void *)cfg->secret, 16); + + err = tc_sha256_update(&s, out, sizeof(out)); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Update Sha256"); + return; + } + + err = tc_sha256_final(dig, &s); + if (err != TC_CRYPTO_SUCCESS) + { + APP_DBG("Unable Generate sha256 value"); + return; + } + + memcpy(static_key, dig, 16); +} + +/******************************************************************************* +* Function Name : ind_reset +* Description : Ƴб÷ɻصͷŻ +* Input : indҪõ֪ͨ + err +* Return : None +*******************************************************************************/ +static void ind_reset(struct bt_mesh_indicate *ind, int err) +{ + if (ind->param.cb && ind->param.cb->end) + { + ind->param.cb->end(err, ind->param.cb_data); + } + + tmos_msg_deallocate(ind->buf->__buf); + ind->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_reset +* Description : ͷδ͵֪ͨ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_reset(void) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf != NULL ) + { + ind_reset(&indicate[i], -ECANCELED); + } + } +} + +/******************************************************************************* +* Function Name : ind_start +* Description : indicate ʼص +* Input : durationηͽҪʱ + err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(als_vendor_model_TaskID, ind->event, K_MSEC(100) ); + return; + } +} + +/******************************************************************************* +* Function Name : ind_end +* Description : indicate ص +* Input : err + cb_data ص +* Return : None +*******************************************************************************/ +static void ind_end(int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.period ); +} + +// indicate صṹ +const struct bt_mesh_send_cb ind_cb = +{ + .start = ind_start, + .end = ind_end, +}; + +/******************************************************************************* +* Function Name : adv_ind_send +* Description : indicate +* Input : indҪ͵֪ͨ +* Return : None +*******************************************************************************/ +static void adv_ind_send(struct bt_mesh_indicate *ind) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, 32); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = vnd_models[0].keys[0], + .addr = ALI_TM_SUB_ADDRESS, + }; + + if (ind->buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (ind->param.trans_cnt == 0) + { + ind_reset(ind, -ETIMEDOUT); + return; + } + + ind->param.trans_cnt --; + + ctx.send_ttl = ind->param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, ind->buf->data, ind->buf->len); + + err = bt_mesh_model_send(vnd_models, &ctx, &msg, &ind_cb, ind); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + ind_reset(ind, -EIO); + return; + } +} + +/******************************************************************************* +* Function Name : bt_mesh_ind_allocһյ +* Description : һյindicateڴ +* Input : buf: Ҫ +* Return : indicateṹָ +*******************************************************************************/ +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ) +{ + uint8 i; + for(i = 0; i < CONFIG_INDICATE_NUM; i++) + { + if( indicate[i].buf->__buf == NULL ) + break; + } + if( i == CONFIG_INDICATE_NUM ) + return NULL; + + indicate[i].buf->__buf = tmos_msg_allocate(len); + indicate[i].buf->size = len; + + if( indicate[i].buf->__buf == NULL ) + return NULL; + + return &indicate[i]; +} + +/******************************************************************************* +* Function Name : bt_mesh_indicate_send +* Description : ֪ͨ¼ +* Input : None +* Return : None +*******************************************************************************/ +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ) +{ + tmos_start_task(als_vendor_model_TaskID, ind->event, ind->param.rand ); +} + +/******************************************************************************* +* Function Name : send_led_indicate +* Description : ͵ǰLED״̬LED״̬ʱҪô˺ +* Input : param ֪ͨķͲ +* Return : None +*******************************************************************************/ +void send_led_indicate(struct indicate_param *param) +{ + struct bt_mesh_indicate *ind; + + ind = bt_mesh_ind_alloc( 16 ); + if (!ind) + { + APP_DBG("Unable allocate buffers"); + return; + } + memcpy(&(ind->param), param, sizeof(struct indicate_param)); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&(ind->buf->b), OP_VENDOR_MESSAGE_ATTR_INDICATION); + + /* Add tid field */ + net_buf_simple_add_u8(&(ind->buf->b), param->tid); + + /* Add generic onoff attrbute op */ + net_buf_simple_add_le16(&(ind->buf->b), ALI_GEN_ATTR_TYPE_POWER_STATE); + + /* Add current generic onoff status */ + net_buf_simple_add_u8(&(ind->buf->b), read_led_state(MSG_PIN)); + + bt_mesh_indicate_send(ind); +} + +/******************************************************************************* +* Function Name : als_vendor_init +* Description : ģ ʼ +* Input : model: صģͲ +* Return : None +*******************************************************************************/ +static int als_vendor_init(struct bt_mesh_model *model) +{ + u32_t ran; + + uuid_generate(&cfg); + oob_key_generate(&cfg); + + /** Random Local TID Value + * @Caution Don't use single octer only. + */ + ran = tmos_rand(); + als_tid += ((u8_t *)&ran)[0]; + als_tid += ((u8_t *)&ran)[1]; + als_tid += ((u8_t *)&ran)[2]; + als_tid += ((u8_t *)&ran)[3]; + + + for(int i = 0; i < CONFIG_INDICATE_NUM; i++) + { + indicate[i].buf = &ind_buf[i]; + indicate[i].event = (1< ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/include/app_vendor_model.h b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/include/app_vendor_model.h new file mode 100644 index 0000000..3d6fc85 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/include/app_vendor_model.h @@ -0,0 +1,134 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_H +#define app_vendor_model_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/******************************************************************************/ + +#include "MESH_LIB.h" + +/******************************************************************************/ + +#define CID_ALI_GENIE 0x01A8 + +#define OP_VENDOR_MESSAGE_ATTR_GET BLE_MESH_MODEL_OP_3(0xD0, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET BLE_MESH_MODEL_OP_3(0xD1, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_SET_UNACK BLE_MESH_MODEL_OP_3(0xD2, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_STATUS BLE_MESH_MODEL_OP_3(0xD3, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_INDICATION BLE_MESH_MODEL_OP_3(0xD4, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_CONFIRMATION BLE_MESH_MODEL_OP_3(0xD5, CID_ALI_GENIE) +#define OP_VENDOR_MESSAGE_ATTR_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_ALI_GENIE) + +#define ALI_SYS_ATTR_TYPE_ERROR 0x0000 +#define ALI_SYS_ATTR_TYPE_VERSION 0xFF01 +#define ALI_SYS_ATTR_TYPE_DEV_FEATURE 0xFF02 +#define ALI_SYS_ATTR_TYPE_TOTAL_FLASH_SIZE 0xFF03 +#define ALI_SYS_ATTR_TYPE_USED_FLASH_SIZE 0xFF04 +#define ALI_SYS_ATTR_TYPE_FREE_FLASH_SIZE 0xFF05 +#define ALI_SYS_ATTR_TYPE_ENGINEER_MODE 0xFF06 + +#define ALI_GEN_ATTR_TYPE_WORK_STATUS 0xF001 +#define ALI_GEN_ATTR_TYPE_USER_ID 0xF002 +#define ALI_GEN_ATTR_TYPE_DEVICE_NAME 0xF003 +#define ALI_GEN_ATTR_TYPE_MODE_NUMBER 0xF004 +#define ALI_GEN_ATTR_TYPE_ONOFF_PLAN 0xF008 +#define ALI_GEN_ATTR_TYPE_EVENT_TRIGGER 0xF009 +#define ALI_GEN_ATTR_TYPE_EVENT_CLEAR 0xF019 +#define ALI_GEN_ATTR_TYPE_SIGNAL_INTENSITY 0xF00A +#define ALI_GEN_ATTR_TYPE_DELTA_VALUE 0xF00B +#define ALI_GEN_ATTR_TYPE_ELEMENT_COUNT 0xF00C +#define ALI_GEN_ATTR_TYPE_ATTR_SWITCH 0xF00D +#define ALI_GEN_ATTR_TYPE_REMOTE_ADDRESS 0xF00E +#define ALI_GEN_ATTR_TYPE_NEARBY_SIGNAL_INTEN 0xF00F +#define ALI_GEN_ATTR_TYPE_SET_VALUE_TIMING 0xF010 +#define ALI_GEN_ATTR_TYPE_SET_VALUE_PERIODIC 0xF011 +#define ALI_GEN_ATTR_TYPE_DEL_TIMING 0xF012 +#define ALI_GEN_ATTR_TYPE_REQ_UPDATE_TIMING 0xF013 +#define ALI_GEN_ATTR_TYPE_SETTING_TIMING 0xF01D +#define ALI_GEN_ATTR_TYPE_TIME_ZONE 0xF01E +#define ALI_GEN_ATTR_TYPE_UNIX_TIMER 0xF01F +#define ALI_GEN_ATTR_TYPE_POWERDOWN_MEM 0xF021 +#define ALI_GEN_ATTR_TYPE_CALORIES 0x06D5 +#define ALI_GEN_ATTR_TYPE_SPORTCOUNT 0x0212 +#define ALI_GEN_ATTR_TYPE_POWER_STATE 0x0100 +#define ALI_GEN_ATTR_TYPE_BRIGHTNESS 0x0121 +#define ALI_GEN_ATTR_TYPE_HARDWARE_RESET 0x0023 + +#define ALI_TM_SUB_ADDRESS 0xF000 + +/** Default number of Indication */ +#define CONFIG_INDICATE_NUM (3) + +/******************************************************************************/ + +struct bt_adv_ind_send_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + +struct indicate_param +{ + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_ind_send_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct indicate_param param; + struct net_buf *buf; + uint8 event; +}; + +struct bt_als_cfg +{ + /** Company Identify */ + u16_t cid; + + /** Product Identify */ + u32_t pid; + + /** Mac Address */ + u8_t mac[6]; + + /** Secret Information */ + u8_t secret[16]; + + /** Currently Library Version */ + u32_t version; +}; + +extern struct bt_mesh_model vnd_models[1]; +extern u8_t static_key[16]; +extern u8_t tm_uuid[16]; +extern const struct bt_mesh_model_cb bt_mesh_als_vendor_model_cb; +/******************************************************************************/ +u8_t als_avail_tid_get(void); +struct bt_mesh_indicate *bt_mesh_ind_alloc( uint16 len ); +void bt_mesh_indicate_send( struct bt_mesh_indicate *ind ); +void send_led_indicate(struct indicate_param *param); +void bt_mesh_indicate_reset(void); + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/include/peripheral.h b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/include/peripheral.h new file mode 100644 index 0000000..c139535 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/include/peripheral.h @@ -0,0 +1,66 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef PERIPHERAL_H +#define PERIPHERAL_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// Peripheral Task Events +#define SBP_START_DEVICE_EVT 0x0001 +#define SBP_PERIODIC_EVT 0x0002 +#define SBP_READ_RSSI_EVT 0x0004 +#define SBP_PARAM_UPDATE_EVT 0x0008 + +/********************************************************************* + * MACROS + */ +typedef struct +{ + uint16 connHandle; // Connection handle of current connection + uint16 connInterval; + uint16 connSlaveLatency; + uint16 connTimeout; +} peripheralConnItem_t; + + +/********************************************************************* + * FUNCTIONS + */ + +/* + * Task Initialization for the BLE Application + */ +extern void Peripheral_Init( void ); + +/* + * Task Event Processor for the BLE Application + */ +extern uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ); +extern void peripheralChar4Notify( uint8 *pValue, uint16 len ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/peripheral.c b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/peripheral.c new file mode 100644 index 0000000..84bd014 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/APP/peripheral.c @@ -0,0 +1,662 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ӻӦó򣬳ʼ㲥ӲȻ㲥 +* ӲͨԶ +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "gattprofile.h" +#include "peripheral.h" +#include "app.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// How often to perform periodic event +#define SBP_PERIODIC_EVT_PERIOD 1600 + +// How often to perform read rssi event +#define SBP_READ_RSSI_EVT_PERIOD 3200 + +// Parameter update delay +#define SBP_PARAM_UPDATE_DELAY 6400 + +// What is the advertising interval when device is discoverable (units of 625us, 80=50ms) +#define DEFAULT_ADVERTISING_INTERVAL 80 + +// Limited discoverable mode advertises for 30.72s, and then stops +// General discoverable mode advertises indefinitely +#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL + +// Minimum connection interval (units of 1.25ms, 20=25ms) +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 20 + +// Maximum connection interval (units of 1.25ms, 100=125ms) +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 100 + +// Slave latency to use parameter update +#define DEFAULT_DESIRED_SLAVE_LATENCY 0 + +// Supervision timeout value (units of 10ms, 100=1s) +#define DEFAULT_DESIRED_CONN_TIMEOUT 100 + +// Company Identifier: WCH +#define WCH_COMPANY_ID 0x07D7 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ +static uint8 Peripheral_TaskID = INVALID_TASK_ID; // Task ID for internal task/event processing + +// GAP - SCAN RSP data (max size = 31 bytes) +static uint8 scanRspData[ ] = +{ + // complete name + 0x12, // length of this data + GAP_ADTYPE_LOCAL_NAME_COMPLETE, + 'S', + 'i', + 'm', + 'p', + 'l', + 'e', + ' ', + 'P', + 'e', + 'r', + 'i', + 'p', + 'h', + 'e', + 'r', + 'a', + 'l', + // connection interval range + 0x05, // length of this data + GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE, + LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), // 100ms + HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), + LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), // 1s + HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), + + // Tx power level + 0x02, // length of this data + GAP_ADTYPE_POWER_LEVEL, + 0 // 0dBm +}; + +// GAP - Advertisement data (max size = 31 bytes, though this is +// best kept short to conserve power while advertising) +static uint8 advertData[] = +{ + // Flags; this sets the device to use limited discoverable + // mode (advertises for 30 seconds at a time) instead of general + // discoverable mode (advertises indefinitely) + 0x02, // length of this data + GAP_ADTYPE_FLAGS, + DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED, + + // service UUID, to notify central devices what services are included + // in this peripheral + 0x03, // length of this data + GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all + LO_UINT16( SIMPLEPROFILE_SERV_UUID ), + HI_UINT16( SIMPLEPROFILE_SERV_UUID ) +}; + +// GAP GATT Attributes +static uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "Simple Peripheral"; + +// Connection item list +static peripheralConnItem_t peripheralConnList; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ); +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent); +static void performPeriodicTask( void ); +static void simpleProfileChangeCB( uint8 paramID, uint8 *pValue, uint16 len ); +static void peripheralParamUpdateCB( uint16 connHandle, uint16 connInterval, + uint16 connSlaveLatency, uint16 connTimeout ); +static void peripheralInitConnItem( peripheralConnItem_t* peripheralConnList ); +static void peripheralRssiCB( uint16 connHandle, int8 rssi ); + +/********************************************************************* + * PROFILE CALLBACKS + */ + +// GAP Role Callbacks +static gapRolesCBs_t Peripheral_PeripheralCBs = +{ + peripheralStateNotificationCB, // Profile State Change Callbacks + peripheralRssiCB, // When a valid RSSI is read from controller (not used by application) + peripheralParamUpdateCB +}; + +// Broadcast Callbacks +static gapRolesBroadcasterCBs_t Broadcaster_BroadcasterCBs = +{ + NULL, // Not used in peripheral role + NULL // Receive scan request callback +}; + +// GAP Bond Manager Callbacks +static gapBondCBs_t Peripheral_BondMgrCBs = +{ + NULL, // Passcode callback (not used by application) + NULL // Pairing / Bonding state Callback (not used by application) +}; + +// Simple GATT Profile Callbacks +static simpleProfileCBs_t Peripheral_SimpleProfileCBs = +{ + simpleProfileChangeCB // Characteristic value change callback +}; +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn Peripheral_Init + * + * @brief Initialization function for the 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 TMOS. This ID should be + * used to send messages and set timers. + * + * @return none + */ +void Peripheral_Init( ) +{ + + Peripheral_TaskID = TMOS_ProcessEventRegister( Peripheral_ProcessEvent ); + + // Setup the GAP Peripheral Role Profile + { + uint8 initial_advertising_enable = TRUE; + uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL; + uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); + GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); + GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval ); + GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval ); + } + + // Set the GAP Characteristics + GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); + + // Set advertising interval + { + uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; + + GAP_SetParamValue( TGAP_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_DISC_ADV_INT_MAX, advInt ); + } + + // Setup the GAP Bond Manager + { + uint32 passkey = 0; // passkey "000000" + uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; + uint8 mitm = TRUE; + uint8 bonding = TRUE; + uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; + GAPBondMgr_SetParameter( GAPBOND_PERI_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); + GAPBondMgr_SetParameter( GAPBOND_PERI_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); + GAPBondMgr_SetParameter( GAPBOND_PERI_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); + GAPBondMgr_SetParameter( GAPBOND_PERI_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); + GAPBondMgr_SetParameter( GAPBOND_PERI_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); + } + + // Initialize GATT attributes + GGS_AddService( GATT_ALL_SERVICES ); // GAP + GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes + SimpleProfile_AddService( GATT_ALL_SERVICES ); // Simple GATT Profile + + // Setup the SimpleProfile Characteristic Values + { + uint8 charValue1[SIMPLEPROFILE_CHAR1_LEN] = { 1 }; + uint8 charValue2[SIMPLEPROFILE_CHAR2_LEN] = { 2 }; + uint8 charValue3[SIMPLEPROFILE_CHAR3_LEN] = { 3 }; + uint8 charValue4[SIMPLEPROFILE_CHAR4_LEN] = { 4 }; + uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 }; + + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, SIMPLEPROFILE_CHAR1_LEN, charValue1 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, SIMPLEPROFILE_CHAR2_LEN, charValue2 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, SIMPLEPROFILE_CHAR3_LEN, charValue3 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, charValue4 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); + } + + // Init Connection Item + peripheralInitConnItem( &peripheralConnList ); + + // Register callback with SimpleGATTprofile + SimpleProfile_RegisterAppCBs( &Peripheral_SimpleProfileCBs ); + + // Register receive scan request callback + GAPRole_BroadcasterSetCB( &Broadcaster_BroadcasterCBs ); + + // Setup a delayed profile startup + tmos_set_event( Peripheral_TaskID, SBP_START_DEVICE_EVT ); +} + +/********************************************************************* + * @fn peripheralInitConnItem + * + * @brief Init Connection Item + * + * @param peripheralConnList - + * + * @return NULL + */ +static void peripheralInitConnItem( peripheralConnItem_t* peripheralConnList ) +{ + peripheralConnList->connHandle = GAP_CONNHANDLE_INIT; + peripheralConnList->connInterval = 0; + peripheralConnList->connSlaveLatency = 0; + peripheralConnList->connTimeout = 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessEvent + * + * @brief 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 TMOS assigned task ID. + * @param events - events to process. This is a bit map and can + * contain more than one event. + * + * @return events not processed + */ +uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ) +{ + +// VOID task_id; // TMOS required parameter that isn't used in this function + + if ( events & SYS_EVENT_MSG ){ + uint8 *pMsg; + + if ( (pMsg = tmos_msg_receive( Peripheral_TaskID )) != NULL ){ + Peripheral_ProcessTMOSMsg( (tmos_event_hdr_t *)pMsg ); + // Release the TMOS message + tmos_msg_deallocate( pMsg ); + } + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } + + if ( events & SBP_START_DEVICE_EVT ){ + // Start the Device + GAPRole_PeripheralStartDevice( Peripheral_TaskID, &Peripheral_BondMgrCBs, &Peripheral_PeripheralCBs ); + return ( events ^ SBP_START_DEVICE_EVT ); + } + + if ( events & SBP_PERIODIC_EVT ) + { + // Restart timer + if ( SBP_PERIODIC_EVT_PERIOD ){ + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + } + // Perform periodic application task + performPeriodicTask(); + return (events ^ SBP_PERIODIC_EVT); + } + + if ( events & SBP_PARAM_UPDATE_EVT ) + { + // Send connect param update request + GAPRole_PeripheralConnParamUpdateReq( peripheralConnList.connHandle, + DEFAULT_DESIRED_MIN_CONN_INTERVAL, + DEFAULT_DESIRED_MAX_CONN_INTERVAL, + DEFAULT_DESIRED_SLAVE_LATENCY, + DEFAULT_DESIRED_CONN_TIMEOUT, + Peripheral_TaskID); + + return (events ^ SBP_PARAM_UPDATE_EVT); + } + + if ( events & SBP_READ_RSSI_EVT ) + { + GAPRole_ReadRssiCmd(peripheralConnList.connHandle); + tmos_start_task( Peripheral_TaskID, SBP_READ_RSSI_EVT, SBP_READ_RSSI_EVT_PERIOD ); + return (events ^ SBP_READ_RSSI_EVT); + } + + // Discard unknown events + return 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessTMOSMsg + * + * @brief Process an incoming task message. + * + * @param pMsg - message to process + * + * @return none + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ) +{ + switch ( pMsg->event ){ + default: + break; + } +} + +/********************************************************************* + * @fn Peripheral_LinkEstablished + * + * @brief Process link established. + * + * @param pEvent - event to process + * + * @return none + */ +static void Peripheral_LinkEstablished( gapRoleEvent_t * pEvent ) +{ + gapEstLinkReqEvent_t *event = (gapEstLinkReqEvent_t *) pEvent; + + // See if already connected + if( peripheralConnList.connHandle != GAP_CONNHANDLE_INIT ) + { + GAPRole_TerminateLink( pEvent->linkCmpl.connectionHandle ); + PRINT( "Connection max...\n" ); + } + else + { + peripheralConnList.connHandle = event->connectionHandle; + peripheralConnList.connInterval = event->connInterval; + peripheralConnList.connSlaveLatency = event->connLatency; + peripheralConnList.connTimeout = event->connTimeout; + + // Set timer for periodic event +// tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + + // Set timer for param update event + tmos_start_task( Peripheral_TaskID, SBP_PARAM_UPDATE_EVT, SBP_PARAM_UPDATE_DELAY ); + + // Start read rssi + tmos_start_task( Peripheral_TaskID, SBP_READ_RSSI_EVT, SBP_READ_RSSI_EVT_PERIOD ); + + PRINT("Conn %x - Int %x \n", event->connectionHandle, event->connInterval); + } +} + +/********************************************************************* + * @fn Peripheral_LinkTerminated + * + * @brief Process link terminated. + * + * @param pEvent - event to process + * + * @return none + */ +static void Peripheral_LinkTerminated( gapRoleEvent_t * pEvent ) +{ + gapTerminateLinkEvent_t *event = (gapTerminateLinkEvent_t *) pEvent; + + if( event->connectionHandle == peripheralConnList.connHandle ) + { + peripheralConnList.connHandle = GAP_CONNHANDLE_INIT; + peripheralConnList.connInterval = 0; + peripheralConnList.connSlaveLatency = 0; + peripheralConnList.connTimeout = 0; + tmos_stop_task( Peripheral_TaskID, SBP_PERIODIC_EVT ); + tmos_stop_task( Peripheral_TaskID, SBP_READ_RSSI_EVT ); + + // Restart advertising + { + uint8 advertising_enable = TRUE; + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &advertising_enable ); + } + } + else + { + PRINT("ERR..\n"); + } +} + +/********************************************************************* + * @fn peripheralRssiCB + * + * @brief RSSI callback. + * + * @param connHandle - connection handle + * @param rssi - RSSI + * + * @return none + */ +static void peripheralRssiCB( uint16 connHandle, int8 rssi ) +{ + PRINT( "RSSI -%d dB Conn %x \n", -rssi, connHandle); +} + +/********************************************************************* + * @fn peripheralParamUpdateCB + * + * @brief Parameter update complete callback + * + * @param connHandle - connect handle + * connInterval - connect interval + * connSlaveLatency - connect slave latency + * connTimeout - connect timeout + * + * @return none + */ +static void peripheralParamUpdateCB( uint16 connHandle, uint16 connInterval, + uint16 connSlaveLatency, uint16 connTimeout ) +{ + if( connHandle == peripheralConnList.connHandle ) + { + peripheralConnList.connInterval = connInterval; + peripheralConnList.connSlaveLatency = connSlaveLatency; + peripheralConnList.connTimeout = connTimeout; + + PRINT("Update %x - Int %x \n", connHandle, connInterval); + } + else + { + PRINT("ERR..\n"); + } +} + +/********************************************************************* + * @fn peripheralStateNotificationCB + * + * @brief Notification from the profile of a state change. + * + * @param newState - new state + * + * @return none + */ +static void peripheralStateNotificationCB( gapRole_States_t newState, gapRoleEvent_t * pEvent ) +{ + switch ( newState ) + { + case GAPROLE_STARTED: + PRINT( "Initialized..\n" ); + break; + + case GAPROLE_ADVERTISING: + if( pEvent->gap.opcode == GAP_LINK_TERMINATED_EVENT ) + { + Peripheral_LinkTerminated( pEvent ); + PRINT( "Disconnected.. Reason:%x\n",pEvent->linkTerminate.reason ); + } + PRINT( "Advertising..\n" ); + break; + + case GAPROLE_CONNECTED: + if( pEvent->gap.opcode == GAP_LINK_ESTABLISHED_EVENT ) + { + Peripheral_LinkEstablished( pEvent ); + } + PRINT( "Connected..\n" ); + break; + + case GAPROLE_CONNECTED_ADV: + PRINT( "Connected Advertising..\n" ); + break; + + case GAPROLE_WAITING: + if( pEvent->gap.opcode == GAP_END_DISCOVERABLE_DONE_EVENT ) + { + PRINT( "Waiting for advertising..\n" ); + } + else if( pEvent->gap.opcode == GAP_LINK_TERMINATED_EVENT ) + { + Peripheral_LinkTerminated( pEvent ); + PRINT( "Disconnected.. Reason:%x\n",pEvent->linkTerminate.reason ); + } + else if( pEvent->gap.opcode == GAP_LINK_ESTABLISHED_EVENT ) + { + if( pEvent->gap.hdr.status != SUCCESS ) + { + PRINT( "Waiting for advertising..\n" ); + } + else + { + PRINT( "Error..\n" ); + } + } + else + { + PRINT( "Error..%x\n",pEvent->gap.opcode ); + } + break; + + case GAPROLE_ERROR: + PRINT( "Error..\n" ); + break; + + default: + break; + } +} + +/********************************************************************* + * @fn performPeriodicTask + * + * @brief Perform a periodic application task. This function gets + * called every five seconds as a result of the SBP_PERIODIC_EVT + * TMOS event. In this example, the value of the third + * characteristic in the SimpleGATTProfile service is retrieved + * from the profile, and then copied into the value of the + * the fourth characteristic. + * + * @param none + * + * @return none + */ +static void performPeriodicTask( void ) +{ + uint8 notiData[SIMPLEPROFILE_CHAR4_LEN] = { 0x88 }; + peripheralChar4Notify( notiData, SIMPLEPROFILE_CHAR4_LEN ); +} + +/********************************************************************* + * @fn peripheralChar4Notify + * + * @brief Prepare and send simpleProfileChar4 notification + * + * @param pValue - data to notify + * len - length of data + * + * @return none + */ +void peripheralChar4Notify( uint8 *pValue, uint16 len ) +{ + attHandleValueNoti_t noti; + noti.len = len; + noti.pValue = GATT_bm_alloc( peripheralConnList.connHandle, ATT_HANDLE_VALUE_NOTI, noti.len, NULL, 0 ); + tmos_memcpy( noti.pValue, pValue, noti.len ); + if( simpleProfile_Notify( peripheralConnList.connHandle, ¬i ) != SUCCESS ) + { + GATT_bm_free( (gattMsg_t *)¬i, ATT_HANDLE_VALUE_NOTI ); + } +} + +/********************************************************************* + * @fn simpleProfileChangeCB + * + * @brief Callback from SimpleBLEProfile indicating a value change + * + * @param paramID - parameter ID of the value that was changed. + * pValue - pointer to data that was changed + * len - length of data + * + * @return none + */ +static void simpleProfileChangeCB( uint8 paramID, uint8 *pValue, uint16 len ) +{ + + switch( paramID ) + { + case SIMPLEPROFILE_CHAR1: + { + uint8 newValue[SIMPLEPROFILE_CHAR1_LEN]; + tmos_memcpy( newValue, pValue, len ); + // յCHAR1ݣת״̬ + send_led_state(); + PRINT("profile ChangeCB CHAR1.. \n"); + break; + } + + case SIMPLEPROFILE_CHAR3: + { + uint8 newValue[SIMPLEPROFILE_CHAR3_LEN]; + tmos_memcpy( newValue, pValue, len ); + // յCHAR3ݣmesh + send_reset_indicate(); + PRINT("profile ChangeCB CHAR3..\n"); + break; + } + + default: + // should not reach here! + break; + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Profile/gattprofile.c b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Profile/gattprofile.c new file mode 100644 index 0000000..e7d852e --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Profile/gattprofile.c @@ -0,0 +1,744 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : gattprofile.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ԶֲͬԵķ񣬰ɶд֪ͨɶдȫɶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "gattprofile.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// Position of simpleProfilechar4 value in attribute array +#define SIMPLEPROFILE_CHAR4_VALUE_POS 11 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// 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: 0xFFF1 +CONST uint8 simpleProfilechar1UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR1_UUID), HI_UINT16(SIMPLEPROFILE_CHAR1_UUID) +}; + +// Characteristic 2 UUID: 0xFFF2 +CONST uint8 simpleProfilechar2UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR2_UUID), HI_UINT16(SIMPLEPROFILE_CHAR2_UUID) +}; + +// Characteristic 3 UUID: 0xFFF3 +CONST uint8 simpleProfilechar3UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR3_UUID), HI_UINT16(SIMPLEPROFILE_CHAR3_UUID) +}; + +// Characteristic 4 UUID: 0xFFF4 +CONST uint8 simpleProfilechar4UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR4_UUID), HI_UINT16(SIMPLEPROFILE_CHAR4_UUID) +}; + +// Characteristic 5 UUID: 0xFFF5 +CONST uint8 simpleProfilechar5UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR5_UUID), HI_UINT16(SIMPLEPROFILE_CHAR5_UUID) +}; + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +static simpleProfileCBs_t *simpleProfile_AppCBs = NULL; + +/********************************************************************* + * Profile Attributes - variables + */ + +// Simple Profile Service attribute +static CONST gattAttrType_t simpleProfileService = { ATT_BT_UUID_SIZE, simpleProfileServUUID }; + + +// Simple Profile Characteristic 1 Properties +static uint8 simpleProfileChar1Props = GATT_PROP_READ | GATT_PROP_WRITE; + +// Characteristic 1 Value +static uint8 simpleProfileChar1[SIMPLEPROFILE_CHAR1_LEN] = { 0 }; + +// Simple Profile Characteristic 1 User Description +static uint8 simpleProfileChar1UserDesp[] = "Characteristic 1\0"; + + +// Simple Profile Characteristic 2 Properties +static uint8 simpleProfileChar2Props = GATT_PROP_READ; + +// Characteristic 2 Value +static uint8 simpleProfileChar2[SIMPLEPROFILE_CHAR2_LEN] = { 0 }; + +// Simple Profile Characteristic 2 User Description +static uint8 simpleProfileChar2UserDesp[] = "Characteristic 2\0"; + + +// Simple Profile Characteristic 3 Properties +static uint8 simpleProfileChar3Props = GATT_PROP_WRITE; + +// Characteristic 3 Value +static uint8 simpleProfileChar3[SIMPLEPROFILE_CHAR3_LEN] = { 0 }; + +// Simple Profile Characteristic 3 User Description +static uint8 simpleProfileChar3UserDesp[] = "Characteristic 3\0"; + + +// Simple Profile Characteristic 4 Properties +static uint8 simpleProfileChar4Props = GATT_PROP_NOTIFY; + +// Characteristic 4 Value +static uint8 simpleProfileChar4[SIMPLEPROFILE_CHAR4_LEN] = { 0 }; + +// Simple Profile Characteristic 4 Configuration Each client has its own +// instantiation of the Client Characteristic Configuration. Reads of the +// Client Characteristic Configuration only shows the configuration for +// that client and writes only affect the configuration of that client. +static gattCharCfg_t simpleProfileChar4Config[4]; + +// Simple Profile Characteristic 4 User Description +static uint8 simpleProfileChar4UserDesp[] = "Characteristic 4\0"; + + +// Simple Profile Characteristic 5 Properties +static uint8 simpleProfileChar5Props = GATT_PROP_READ; + +// Characteristic 5 Value +static uint8 simpleProfileChar5[SIMPLEPROFILE_CHAR5_LEN] = { 0 }; + +// Simple Profile Characteristic 5 User Description +static uint8 simpleProfileChar5UserDesp[] = "Characteristic 5\0"; + + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t simpleProfileAttrTbl[] = +{ + // Simple Profile Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&simpleProfileService /* pValue */ + }, + + // Characteristic 1 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar1Props + }, + + // Characteristic Value 1 + { + { ATT_BT_UUID_SIZE, simpleProfilechar1UUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + simpleProfileChar1 + }, + + // Characteristic 1 User Description + { + { 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, + 0, + simpleProfileChar2 + }, + + // Characteristic 2 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar2UserDesp + }, + + // Characteristic 3 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar3Props + }, + + // Characteristic Value 3 + { + { ATT_BT_UUID_SIZE, simpleProfilechar3UUID }, + GATT_PERMIT_WRITE, + 0, + simpleProfileChar3 + }, + + // Characteristic 3 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar3UserDesp + }, + + // Characteristic 4 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar4Props + }, + + // Characteristic Value 4 + { + { ATT_BT_UUID_SIZE, simpleProfilechar4UUID }, + 0, + 0, + simpleProfileChar4 + }, + + // Characteristic 4 configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8 *)simpleProfileChar4Config + }, + + // Characteristic 4 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar4UserDesp + }, + + // Characteristic 5 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar5Props + }, + + // Characteristic Value 5 + { + { ATT_BT_UUID_SIZE, simpleProfilechar5UUID }, + GATT_PERMIT_AUTHEN_READ, + 0, + simpleProfileChar5 + }, + + // Characteristic 5 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar5UserDesp + }, +}; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ); + +static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); + + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Simple Profile Service Callbacks +gattServiceCBs_t simpleProfileCBs = +{ + simpleProfile_ReadAttrCB, // Read callback function pointer + simpleProfile_WriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn SimpleProfile_AddService + * + * @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. + * + * @return Success or Failure + */ +bStatus_t SimpleProfile_AddService( uint32 services ) +{ + uint8 status = SUCCESS; + + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar4Config ); + + // Register with Link DB to receive link status change callback + 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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &simpleProfileCBs ); + } + + return ( status ); +} + + +/********************************************************************* + * @fn SimpleProfile_RegisterAppCBs + * + * @brief Registers the application callback function. Only call + * this function once. + * + * @param callbacks - pointer to application callbacks. + * + * @return SUCCESS or bleAlreadyInRequestedMode + */ +bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) +{ + if ( appCallbacks ) + { + simpleProfile_AppCBs = appCallbacks; + + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } +} + + +/********************************************************************* + * @fn SimpleProfile_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + if ( len == SIMPLEPROFILE_CHAR1_LEN ) + { + tmos_memcpy( simpleProfileChar1, value, SIMPLEPROFILE_CHAR1_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR2: + if ( len == SIMPLEPROFILE_CHAR2_LEN ) + { + tmos_memcpy( simpleProfileChar2, value, SIMPLEPROFILE_CHAR2_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR3: + if ( len == SIMPLEPROFILE_CHAR3_LEN ) + { + tmos_memcpy( simpleProfileChar3, value, SIMPLEPROFILE_CHAR3_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR4: + if ( len == SIMPLEPROFILE_CHAR4_LEN ) + { + tmos_memcpy( simpleProfileChar4, value, SIMPLEPROFILE_CHAR4_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR5: + if ( len == SIMPLEPROFILE_CHAR5_LEN ) + { + tmos_memcpy( simpleProfileChar5, value, SIMPLEPROFILE_CHAR5_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn SimpleProfile_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + tmos_memcpy( value, simpleProfileChar1, SIMPLEPROFILE_CHAR1_LEN ); + break; + + case SIMPLEPROFILE_CHAR2: + tmos_memcpy( value, simpleProfileChar2, SIMPLEPROFILE_CHAR2_LEN ); + break; + + case SIMPLEPROFILE_CHAR3: + tmos_memcpy( value, simpleProfileChar3, SIMPLEPROFILE_CHAR3_LEN ); + break; + + case SIMPLEPROFILE_CHAR4: + tmos_memcpy( value, simpleProfileChar4, SIMPLEPROFILE_CHAR4_LEN ); + break; + + case SIMPLEPROFILE_CHAR5: + tmos_memcpy( value, simpleProfileChar5, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn simpleProfile_Notify + * + * @brief Send a notification containing a heart rate + * measurement. + * + * @param connHandle - connection handle + * @param pNoti - pointer to notification structure + * + * @return Success or Failure + */ +bStatus_t simpleProfile_Notify( uint16 connHandle, attHandleValueNoti_t *pNoti ) +{ + uint16 value = GATTServApp_ReadCharCfg( connHandle, simpleProfileChar4Config ); + + // If notifications enabled + if ( value & GATT_CLIENT_CFG_NOTIFY ) + { + // Set the handle + pNoti->handle = simpleProfileAttrTbl[SIMPLEPROFILE_CHAR4_VALUE_POS].handle; + + // Send the notification + return GATT_Notification( connHandle, pNoti, FALSE ); + } + return bleIncorrectMode; +} + +/********************************************************************* + * @fn simpleProfile_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + + // If attribute permissions require authorization to read, return error + if ( gattPermitAuthorRead( pAttr->permissions ) ) + { + // 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 + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + // No need for "GATT_SERVICE_UUID" or "GATT_CLIENT_CHAR_CFG_UUID" cases; + // gattserverapp handles those reads + + // characteristics 1 and 2 have read permissions + // characteritisc 3 does not have read permissions; therefore it is not + // included here + // characteristic 4 does not have read permissions, but because it + // can be sent as a notification, it is included here + case SIMPLEPROFILE_CHAR1_UUID: + *pLen = SIMPLEPROFILE_CHAR1_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR1_LEN ); + break; + + case SIMPLEPROFILE_CHAR2_UUID: + *pLen = SIMPLEPROFILE_CHAR2_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR2_LEN ); + break; + + case SIMPLEPROFILE_CHAR4_UUID: + *pLen = SIMPLEPROFILE_CHAR4_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR4_LEN ); + break; + + case SIMPLEPROFILE_CHAR5_UUID: + *pLen = SIMPLEPROFILE_CHAR5_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint8 notifyApp = 0xFF; + + // If attribute permissions require authorization to write, return error + if ( gattPermitAuthorWrite( pAttr->permissions ) ) + { + // Insufficient authorization + return ( ATT_ERR_INSUFFICIENT_AUTHOR ); + } + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + case SIMPLEPROFILE_CHAR1_UUID: + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len > SIMPLEPROFILE_CHAR1_LEN ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + tmos_memcpy( pAttr->pValue, pValue, SIMPLEPROFILE_CHAR1_LEN ); + notifyApp = SIMPLEPROFILE_CHAR1; + } + break; + + case SIMPLEPROFILE_CHAR3_UUID: + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len > SIMPLEPROFILE_CHAR3_LEN ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + tmos_memcpy( pAttr->pValue, pValue, SIMPLEPROFILE_CHAR3_LEN ); + notifyApp = SIMPLEPROFILE_CHAR3; + } + break; + + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); + break; + + default: + // Should never get here! (characteristics 2 and 4 do not have write permissions) + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + status = ATT_ERR_INVALID_HANDLE; + } + + // 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, pValue, len ); + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_HandleConnStatusCB + * + * @brief Simple Profile link status change handler function. + * + * @param connHandle - connection handle + * @param changeType - type of change + * + * @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 ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, simpleProfileChar4Config ); + } + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Profile/include/gattprofile.h b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Profile/include/gattprofile.h new file mode 100644 index 0000000..a5a10b8 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Profile/include/gattprofile.h @@ -0,0 +1,137 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : gattprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef GATTPROFILE_H +#define GATTPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// 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 + +// Simple Profile Service UUID +#define SIMPLEPROFILE_SERV_UUID 0xFFE0 + +// Key Pressed UUID +#define SIMPLEPROFILE_CHAR1_UUID 0xFFE1 +#define SIMPLEPROFILE_CHAR2_UUID 0xFFE2 +#define SIMPLEPROFILE_CHAR3_UUID 0xFFE3 +#define SIMPLEPROFILE_CHAR4_UUID 0xFFE4 +#define SIMPLEPROFILE_CHAR5_UUID 0xFFE5 + +// Simple Keys Profile Services bit fields +#define SIMPLEPROFILE_SERVICE 0x00000001 + +// Length of characteristic in bytes ( Default MTU is 23 ) +#define SIMPLEPROFILE_CHAR1_LEN 21 +#define SIMPLEPROFILE_CHAR2_LEN 1 +#define SIMPLEPROFILE_CHAR3_LEN 21 +#define SIMPLEPROFILE_CHAR4_LEN 19 +#define SIMPLEPROFILE_CHAR5_LEN 5 + +/********************************************************************* + * TYPEDEFS + */ + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// Callback when a characteristic value has changed +typedef void (*simpleProfileChange_t)( uint8 paramID, uint8 *pValue, uint16 len ); + +typedef struct +{ + simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes +} simpleProfileCBs_t; + + + +/********************************************************************* + * API FUNCTIONS + */ + + +/* + * SimpleProfile_AddService- Initializes the Simple GATT 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. + */ + +extern bStatus_t SimpleProfile_AddService( uint32 services ); + +/* + * SimpleProfile_RegisterAppCBs - Registers the application callback function. + * Only call this function once. + * + * 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). + */ +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). + */ +extern bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ); + +/* + * simpleProfile_Notify - Send notification. + * + * connHandle - connect handle + * pNoti - pointer to structure to notify. + */ +extern bStatus_t simpleProfile_Notify( uint16 connHandle, attHandleValueNoti_t *pNoti ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Project/BLE.uvprojx new file mode 100644 index 0000000..8f36118 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_ali_light_with_peripheral/Project/BLE.uvprojx @@ -0,0 +1,592 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model.c + 1 + ..\APP\app_vendor_model.c + + + app_generic_onoff_model.c + 1 + ..\APP\app_generic_onoff_model.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + peripheral.c + 1 + ..\APP\peripheral.c + + + gattprofile.c + 1 + ..\Profile\gattprofile.c + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/adv_proxy/APP/app.c b/src/EXAM/BLE/MESH/adv_proxy/APP/app.c new file mode 100644 index 0000000..a714830 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/APP/app.c @@ -0,0 +1,352 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_generic_onoff_model.h" +#include "app.h" +#include "HAL.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void prov_reset(void); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +static struct bt_mesh_health_srv health_srv; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), + BLE_MESH_MODEL(BLE_MESH_MODEL_ID_GEN_ONOFF_SRV, gen_onoff_op, NULL, NULL), +}; + +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + } +}; +static uint8_t dev_uuid[16]; +u8 MACAddr[6]; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = dev_uuid, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .reset = prov_reset, +}; + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } + +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkصֹͣ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(" "); +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : reason : link close reason ͷļ +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG("reason %x",reason); + + if (!bt_mesh_is_provisioned()) + { + prov_enable(); + } + else + { + } +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص¿ʼ㲥 +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ +} + +/******************************************************************************* +* Function Name : prov_reset +* Description : λܻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_reset(void) +{ + APP_DBG(""); + + prov_enable(); +} + +/******************************************************************************* +* Function Name : keyPress +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void keyPress(uint8 keys) +{ + APP_DBG("keys %d ",keys); + + switch (keys) + { + default: + break; + } +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + PRINT("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + GetMACAddress( MACAddr ); + tmos_memcpy(dev_uuid, MACAddr, 6); + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MACAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress); + + tmos_set_event(App_TaskID, APP_USER_EVT); + +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_USER_EVT ) + { + return ( events ^ APP_USER_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_proxy/APP/app_generic_onoff_model.c b/src/EXAM/BLE/MESH/adv_proxy/APP/app_generic_onoff_model.c new file mode 100644 index 0000000..96aa8b7 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/APP/app_generic_onoff_model.c @@ -0,0 +1,163 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_generic_onoff_model.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +#define ALI_DEF_TTL (10) + +/******************************************************************************* +* Function Name : read_led_state +* Description : ȡǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : õǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : תǰ״̬ +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + + +/******************************************************************************* +* Function Name : gen_onoff_status +* Description : ظè鿪״̬ +* Input : model: ģͲ +* ctxݲ +* Return : None +*******************************************************************************/ +static void gen_onoff_status(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx) +{ + NET_BUF_SIMPLE_DEFINE(msg, 32); + int err; + + bt_mesh_model_msg_init(&msg, BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS); + net_buf_simple_add_u8(&msg, read_led_state(MSG_PIN)); + + APP_DBG("ttl: 0x%02x dst: 0x%04x", ctx->recv_ttl, ctx->recv_dst); + + if (ctx->recv_ttl != ALI_DEF_TTL) + { + ctx->send_ttl = BLE_MESH_TTL_DEFAULT; + } + else + { + ctx->send_ttl = 0; + } + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : gen_onoff_get +* Description : è·Ļȡ״̬ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_get(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG(" "); + + gen_onoff_status(model, ctx); +} + + +/******************************************************************************* +* Function Name : gen_onoff_set +* Description : è·ÿ״̬ + 뵱ǰ״̬ͬ,Ҫindè +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + APP_DBG("ttl: 0x%02x dst: 0x%04x rssi: %d", + ctx->recv_ttl, ctx->recv_dst, ctx->recv_rssi); + + set_led_state(MSG_PIN, buf->data[0]); + gen_onoff_status(model, ctx); +} + +/******************************************************************************* +* Function Name : gen_onoff_set_unack +* Description : è·ÿ״̬(Ӧ) +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void gen_onoff_set_unack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t status; + + APP_DBG(" "); + + status = read_led_state(MSG_PIN); + if (status != buf->data[0]) + { + set_led_state(MSG_PIN, buf->data[0]); + } +} + +const struct bt_mesh_model_op gen_onoff_op[] = { + {BLE_MESH_MODEL_OP_GEN_ONOFF_GET, 0, gen_onoff_get}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET, 2, gen_onoff_set}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK, 2, gen_onoff_set_unack}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_proxy/APP/app_main.c b/src/EXAM/BLE/MESH/adv_proxy/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_proxy/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_proxy/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_proxy/APP/include/app.h b/src/EXAM/BLE/MESH/adv_proxy/APP/include/app.h new file mode 100644 index 0000000..d1403e4 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/APP/include/app.h @@ -0,0 +1,34 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_H +#define app_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/******************************************************************************/ + +#define APP_USER_EVT (1<<0) + +/******************************************************************************/ + +void App_Init(void); + +/******************************************************************************/ + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_proxy/APP/include/app_generic_onoff_model.h b/src/EXAM/BLE/MESH/adv_proxy/APP/include/app_generic_onoff_model.h new file mode 100644 index 0000000..bedeb89 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/APP/include/app_generic_onoff_model.h @@ -0,0 +1,32 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_generic_onoff_model_H +#define app_generic_onoff_model_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "MESH_LIB.h" +#define MSG_PIN GPIO_Pin_12 + +BOOL read_led_state(u32_t led_pin); + +extern const struct bt_mesh_model_op gen_onoff_op[]; +void set_led_state(u32_t led_pin, BOOL on); + +void toggle_led_state(u32_t led_pin); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_proxy/APP/include/app_mesh_config.h b/src/EXAM/BLE/MESH/adv_proxy/APP/include/app_mesh_config.h new file mode 100644 index 0000000..7240a16 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/APP/include/app_mesh_config.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + +#ifndef APP_MESH_CONFIG_H +#define APP_MESH_CONFIG_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/**************************,ֱӲοͬ*****************************/ + +// relay +#define CONFIG_BLE_MESH_RELAY 1 +// +#define CONFIG_BLE_MESH_PROXY 1 +// GATT +#define CONFIG_BLE_MESH_PB_GATT 1 +// FLASH洢 +#define CONFIG_BLE_MESH_SETTINGS 1 +// ѽڵ㹦 +#define CONFIG_BLE_MESH_FRIEND 0 +// ͹Ľڵ㹦 +#define CONFIG_BLE_MESH_LOW_POWER 0 +// configģͿͻ˹ +#define CONFIG_BLE_MESH_CFG_CLI 0 +// healthģͿͻ˹ +#define CONFIG_BLE_MESH_HLTH_CLI 0 + + +/******************************************************************************/ + +// Netݻ +#define CONFIG_MESH_ADV_BUF_COUNT_MIN (6) +#define CONFIG_MESH_ADV_BUF_COUNT_DEF (10) +#define CONFIG_MESH_ADV_BUF_COUNT_MAX (40) + +// RPLݻ +#define CONFIG_MESH_RPL_COUNT_MIN (6) +#define CONFIG_MESH_RPL_COUNT_DEF (6) +#define CONFIG_MESH_RPL_COUNT_MAX (20) + +// IV Update State Timer 96HķƵϵ +#define CONFIG_MESH_IVU_DIVIDER_MIN (1) +#define CONFIG_MESH_IVU_DIVIDER_DEF (96) +#define CONFIG_MESH_IVU_DIVIDER_MAX (96) + +// ڰܴ洢 +#define CONFIG_MESH_PROXY_FILTER_MIN (2) +#define CONFIG_MESH_PROXY_FILTER_DEF (5) +#define CONFIG_MESH_PROXY_FILTER_MAX (20) + +// Ϣ +#define CONFIG_MESH_MSG_CACHE_MIN (3) +#define CONFIG_MESH_MSG_CACHE_DEF (20) +#define CONFIG_MESH_MSG_CACHE_MAX (20) + +// +#define CONFIG_MESH_SUBNET_COUNT_MIN (1) +#define CONFIG_MESH_SUBNET_COUNT_DEF (1) +#define CONFIG_MESH_SUBNET_COUNT_MAX (4) + +// APP key +#define CONFIG_MESH_APPKEY_COUNT_MIN (1) +#define CONFIG_MESH_APPKEY_COUNT_DEF (3) +#define CONFIG_MESH_APPKEY_COUNT_MAX (5) + +// ǷһдַͬĽڵ㣨ʹְܺܲã +#define CONFIG_MESH_ALLOW_SAME_ADDR (FALSE) + +// ְϢֵ֧ijȣ˳ҪְĬֵΪ7޸Ĵֵϱ׼meshЭ飩 +#define CONFIG_MESH_UNSEG_LENGTH_MIN (7) +#define CONFIG_MESH_UNSEG_LENGTH_DEF (7) +#define CONFIG_MESH_UNSEG_LENGTH_MAX (221) + +// ÿϢְ +#define CONFIG_MESH_TX_SEG_MIN (2) +#define CONFIG_MESH_TX_SEG_DEF (8) +#define CONFIG_MESH_TX_SEG_MAX (32) + +// ͬʱڵķְϢ͸ +#define CONFIG_MESH_TX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_TX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_TX_SEG_COUNT_MAX (4) + +// ͬʱڵķְϢո +#define CONFIG_MESH_RX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_RX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_RX_SEG_COUNT_MAX (4) + +// ÿյķְϢֽ +#define CONFIG_MESH_RX_SDU_MIN (12) +#define CONFIG_MESH_RX_SDU_DEF (192) +#define CONFIG_MESH_RX_SDU_MAX (384) + +// ַ +#define CONFIG_MESH_LABEL_COUNT_MIN (1) +#define CONFIG_MESH_LABEL_COUNT_DEF (2) +#define CONFIG_MESH_LABEL_COUNT_MAX (4) + +// NVS洢ʹ +#define CONFIG_MESH_SECTOR_COUNT_MIN (2) +#define CONFIG_MESH_SECTOR_COUNT_DEF (3) + +// NVS洢׵ַ +#define CONFIG_MESH_NVS_ADDR_DEF (0x3E800) + +// RPLº洢ijʱʱ(s) +#define CONFIG_MESH_RPL_STORE_RATE_MIN (5) +#define CONFIG_MESH_RPL_STORE_RATE_DEF (60) +#define CONFIG_MESH_RPL_STORE_RATE_MAX (3600) + +// SEQº洢ijʱʱ(s) +#define CONFIG_MESH_SEQ_STORE_RATE_MIN (5) +#define CONFIG_MESH_SEQ_STORE_RATE_DEF (60) +#define CONFIG_MESH_SEQ_STORE_RATE_MAX (3600) + +// Ϣº洢ijʱʱ(s) +#define CONFIG_MESH_STORE_RATE_MIN (2) +#define CONFIG_MESH_STORE_RATE_DEF (2) +#define CONFIG_MESH_STORE_RATE_MAX (5) + +// ѽڵֵ֧ÿϢķְ +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF (2) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MAX (4) + +// ѽڵֵ֧Ķĸ +#define CONFIG_MESH_FRIEND_SUB_SIZE_MIN (1) +#define CONFIG_MESH_FRIEND_SUB_SIZE_DEF (4) +#define CONFIG_MESH_FRIEND_SUB_SIZE_MAX (8) + +// ѽڵֵ֧ĵ͹Ľڵ +#define CONFIG_MESH_FRIEND_LPN_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_DEF (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_MAX (4) + +// ѽڵ洢ϢдС +#define CONFIG_MESH_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_QUEUE_SIZE_DEF (4) +#define CONFIG_MESH_QUEUE_SIZE_MAX (30) + +// ѽڵմڴС(ms) +#define CONFIG_MESH_FRIEND_RECV_WIN_MIN (1) +#define CONFIG_MESH_FRIEND_RECV_WIN_DEF (20) +#define CONFIG_MESH_FRIEND_RECV_WIN_MAX (255) + +// ͹ĽڵϢдС +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MAX (20) + +// ͹ĽڵϢʱʱ(10ms) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MIN (30) +#define CONFIG_MESH_LPN_POLLTIMEOUT_DEF (40) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MAX (400) + +// ͹Ľڵֵ֧Ľӳ(ms) +#define CONFIG_MESH_LPN_RECV_DELAY_MIN (100) +#define CONFIG_MESH_LPN_RECV_DELAY_DEF (100) +#define CONFIG_MESH_LPN_RECV_DELAY_MAX (400) + +// ѹϵؽȴʱ(s) +#define CONFIG_MESH_RETRY_TIMEOUT_MIN (3) +#define CONFIG_MESH_RETRY_TIMEOUT_DEF (10) +#define CONFIG_MESH_RETRY_TIMEOUT_MAX (60) + +// ֵ֧豸ڵ +#define CONFIG_MESH_PROV_NODE_COUNT_MIN (1) +#define CONFIG_MESH_PROV_NODE_COUNT_DEF (2) + +// ADV_RF +#define CONFIG_MESH_RF_ACCESSADDRESS (0x8E89BED6) +#define CONFIG_MESH_RF_CHANNEL_37 (37) +#define CONFIG_MESH_RF_CHANNEL_38 (38) +#define CONFIG_MESH_RF_CHANNEL_39 (39) + +#define APP_DBG(X...) \ + if (1) \ + { \ + printf("APP_DBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_proxy/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_proxy/Project/BLE.uvprojx new file mode 100644 index 0000000..e7b5951 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_proxy/Project/BLE.uvprojx @@ -0,0 +1,577 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_generic_onoff_model.c + 1 + ..\APP\app_generic_onoff_model.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/adv_vendor/APP/app.c b/src/EXAM/BLE/MESH/adv_vendor/APP/app.c new file mode 100644 index 0000000..910cb11 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/APP/app.c @@ -0,0 +1,420 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model_srv.h" +#include "app.h" +#include "HAL.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +static uint8_t dev_uuid[16]={0}; // 豸UUID +u8 MACAddr[6]; // 豸mac + + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void vendor_model_srv_rsp_handler(const vendor_model_srv_status_t *val); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +/* Attention on */ +void app_prov_attn_on(struct bt_mesh_model *model) +{ + APP_DBG("app_prov_attn_on"); +} + +/* Attention off */ +void app_prov_attn_off(struct bt_mesh_model *model) +{ + APP_DBG("app_prov_attn_off"); +} + +const struct bt_mesh_health_srv_cb health_srv_cb={ + .attn_on = app_prov_attn_on, + .attn_off = app_prov_attn_off, +}; + +static struct bt_mesh_health_srv health_srv={ + .cb = &health_srv_cb, +}; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +// rootģͼ +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), +}; + +struct bt_mesh_vendor_model_srv vendor_model_srv = { + .srv_tid.trans_tid = 0xFF, + .handler = vendor_model_srv_rsp_handler, +}; + +// Զģͼ +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_WCH, BLE_MESH_MODEL_ID_WCH_SRV, vnd_model_srv_op, NULL, &vendor_model_srv, &bt_mesh_vendor_model_srv_cb), +}; + +// ģ elements +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = dev_uuid, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, +}; + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkص +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(""); + +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : reason : link close reason ͷļ +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + if( reason != CLOSE_REASON_SUCCESS ) + APP_DBG("reason %x",reason); +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + APP_DBG(""); +} + +/******************************************************************************* +* Function Name : vendor_model_srv_rsp_handler +* Description : Զģͷص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_rsp_handler(const vendor_model_srv_status_t *val) +{ + if( val->vendor_model_srv_Hdr.status) + { + // Ӧݴ ʱδյӦ + APP_DBG("Timeout opcode 0x%02x",val->vendor_model_srv_Hdr.opcode); + return; + } + if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_MSG ) + { + // յ͸ + APP_DBG("len %d, data 0x%02x",val->vendor_model_srv_Event.trans.len, + val->vendor_model_srv_Event.trans.pdata[0]); + } + else if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_WRT ) + { + // յwrite + APP_DBG("len %d, data 0x%02x",val->vendor_model_srv_Event.write.len, + val->vendor_model_srv_Event.write.pdata[0]); + } + else if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_IND ) + { + // ͵indicateյӦ + } + else + { + APP_DBG("Unknow opcode 0x%02x",val->vendor_model_srv_Hdr.opcode); + } +} + +/******************************************************************************* +* Function Name : keyPress +* Description : ص·һݸ +* Input : None +* Return : None +*******************************************************************************/ +void keyPress( uint8 keys ) +{ + APP_DBG("%d", keys); + + switch (keys) + { + default: + { + uint8 status; + struct send_param param = { + .app_idx = vnd_models[0].keys[0], // Ϣʹõapp keyضʹõ0key + .addr = 0x01, // ϢĿĵصַΪߣĬϵַΪ0x0001 + .trans_cnt = 0x01, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_srv_tid_get(), // tidÿϢѭsrvʹ128~191 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + uint8 data[8] = {0,1,2,3,4,5,6,7}; + status = vendor_message_srv_indicate(¶m, data, 8); // ԶģͷӦָʾ + if( status ) APP_DBG("indicate failed %d",status); + break; + } + } +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + PRINT("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + GetMACAddress( MACAddr ); + tmos_memcpy(dev_uuid, MACAddr, 6); + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MACAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress); + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 1600); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_NODE_TEST_EVT ) + { + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 2400); + return ( events ^ APP_NODE_TEST_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor/APP/app_main.c b/src/EXAM/BLE/MESH/adv_vendor/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_vendor/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor/APP/app_vendor_model_srv.c b/src/EXAM/BLE/MESH/adv_vendor/APP/app_vendor_model_srv.c new file mode 100644 index 0000000..863aca4 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/APP/app_vendor_model_srv.c @@ -0,0 +1,640 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_vendor_model_srv.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +// ӦòͳȣְΪCONFIG_MESH_UNSEG_LENGTH_DEFְΪCONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8RAMʹ +#define APP_MAX_TX_SIZE MAX(CONFIG_MESH_UNSEG_LENGTH_DEF,CONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8) + +static uint8 vendor_model_srv_TaskID = 0; // Task ID for internal task/event processing +static uint8 srv_send_tid=128; +static s32_t srv_msg_timeout = K_SECONDS(2); //Ӧݴ䳬ʱʱ䣬Ĭ2 + +static struct net_buf ind_buf; +static struct bt_mesh_indicate indicate = +{ + .buf = &ind_buf, +}; + +static struct net_buf srv_trans_buf; +static struct bt_mesh_trans srv_trans = +{ + .buf = &srv_trans_buf, +}; + + +static struct bt_mesh_vendor_model_srv *vendor_model_srv; + + + +static void ind_reset(struct bt_mesh_indicate *ind, int err); + +static uint16 vendor_model_srv_ProcessEvent( uint8 task_id, uint16 events ); +static void ind_reset(struct bt_mesh_indicate *ind, int err); + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void) +{ + srv_send_tid++; + if(srv_send_tid > 191) + srv_send_tid = 128; + return srv_send_tid; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_reset +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_reset(void) +{ + APP_DBG(""); + vendor_model_srv->op_pending = 0U; + vendor_model_srv->op_req = 0U; + + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT); + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT); +} + +/******************************************************************************* +* Function Name : vendor_model_srv_rsp_recv +* Description : Ӧò㴫Ļص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_rsp_recv(vendor_model_srv_status_t *val, u8_t status) +{ + if (vendor_model_srv == NULL || (!vendor_model_srv->op_req) ) + { + return; + } + + val->vendor_model_srv_Hdr.opcode = vendor_model_srv->op_req; + val->vendor_model_srv_Hdr.status = status; + + vendor_model_srv_reset(); + + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(val); + } +} + +/******************************************************************************* +* Function Name : vendor_model_srv_wait +* Description : Ĭ볬ʱ֪ͨӦò +* Input : None +* Return : None +*******************************************************************************/ +static int vendor_model_srv_wait(void) +{ + int err; + + err = tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT, srv_msg_timeout); + + return err; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_prepare +* Description : Ԥ +* Input : op_req: ͵ +* op: ķ +* Return : None +*******************************************************************************/ +static int vendor_model_srv_prepare(u32_t op_req, u32_t op) +{ + if (!vendor_model_srv) + { + APP_DBG("No available Configuration Client context!"); + return -EINVAL; + } + + if (vendor_model_srv->op_pending) + { + APP_DBG("Another synchronous operation pending"); + return -EBUSY; + } + + vendor_model_srv->op_req = op_req; + vendor_model_srv->op_pending = op; + + return 0; +} + +/******************************************************************************* +* Function Name : vendor_srv_sync_handler +* Description : ֪ͨӦò㵱ǰop_codeʱ +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_srv_sync_handler( void ) +{ + vendor_model_srv_status_t vendor_model_srv_status; + + tmos_memset(&vendor_model_srv_status, 0, sizeof(vendor_model_srv_status_t)); + + ind_reset(&indicate, -ETIMEDOUT); + + vendor_model_srv_rsp_recv(&vendor_model_srv_status, 0xFF); +} + + +/******************************************************************************* +* Function Name : vendor_message_srv_confirm +* Description : vendor_message_srv_confirm - ϢVendor Model ServerظVendor Model Client + ڱʾյVendor Model Client Write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_confirm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + u8_t recv_tid; + int err; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("tid 0x%02x ", recv_tid); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&msg, OP_VENDOR_MESSAGE_TRANSPARENT_CFM); + + /* Add tid field */ + net_buf_simple_add_u8(&msg, recv_tid); + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("#mesh-onoff STATUS: send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : vendor_message_srv_trans +* Description : ͸ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_srv_status_t vendor_model_srv_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_srv->srv_tid.trans_tid ) + { + vendor_model_srv->srv_tid.trans_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_srv_status.vendor_model_srv_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_MSG; + vendor_model_srv_status.vendor_model_srv_Hdr.status = 0; + vendor_model_srv_status.vendor_model_srv_Event.trans.pdata = pData; + vendor_model_srv_status.vendor_model_srv_Event.trans.len = len; + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(&vendor_model_srv_status); + } + } +} + +/******************************************************************************* +* Function Name : vendor_message_srv_write +* Description : write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_write(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_srv_status_t vendor_model_srv_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_srv->srv_tid.write_tid ) + { + vendor_model_srv->srv_tid.write_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_srv_status.vendor_model_srv_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_WRT; + vendor_model_srv_status.vendor_model_srv_Hdr.status = 0; + vendor_model_srv_status.vendor_model_srv_Event.trans.pdata = pData; + vendor_model_srv_status.vendor_model_srv_Event.trans.len = len; + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(&vendor_model_srv_status); + } + } + vendor_message_srv_confirm(model, ctx, buf); +} + + +/******************************************************************************* +* Function Name : vendor_message_srv_ack +* Description : յvendor_message_srv_ack - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_ack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + vendor_model_srv_status_t vendor_model_srv_status; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + if (indicate.param.tid == recv_tid) + { + ind_reset(&indicate, 0); + vendor_model_srv_rsp_recv(&vendor_model_srv_status, 0); + } +} + + +// opcode ӦĴ +const struct bt_mesh_model_op vnd_model_srv_op[] = { + {OP_VENDOR_MESSAGE_TRANSPARENT_MSG, 0, vendor_message_srv_trans}, + {OP_VENDOR_MESSAGE_TRANSPARENT_WRT, 0, vendor_message_srv_write}, + {OP_VENDOR_MESSAGE_TRANSPARENT_ACK, 0, vendor_message_srv_ack}, + BLE_MESH_MODEL_OP_END, +}; + + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len) +{ + if( !param->addr) + return -EINVAL; + if( indicate.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + indicate.buf->__buf = tmos_msg_allocate(len+8); + if( !(indicate.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + indicate.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(indicate.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_IND); + + /* Add tid field */ + net_buf_simple_add_u8(&(indicate.buf->b), param->tid); + + net_buf_simple_add_mem(&(indicate.buf->b), pData, len); + + memcpy(&indicate.param, param, sizeof(struct send_param)); + + vendor_model_srv_prepare(OP_VENDOR_MESSAGE_TRANSPARENT_IND, OP_VENDOR_MESSAGE_TRANSPARENT_ACK); + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, param->rand); + + vendor_model_srv_wait(); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len) +{ + if(!param->addr) + return -EINVAL; + if( srv_trans.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + srv_trans.buf->__buf = tmos_msg_allocate(len+8); + if( !(srv_trans.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + srv_trans.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(srv_trans.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_MSG); + + /* Add tid field */ + net_buf_simple_add_u8(&(srv_trans.buf->b), param->tid); + + net_buf_simple_add_mem(&(srv_trans.buf->b), pData, len); + + memcpy(&srv_trans.param, param, sizeof(struct send_param)); + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT, param->rand); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ) +{ + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT); +} + +/******************************************************************************* +* Function Name : ind_reset +* Description : ÷ɻصͷŻ +* Input : None +* Return : None +*******************************************************************************/ +static void ind_reset(struct bt_mesh_indicate *ind, int err) +{ + if (ind->param.cb && ind->param.cb->end) + { + ind->param.cb->end(err, ind->param.cb_data); + } + + tmos_msg_deallocate(ind->buf->__buf); + ind->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : ind_start +* Description : indicate ʼص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, K_MSEC(100)); + return; + } +} + +/******************************************************************************* +* Function Name : ind_end +* Description : indicate ص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_end(int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, ind->param.period); +} + +// indicate صṹ +const struct bt_mesh_send_cb ind_cb = +{ + .start = ind_start, + .end = ind_end, +}; + +/******************************************************************************* +* Function Name : adv_ind_send +* Description : indicate +* Input : None +* Return : None +*******************************************************************************/ +static void adv_ind_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = indicate.param.app_idx ? indicate.param.app_idx : vendor_model_srv->model->keys[0], + .addr = indicate.param.addr, + }; + + if (indicate.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (indicate.param.trans_cnt == 0) + { +// APP_DBG("indicate.buf.trans_cnt over"); + ind_reset(&indicate, -ETIMEDOUT); + return; + } + + indicate.param.trans_cnt --; + + ctx.send_ttl = indicate.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, indicate.buf->data, indicate.buf->len); + + err = bt_mesh_model_send(vendor_model_srv->model, &ctx, &msg, &ind_cb, &indicate); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + + ind_reset(&indicate, err); + return; + } +} + +/******************************************************************************* +* Function Name : adv_srv_trans_send +* Description : ͸ srv_trans +* Input : None +* Return : None +*******************************************************************************/ +static void adv_srv_trans_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = srv_trans.param.app_idx ? srv_trans.param.app_idx : vendor_model_srv->model->keys[0], + .addr = srv_trans.param.addr, + }; + + if (srv_trans.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (srv_trans.param.trans_cnt == 0) + { +// APP_DBG("srv_trans.buf.trans_cnt over"); + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + return; + } + + srv_trans.param.trans_cnt --; + + ctx.send_ttl = srv_trans.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, srv_trans.buf->data, srv_trans.buf->len); + + err = bt_mesh_model_send(vendor_model_srv->model, &ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + return; + } + // ش + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT, srv_trans.param.period); +} + + +/******************************************************************************* +* Function Name : vendor_model_srv_init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static int vendor_model_srv_init(struct bt_mesh_model *model) +{ + vendor_model_srv = model->user_data; + vendor_model_srv->model = model; + + vendor_model_srv_TaskID = TMOS_ProcessEventRegister( vendor_model_srv_ProcessEvent ); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 vendor_model_srv_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & VENDOR_MODEL_SRV_INDICATE_EVT ) + { + adv_ind_send(); + return ( events ^ VENDOR_MODEL_SRV_INDICATE_EVT ); + } + + if ( events & VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT ) + { + vendor_srv_sync_handler(); + return ( events ^ VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT ); + } + + if ( events & VENDOR_MODEL_SRV_TRANS_EVT ) + { + adv_srv_trans_send(); + return ( events ^ VENDOR_MODEL_SRV_TRANS_EVT ); + } + // Discard unknown events + return 0; +} + + +const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb = { + .init = vendor_model_srv_init, +}; +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor/APP/include/app.h b/src/EXAM/BLE/MESH/adv_vendor/APP/include/app.h new file mode 100644 index 0000000..b75f988 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/APP/include/app.h @@ -0,0 +1,35 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_H +#define app_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/******************************************************************************/ + +#define APP_NODE_EVT (1<<0) +#define APP_NODE_TEST_EVT (1<<1) + +/******************************************************************************/ + +void App_Init(void); + +/******************************************************************************/ + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor/APP/include/app_mesh_config.h b/src/EXAM/BLE/MESH/adv_vendor/APP/include/app_mesh_config.h new file mode 100644 index 0000000..d8b299f --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/APP/include/app_mesh_config.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + +#ifndef APP_MESH_CONFIG_H +#define APP_MESH_CONFIG_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/**************************,ֱӲοͬ*****************************/ + +// relay +#define CONFIG_BLE_MESH_RELAY 1 +// +#define CONFIG_BLE_MESH_PROXY 0 +// GATT +#define CONFIG_BLE_MESH_PB_GATT 0 +// FLASH洢 +#define CONFIG_BLE_MESH_SETTINGS 1 +// ѽڵ㹦 +#define CONFIG_BLE_MESH_FRIEND 0 +// ͹Ľڵ㹦 +#define CONFIG_BLE_MESH_LOW_POWER 0 +// configģͿͻ˹ +#define CONFIG_BLE_MESH_CFG_CLI 0 +// healthģͿͻ˹ +#define CONFIG_BLE_MESH_HLTH_CLI 0 + + +/******************************************************************************/ + +// Netݻ +#define CONFIG_MESH_ADV_BUF_COUNT_MIN (6) +#define CONFIG_MESH_ADV_BUF_COUNT_DEF (10) +#define CONFIG_MESH_ADV_BUF_COUNT_MAX (40) + +// RPLݻ +#define CONFIG_MESH_RPL_COUNT_MIN (6) +#define CONFIG_MESH_RPL_COUNT_DEF (6) +#define CONFIG_MESH_RPL_COUNT_MAX (20) + +// IV Update State Timer 96HķƵϵ +#define CONFIG_MESH_IVU_DIVIDER_MIN (1) +#define CONFIG_MESH_IVU_DIVIDER_DEF (96) +#define CONFIG_MESH_IVU_DIVIDER_MAX (96) + +// ڰܴ洢 +#define CONFIG_MESH_PROXY_FILTER_MIN (2) +#define CONFIG_MESH_PROXY_FILTER_DEF (5) +#define CONFIG_MESH_PROXY_FILTER_MAX (20) + +// Ϣ +#define CONFIG_MESH_MSG_CACHE_MIN (3) +#define CONFIG_MESH_MSG_CACHE_DEF (20) +#define CONFIG_MESH_MSG_CACHE_MAX (20) + +// +#define CONFIG_MESH_SUBNET_COUNT_MIN (1) +#define CONFIG_MESH_SUBNET_COUNT_DEF (1) +#define CONFIG_MESH_SUBNET_COUNT_MAX (4) + +// APP key +#define CONFIG_MESH_APPKEY_COUNT_MIN (1) +#define CONFIG_MESH_APPKEY_COUNT_DEF (3) +#define CONFIG_MESH_APPKEY_COUNT_MAX (5) + +// ǷһдַͬĽڵ㣨ʹְܺܲã +#define CONFIG_MESH_ALLOW_SAME_ADDR (FALSE) + +// ְϢֵ֧ijȣ˳ҪְĬֵΪ7޸Ĵֵϱ׼meshЭ飩 +#define CONFIG_MESH_UNSEG_LENGTH_MIN (7) +#define CONFIG_MESH_UNSEG_LENGTH_DEF (7) +#define CONFIG_MESH_UNSEG_LENGTH_MAX (221) + +// ÿϢְ +#define CONFIG_MESH_TX_SEG_MIN (2) +#define CONFIG_MESH_TX_SEG_DEF (8) +#define CONFIG_MESH_TX_SEG_MAX (32) + +// ͬʱڵķְϢ͸ +#define CONFIG_MESH_TX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_TX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_TX_SEG_COUNT_MAX (4) + +// ͬʱڵķְϢո +#define CONFIG_MESH_RX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_RX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_RX_SEG_COUNT_MAX (4) + +// ÿյķְϢֽ +#define CONFIG_MESH_RX_SDU_MIN (12) +#define CONFIG_MESH_RX_SDU_DEF (192) +#define CONFIG_MESH_RX_SDU_MAX (384) + +// ַ +#define CONFIG_MESH_LABEL_COUNT_MIN (1) +#define CONFIG_MESH_LABEL_COUNT_DEF (2) +#define CONFIG_MESH_LABEL_COUNT_MAX (4) + +// NVS洢ʹ +#define CONFIG_MESH_SECTOR_COUNT_MIN (2) +#define CONFIG_MESH_SECTOR_COUNT_DEF (3) + +// NVS洢׵ַ +#define CONFIG_MESH_NVS_ADDR_DEF (0x3E800) + +// RPLº洢ijʱʱ(s) +#define CONFIG_MESH_RPL_STORE_RATE_MIN (5) +#define CONFIG_MESH_RPL_STORE_RATE_DEF (60) +#define CONFIG_MESH_RPL_STORE_RATE_MAX (3600) + +// SEQº洢ijʱʱ(s) +#define CONFIG_MESH_SEQ_STORE_RATE_MIN (5) +#define CONFIG_MESH_SEQ_STORE_RATE_DEF (60) +#define CONFIG_MESH_SEQ_STORE_RATE_MAX (3600) + +// Ϣº洢ijʱʱ(s) +#define CONFIG_MESH_STORE_RATE_MIN (2) +#define CONFIG_MESH_STORE_RATE_DEF (2) +#define CONFIG_MESH_STORE_RATE_MAX (5) + +// ѽڵֵ֧ÿϢķְ +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF (2) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MAX (4) + +// ѽڵֵ֧Ķĸ +#define CONFIG_MESH_FRIEND_SUB_SIZE_MIN (1) +#define CONFIG_MESH_FRIEND_SUB_SIZE_DEF (4) +#define CONFIG_MESH_FRIEND_SUB_SIZE_MAX (8) + +// ѽڵֵ֧ĵ͹Ľڵ +#define CONFIG_MESH_FRIEND_LPN_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_DEF (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_MAX (4) + +// ѽڵ洢ϢдС +#define CONFIG_MESH_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_QUEUE_SIZE_DEF (4) +#define CONFIG_MESH_QUEUE_SIZE_MAX (30) + +// ѽڵմڴС(ms) +#define CONFIG_MESH_FRIEND_RECV_WIN_MIN (1) +#define CONFIG_MESH_FRIEND_RECV_WIN_DEF (20) +#define CONFIG_MESH_FRIEND_RECV_WIN_MAX (255) + +// ͹ĽڵϢдС +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MAX (20) + +// ͹ĽڵϢʱʱ(10ms) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MIN (30) +#define CONFIG_MESH_LPN_POLLTIMEOUT_DEF (40) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MAX (400) + +// ͹Ľڵֵ֧Ľӳ(ms) +#define CONFIG_MESH_LPN_RECV_DELAY_MIN (100) +#define CONFIG_MESH_LPN_RECV_DELAY_DEF (100) +#define CONFIG_MESH_LPN_RECV_DELAY_MAX (400) + +// ѹϵؽȴʱ(s) +#define CONFIG_MESH_RETRY_TIMEOUT_MIN (3) +#define CONFIG_MESH_RETRY_TIMEOUT_DEF (10) +#define CONFIG_MESH_RETRY_TIMEOUT_MAX (60) + +// ֵ֧豸ڵ +#define CONFIG_MESH_PROV_NODE_COUNT_MIN (1) +#define CONFIG_MESH_PROV_NODE_COUNT_DEF (2) + +// ADV_RF +#define CONFIG_MESH_RF_ACCESSADDRESS (0x8E89BED6) +#define CONFIG_MESH_RF_CHANNEL_37 (37) +#define CONFIG_MESH_RF_CHANNEL_38 (38) +#define CONFIG_MESH_RF_CHANNEL_39 (39) + +#define APP_DBG(X...) \ + if (1) \ + { \ + printf("APP_DBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor/APP/include/app_vendor_model_srv.h b/src/EXAM/BLE/MESH/adv_vendor/APP/include/app_vendor_model_srv.h new file mode 100644 index 0000000..83b8329 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/APP/include/app_vendor_model_srv.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_srv_H +#define app_vendor_model_srv_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "MESH_LIB.h" + +#define MSG_PIN GPIO_Pin_12 + +#define CID_WCH 0x07D7 + +#define OP_VENDOR_MESSAGE_TRANSPARENT_CFM BLE_MESH_MODEL_OP_3(0xCB, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_WRT BLE_MESH_MODEL_OP_3(0xCC, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_ACK BLE_MESH_MODEL_OP_3(0xCD, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_IND BLE_MESH_MODEL_OP_3(0xCE, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_WCH) + +#define BLE_MESH_MODEL_ID_WCH_SRV 0x0000 +#define BLE_MESH_MODEL_ID_WCH_CLI 0x0001 + +#define VENDOR_MODEL_SRV_TRANS_EVT (1<<0) +#define VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT (1<<1) +#define VENDOR_MODEL_SRV_INDICATE_EVT (1<<2) + +struct bt_adv_trans_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + + +struct send_param +{ + u16_t net_idx; + u16_t app_idx; + u16_t addr; + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_trans_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_trans +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_write +{ + struct send_param param; + struct net_buf *buf; +}; + + +struct bt_mesh_vendor_model_write +{ + u8_t *pdata; + u16_t len; +}; + +struct bt_mesh_vendor_model_srv_trans +{ + u8_t *pdata; + u16_t len; +}; + +struct vendor_model_srv_EventHdr +{ + u8_t status; + u32_t opcode; +}; + +union vendor_model_srv_Event_t +{ + struct bt_mesh_vendor_model_srv_trans trans; + struct bt_mesh_vendor_model_write write; +}; + +typedef struct +{ + struct vendor_model_srv_EventHdr vendor_model_srv_Hdr; + union vendor_model_srv_Event_t vendor_model_srv_Event; +}vendor_model_srv_status_t; + + +typedef void (*vendor_model_srv_rsp_handler_t)(const vendor_model_srv_status_t *val); + +struct vendor_model_srv_tid +{ + u8_t trans_tid; + u8_t write_tid; +}; + +/** Mesh vendor_model_srv Model Context */ +struct bt_mesh_vendor_model_srv { + struct bt_mesh_model *model; + u32_t op_req; + u32_t op_pending; + struct vendor_model_srv_tid srv_tid; + + vendor_model_srv_rsp_handler_t handler; + +}; + + + +extern const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb; + +extern const struct bt_mesh_model_op vnd_model_srv_op[]; + + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on); + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method ÿϢѭsrvʹ128~191 +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void); + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_vendor/Project/BLE.uvprojx new file mode 100644 index 0000000..bb977ef --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor/Project/BLE.uvprojx @@ -0,0 +1,577 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model_srv.c + 1 + ..\APP\app_vendor_model_srv.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app.c b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app.c new file mode 100644 index 0000000..0d858fb --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app.c @@ -0,0 +1,442 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model_srv.h" +#include "app.h" +#include "HAL.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +static uint8_t dev_uuid[16]={0}; // 豸UUID +u8 MACAddr[6]; // 豸mac + + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void vendor_model_srv_rsp_handler(const vendor_model_srv_status_t *val); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +/* Attention on */ +void app_prov_attn_on(struct bt_mesh_model *model) +{ + APP_DBG("app_prov_attn_on"); +} + +/* Attention off */ +void app_prov_attn_off(struct bt_mesh_model *model) +{ + APP_DBG("app_prov_attn_off"); +} + +const struct bt_mesh_health_srv_cb health_srv_cb={ + .attn_on = app_prov_attn_on, + .attn_off = app_prov_attn_off, +}; + +static struct bt_mesh_health_srv health_srv={ + .cb = &health_srv_cb, +}; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +// rootģͼ +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), +}; + +struct bt_mesh_vendor_model_srv vendor_model_srv = { + .srv_tid.trans_tid = 0xFF, + .handler = vendor_model_srv_rsp_handler, +}; + +// Զģͼ +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_WCH, BLE_MESH_MODEL_ID_WCH_SRV, vnd_model_srv_op, NULL, &vendor_model_srv, &bt_mesh_vendor_model_srv_cb), +}; + +// ģ elements +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = dev_uuid, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, +}; + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkص +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(""); + +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : reason : link close reason ͷļ +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + if( reason != CLOSE_REASON_SUCCESS ) + APP_DBG("reason %x",reason); +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + APP_DBG("net_idx %x, addr %x",net_idx,addr); +} + +/******************************************************************************* +* Function Name : friend_state +* Description : ѹϵص +* Input : None +* Return : None +*******************************************************************************/ +static void friend_state(u16_t lpn_addr, u8_t state) +{ + if( state == FRIEND_FRIENDSHIP_ESTABLISHED ) + { + APP_DBG("friend friendship established, lpn addr 0x%04x",lpn_addr); + } + else if( state == FRIEND_FRIENDSHIP_TERMINATED ) + { + APP_DBG("friend friendship terminated, lpn addr 0x%04x",lpn_addr); + } + else + { + APP_DBG("unknow state %x",state); + } +} + +/******************************************************************************* +* Function Name : vendor_model_srv_rsp_handler +* Description : Զģͷص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_rsp_handler(const vendor_model_srv_status_t *val) +{ + if( val->vendor_model_srv_Hdr.status) + { + // Ӧݴ ʱδյӦ + APP_DBG("Timeout opcode 0x%02x",val->vendor_model_srv_Hdr.opcode); + return; + } + if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_MSG ) + { + // յ͸ + APP_DBG("len %d, data 0x%02x",val->vendor_model_srv_Event.trans.len, + val->vendor_model_srv_Event.trans.pdata[0]); + } + else if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_WRT ) + { + // յwrite + APP_DBG("len %d, data 0x%02x",val->vendor_model_srv_Event.write.len, + val->vendor_model_srv_Event.write.pdata[0]); + } + else if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_IND ) + { + // ͵indicateյӦ + } + else + { + APP_DBG("Unknow opcode 0x%02x",val->vendor_model_srv_Hdr.opcode); + } +} + +/******************************************************************************* +* Function Name : keyPress +* Description : ص·һݸ +* Input : None +* Return : None +*******************************************************************************/ +void keyPress( uint8 keys ) +{ + APP_DBG("%d", keys); + + switch (keys) + { + default: + { + uint8 status; + struct send_param param = { + .app_idx = vnd_models[0].keys[0], // Ϣʹõapp keyضʹõ0key + .addr = 0x01, // ϢĿĵصַΪߣĬϵַΪ0x0001 + .trans_cnt = 0x01, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_srv_tid_get(), // tidÿϢѭsrvʹ128~191 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + uint8 data[8] = {0,1,2,3,4,5,6,7}; + status = vendor_message_srv_indicate(¶m, data, 8); // ԶģͷӦָʾ + if( status ) APP_DBG("indicate failed %d",status); + break; + } + } +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + PRINT("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + GetMACAddress( MACAddr ); + tmos_memcpy(dev_uuid, MACAddr, 6); + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MACAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress); + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 1600); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_NODE_TEST_EVT ) + { + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 2400); + return ( events ^ APP_NODE_TEST_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_main.c b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_vendor_model_srv.c b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_vendor_model_srv.c new file mode 100644 index 0000000..863aca4 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/app_vendor_model_srv.c @@ -0,0 +1,640 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_vendor_model_srv.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +// ӦòͳȣְΪCONFIG_MESH_UNSEG_LENGTH_DEFְΪCONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8RAMʹ +#define APP_MAX_TX_SIZE MAX(CONFIG_MESH_UNSEG_LENGTH_DEF,CONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8) + +static uint8 vendor_model_srv_TaskID = 0; // Task ID for internal task/event processing +static uint8 srv_send_tid=128; +static s32_t srv_msg_timeout = K_SECONDS(2); //Ӧݴ䳬ʱʱ䣬Ĭ2 + +static struct net_buf ind_buf; +static struct bt_mesh_indicate indicate = +{ + .buf = &ind_buf, +}; + +static struct net_buf srv_trans_buf; +static struct bt_mesh_trans srv_trans = +{ + .buf = &srv_trans_buf, +}; + + +static struct bt_mesh_vendor_model_srv *vendor_model_srv; + + + +static void ind_reset(struct bt_mesh_indicate *ind, int err); + +static uint16 vendor_model_srv_ProcessEvent( uint8 task_id, uint16 events ); +static void ind_reset(struct bt_mesh_indicate *ind, int err); + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void) +{ + srv_send_tid++; + if(srv_send_tid > 191) + srv_send_tid = 128; + return srv_send_tid; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_reset +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_reset(void) +{ + APP_DBG(""); + vendor_model_srv->op_pending = 0U; + vendor_model_srv->op_req = 0U; + + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT); + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT); +} + +/******************************************************************************* +* Function Name : vendor_model_srv_rsp_recv +* Description : Ӧò㴫Ļص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_rsp_recv(vendor_model_srv_status_t *val, u8_t status) +{ + if (vendor_model_srv == NULL || (!vendor_model_srv->op_req) ) + { + return; + } + + val->vendor_model_srv_Hdr.opcode = vendor_model_srv->op_req; + val->vendor_model_srv_Hdr.status = status; + + vendor_model_srv_reset(); + + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(val); + } +} + +/******************************************************************************* +* Function Name : vendor_model_srv_wait +* Description : Ĭ볬ʱ֪ͨӦò +* Input : None +* Return : None +*******************************************************************************/ +static int vendor_model_srv_wait(void) +{ + int err; + + err = tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT, srv_msg_timeout); + + return err; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_prepare +* Description : Ԥ +* Input : op_req: ͵ +* op: ķ +* Return : None +*******************************************************************************/ +static int vendor_model_srv_prepare(u32_t op_req, u32_t op) +{ + if (!vendor_model_srv) + { + APP_DBG("No available Configuration Client context!"); + return -EINVAL; + } + + if (vendor_model_srv->op_pending) + { + APP_DBG("Another synchronous operation pending"); + return -EBUSY; + } + + vendor_model_srv->op_req = op_req; + vendor_model_srv->op_pending = op; + + return 0; +} + +/******************************************************************************* +* Function Name : vendor_srv_sync_handler +* Description : ֪ͨӦò㵱ǰop_codeʱ +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_srv_sync_handler( void ) +{ + vendor_model_srv_status_t vendor_model_srv_status; + + tmos_memset(&vendor_model_srv_status, 0, sizeof(vendor_model_srv_status_t)); + + ind_reset(&indicate, -ETIMEDOUT); + + vendor_model_srv_rsp_recv(&vendor_model_srv_status, 0xFF); +} + + +/******************************************************************************* +* Function Name : vendor_message_srv_confirm +* Description : vendor_message_srv_confirm - ϢVendor Model ServerظVendor Model Client + ڱʾյVendor Model Client Write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_confirm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + u8_t recv_tid; + int err; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("tid 0x%02x ", recv_tid); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&msg, OP_VENDOR_MESSAGE_TRANSPARENT_CFM); + + /* Add tid field */ + net_buf_simple_add_u8(&msg, recv_tid); + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("#mesh-onoff STATUS: send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : vendor_message_srv_trans +* Description : ͸ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_srv_status_t vendor_model_srv_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_srv->srv_tid.trans_tid ) + { + vendor_model_srv->srv_tid.trans_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_srv_status.vendor_model_srv_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_MSG; + vendor_model_srv_status.vendor_model_srv_Hdr.status = 0; + vendor_model_srv_status.vendor_model_srv_Event.trans.pdata = pData; + vendor_model_srv_status.vendor_model_srv_Event.trans.len = len; + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(&vendor_model_srv_status); + } + } +} + +/******************************************************************************* +* Function Name : vendor_message_srv_write +* Description : write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_write(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_srv_status_t vendor_model_srv_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_srv->srv_tid.write_tid ) + { + vendor_model_srv->srv_tid.write_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_srv_status.vendor_model_srv_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_WRT; + vendor_model_srv_status.vendor_model_srv_Hdr.status = 0; + vendor_model_srv_status.vendor_model_srv_Event.trans.pdata = pData; + vendor_model_srv_status.vendor_model_srv_Event.trans.len = len; + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(&vendor_model_srv_status); + } + } + vendor_message_srv_confirm(model, ctx, buf); +} + + +/******************************************************************************* +* Function Name : vendor_message_srv_ack +* Description : յvendor_message_srv_ack - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_ack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + vendor_model_srv_status_t vendor_model_srv_status; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + if (indicate.param.tid == recv_tid) + { + ind_reset(&indicate, 0); + vendor_model_srv_rsp_recv(&vendor_model_srv_status, 0); + } +} + + +// opcode ӦĴ +const struct bt_mesh_model_op vnd_model_srv_op[] = { + {OP_VENDOR_MESSAGE_TRANSPARENT_MSG, 0, vendor_message_srv_trans}, + {OP_VENDOR_MESSAGE_TRANSPARENT_WRT, 0, vendor_message_srv_write}, + {OP_VENDOR_MESSAGE_TRANSPARENT_ACK, 0, vendor_message_srv_ack}, + BLE_MESH_MODEL_OP_END, +}; + + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len) +{ + if( !param->addr) + return -EINVAL; + if( indicate.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + indicate.buf->__buf = tmos_msg_allocate(len+8); + if( !(indicate.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + indicate.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(indicate.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_IND); + + /* Add tid field */ + net_buf_simple_add_u8(&(indicate.buf->b), param->tid); + + net_buf_simple_add_mem(&(indicate.buf->b), pData, len); + + memcpy(&indicate.param, param, sizeof(struct send_param)); + + vendor_model_srv_prepare(OP_VENDOR_MESSAGE_TRANSPARENT_IND, OP_VENDOR_MESSAGE_TRANSPARENT_ACK); + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, param->rand); + + vendor_model_srv_wait(); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len) +{ + if(!param->addr) + return -EINVAL; + if( srv_trans.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + srv_trans.buf->__buf = tmos_msg_allocate(len+8); + if( !(srv_trans.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + srv_trans.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(srv_trans.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_MSG); + + /* Add tid field */ + net_buf_simple_add_u8(&(srv_trans.buf->b), param->tid); + + net_buf_simple_add_mem(&(srv_trans.buf->b), pData, len); + + memcpy(&srv_trans.param, param, sizeof(struct send_param)); + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT, param->rand); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ) +{ + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT); +} + +/******************************************************************************* +* Function Name : ind_reset +* Description : ÷ɻصͷŻ +* Input : None +* Return : None +*******************************************************************************/ +static void ind_reset(struct bt_mesh_indicate *ind, int err) +{ + if (ind->param.cb && ind->param.cb->end) + { + ind->param.cb->end(err, ind->param.cb_data); + } + + tmos_msg_deallocate(ind->buf->__buf); + ind->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : ind_start +* Description : indicate ʼص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, K_MSEC(100)); + return; + } +} + +/******************************************************************************* +* Function Name : ind_end +* Description : indicate ص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_end(int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, ind->param.period); +} + +// indicate صṹ +const struct bt_mesh_send_cb ind_cb = +{ + .start = ind_start, + .end = ind_end, +}; + +/******************************************************************************* +* Function Name : adv_ind_send +* Description : indicate +* Input : None +* Return : None +*******************************************************************************/ +static void adv_ind_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = indicate.param.app_idx ? indicate.param.app_idx : vendor_model_srv->model->keys[0], + .addr = indicate.param.addr, + }; + + if (indicate.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (indicate.param.trans_cnt == 0) + { +// APP_DBG("indicate.buf.trans_cnt over"); + ind_reset(&indicate, -ETIMEDOUT); + return; + } + + indicate.param.trans_cnt --; + + ctx.send_ttl = indicate.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, indicate.buf->data, indicate.buf->len); + + err = bt_mesh_model_send(vendor_model_srv->model, &ctx, &msg, &ind_cb, &indicate); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + + ind_reset(&indicate, err); + return; + } +} + +/******************************************************************************* +* Function Name : adv_srv_trans_send +* Description : ͸ srv_trans +* Input : None +* Return : None +*******************************************************************************/ +static void adv_srv_trans_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = srv_trans.param.app_idx ? srv_trans.param.app_idx : vendor_model_srv->model->keys[0], + .addr = srv_trans.param.addr, + }; + + if (srv_trans.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (srv_trans.param.trans_cnt == 0) + { +// APP_DBG("srv_trans.buf.trans_cnt over"); + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + return; + } + + srv_trans.param.trans_cnt --; + + ctx.send_ttl = srv_trans.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, srv_trans.buf->data, srv_trans.buf->len); + + err = bt_mesh_model_send(vendor_model_srv->model, &ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + return; + } + // ش + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT, srv_trans.param.period); +} + + +/******************************************************************************* +* Function Name : vendor_model_srv_init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static int vendor_model_srv_init(struct bt_mesh_model *model) +{ + vendor_model_srv = model->user_data; + vendor_model_srv->model = model; + + vendor_model_srv_TaskID = TMOS_ProcessEventRegister( vendor_model_srv_ProcessEvent ); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 vendor_model_srv_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & VENDOR_MODEL_SRV_INDICATE_EVT ) + { + adv_ind_send(); + return ( events ^ VENDOR_MODEL_SRV_INDICATE_EVT ); + } + + if ( events & VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT ) + { + vendor_srv_sync_handler(); + return ( events ^ VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT ); + } + + if ( events & VENDOR_MODEL_SRV_TRANS_EVT ) + { + adv_srv_trans_send(); + return ( events ^ VENDOR_MODEL_SRV_TRANS_EVT ); + } + // Discard unknown events + return 0; +} + + +const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb = { + .init = vendor_model_srv_init, +}; +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app.h b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app.h new file mode 100644 index 0000000..b75f988 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app.h @@ -0,0 +1,35 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_H +#define app_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/******************************************************************************/ + +#define APP_NODE_EVT (1<<0) +#define APP_NODE_TEST_EVT (1<<1) + +/******************************************************************************/ + +void App_Init(void); + +/******************************************************************************/ + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app_mesh_config.h b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app_mesh_config.h new file mode 100644 index 0000000..d2b595c --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app_mesh_config.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + +#ifndef APP_MESH_CONFIG_H +#define APP_MESH_CONFIG_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/**************************,ֱӲοͬ*****************************/ + +// relay +#define CONFIG_BLE_MESH_RELAY 1 +// +#define CONFIG_BLE_MESH_PROXY 0 +// GATT +#define CONFIG_BLE_MESH_PB_GATT 0 +// FLASH洢 +#define CONFIG_BLE_MESH_SETTINGS 1 +// ѽڵ㹦 +#define CONFIG_BLE_MESH_FRIEND 1 +// ͹Ľڵ㹦 +#define CONFIG_BLE_MESH_LOW_POWER 0 +// configģͿͻ˹ +#define CONFIG_BLE_MESH_CFG_CLI 0 +// healthģͿͻ˹ +#define CONFIG_BLE_MESH_HLTH_CLI 0 + + +/******************************************************************************/ + +// Netݻ +#define CONFIG_MESH_ADV_BUF_COUNT_MIN (6) +#define CONFIG_MESH_ADV_BUF_COUNT_DEF (10) +#define CONFIG_MESH_ADV_BUF_COUNT_MAX (40) + +// RPLݻ +#define CONFIG_MESH_RPL_COUNT_MIN (6) +#define CONFIG_MESH_RPL_COUNT_DEF (6) +#define CONFIG_MESH_RPL_COUNT_MAX (20) + +// IV Update State Timer 96HķƵϵ +#define CONFIG_MESH_IVU_DIVIDER_MIN (1) +#define CONFIG_MESH_IVU_DIVIDER_DEF (96) +#define CONFIG_MESH_IVU_DIVIDER_MAX (96) + +// ڰܴ洢 +#define CONFIG_MESH_PROXY_FILTER_MIN (2) +#define CONFIG_MESH_PROXY_FILTER_DEF (5) +#define CONFIG_MESH_PROXY_FILTER_MAX (20) + +// Ϣ +#define CONFIG_MESH_MSG_CACHE_MIN (3) +#define CONFIG_MESH_MSG_CACHE_DEF (20) +#define CONFIG_MESH_MSG_CACHE_MAX (20) + +// +#define CONFIG_MESH_SUBNET_COUNT_MIN (1) +#define CONFIG_MESH_SUBNET_COUNT_DEF (1) +#define CONFIG_MESH_SUBNET_COUNT_MAX (4) + +// APP key +#define CONFIG_MESH_APPKEY_COUNT_MIN (1) +#define CONFIG_MESH_APPKEY_COUNT_DEF (3) +#define CONFIG_MESH_APPKEY_COUNT_MAX (5) + +// ǷһдַͬĽڵ㣨ʹְܺܲã +#define CONFIG_MESH_ALLOW_SAME_ADDR (FALSE) + +// ְϢֵ֧ijȣ˳ҪְĬֵΪ7޸Ĵֵϱ׼meshЭ飩 +#define CONFIG_MESH_UNSEG_LENGTH_MIN (7) +#define CONFIG_MESH_UNSEG_LENGTH_DEF (7) +#define CONFIG_MESH_UNSEG_LENGTH_MAX (221) + +// ÿϢְ +#define CONFIG_MESH_TX_SEG_MIN (2) +#define CONFIG_MESH_TX_SEG_DEF (8) +#define CONFIG_MESH_TX_SEG_MAX (32) + +// ͬʱڵķְϢ͸ +#define CONFIG_MESH_TX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_TX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_TX_SEG_COUNT_MAX (4) + +// ͬʱڵķְϢո +#define CONFIG_MESH_RX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_RX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_RX_SEG_COUNT_MAX (4) + +// ÿյķְϢֽ +#define CONFIG_MESH_RX_SDU_MIN (12) +#define CONFIG_MESH_RX_SDU_DEF (192) +#define CONFIG_MESH_RX_SDU_MAX (384) + +// ַ +#define CONFIG_MESH_LABEL_COUNT_MIN (1) +#define CONFIG_MESH_LABEL_COUNT_DEF (2) +#define CONFIG_MESH_LABEL_COUNT_MAX (4) + +// NVS洢ʹ +#define CONFIG_MESH_SECTOR_COUNT_MIN (2) +#define CONFIG_MESH_SECTOR_COUNT_DEF (3) + +// NVS洢׵ַ +#define CONFIG_MESH_NVS_ADDR_DEF (0x3E800) + +// RPLº洢ijʱʱ(s) +#define CONFIG_MESH_RPL_STORE_RATE_MIN (5) +#define CONFIG_MESH_RPL_STORE_RATE_DEF (60) +#define CONFIG_MESH_RPL_STORE_RATE_MAX (3600) + +// SEQº洢ijʱʱ(s) +#define CONFIG_MESH_SEQ_STORE_RATE_MIN (5) +#define CONFIG_MESH_SEQ_STORE_RATE_DEF (60) +#define CONFIG_MESH_SEQ_STORE_RATE_MAX (3600) + +// Ϣº洢ijʱʱ(s) +#define CONFIG_MESH_STORE_RATE_MIN (2) +#define CONFIG_MESH_STORE_RATE_DEF (2) +#define CONFIG_MESH_STORE_RATE_MAX (5) + +// ѽڵֵ֧ÿϢķְ +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF (2) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MAX (4) + +// ѽڵֵ֧Ķĸ +#define CONFIG_MESH_FRIEND_SUB_SIZE_MIN (1) +#define CONFIG_MESH_FRIEND_SUB_SIZE_DEF (4) +#define CONFIG_MESH_FRIEND_SUB_SIZE_MAX (8) + +// ѽڵֵ֧ĵ͹Ľڵ +#define CONFIG_MESH_FRIEND_LPN_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_DEF (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_MAX (4) + +// ѽڵ洢ϢдС +#define CONFIG_MESH_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_QUEUE_SIZE_DEF (4) +#define CONFIG_MESH_QUEUE_SIZE_MAX (30) + +// ѽڵմڴС(ms) +#define CONFIG_MESH_FRIEND_RECV_WIN_MIN (1) +#define CONFIG_MESH_FRIEND_RECV_WIN_DEF (20) +#define CONFIG_MESH_FRIEND_RECV_WIN_MAX (255) + +// ͹ĽڵϢдС +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MAX (20) + +// ͹ĽڵϢʱʱ(10ms) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MIN (30) +#define CONFIG_MESH_LPN_POLLTIMEOUT_DEF (40) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MAX (400) + +// ͹Ľڵֵ֧Ľӳ(ms) +#define CONFIG_MESH_LPN_RECV_DELAY_MIN (100) +#define CONFIG_MESH_LPN_RECV_DELAY_DEF (100) +#define CONFIG_MESH_LPN_RECV_DELAY_MAX (400) + +// ѹϵؽȴʱ(s) +#define CONFIG_MESH_RETRY_TIMEOUT_MIN (3) +#define CONFIG_MESH_RETRY_TIMEOUT_DEF (10) +#define CONFIG_MESH_RETRY_TIMEOUT_MAX (60) + +// ֵ֧豸ڵ +#define CONFIG_MESH_PROV_NODE_COUNT_MIN (1) +#define CONFIG_MESH_PROV_NODE_COUNT_DEF (2) + +// ADV_RF +#define CONFIG_MESH_RF_ACCESSADDRESS (0x8E89BED6) +#define CONFIG_MESH_RF_CHANNEL_37 (37) +#define CONFIG_MESH_RF_CHANNEL_38 (38) +#define CONFIG_MESH_RF_CHANNEL_39 (39) + +#define APP_DBG(X...) \ + if (1) \ + { \ + printf("APP_DBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app_vendor_model_srv.h b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app_vendor_model_srv.h new file mode 100644 index 0000000..83b8329 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/APP/include/app_vendor_model_srv.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_srv_H +#define app_vendor_model_srv_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "MESH_LIB.h" + +#define MSG_PIN GPIO_Pin_12 + +#define CID_WCH 0x07D7 + +#define OP_VENDOR_MESSAGE_TRANSPARENT_CFM BLE_MESH_MODEL_OP_3(0xCB, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_WRT BLE_MESH_MODEL_OP_3(0xCC, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_ACK BLE_MESH_MODEL_OP_3(0xCD, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_IND BLE_MESH_MODEL_OP_3(0xCE, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_WCH) + +#define BLE_MESH_MODEL_ID_WCH_SRV 0x0000 +#define BLE_MESH_MODEL_ID_WCH_CLI 0x0001 + +#define VENDOR_MODEL_SRV_TRANS_EVT (1<<0) +#define VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT (1<<1) +#define VENDOR_MODEL_SRV_INDICATE_EVT (1<<2) + +struct bt_adv_trans_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + + +struct send_param +{ + u16_t net_idx; + u16_t app_idx; + u16_t addr; + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_trans_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_trans +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_write +{ + struct send_param param; + struct net_buf *buf; +}; + + +struct bt_mesh_vendor_model_write +{ + u8_t *pdata; + u16_t len; +}; + +struct bt_mesh_vendor_model_srv_trans +{ + u8_t *pdata; + u16_t len; +}; + +struct vendor_model_srv_EventHdr +{ + u8_t status; + u32_t opcode; +}; + +union vendor_model_srv_Event_t +{ + struct bt_mesh_vendor_model_srv_trans trans; + struct bt_mesh_vendor_model_write write; +}; + +typedef struct +{ + struct vendor_model_srv_EventHdr vendor_model_srv_Hdr; + union vendor_model_srv_Event_t vendor_model_srv_Event; +}vendor_model_srv_status_t; + + +typedef void (*vendor_model_srv_rsp_handler_t)(const vendor_model_srv_status_t *val); + +struct vendor_model_srv_tid +{ + u8_t trans_tid; + u8_t write_tid; +}; + +/** Mesh vendor_model_srv Model Context */ +struct bt_mesh_vendor_model_srv { + struct bt_mesh_model *model; + u32_t op_req; + u32_t op_pending; + struct vendor_model_srv_tid srv_tid; + + vendor_model_srv_rsp_handler_t handler; + +}; + + + +extern const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb; + +extern const struct bt_mesh_model_op vnd_model_srv_op[]; + + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on); + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method ÿϢѭsrvʹ128~191 +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void); + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor_friend/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_vendor_friend/Project/BLE.uvprojx new file mode 100644 index 0000000..bb977ef --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_friend/Project/BLE.uvprojx @@ -0,0 +1,577 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model_srv.c + 1 + ..\APP\app_vendor_model_srv.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app.c b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app.c new file mode 100644 index 0000000..911b9aa --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app.c @@ -0,0 +1,465 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model_srv.h" +#include "app.h" +#include "HAL.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024 * 2]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +static uint8_t dev_uuid[16]={0}; // 豸UUID +u8 MACAddr[6]; // 豸mac + + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void vendor_model_srv_rsp_handler(const vendor_model_srv_status_t *val); + +static struct bt_mesh_cfg_srv cfg_srv = { + .relay = BLE_MESH_RELAY_ENABLED, + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +/* Attention on */ +void app_prov_attn_on(struct bt_mesh_model *model) +{ + APP_DBG("app_prov_attn_on"); +} + +/* Attention off */ +void app_prov_attn_off(struct bt_mesh_model *model) +{ + APP_DBG("app_prov_attn_off"); +} + +const struct bt_mesh_health_srv_cb health_srv_cb={ + .attn_on = app_prov_attn_on, + .attn_off = app_prov_attn_off, +}; + +static struct bt_mesh_health_srv health_srv={ + .cb = &health_srv_cb, +}; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +// rootģͼ +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), +}; + +struct bt_mesh_vendor_model_srv vendor_model_srv = { + .srv_tid.trans_tid = 0xFF, + .handler = vendor_model_srv_rsp_handler, +}; + +// Զģͼ +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_WCH, BLE_MESH_MODEL_ID_WCH_SRV, vnd_model_srv_op, NULL, &vendor_model_srv, &bt_mesh_vendor_model_srv_cb), +}; + +// ģ elements +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = dev_uuid, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, +}; + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : prov_enable +* Description : ʹܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +static void prov_enable(void) +{ + if (bt_mesh_is_provisioned()) + { + return; + } + + // Make sure we're scanning for provisioning inviations + bt_mesh_scan_enable(); + // Enable unprovisioned beacon sending + bt_mesh_beacon_enable(); + + if ( CONFIG_BLE_MESH_PB_GATT ) + { + bt_mesh_proxy_prov_enable(); + } +} + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkص +* Input : None +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(""); + +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : reason : link close reason ͷļ +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG(""); + if( reason != CLOSE_REASON_SUCCESS ) + APP_DBG("reason %x",reason); + + // ӳһ¼LPNΪ˵ȴ׵·appkey + tmos_start_task(App_TaskID, APP_LPN_ENABLE_EVT, 3200); +} + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻص +* Input : None +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + APP_DBG("net_idx %x, addr %x",net_idx,addr); +} + +/******************************************************************************* +* Function Name : lpn_state +* Description : ѹϵص +* Input : None +* Return : None +*******************************************************************************/ +static void lpn_state(u8_t state) +{ + if( state == LPN_FRIENDSHIP_ESTABLISHED ) + { + APP_DBG("lpn friendship established"); + } + else if( state == LPN_FRIENDSHIP_TERMINATED ) + { + APP_DBG("lpn friendship terminated"); + } + else + { + APP_DBG("unknow state %x",state); + } +} + +/******************************************************************************* +* Function Name : vendor_model_srv_rsp_handler +* Description : Զģͷص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_rsp_handler(const vendor_model_srv_status_t *val) +{ + if( val->vendor_model_srv_Hdr.status) + { + // Ӧݴ ʱδյӦ + APP_DBG("Timeout opcode 0x%02x",val->vendor_model_srv_Hdr.opcode); + return; + } + if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_MSG ) + { + // յ͸ + APP_DBG("len %d, data 0x%02x",val->vendor_model_srv_Event.trans.len, + val->vendor_model_srv_Event.trans.pdata[0]); + } + else if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_WRT ) + { + // յwrite + APP_DBG("len %d, data 0x%02x",val->vendor_model_srv_Event.write.len, + val->vendor_model_srv_Event.write.pdata[0]); + } + else if( val->vendor_model_srv_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_IND ) + { + // ͵indicateյӦ + } + else + { + APP_DBG("Unknow opcode 0x%02x",val->vendor_model_srv_Hdr.opcode); + } +} + +/******************************************************************************* +* Function Name : keyPress +* Description : ص·һݸ +* Input : None +* Return : None +*******************************************************************************/ +void keyPress( uint8 keys ) +{ + APP_DBG("%d", keys); + + switch (keys) + { + default: + { + uint8 status; + struct send_param param = { + .app_idx = vnd_models[0].keys[0], // Ϣʹõapp keyضʹõ0key + .addr = 0x01, // ϢĿĵصַΪߣĬϵַΪ0x0001 + .trans_cnt = 0x01, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_srv_tid_get(), // tidÿϢѭsrvʹ128~191 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + uint8 data[8] = {0,1,2,3,4,5,6,7}; + status = vendor_message_srv_indicate(¶m, data, 8); // ԶģͷӦָʾ + if( status ) APP_DBG("indicate failed %d",status); + break; + } + } +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + PRINT("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); + +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init, friend_state); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init, lpn_state); +#endif /* LPN */ + + GetMACAddress( MACAddr ); + tmos_memcpy(dev_uuid, MACAddr, 6); + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MACAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + + // flashлظϢֱӽLPNģʽ + tmos_set_event(App_TaskID, APP_LPN_ENABLE_EVT); + } + else + { + prov_enable(); + } + + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + HAL_KeyInit(); + HalKeyConfig( keyPress); + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 1600); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & APP_NODE_TEST_EVT ) + { + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 2400); + return ( events ^ APP_NODE_TEST_EVT ); + } + if ( events & APP_LPN_ENABLE_EVT ) + { + if( bt_mesh_app_key_find(vnd_models[0].keys[0]) != NULL ) + { + // lpnʼͽfriend +#if (CONFIG_BLE_MESH_LOW_POWER) + bt_mesh_lpn_set(TRUE); + APP_DBG("Low power enable"); +#endif /* LPN */ + } + else + { + tmos_start_task(App_TaskID, APP_LPN_ENABLE_EVT, 1600); + } + return ( events ^ APP_LPN_ENABLE_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_main.c b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_vendor_model_srv.c b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_vendor_model_srv.c new file mode 100644 index 0000000..863aca4 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/app_vendor_model_srv.c @@ -0,0 +1,640 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "app_mesh_config.h" +#include "CH57x_common.h" +#include "app_vendor_model_srv.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +// ӦòͳȣְΪCONFIG_MESH_UNSEG_LENGTH_DEFְΪCONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8RAMʹ +#define APP_MAX_TX_SIZE MAX(CONFIG_MESH_UNSEG_LENGTH_DEF,CONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8) + +static uint8 vendor_model_srv_TaskID = 0; // Task ID for internal task/event processing +static uint8 srv_send_tid=128; +static s32_t srv_msg_timeout = K_SECONDS(2); //Ӧݴ䳬ʱʱ䣬Ĭ2 + +static struct net_buf ind_buf; +static struct bt_mesh_indicate indicate = +{ + .buf = &ind_buf, +}; + +static struct net_buf srv_trans_buf; +static struct bt_mesh_trans srv_trans = +{ + .buf = &srv_trans_buf, +}; + + +static struct bt_mesh_vendor_model_srv *vendor_model_srv; + + + +static void ind_reset(struct bt_mesh_indicate *ind, int err); + +static uint16 vendor_model_srv_ProcessEvent( uint8 task_id, uint16 events ); +static void ind_reset(struct bt_mesh_indicate *ind, int err); + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin) +{ + return (GPIOB_ReadPortPin(led_pin)>0) ? 0 : 1; +} + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + on ? GPIOB_ResetBits(led_pin) : GPIOB_SetBits(led_pin); +} + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin) +{ + GPIOB_ModeCfg( led_pin, GPIO_ModeOut_PP_5mA ); + GPIOB_InverseBits(led_pin); +} + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void) +{ + srv_send_tid++; + if(srv_send_tid > 191) + srv_send_tid = 128; + return srv_send_tid; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_reset +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_reset(void) +{ + APP_DBG(""); + vendor_model_srv->op_pending = 0U; + vendor_model_srv->op_req = 0U; + + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT); + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT); +} + +/******************************************************************************* +* Function Name : vendor_model_srv_rsp_recv +* Description : Ӧò㴫Ļص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_srv_rsp_recv(vendor_model_srv_status_t *val, u8_t status) +{ + if (vendor_model_srv == NULL || (!vendor_model_srv->op_req) ) + { + return; + } + + val->vendor_model_srv_Hdr.opcode = vendor_model_srv->op_req; + val->vendor_model_srv_Hdr.status = status; + + vendor_model_srv_reset(); + + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(val); + } +} + +/******************************************************************************* +* Function Name : vendor_model_srv_wait +* Description : Ĭ볬ʱ֪ͨӦò +* Input : None +* Return : None +*******************************************************************************/ +static int vendor_model_srv_wait(void) +{ + int err; + + err = tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT, srv_msg_timeout); + + return err; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_prepare +* Description : Ԥ +* Input : op_req: ͵ +* op: ķ +* Return : None +*******************************************************************************/ +static int vendor_model_srv_prepare(u32_t op_req, u32_t op) +{ + if (!vendor_model_srv) + { + APP_DBG("No available Configuration Client context!"); + return -EINVAL; + } + + if (vendor_model_srv->op_pending) + { + APP_DBG("Another synchronous operation pending"); + return -EBUSY; + } + + vendor_model_srv->op_req = op_req; + vendor_model_srv->op_pending = op; + + return 0; +} + +/******************************************************************************* +* Function Name : vendor_srv_sync_handler +* Description : ֪ͨӦò㵱ǰop_codeʱ +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_srv_sync_handler( void ) +{ + vendor_model_srv_status_t vendor_model_srv_status; + + tmos_memset(&vendor_model_srv_status, 0, sizeof(vendor_model_srv_status_t)); + + ind_reset(&indicate, -ETIMEDOUT); + + vendor_model_srv_rsp_recv(&vendor_model_srv_status, 0xFF); +} + + +/******************************************************************************* +* Function Name : vendor_message_srv_confirm +* Description : vendor_message_srv_confirm - ϢVendor Model ServerظVendor Model Client + ڱʾյVendor Model Client Write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_confirm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + u8_t recv_tid; + int err; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("tid 0x%02x ", recv_tid); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&msg, OP_VENDOR_MESSAGE_TRANSPARENT_CFM); + + /* Add tid field */ + net_buf_simple_add_u8(&msg, recv_tid); + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("#mesh-onoff STATUS: send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : vendor_message_srv_trans +* Description : ͸ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_srv_status_t vendor_model_srv_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_srv->srv_tid.trans_tid ) + { + vendor_model_srv->srv_tid.trans_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_srv_status.vendor_model_srv_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_MSG; + vendor_model_srv_status.vendor_model_srv_Hdr.status = 0; + vendor_model_srv_status.vendor_model_srv_Event.trans.pdata = pData; + vendor_model_srv_status.vendor_model_srv_Event.trans.len = len; + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(&vendor_model_srv_status); + } + } +} + +/******************************************************************************* +* Function Name : vendor_message_srv_write +* Description : write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_write(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_srv_status_t vendor_model_srv_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_srv->srv_tid.write_tid ) + { + vendor_model_srv->srv_tid.write_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_srv_status.vendor_model_srv_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_WRT; + vendor_model_srv_status.vendor_model_srv_Hdr.status = 0; + vendor_model_srv_status.vendor_model_srv_Event.trans.pdata = pData; + vendor_model_srv_status.vendor_model_srv_Event.trans.len = len; + if (vendor_model_srv->handler) + { + vendor_model_srv->handler(&vendor_model_srv_status); + } + } + vendor_message_srv_confirm(model, ctx, buf); +} + + +/******************************************************************************* +* Function Name : vendor_message_srv_ack +* Description : յvendor_message_srv_ack - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_srv_ack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + vendor_model_srv_status_t vendor_model_srv_status; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + if (indicate.param.tid == recv_tid) + { + ind_reset(&indicate, 0); + vendor_model_srv_rsp_recv(&vendor_model_srv_status, 0); + } +} + + +// opcode ӦĴ +const struct bt_mesh_model_op vnd_model_srv_op[] = { + {OP_VENDOR_MESSAGE_TRANSPARENT_MSG, 0, vendor_message_srv_trans}, + {OP_VENDOR_MESSAGE_TRANSPARENT_WRT, 0, vendor_message_srv_write}, + {OP_VENDOR_MESSAGE_TRANSPARENT_ACK, 0, vendor_message_srv_ack}, + BLE_MESH_MODEL_OP_END, +}; + + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len) +{ + if( !param->addr) + return -EINVAL; + if( indicate.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + indicate.buf->__buf = tmos_msg_allocate(len+8); + if( !(indicate.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + indicate.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(indicate.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_IND); + + /* Add tid field */ + net_buf_simple_add_u8(&(indicate.buf->b), param->tid); + + net_buf_simple_add_mem(&(indicate.buf->b), pData, len); + + memcpy(&indicate.param, param, sizeof(struct send_param)); + + vendor_model_srv_prepare(OP_VENDOR_MESSAGE_TRANSPARENT_IND, OP_VENDOR_MESSAGE_TRANSPARENT_ACK); + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, param->rand); + + vendor_model_srv_wait(); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len) +{ + if(!param->addr) + return -EINVAL; + if( srv_trans.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + srv_trans.buf->__buf = tmos_msg_allocate(len+8); + if( !(srv_trans.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + srv_trans.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(srv_trans.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_MSG); + + /* Add tid field */ + net_buf_simple_add_u8(&(srv_trans.buf->b), param->tid); + + net_buf_simple_add_mem(&(srv_trans.buf->b), pData, len); + + memcpy(&srv_trans.param, param, sizeof(struct send_param)); + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT, param->rand); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ) +{ + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + tmos_stop_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT); +} + +/******************************************************************************* +* Function Name : ind_reset +* Description : ÷ɻصͷŻ +* Input : None +* Return : None +*******************************************************************************/ +static void ind_reset(struct bt_mesh_indicate *ind, int err) +{ + if (ind->param.cb && ind->param.cb->end) + { + ind->param.cb->end(err, ind->param.cb_data); + } + + tmos_msg_deallocate(ind->buf->__buf); + ind->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : ind_start +* Description : indicate ʼص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, K_MSEC(100)); + return; + } +} + +/******************************************************************************* +* Function Name : ind_end +* Description : indicate ص +* Input : None +* Return : None +*******************************************************************************/ +static void ind_end(int err, void *cb_data) +{ + struct bt_mesh_indicate *ind = cb_data; + + if (ind->buf->__buf == NULL) + { + return; + } + + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_INDICATE_EVT, ind->param.period); +} + +// indicate صṹ +const struct bt_mesh_send_cb ind_cb = +{ + .start = ind_start, + .end = ind_end, +}; + +/******************************************************************************* +* Function Name : adv_ind_send +* Description : indicate +* Input : None +* Return : None +*******************************************************************************/ +static void adv_ind_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = indicate.param.app_idx ? indicate.param.app_idx : vendor_model_srv->model->keys[0], + .addr = indicate.param.addr, + }; + + if (indicate.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (indicate.param.trans_cnt == 0) + { +// APP_DBG("indicate.buf.trans_cnt over"); + ind_reset(&indicate, -ETIMEDOUT); + return; + } + + indicate.param.trans_cnt --; + + ctx.send_ttl = indicate.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, indicate.buf->data, indicate.buf->len); + + err = bt_mesh_model_send(vendor_model_srv->model, &ctx, &msg, &ind_cb, &indicate); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + + ind_reset(&indicate, err); + return; + } +} + +/******************************************************************************* +* Function Name : adv_srv_trans_send +* Description : ͸ srv_trans +* Input : None +* Return : None +*******************************************************************************/ +static void adv_srv_trans_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = srv_trans.param.app_idx ? srv_trans.param.app_idx : vendor_model_srv->model->keys[0], + .addr = srv_trans.param.addr, + }; + + if (srv_trans.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (srv_trans.param.trans_cnt == 0) + { +// APP_DBG("srv_trans.buf.trans_cnt over"); + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + return; + } + + srv_trans.param.trans_cnt --; + + ctx.send_ttl = srv_trans.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, srv_trans.buf->data, srv_trans.buf->len); + + err = bt_mesh_model_send(vendor_model_srv->model, &ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + tmos_msg_deallocate(srv_trans.buf->__buf); + srv_trans.buf->__buf = NULL; + return; + } + // ش + tmos_start_task(vendor_model_srv_TaskID, VENDOR_MODEL_SRV_TRANS_EVT, srv_trans.param.period); +} + + +/******************************************************************************* +* Function Name : vendor_model_srv_init +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static int vendor_model_srv_init(struct bt_mesh_model *model) +{ + vendor_model_srv = model->user_data; + vendor_model_srv->model = model; + + vendor_model_srv_TaskID = TMOS_ProcessEventRegister( vendor_model_srv_ProcessEvent ); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_model_srv_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 vendor_model_srv_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & VENDOR_MODEL_SRV_INDICATE_EVT ) + { + adv_ind_send(); + return ( events ^ VENDOR_MODEL_SRV_INDICATE_EVT ); + } + + if ( events & VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT ) + { + vendor_srv_sync_handler(); + return ( events ^ VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT ); + } + + if ( events & VENDOR_MODEL_SRV_TRANS_EVT ) + { + adv_srv_trans_send(); + return ( events ^ VENDOR_MODEL_SRV_TRANS_EVT ); + } + // Discard unknown events + return 0; +} + + +const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb = { + .init = vendor_model_srv_init, +}; +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app.h b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app.h new file mode 100644 index 0000000..cf774b6 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app.h @@ -0,0 +1,35 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_H +#define app_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/******************************************************************************/ + +#define APP_LPN_ENABLE_EVT (1<<0) +#define APP_NODE_TEST_EVT (1<<1) + +/******************************************************************************/ + +void App_Init(void); + +/******************************************************************************/ + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app_mesh_config.h b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app_mesh_config.h new file mode 100644 index 0000000..c48e28a --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app_mesh_config.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + +#ifndef APP_MESH_CONFIG_H +#define APP_MESH_CONFIG_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/**************************,ֱӲοͬ*****************************/ + +// relay +#define CONFIG_BLE_MESH_RELAY 1 +// +#define CONFIG_BLE_MESH_PROXY 0 +// GATT +#define CONFIG_BLE_MESH_PB_GATT 0 +// FLASH洢 +#define CONFIG_BLE_MESH_SETTINGS 1 +// ѽڵ㹦 +#define CONFIG_BLE_MESH_FRIEND 0 +// ͹Ľڵ㹦 +#define CONFIG_BLE_MESH_LOW_POWER 1 +// configģͿͻ˹ +#define CONFIG_BLE_MESH_CFG_CLI 0 +// healthģͿͻ˹ +#define CONFIG_BLE_MESH_HLTH_CLI 0 + + +/******************************************************************************/ + +// Netݻ +#define CONFIG_MESH_ADV_BUF_COUNT_MIN (6) +#define CONFIG_MESH_ADV_BUF_COUNT_DEF (10) +#define CONFIG_MESH_ADV_BUF_COUNT_MAX (40) + +// RPLݻ +#define CONFIG_MESH_RPL_COUNT_MIN (6) +#define CONFIG_MESH_RPL_COUNT_DEF (6) +#define CONFIG_MESH_RPL_COUNT_MAX (20) + +// IV Update State Timer 96HķƵϵ +#define CONFIG_MESH_IVU_DIVIDER_MIN (1) +#define CONFIG_MESH_IVU_DIVIDER_DEF (96) +#define CONFIG_MESH_IVU_DIVIDER_MAX (96) + +// ڰܴ洢 +#define CONFIG_MESH_PROXY_FILTER_MIN (2) +#define CONFIG_MESH_PROXY_FILTER_DEF (5) +#define CONFIG_MESH_PROXY_FILTER_MAX (20) + +// Ϣ +#define CONFIG_MESH_MSG_CACHE_MIN (3) +#define CONFIG_MESH_MSG_CACHE_DEF (20) +#define CONFIG_MESH_MSG_CACHE_MAX (20) + +// +#define CONFIG_MESH_SUBNET_COUNT_MIN (1) +#define CONFIG_MESH_SUBNET_COUNT_DEF (1) +#define CONFIG_MESH_SUBNET_COUNT_MAX (4) + +// APP key +#define CONFIG_MESH_APPKEY_COUNT_MIN (1) +#define CONFIG_MESH_APPKEY_COUNT_DEF (3) +#define CONFIG_MESH_APPKEY_COUNT_MAX (5) + +// ǷһдַͬĽڵ㣨ʹְܺܲã +#define CONFIG_MESH_ALLOW_SAME_ADDR (FALSE) + +// ְϢֵ֧ijȣ˳ҪְĬֵΪ7޸Ĵֵϱ׼meshЭ飩 +#define CONFIG_MESH_UNSEG_LENGTH_MIN (7) +#define CONFIG_MESH_UNSEG_LENGTH_DEF (7) +#define CONFIG_MESH_UNSEG_LENGTH_MAX (221) + +// ÿϢְ +#define CONFIG_MESH_TX_SEG_MIN (2) +#define CONFIG_MESH_TX_SEG_DEF (8) +#define CONFIG_MESH_TX_SEG_MAX (32) + +// ͬʱڵķְϢ͸ +#define CONFIG_MESH_TX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_TX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_TX_SEG_COUNT_MAX (4) + +// ͬʱڵķְϢո +#define CONFIG_MESH_RX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_RX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_RX_SEG_COUNT_MAX (4) + +// ÿյķְϢֽ +#define CONFIG_MESH_RX_SDU_MIN (12) +#define CONFIG_MESH_RX_SDU_DEF (192) +#define CONFIG_MESH_RX_SDU_MAX (384) + +// ַ +#define CONFIG_MESH_LABEL_COUNT_MIN (1) +#define CONFIG_MESH_LABEL_COUNT_DEF (2) +#define CONFIG_MESH_LABEL_COUNT_MAX (4) + +// NVS洢ʹ +#define CONFIG_MESH_SECTOR_COUNT_MIN (2) +#define CONFIG_MESH_SECTOR_COUNT_DEF (3) + +// NVS洢׵ַ +#define CONFIG_MESH_NVS_ADDR_DEF (0x3E800) + +// RPLº洢ijʱʱ(s) +#define CONFIG_MESH_RPL_STORE_RATE_MIN (5) +#define CONFIG_MESH_RPL_STORE_RATE_DEF (60) +#define CONFIG_MESH_RPL_STORE_RATE_MAX (3600) + +// SEQº洢ijʱʱ(s) +#define CONFIG_MESH_SEQ_STORE_RATE_MIN (5) +#define CONFIG_MESH_SEQ_STORE_RATE_DEF (60) +#define CONFIG_MESH_SEQ_STORE_RATE_MAX (3600) + +// Ϣº洢ijʱʱ(s) +#define CONFIG_MESH_STORE_RATE_MIN (2) +#define CONFIG_MESH_STORE_RATE_DEF (2) +#define CONFIG_MESH_STORE_RATE_MAX (5) + +// ѽڵֵ֧ÿϢķְ +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF (2) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MAX (4) + +// ѽڵֵ֧Ķĸ +#define CONFIG_MESH_FRIEND_SUB_SIZE_MIN (1) +#define CONFIG_MESH_FRIEND_SUB_SIZE_DEF (4) +#define CONFIG_MESH_FRIEND_SUB_SIZE_MAX (8) + +// ѽڵֵ֧ĵ͹Ľڵ +#define CONFIG_MESH_FRIEND_LPN_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_DEF (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_MAX (4) + +// ѽڵ洢ϢдС +#define CONFIG_MESH_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_QUEUE_SIZE_DEF (4) +#define CONFIG_MESH_QUEUE_SIZE_MAX (30) + +// ѽڵմڴС(ms) +#define CONFIG_MESH_FRIEND_RECV_WIN_MIN (1) +#define CONFIG_MESH_FRIEND_RECV_WIN_DEF (20) +#define CONFIG_MESH_FRIEND_RECV_WIN_MAX (255) + +// ͹ĽڵϢдС +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MAX (20) + +// ͹ĽڵϢʱʱ(10ms) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MIN (30) +#define CONFIG_MESH_LPN_POLLTIMEOUT_DEF (40) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MAX (400) + +// ͹Ľڵֵ֧Ľӳ(ms) +#define CONFIG_MESH_LPN_RECV_DELAY_MIN (100) +#define CONFIG_MESH_LPN_RECV_DELAY_DEF (100) +#define CONFIG_MESH_LPN_RECV_DELAY_MAX (400) + +// ѹϵؽȴʱ(s) +#define CONFIG_MESH_RETRY_TIMEOUT_MIN (3) +#define CONFIG_MESH_RETRY_TIMEOUT_DEF (10) +#define CONFIG_MESH_RETRY_TIMEOUT_MAX (60) + +// ֵ֧豸ڵ +#define CONFIG_MESH_PROV_NODE_COUNT_MIN (1) +#define CONFIG_MESH_PROV_NODE_COUNT_DEF (2) + +// ADV_RF +#define CONFIG_MESH_RF_ACCESSADDRESS (0x8E89BED6) +#define CONFIG_MESH_RF_CHANNEL_37 (37) +#define CONFIG_MESH_RF_CHANNEL_38 (38) +#define CONFIG_MESH_RF_CHANNEL_39 (39) + +#define APP_DBG(X...) \ + if (1) \ + { \ + printf("APP_DBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app_vendor_model_srv.h b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app_vendor_model_srv.h new file mode 100644 index 0000000..83b8329 --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/APP/include/app_vendor_model_srv.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_srv_H +#define app_vendor_model_srv_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "MESH_LIB.h" + +#define MSG_PIN GPIO_Pin_12 + +#define CID_WCH 0x07D7 + +#define OP_VENDOR_MESSAGE_TRANSPARENT_CFM BLE_MESH_MODEL_OP_3(0xCB, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_WRT BLE_MESH_MODEL_OP_3(0xCC, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_ACK BLE_MESH_MODEL_OP_3(0xCD, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_IND BLE_MESH_MODEL_OP_3(0xCE, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_WCH) + +#define BLE_MESH_MODEL_ID_WCH_SRV 0x0000 +#define BLE_MESH_MODEL_ID_WCH_CLI 0x0001 + +#define VENDOR_MODEL_SRV_TRANS_EVT (1<<0) +#define VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT (1<<1) +#define VENDOR_MODEL_SRV_INDICATE_EVT (1<<2) + +struct bt_adv_trans_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + + +struct send_param +{ + u16_t net_idx; + u16_t app_idx; + u16_t addr; + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_trans_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_trans +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_write +{ + struct send_param param; + struct net_buf *buf; +}; + + +struct bt_mesh_vendor_model_write +{ + u8_t *pdata; + u16_t len; +}; + +struct bt_mesh_vendor_model_srv_trans +{ + u8_t *pdata; + u16_t len; +}; + +struct vendor_model_srv_EventHdr +{ + u8_t status; + u32_t opcode; +}; + +union vendor_model_srv_Event_t +{ + struct bt_mesh_vendor_model_srv_trans trans; + struct bt_mesh_vendor_model_write write; +}; + +typedef struct +{ + struct vendor_model_srv_EventHdr vendor_model_srv_Hdr; + union vendor_model_srv_Event_t vendor_model_srv_Event; +}vendor_model_srv_status_t; + + +typedef void (*vendor_model_srv_rsp_handler_t)(const vendor_model_srv_status_t *val); + +struct vendor_model_srv_tid +{ + u8_t trans_tid; + u8_t write_tid; +}; + +/** Mesh vendor_model_srv Model Context */ +struct bt_mesh_vendor_model_srv { + struct bt_mesh_model *model; + u32_t op_req; + u32_t op_pending; + struct vendor_model_srv_tid srv_tid; + + vendor_model_srv_rsp_handler_t handler; + +}; + + + +extern const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb; + +extern const struct bt_mesh_model_op vnd_model_srv_op[]; + + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on); + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method ÿϢѭsrvʹ128~191 +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void); + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/adv_vendor_low_power/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/adv_vendor_low_power/Project/BLE.uvprojx new file mode 100644 index 0000000..bb977ef --- /dev/null +++ b/src/EXAM/BLE/MESH/adv_vendor_low_power/Project/BLE.uvprojx @@ -0,0 +1,577 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model_srv.c + 1 + ..\APP\app_vendor_model_srv.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app.c b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app.c new file mode 100644 index 0000000..2981f87 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app.c @@ -0,0 +1,937 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/22 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model_srv.h" +#include "app_vendor_model_cli.h" +#include "app.h" +#include "HAL.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024*2+30*CONFIG_MESH_PROV_NODE_COUNT_DEF]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +static uint8_t dev_uuid[16]={0}; // 豸UUID +u8 MACAddr[6]; // 豸mac + +static const u8_t self_prov_net_key[16] = { + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, +}; + +static const u8_t self_prov_dev_key[16] = { + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, +}; + +static const u8_t self_prov_app_key[16] = { + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, +}; + +const u16_t self_prov_net_idx = 0x0000; // õnet key +const u16_t self_prov_app_idx = 0x0001; // õapp key +const u32_t self_prov_iv_index = 0x00000000; // iv_index +const u16_t self_prov_addr = 0x0001; // Ԫصַ +const u8_t self_prov_flags = 0x00; // Ƿkey״̬ĬΪ +const u16_t vendor_sub_addr = 0xC000; // Զģ͵Ķgroupַ + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void unprov_recv(bt_mesh_prov_bearer_t bearer, + const u8_t uuid[16], bt_mesh_prov_oob_info_t oob_info, + const unprivison_info_t *info); +static void node_added(u16_t net_idx, u16_t addr, u8_t num_elem); +static void cfg_cli_rsp_handler(const cfg_cli_status_t *val); +static void vendor_model_cli_rsp_handler(const vendor_model_cli_status_t *val); +static void node_init(void); + +static struct bt_mesh_cfg_srv cfg_srv = { +#if (CONFIG_BLE_MESH_RELAY) + .relay = BLE_MESH_RELAY_ENABLED, +#endif + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +static struct bt_mesh_health_srv health_srv; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +struct bt_mesh_cfg_cli cfg_cli = { + .handler = cfg_cli_rsp_handler, +}; + +// rootģͼ +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_CFG_CLI(&cfg_cli), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), +}; + +struct bt_mesh_vendor_model_cli vendor_model_cli = { + .cli_tid.trans_tid = 0xFF, + .cli_tid.ind_tid = 0xFF, + .handler = vendor_model_cli_rsp_handler, +}; + +// Զģͼ +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_WCH, BLE_MESH_MODEL_ID_WCH_CLI, vnd_model_cli_op, NULL, &vendor_model_cli, &bt_mesh_vendor_model_cli_cb), +}; + +// ģ elements +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = dev_uuid, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .unprovisioned_beacon = unprov_recv, + .node_added = node_added, +}; + +// ߹Ľڵ㣬0ΪԼ12Ϊ˳Ľڵ +node_t app_nodes[ 1 + CONFIG_MESH_PROV_NODE_COUNT_DEF ]={0}; + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkصֹͣ㲥 +* Input : bearer +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(""); +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : reason : link close reason ͷļ +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG("reason %x",reason); + if( reason == CLOSE_REASON_RESOURCES ) + { + // 洢Ľڵѡ ֹͣ ȫڵ ַڵ(עӦòĽڵҲҪӦ) + bt_mesh_provisioner_disable(BLE_MESH_PROV_ADV, TRUE); + //bt_mesh_node_clear();node_init(); + //bt_mesh_node_del_by_addr(app_nodes[1].node_addr); + } + else + bt_mesh_provisioner_enable(BLE_MESH_PROV_ADV); +} + +/******************************************************************************* +* Function Name : node_unblock_get +* Description : ȡ unblocked node +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_unblock_get(void) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr != BLE_MESH_ADDR_UNASSIGNED && + app_nodes[i].fixed != TRUE && + app_nodes[i].blocked == FALSE) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_block_get +* Description : ȡ blocked node +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_block_get(void) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr != BLE_MESH_ADDR_UNASSIGNED && + app_nodes[i].fixed != TRUE && + app_nodes[i].blocked == TRUE) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_work_handler +* Description : node ִУжǷδɵĽڵ㣬ýڵú +* Input : None +* Return : TRUE: ִýڵ +* FALSE: ڵɣֹͣ +*******************************************************************************/ +static BOOL node_work_handler( void ) +{ + node_t *node; + + node = node_unblock_get(); + if (!node) + { + APP_DBG("Unable find Unblocked Node"); + return FALSE; + } + + if (node->retry_cnt -- == 0) + { + APP_DBG("Ran Out of Retransmit"); + goto unblock; + } + + if (!node->cb->stage(node)) + { + return FALSE; + } + +unblock: + + node->fixed = TRUE; + + node = node_block_get(); + if (node) + { + node->blocked = FALSE; + return TRUE; + } + return FALSE; +} + +/******************************************************************************* +* Function Name : node_init +* Description : node ʼ +* Input : None +* Return : None +*******************************************************************************/ +static void node_init(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + app_nodes[i].stage.node = NODE_INIT; + app_nodes[i].node_addr = BLE_MESH_ADDR_UNASSIGNED; + } +} + +/******************************************************************************* +* Function Name : free_node_get +* Description : ȡһյnode +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * free_node_get(void) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr == BLE_MESH_ADDR_UNASSIGNED) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_get +* Description : ȡƥnode +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_get(u16_t node_addr) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr == node_addr) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_should_blocked +* Description : жǷnode +* Input : None +* Return : TRUE: nodeδ +* FALSE: nodeѾûҪ +*******************************************************************************/ +static BOOL node_should_blocked(u16_t node_addr) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr != BLE_MESH_ADDR_UNASSIGNED && + app_nodes[i].node_addr != node_addr && + app_nodes[i].fixed != TRUE && + app_nodes[i].blocked == FALSE) + { + return TRUE; + } + } + return FALSE; +} + +/******************************************************************************* +* Function Name : node_cfg_process +* Description : һеĽڵ㣬ִ +* Input : node +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_cfg_process(node_t *node, u16_t net_idx, u16_t addr, u8_t num_elem) +{ + if (!node) + { + node = free_node_get(); + if (!node) + { + APP_DBG("No Free Node Object Available"); + return NULL; + } + node->net_idx = net_idx; + node->node_addr = addr; + node->elem_count = num_elem; + } + + node->blocked = node_should_blocked(addr); + + if (!node->blocked) + { + tmos_set_event(App_TaskID, APP_NODE_EVT); + } + return node; +} + +/******************************************************************************* +* Function Name : node_stage_set +* Description : Զnodeõһ׶ +* Input : new_stage: ½׶ +* Return : None +*******************************************************************************/ +static void node_stage_set(node_t *node, node_stage_t new_stage) +{ + node->retry_cnt = 3; + node->stage.node = new_stage; +} + +/******************************************************************************* +* Function Name : local_stage_set +* Description : ñnodeõһ׶ +* Input : new_stage: ½׶ +* Return : None +*******************************************************************************/ +static void local_stage_set(node_t *node, local_stage_t new_stage) +{ + node->retry_cnt = 1; + node->stage.local = new_stage; +} + +/******************************************************************************* +* Function Name : node_rsp +* Description : ÿִһԶ˽ڵ̵Ļص +* Input : p1ҪõԶnode +* p2ǰ״̬ +* Return : None +*******************************************************************************/ +static void node_rsp(void *p1, const void *p2) +{ + node_t *node = p1; + const cfg_cli_status_t *val = p2; + + switch (val->cfgHdr.opcode) + { + case OP_APP_KEY_ADD: + APP_DBG("node Application Key Added"); + node_stage_set(node, NODE_MOD_BIND_SET); + break; + case OP_MOD_APP_BIND: + APP_DBG("node vendor Model Binded"); + node_stage_set(node, NODE_MOD_SUB_SET); + break; + case OP_MOD_SUB_ADD: + APP_DBG("node vendor Model Subscription Set"); + node_stage_set(node, NODE_CONFIGURATIONED); + break; + default: + APP_DBG("Unknown Opcode (0x%04x)", val->cfgHdr.opcode); + return; + } +} + +/******************************************************************************* +* Function Name : local_rsp +* Description : ÿִһؽڵ̵Ļص +* Input : p1Ҫõınode +* p2ǰ״̬ +* Return : None +*******************************************************************************/ +static void local_rsp(void *p1, const void *p2) +{ + node_t *node = p1; + const cfg_cli_status_t *val = p2; + + switch (val->cfgHdr.opcode) + { + case OP_APP_KEY_ADD: + APP_DBG("local Application Key Added"); + local_stage_set(node, LOCAL_MOD_BIND_SET); + break; + case OP_MOD_APP_BIND: + APP_DBG("local vendor Model Binded"); + local_stage_set(node, LOCAL_CONFIGURATIONED); + break; + default: + APP_DBG("Unknown Opcode (0x%04x)", val->cfgHdr.opcode); + return; + } +} + +/******************************************************************************* +* Function Name : node_stage +* Description : Զ˽ڵãapp keyΪԶapp key +* Input : p1Ҫõınode +* Return : TRUE: +*******************************************************************************/ +static BOOL node_stage(void *p1) +{ + int err; + BOOL ret = FALSE; + node_t *node = p1; + + switch (node->stage.node) + { + case NODE_APPKEY_ADD: + err = bt_mesh_cfg_app_key_add(node->net_idx, node->node_addr, self_prov_net_idx, self_prov_app_idx, self_prov_app_key); + if (err) + { + APP_DBG("Unable to adding Application key (err %d)", err); + ret = TRUE; + } + break; + + case NODE_MOD_BIND_SET: + err = bt_mesh_cfg_mod_app_bind_vnd(node->net_idx, node->node_addr, node->node_addr, self_prov_app_idx, BLE_MESH_MODEL_ID_WCH_SRV, CID_WCH); + if (err) + { + APP_DBG("Unable to Binding vendor Model (err %d)", err); + ret = TRUE; + } + break; + + // ģͶ + case NODE_MOD_SUB_SET: + err = bt_mesh_cfg_mod_sub_add_vnd(node->net_idx, node->node_addr, node->node_addr, vendor_sub_addr, BLE_MESH_MODEL_ID_WCH_SRV, CID_WCH); + if (err) + { + APP_DBG("Unable to Set vendor Model Subscription (err %d)", err); + ret = TRUE; + } + break; + + default: + ret = TRUE; + break; + } + + return ret; +} + +/******************************************************************************* +* Function Name : local_stage +* Description : ؽڵãapp keyΪԶͻ˰app key +* Input : None +* Return : None +*******************************************************************************/ +static BOOL local_stage(void *p1) +{ + int err; + BOOL ret = FALSE; + node_t *node = p1; + + switch (node->stage.local) + { + case LOCAL_APPKEY_ADD: + err = bt_mesh_cfg_app_key_add(node->net_idx, node->node_addr, self_prov_net_idx, self_prov_app_idx, self_prov_app_key); + if (err) + { + APP_DBG("Unable to adding Application key (err %d)", err); + ret = 1; + } + break; + + case LOCAL_MOD_BIND_SET: + err = bt_mesh_cfg_mod_app_bind_vnd(node->net_idx, node->node_addr, node->node_addr, self_prov_app_idx, BLE_MESH_MODEL_ID_WCH_CLI,CID_WCH); + if (err) + { + APP_DBG("Unable to Binding vendor Model (err %d)", err); + ret = 1; + } + break; + + default: + ret = 1; + break; + } + + return ret; +} + +static const cfg_cb_t node_cfg_cb = { + node_rsp, + node_stage, +}; + +static const cfg_cb_t local_cfg_cb = { + local_rsp, + local_stage, +}; + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻصɺʼؽڵ +* Input : Ľڵ +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + int err; + node_t *node; + + APP_DBG(""); + + err = bt_mesh_provisioner_enable(BLE_MESH_PROV_ADV); + if (err) + { + APP_DBG("Unabled Enable Provisoner (err:%d)", err); + } + + node = node_get(addr); + if (!node || !node->fixed) + { + node = node_cfg_process(node, net_idx, addr, ARRAY_SIZE(elements)); + if (!node) + { + APP_DBG("Unable allocate node object"); + return; + } + + node->cb = &local_cfg_cb; + local_stage_set(node, LOCAL_APPKEY_ADD); + } +} + +/******************************************************************************* +* Function Name : unprov_recv +* Description : յδݣ +* Input : None +* Return : None +*******************************************************************************/ +static void unprov_recv(bt_mesh_prov_bearer_t bearer, + const u8_t uuid[16], bt_mesh_prov_oob_info_t oob_info, + const unprivison_info_t *info) +{ + APP_DBG(""); + int err; + + if (bearer & BLE_MESH_PROV_ADV) + { + err = bt_mesh_provision_adv(uuid, self_prov_net_idx, BLE_MESH_ADDR_UNASSIGNED, 5); + if (err) + { + APP_DBG("Unable Open PB-ADV Session (err:%d)", err); + } + } +} + +/******************************************************************************* +* Function Name : node_added +* Description : Զ˽ڵɹӵؽڵʼԶ˽ڵ +* Input : None +* Return : None +*******************************************************************************/ +static void node_added(u16_t net_idx, u16_t addr, u8_t num_elem) +{ + node_t *node; + APP_DBG(""); + + node = node_get(addr); + if (!node || !node->fixed) + { + node = node_cfg_process(node, net_idx, addr, num_elem); + if (!node) + { + APP_DBG("Unable allocate node object"); + return; + } + + node->cb = &node_cfg_cb; + node_stage_set(node, NODE_APPKEY_ADD); + } +} + +/******************************************************************************* +* Function Name : cfg_cli_rsp_handler +* Description : յcfgӦص +* Input : None +* Return : None +*******************************************************************************/ +static void cfg_cli_rsp_handler(const cfg_cli_status_t *val) +{ + node_t *node; + APP_DBG(""); + + node = node_unblock_get(); + if (!node) + { + APP_DBG("Unable find Unblocked Node"); + return; + } + + if (val->cfgHdr.status == 0xFF) + { + APP_DBG("Opcode 0x%04x, timeout", val->cfgHdr.opcode); + goto end; + } + + node->cb->rsp(node, val); + +end: + tmos_start_task(App_TaskID, APP_NODE_EVT, K_SECONDS(1)); +} + +/******************************************************************************* +* Function Name : vendor_model_cli_rsp_handler +* Description : vendor_model cli յص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_cli_rsp_handler(const vendor_model_cli_status_t *val) +{ + if( val->vendor_model_cli_Hdr.status) + { + // Ӧݴ ʱδյӦ + APP_DBG("Timeout opcode 0x%02x",val->vendor_model_cli_Hdr.opcode); + return; + } + if( val->vendor_model_cli_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_MSG ) + { + // յ͸ + APP_DBG("trans len %d, data 0x%02x",val->vendor_model_cli_Event.trans.len, + val->vendor_model_cli_Event.trans.pdata[0]); + } + else if( val->vendor_model_cli_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_IND ) + { + // յindicate + APP_DBG("ind len %d, data 0x%02x",val->vendor_model_cli_Event.ind.len, + val->vendor_model_cli_Event.ind.pdata[0]); + } + else if( val->vendor_model_cli_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_WRT ) + { + // յwriteӦ + } + else + { + APP_DBG("Unknow opcode 0x%02x",val->vendor_model_cli_Hdr.opcode); + } +} + +/******************************************************************************* +* Function Name : keyPress +* Description : صڶĽڵ㷢͸ +* Input : keys: İ +* Return : None +*******************************************************************************/ +void keyPress(uint8 keys) +{ + APP_DBG("%d", keys); + + switch (keys) + { + default: + { + if(app_nodes[1].node_addr) + { + uint8 status; + APP_DBG("node1_addr %x",app_nodes[1].node_addr); + struct send_param param = { + .app_idx = self_prov_app_idx, // Ϣʹõapp key + .addr = app_nodes[1].node_addr, // ϢĿĵصַ˴Ϊ1Ľڵ + .trans_cnt = 0x03, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_cli_tid_get(), // tidÿϢѭcliʹ0~127 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + uint8 data[16] = {0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16}; + status = vendor_message_cli_write(¶m, data, 16); // ԶģͿͻ˵Ӧд + if( status ) APP_DBG("write failed %d",status); + } + break; + } + } +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + PRINT("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init); +#endif /* LPN */ + GetMACAddress( MACAddr ); + tmos_memcpy(dev_uuid, MACAddr, 6); + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MACAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + node_init(); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); + +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + +#if (CONFIG_BLE_MESH_LOW_POWER) + bt_mesh_lpn_set(TRUE); +#endif /* LPN */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + err = bt_mesh_provision(self_prov_net_key, self_prov_net_idx, self_prov_flags, + self_prov_iv_index, self_prov_addr, self_prov_dev_key); + if (err) + { + APP_DBG("Self Privisioning (err %d)", err); + return; + } + } + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : ʼ +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + + HAL_KeyInit(); + HalKeyConfig( keyPress ); + + // һ񣬶ʱһ豸͸ + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 4800); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + // ڵ¼ + if ( events & APP_NODE_EVT ) + { + if (node_work_handler() ) + return ( events ); + else + return ( events ^ APP_NODE_EVT ); + } + + // ¼ + if ( events & APP_NODE_TEST_EVT ) + { + if(app_nodes[1].node_addr) + { + uint8 status; + APP_DBG("app_nodes[1] ADDR %x",app_nodes[1].node_addr); + struct send_param param = { + .app_idx = self_prov_app_idx, // Ϣʹõapp key + .addr = app_nodes[1].node_addr, // ϢĿĵصַ˴ΪԶ˽ڵ1ĵַ + .trans_cnt = 0x03, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_cli_tid_get(), // tidÿϢѭcliʹ0~127 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + uint8 data[16] = {0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16}; + status = vendor_message_cli_send_trans(¶m, data, 4); // ԶģͿͻ˵͸ + if( status ) APP_DBG("trans failed %d",status); + } + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 3200); + return ( events ^ APP_NODE_TEST_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_main.c b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_vendor_model_cli.c b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_vendor_model_cli.c new file mode 100644 index 0000000..df92946 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/app_vendor_model_cli.c @@ -0,0 +1,618 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_cli.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/22 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "app_vendor_model_cli.h" +#include "app_vendor_model_srv.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +// ӦòͳȣְΪCONFIG_MESH_UNSEG_LENGTH_DEFְΪCONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8RAMʹ +#define APP_MAX_TX_SIZE MAX(CONFIG_MESH_UNSEG_LENGTH_DEF,CONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8) + +static uint8 vendor_model_cli_TaskID = 0; // Task ID for internal task/event processing +static uint8 cli_send_tid=0; +static s32_t cli_msg_timeout = K_SECONDS(2); //Ӧݴ䳬ʱʱ䣬Ĭ2 + +static struct net_buf cli_trans_buf; +static struct bt_mesh_trans cli_trans = +{ + .buf = &cli_trans_buf, +}; + +static struct net_buf cli_write_buf; +static struct bt_mesh_write cli_write = +{ + .buf = &cli_write_buf, +}; + +static struct bt_mesh_vendor_model_cli *vendor_model_cli; + +static uint16 vendor_model_cli_ProcessEvent( uint8 task_id, uint16 events ); +static void write_reset(struct bt_mesh_write *write, int err); + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : vendor_cli_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_cli_tid_get(void) +{ + cli_send_tid++; + if(cli_send_tid > 127) + cli_send_tid = 0; + return cli_send_tid; +} + +/******************************************************************************* +* Function Name : vendor_model_cli_reset +* Description : vendor_model_cli״ִ̬е +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_cli_reset(void) +{ + vendor_model_cli->op_pending = 0U; + vendor_model_cli->op_req = 0U; + + tmos_stop_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT); + tmos_stop_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT); +} + +/******************************************************************************* +* Function Name : vendor_model_cli_rsp_recv +* Description : Ӧò㴫Ļص +* Input : val: vendor_model_cli_status_t +* status: status +* Return : None +*******************************************************************************/ +static void vendor_model_cli_rsp_recv(vendor_model_cli_status_t *val, u8_t status) +{ + if (vendor_model_cli == NULL || (!vendor_model_cli->op_req)) + { + return; + } + + val->vendor_model_cli_Hdr.opcode = vendor_model_cli->op_req; + val->vendor_model_cli_Hdr.status = status; + + vendor_model_cli_reset(); + + if (vendor_model_cli->handler) + { + vendor_model_cli->handler(val); + } +} + +/******************************************************************************* +* Function Name : vendor_model_cli_wait +* Description : Ĭ볬ʱ֪ͨӦò +* Input : None +* Return : err: οBLE_LIB err code +*******************************************************************************/ +static int vendor_model_cli_wait(void) +{ + int err; + + err = tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT, cli_msg_timeout); + + return err; +} + +/******************************************************************************* +* Function Name : vendor_model_cli_prepare +* Description : Ԥ +* Input : op_req: ͵ +* op: ķ +* Return : None +*******************************************************************************/ +static int vendor_model_cli_prepare(u32_t op_req, u32_t op) +{ + if (!vendor_model_cli) + { + APP_DBG("No available Configuration Client context!"); + return -EINVAL; + } + + if (vendor_model_cli->op_pending) + { + APP_DBG("Another synchronous operation pending"); + return -EBUSY; + } + + vendor_model_cli->op_req = op_req; + vendor_model_cli->op_pending = op; + + return 0; +} + +/******************************************************************************* +* Function Name : vendor_cli_sync_handler +* Description : ֪ͨӦò㵱ǰop_codeʱ +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_cli_sync_handler( void ) +{ + vendor_model_cli_status_t vendor_model_cli_status; + + tmos_memset(&vendor_model_cli_status, 0, sizeof(vendor_model_cli_status_t)); + + write_reset(&cli_write, -ETIMEDOUT); + + vendor_model_cli_rsp_recv(&vendor_model_cli_status, 0xFF); +} + + +/******************************************************************************* +* Function Name : vendor_message_cli_ack +* Description : vendor_message_cli_ack - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_ack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + u8_t recv_tid; + int err; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("tid 0x%02x ", recv_tid); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&msg, OP_VENDOR_MESSAGE_TRANSPARENT_ACK); + + /* Add tid field */ + net_buf_simple_add_u8(&msg, recv_tid); + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("#mesh-onoff STATUS: send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : vendor_message_cli_trans +* Description : ͸ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_cli_status_t vendor_model_cli_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_cli->cli_tid.trans_tid ) + { + vendor_model_cli->cli_tid.trans_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_cli_status.vendor_model_cli_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_MSG; + vendor_model_cli_status.vendor_model_cli_Hdr.status = 0; + vendor_model_cli_status.vendor_model_cli_Event.trans.pdata = pData; + vendor_model_cli_status.vendor_model_cli_Event.trans.len = len; + + if (vendor_model_cli->handler) + { + vendor_model_cli->handler(&vendor_model_cli_status); + } + } +} + +/******************************************************************************* +* Function Name : vendor_message_cli_ind +* Description : յVendor Model ServerIndication +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_ind(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_cli_status_t vendor_model_cli_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + APP_DBG("src: 0x%04x dst: 0x%04x rssi: %d app_idx: 0x%x", + ctx->addr, ctx->recv_dst, ctx->recv_rssi, ctx->app_idx); + + if( pData[0] != vendor_model_cli->cli_tid.ind_tid ) + { + vendor_model_cli->cli_tid.ind_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_cli_status.vendor_model_cli_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_IND; + vendor_model_cli_status.vendor_model_cli_Hdr.status = 0; + vendor_model_cli_status.vendor_model_cli_Event.ind.pdata = pData; + vendor_model_cli_status.vendor_model_cli_Event.ind.len = len; + + if (vendor_model_cli->handler) + { + vendor_model_cli->handler(&vendor_model_cli_status); + } + } + vendor_message_cli_ack(model, ctx, buf); +} + +/******************************************************************************* +* Function Name : vendor_message_cli_cfm +* Description : յ vendor_message_cli_cfm - ϢVendor Model ServerظVendor Model Client + ڱʾյVendor Model Client Write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_cfm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + vendor_model_cli_status_t vendor_model_cli_status; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + if (cli_write.param.tid == recv_tid) + { + write_reset(&cli_write, 0); + vendor_model_cli_rsp_recv(&vendor_model_cli_status, 0); + } +} + + +// opcode ӦĴ +const struct bt_mesh_model_op vnd_model_cli_op[] = { + {OP_VENDOR_MESSAGE_TRANSPARENT_MSG, 0, vendor_message_cli_trans}, + {OP_VENDOR_MESSAGE_TRANSPARENT_IND, 0, vendor_message_cli_ind}, + {OP_VENDOR_MESSAGE_TRANSPARENT_CFM, 0, vendor_message_cli_cfm}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************************************************************* +* Function Name : vendor_message_cli_send_trans +* Description : send_trans ,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_send_trans(struct send_param *param, u8_t *pData, u16_t len) +{ + if(!param->addr) + return -EINVAL; + if( cli_trans.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + cli_trans.buf->__buf = tmos_msg_allocate(len+8); + if( !(cli_trans.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + cli_trans.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(cli_trans.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_MSG); + + /* Add tid field */ + net_buf_simple_add_u8(&(cli_trans.buf->b), param->tid); + + net_buf_simple_add_mem(&(cli_trans.buf->b), pData, len); + + memcpy(&cli_trans.param, param, sizeof(struct send_param)); + + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_TRANS_EVT, param->rand); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_cli_write +* Description : write ,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_write(struct send_param *param, u8_t *pData, u16_t len) +{ + if( !param->addr) + return -EINVAL; + if( cli_write.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + cli_write.buf->__buf = tmos_msg_allocate(len+8); + if( !(cli_write.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + cli_write.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(cli_write.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_WRT); + + /* Add tid field */ + net_buf_simple_add_u8(&(cli_write.buf->b), param->tid); + + net_buf_simple_add_mem(&(cli_write.buf->b), pData, len); + + memcpy(&cli_write.param, param, sizeof(struct send_param)); + + vendor_model_cli_prepare(OP_VENDOR_MESSAGE_TRANSPARENT_WRT, OP_VENDOR_MESSAGE_TRANSPARENT_CFM); + + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT, param->rand); + + vendor_model_cli_wait(); + return 0; +} + +/******************************************************************************* +* Function Name : adv_cli_trans_send +* Description : ͸ cli_trans +* Input : None +* Return : None +*******************************************************************************/ +static void adv_cli_trans_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = cli_trans.param.app_idx ? cli_trans.param.app_idx : vendor_model_cli->model->keys[0], + .addr = cli_trans.param.addr, + }; + + if (cli_trans.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (cli_trans.param.trans_cnt == 0) + { +// APP_DBG("cli_trans.buf.trans_cnt over"); + tmos_msg_deallocate(cli_trans.buf->__buf); + cli_trans.buf->__buf = NULL; + return; + } + + cli_trans.param.trans_cnt --; + + ctx.send_ttl = cli_trans.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, cli_trans.buf->data, cli_trans.buf->len); + + err = bt_mesh_model_send(vendor_model_cli->model, &ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + tmos_msg_deallocate(cli_trans.buf->__buf); + cli_trans.buf->__buf = NULL; + return; + } + // ش + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_TRANS_EVT, cli_trans.param.period); +} + +/******************************************************************************* +* Function Name : vendor_message_cli_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_cli_trans_reset( void ) +{ + tmos_msg_deallocate(cli_trans.buf->__buf); + cli_trans.buf->__buf = NULL; + tmos_stop_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_TRANS_EVT); +} + +/******************************************************************************* +* Function Name : write_reset +* Description : ӦòwriteɻصͷŻ +* Input : write: +* err: οGlobal_Error_Code +* Return : None +*******************************************************************************/ +static void write_reset(struct bt_mesh_write *write, int err) +{ + if (write->param.cb && write->param.cb->end) + { + write->param.cb->end(err, write->param.cb_data); + } + + tmos_msg_deallocate(write->buf->__buf); + write->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : write_start +* Description : write ʼص +* Input : duration: ˷¼¼λ0.625ms +* err: οGlobal_Error_Code +* cb_data: ص +* Return : None +*******************************************************************************/ +static void write_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_write *write = cb_data; + + if (write->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT, K_MSEC(100)); + return; + } +} + +/******************************************************************************* +* Function Name : write_end +* Description : write ص +* Input : err: οGlobal_Error_Code +* cb_data: ص +* Return : None +*******************************************************************************/ +static void write_end(int err, void *cb_data) +{ + struct bt_mesh_write *write = cb_data; + APP_DBG("write_end (err:%d)", err); + + if (write->buf->__buf == NULL) + { + return; + } + + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT, write->param.period); +} + +// indicate صṹ +const struct bt_mesh_send_cb write_cb = +{ + .start = write_start, + .end = write_end, +}; + +/******************************************************************************* +* Function Name : adv_cli_write_send +* Description : Ӧ cli_write +* Input : None +* Return : None +*******************************************************************************/ +static void adv_cli_write_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = cli_write.param.app_idx ? cli_write.param.app_idx : vendor_model_cli->model->keys[0], + .addr = cli_write.param.addr, + }; + + if (cli_write.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (cli_write.param.trans_cnt == 0) + { +// APP_DBG("cli_write.buf.trans_cnt over"); + write_reset(&cli_write, -ETIMEDOUT); + return; + } + + cli_write.param.trans_cnt --; + + ctx.send_ttl = cli_write.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, cli_write.buf->data, cli_write.buf->len); + + err = bt_mesh_model_send(vendor_model_cli->model, &ctx, &msg, &write_cb, &cli_write); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + + write_reset(&cli_write, err); + return; + } +} + + +/******************************************************************************* +* Function Name : vendor_model_cli_init +* Description : vendor_model_cli ʼ +* Input : model; +* Return : SUCCESS +*******************************************************************************/ +static int vendor_model_cli_init(struct bt_mesh_model *model) +{ + vendor_model_cli = model->user_data; + vendor_model_cli->model = model; + + vendor_model_cli_TaskID = TMOS_ProcessEventRegister( vendor_model_cli_ProcessEvent ); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_model_cli_ProcessEvent +* Description : vendor_model_cli +* Input : task_id, events +* Return : events +*******************************************************************************/ +static uint16 vendor_model_cli_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & VENDOR_MODEL_CLI_TRANS_EVT ) + { + adv_cli_trans_send(); + return ( events ^ VENDOR_MODEL_CLI_TRANS_EVT ); + } + if ( events & VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT ) + { + vendor_cli_sync_handler(); + return ( events ^ VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT ); + } + if ( events & VENDOR_MODEL_CLI_WRITE_EVT ) + { + adv_cli_write_send(); + return ( events ^ VENDOR_MODEL_CLI_WRITE_EVT ); + } + // Discard unknown events + return 0; +} + + +const struct bt_mesh_model_cb bt_mesh_vendor_model_cli_cb = { + .init = vendor_model_cli_init, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app.h b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app.h new file mode 100644 index 0000000..afc2952 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app.h @@ -0,0 +1,90 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_H +#define app_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/******************************************************************************/ + +#define APP_NODE_EVT (1<<0) +#define APP_NODE_TEST_EVT (1<<1) + +/******************************************************************************/ +// Զ˽ڵ +typedef enum +{ + NODE_INIT = 0, + NODE_APPKEY_ADD = 1, + NODE_MOD_BIND_SET = 2, + NODE_MOD_SUB_SET = 3, + + NODE_CONFIGURATIONED = 4, +} node_stage_t; + +// ؽڵ +typedef enum +{ + LOCAL_INIT = 0, + LOCAL_APPKEY_ADD = 1, + LOCAL_MOD_BIND_SET = 2, + + LOCAL_CONFIGURATIONED = 4, +} local_stage_t; + +typedef union +{ + node_stage_t node; + local_stage_t local; +}stage_t; + +typedef void (*cfg_rsp_handler_t)(void *node, const void *rsp); +typedef BOOL (*stage_handler_t)(void *node); + +typedef struct +{ + cfg_rsp_handler_t rsp; + stage_handler_t stage; +}cfg_cb_t; + +typedef struct +{ + u16_t node_addr; + u16_t elem_count; + u16_t net_idx; + u16_t retry_cnt:12, + fixed:1, + blocked:1; + + stage_t stage; + const cfg_cb_t *cb; +}node_t; + +extern node_t app_nodes[ 1 + CONFIG_MESH_PROV_NODE_COUNT_DEF ]; +extern const u16_t self_prov_net_idx; +extern const u16_t self_prov_app_idx; +extern const u32_t self_prov_iv_index; +extern const u16_t self_prov_addr; + + +void App_Init(void); + +/******************************************************************************/ + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_mesh_config.h b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_mesh_config.h new file mode 100644 index 0000000..30deebb --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_mesh_config.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + +#ifndef APP_MESH_CONFIG_H +#define APP_MESH_CONFIG_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/**************************,ֱӲοͬ*****************************/ + +// relay +#define CONFIG_BLE_MESH_RELAY 1 +// +#define CONFIG_BLE_MESH_PROXY 0 +// GATT +#define CONFIG_BLE_MESH_PB_GATT 0 +// FLASH洢 +#define CONFIG_BLE_MESH_SETTINGS 1 +// ѽڵ㹦 +#define CONFIG_BLE_MESH_FRIEND 0 +// ͹Ľڵ㹦 +#define CONFIG_BLE_MESH_LOW_POWER 0 +// configģͿͻ˹ +#define CONFIG_BLE_MESH_CFG_CLI 1 +// healthģͿͻ˹ +#define CONFIG_BLE_MESH_HLTH_CLI 1 + + +/******************************************************************************/ + +// Netݻ +#define CONFIG_MESH_ADV_BUF_COUNT_MIN (6) +#define CONFIG_MESH_ADV_BUF_COUNT_DEF (10) +#define CONFIG_MESH_ADV_BUF_COUNT_MAX (40) + +// RPLݻ +#define CONFIG_MESH_RPL_COUNT_MIN (6) +#define CONFIG_MESH_RPL_COUNT_DEF (6) +#define CONFIG_MESH_RPL_COUNT_MAX (20) + +// IV Update State Timer 96HķƵϵ +#define CONFIG_MESH_IVU_DIVIDER_MIN (1) +#define CONFIG_MESH_IVU_DIVIDER_DEF (96) +#define CONFIG_MESH_IVU_DIVIDER_MAX (96) + +// ڰܴ洢 +#define CONFIG_MESH_PROXY_FILTER_MIN (2) +#define CONFIG_MESH_PROXY_FILTER_DEF (5) +#define CONFIG_MESH_PROXY_FILTER_MAX (20) + +// Ϣ +#define CONFIG_MESH_MSG_CACHE_MIN (3) +#define CONFIG_MESH_MSG_CACHE_DEF (20) +#define CONFIG_MESH_MSG_CACHE_MAX (20) + +// +#define CONFIG_MESH_SUBNET_COUNT_MIN (1) +#define CONFIG_MESH_SUBNET_COUNT_DEF (1) +#define CONFIG_MESH_SUBNET_COUNT_MAX (4) + +// APP key +#define CONFIG_MESH_APPKEY_COUNT_MIN (1) +#define CONFIG_MESH_APPKEY_COUNT_DEF (3) +#define CONFIG_MESH_APPKEY_COUNT_MAX (5) + +// ǷһдַͬĽڵ㣨ʹְܺܲã +#define CONFIG_MESH_ALLOW_SAME_ADDR (FALSE) + +// ְϢֵ֧ijȣ˳Ҫְ޸Ĵֵmesh׼ +#define CONFIG_MESH_UNSEG_LENGTH_MIN (7) +#define CONFIG_MESH_UNSEG_LENGTH_DEF (7) +#define CONFIG_MESH_UNSEG_LENGTH_MAX (221) + +// ÿϢְ +#define CONFIG_MESH_TX_SEG_MIN (2) +#define CONFIG_MESH_TX_SEG_DEF (8) +#define CONFIG_MESH_TX_SEG_MAX (32) + +// ͬʱڵķְϢ͸ +#define CONFIG_MESH_TX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_TX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_TX_SEG_COUNT_MAX (4) + +// ͬʱڵķְϢո +#define CONFIG_MESH_RX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_RX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_RX_SEG_COUNT_MAX (4) + +// ÿյķְϢֽ +#define CONFIG_MESH_RX_SDU_MIN (12) +#define CONFIG_MESH_RX_SDU_DEF (192) +#define CONFIG_MESH_RX_SDU_MAX (384) + +// ַ +#define CONFIG_MESH_LABEL_COUNT_MIN (1) +#define CONFIG_MESH_LABEL_COUNT_DEF (2) +#define CONFIG_MESH_LABEL_COUNT_MAX (4) + +// NVS洢ʹ +#define CONFIG_MESH_SECTOR_COUNT_MIN (2) +#define CONFIG_MESH_SECTOR_COUNT_DEF (3) + +// NVS洢׵ַ +#define CONFIG_MESH_NVS_ADDR_DEF (0x3E800) + +// RPLº洢ijʱʱ(s) +#define CONFIG_MESH_RPL_STORE_RATE_MIN (5) +#define CONFIG_MESH_RPL_STORE_RATE_DEF (60) +#define CONFIG_MESH_RPL_STORE_RATE_MAX (3600) + +// SEQº洢ijʱʱ(s) +#define CONFIG_MESH_SEQ_STORE_RATE_MIN (5) +#define CONFIG_MESH_SEQ_STORE_RATE_DEF (60) +#define CONFIG_MESH_SEQ_STORE_RATE_MAX (3600) + +// Ϣº洢ijʱʱ(s) +#define CONFIG_MESH_STORE_RATE_MIN (2) +#define CONFIG_MESH_STORE_RATE_DEF (2) +#define CONFIG_MESH_STORE_RATE_MAX (5) + +// ѽڵֵ֧ÿϢķְ +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF (2) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MAX (4) + +// ѽڵֵ֧Ķĸ +#define CONFIG_MESH_FRIEND_SUB_SIZE_MIN (1) +#define CONFIG_MESH_FRIEND_SUB_SIZE_DEF (4) +#define CONFIG_MESH_FRIEND_SUB_SIZE_MAX (8) + +// ѽڵֵ֧ĵ͹Ľڵ +#define CONFIG_MESH_FRIEND_LPN_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_DEF (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_MAX (4) + +// ѽڵ洢ϢдС +#define CONFIG_MESH_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_QUEUE_SIZE_DEF (4) +#define CONFIG_MESH_QUEUE_SIZE_MAX (30) + +// ѽڵմڴС(ms) +#define CONFIG_MESH_FRIEND_RECV_WIN_MIN (1) +#define CONFIG_MESH_FRIEND_RECV_WIN_DEF (20) +#define CONFIG_MESH_FRIEND_RECV_WIN_MAX (255) + +// ͹ĽڵϢдС +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MAX (20) + +// ͹ĽڵϢʱʱ(10ms) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MIN (30) +#define CONFIG_MESH_LPN_POLLTIMEOUT_DEF (40) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MAX (400) + +// ͹Ľڵֵ֧Ľӳ(ms) +#define CONFIG_MESH_LPN_RECV_DELAY_MIN (100) +#define CONFIG_MESH_LPN_RECV_DELAY_DEF (100) +#define CONFIG_MESH_LPN_RECV_DELAY_MAX (400) + +// ѹϵؽȴʱ(s) +#define CONFIG_MESH_RETRY_TIMEOUT_MIN (3) +#define CONFIG_MESH_RETRY_TIMEOUT_DEF (10) +#define CONFIG_MESH_RETRY_TIMEOUT_MAX (60) + +// ֵ֧豸ڵ +#define CONFIG_MESH_PROV_NODE_COUNT_MIN (1) +#define CONFIG_MESH_PROV_NODE_COUNT_DEF (6) + +// ADV_RF +#define CONFIG_MESH_RF_ACCESSADDRESS (0x8E89BED6) +#define CONFIG_MESH_RF_CHANNEL_37 (37) +#define CONFIG_MESH_RF_CHANNEL_38 (38) +#define CONFIG_MESH_RF_CHANNEL_39 (39) + +#define APP_DBG(X...) \ + if (1) \ + { \ + printf("APP_DBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_vendor_model_cli.h b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_vendor_model_cli.h new file mode 100644 index 0000000..ca0dc42 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_vendor_model_cli.h @@ -0,0 +1,128 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model_cli.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_generic_onoff_model_cli_H +#define app_generic_onoff_model_cli_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "app_vendor_model_srv.h" + +#define CID_WCH 0x07D7 + +#define OP_VENDOR_MESSAGE_TRANSPARENT_CFM BLE_MESH_MODEL_OP_3(0xCB, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_WRT BLE_MESH_MODEL_OP_3(0xCC, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_ACK BLE_MESH_MODEL_OP_3(0xCD, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_IND BLE_MESH_MODEL_OP_3(0xCE, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_WCH) + +#define BLE_MESH_MODEL_ID_WCH_SRV 0x0000 +#define BLE_MESH_MODEL_ID_WCH_CLI 0x0001 + +#define VENDOR_MODEL_CLI_TRANS_EVT (1<<0) +#define VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT (1<<1) +#define VENDOR_MODEL_CLI_WRITE_EVT (1<<2) + +struct bt_mesh_vendor_model_ind +{ + u8_t *pdata; + u16_t len; +}; + +struct bt_mesh_vendor_model_cli_trans +{ + u8_t *pdata; + u16_t len; +}; + +struct vendor_model_cli_EventHdr +{ + u8_t status; + u32_t opcode; +}; + +union vendor_model_cli_Event_t +{ + struct bt_mesh_vendor_model_cli_trans trans; + struct bt_mesh_vendor_model_ind ind; +}; + +typedef struct +{ + struct vendor_model_cli_EventHdr vendor_model_cli_Hdr; + union vendor_model_cli_Event_t vendor_model_cli_Event; +}vendor_model_cli_status_t; + + +typedef void (*vendor_model_cli_rsp_handler_t)(const vendor_model_cli_status_t *val); + +struct vendor_model_cli_tid +{ + u8_t trans_tid; + u8_t ind_tid; +}; + +/** Mesh vendor_model_cli Model Context */ +struct bt_mesh_vendor_model_cli { + struct bt_mesh_model *model; + u32_t op_req; + u32_t op_pending; + struct vendor_model_cli_tid cli_tid; + + vendor_model_cli_rsp_handler_t handler; + +}; + +extern const struct bt_mesh_model_op vnd_model_cli_op[]; +extern const struct bt_mesh_model_cb bt_mesh_vendor_model_cli_cb; + +/******************************************************************************* +* Function Name : vendor_message_cli_send_trans +* Description : send_trans ,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_send_trans(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_message_cli_write +* Description : write ,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_write(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_cli_tid_get +* Description : TODO TID selection method ÿϢѭcliʹ0~127 +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_cli_tid_get(void); + +/******************************************************************************* +* Function Name : vendor_message_cli_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_cli_trans_reset( void ); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_vendor_model_srv.h b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_vendor_model_srv.h new file mode 100644 index 0000000..83b8329 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/APP/include/app_vendor_model_srv.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_srv_H +#define app_vendor_model_srv_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "MESH_LIB.h" + +#define MSG_PIN GPIO_Pin_12 + +#define CID_WCH 0x07D7 + +#define OP_VENDOR_MESSAGE_TRANSPARENT_CFM BLE_MESH_MODEL_OP_3(0xCB, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_WRT BLE_MESH_MODEL_OP_3(0xCC, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_ACK BLE_MESH_MODEL_OP_3(0xCD, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_IND BLE_MESH_MODEL_OP_3(0xCE, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_WCH) + +#define BLE_MESH_MODEL_ID_WCH_SRV 0x0000 +#define BLE_MESH_MODEL_ID_WCH_CLI 0x0001 + +#define VENDOR_MODEL_SRV_TRANS_EVT (1<<0) +#define VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT (1<<1) +#define VENDOR_MODEL_SRV_INDICATE_EVT (1<<2) + +struct bt_adv_trans_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + + +struct send_param +{ + u16_t net_idx; + u16_t app_idx; + u16_t addr; + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_trans_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_trans +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_write +{ + struct send_param param; + struct net_buf *buf; +}; + + +struct bt_mesh_vendor_model_write +{ + u8_t *pdata; + u16_t len; +}; + +struct bt_mesh_vendor_model_srv_trans +{ + u8_t *pdata; + u16_t len; +}; + +struct vendor_model_srv_EventHdr +{ + u8_t status; + u32_t opcode; +}; + +union vendor_model_srv_Event_t +{ + struct bt_mesh_vendor_model_srv_trans trans; + struct bt_mesh_vendor_model_write write; +}; + +typedef struct +{ + struct vendor_model_srv_EventHdr vendor_model_srv_Hdr; + union vendor_model_srv_Event_t vendor_model_srv_Event; +}vendor_model_srv_status_t; + + +typedef void (*vendor_model_srv_rsp_handler_t)(const vendor_model_srv_status_t *val); + +struct vendor_model_srv_tid +{ + u8_t trans_tid; + u8_t write_tid; +}; + +/** Mesh vendor_model_srv Model Context */ +struct bt_mesh_vendor_model_srv { + struct bt_mesh_model *model; + u32_t op_req; + u32_t op_pending; + struct vendor_model_srv_tid srv_tid; + + vendor_model_srv_rsp_handler_t handler; + +}; + + + +extern const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb; + +extern const struct bt_mesh_model_op vnd_model_srv_op[]; + + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on); + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method ÿϢѭsrvʹ128~191 +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void); + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/self_provisioner_vendor/Project/BLE.uvprojx new file mode 100644 index 0000000..c825a1d --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor/Project/BLE.uvprojx @@ -0,0 +1,577 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model_cli.c + 1 + ..\APP\app_vendor_model_cli.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app.c b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app.c new file mode 100644 index 0000000..93c3b18 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app.c @@ -0,0 +1,945 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/22 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "MESH_LIB.h" +#include "app_vendor_model_srv.h" +#include "app_vendor_model_cli.h" +#include "app.h" +#include "peripheral.h" +#include "HAL.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +#define ADV_TIMEOUT K_MINUTES(10) + + +#define SELENCE_ADV_ON 0x01 +#define SELENCE_ADV_OF 0x00 + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +static u8_t MESH_MEM[1024*2+30*CONFIG_MESH_PROV_NODE_COUNT_DEF]={0}; + +extern const ble_mesh_cfg_t app_mesh_cfg; +extern const struct device app_dev; + +static uint8 App_TaskID = 0; // Task ID for internal task/event processing + +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ); + +static uint8_t dev_uuid[16]={0}; // 豸UUID +u8 MACAddr[6]; // 豸mac + +static const u8_t self_prov_net_key[16] = { + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, +}; + +static const u8_t self_prov_dev_key[16] = { + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, +}; + +static const u8_t self_prov_app_key[16] = { + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + 0x00, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, +}; + +const u16_t self_prov_net_idx = 0x0000; // õnet key +const u16_t self_prov_app_idx = 0x0001; // õapp key +const u32_t self_prov_iv_index = 0x00000000; // iv_index +const u16_t self_prov_addr = 0x0001; // Ԫصַ +const u8_t self_prov_flags = 0x00; // Ƿkey״̬ĬΪ +const u16_t vendor_sub_addr = 0xC000; // Զģ͵Ķgroupַ + +#if (!CONFIG_BLE_MESH_PB_GATT) +NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); +#endif /* !PB_GATT */ + +/********************************************************************* + * LOCAL FUNCION + */ + +static void link_open(bt_mesh_prov_bearer_t bearer); +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason); +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index); +static void unprov_recv(bt_mesh_prov_bearer_t bearer, + const u8_t uuid[16], bt_mesh_prov_oob_info_t oob_info, + const unprivison_info_t *info); +static void node_added(u16_t net_idx, u16_t addr, u8_t num_elem); +static void cfg_cli_rsp_handler(const cfg_cli_status_t *val); +static void vendor_model_cli_rsp_handler(const vendor_model_cli_status_t *val); +static void node_init(void); + +static struct bt_mesh_cfg_srv cfg_srv = { +#if (CONFIG_BLE_MESH_RELAY) + .relay = BLE_MESH_RELAY_ENABLED, +#endif + .beacon = BLE_MESH_BEACON_DISABLED, +#if (CONFIG_BLE_MESH_FRIEND) + .frnd = BLE_MESH_FRIEND_ENABLED, +#endif +#if (CONFIG_BLE_MESH_PROXY) + .gatt_proxy = BLE_MESH_GATT_PROXY_ENABLED, +#endif + .default_ttl = 3, + + /* 8 transmissions with 10ms interval */ + .net_transmit = BLE_MESH_TRANSMIT(7, 10), + .relay_retransmit = BLE_MESH_TRANSMIT(7, 10), +}; + +static struct bt_mesh_health_srv health_srv; + +BLE_MESH_HEALTH_PUB_DEFINE(health_pub, 8); + +struct bt_mesh_cfg_cli cfg_cli = { + .handler = cfg_cli_rsp_handler, +}; + +// rootģͼ +static struct bt_mesh_model root_models[] = { + BLE_MESH_MODEL_CFG_SRV(&cfg_srv), + BLE_MESH_MODEL_CFG_CLI(&cfg_cli), + BLE_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), +}; + +struct bt_mesh_vendor_model_cli vendor_model_cli = { + .cli_tid.trans_tid = 0xFF, + .cli_tid.ind_tid = 0xFF, + .handler = vendor_model_cli_rsp_handler, +}; + +// Զģͼ +struct bt_mesh_model vnd_models[] = { + BLE_MESH_MODEL_VND_CB(CID_WCH, BLE_MESH_MODEL_ID_WCH_CLI, vnd_model_cli_op, NULL, &vendor_model_cli, &bt_mesh_vendor_model_cli_cb), +}; + +// ģ elements +static struct bt_mesh_elem elements[] = { + { + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + .loc = (0), + .model_count = ARRAY_SIZE(root_models), + .models = (root_models), + .vnd_model_count = ARRAY_SIZE(vnd_models), + .vnd_models = (vnd_models), + } +}; + +// elements Node Composition +const struct bt_mesh_comp app_comp = { + .cid = 0x07D7, // WCH ˾id + .elem = elements, + .elem_count = ARRAY_SIZE(elements), +}; + +// ͻص +static const struct bt_mesh_prov app_prov = { + .uuid = dev_uuid, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .unprovisioned_beacon = unprov_recv, + .node_added = node_added, +}; + +// ߹Ľڵ㣬0ΪԼ12Ϊ˳Ľڵ +node_t app_nodes[ 1 + CONFIG_MESH_PROV_NODE_COUNT_DEF ]={0}; + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + + +/******************************************************************************* +* Function Name : link_open +* Description : ǰlinkصֹͣ㲥 +* Input : bearer +* Return : None +*******************************************************************************/ +static void link_open(bt_mesh_prov_bearer_t bearer) +{ + APP_DBG(""); +} + +/******************************************************************************* +* Function Name : link_close +* Description : linkرջص +* Input : reason : link close reason ͷļ +* Return : None +*******************************************************************************/ +static void link_close(bt_mesh_prov_bearer_t bearer, u8_t reason) +{ + APP_DBG("reason %x",reason); + if( reason == CLOSE_REASON_RESOURCES ) + { + // 洢Ľڵѡ ֹͣ ȫڵ ַڵ(עӦòĽڵҲҪӦ) + bt_mesh_provisioner_disable(BLE_MESH_PROV_ADV, TRUE); + //bt_mesh_node_clear();node_init(); + //bt_mesh_node_del_by_addr(app_nodes[1].node_addr); + } + else + bt_mesh_provisioner_enable(BLE_MESH_PROV_ADV); +} + +/******************************************************************************* +* Function Name : node_unblock_get +* Description : ȡ unblocked node +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_unblock_get(void) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr != BLE_MESH_ADDR_UNASSIGNED && + app_nodes[i].fixed != TRUE && + app_nodes[i].blocked == FALSE) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_block_get +* Description : ȡ blocked node +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_block_get(void) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr != BLE_MESH_ADDR_UNASSIGNED && + app_nodes[i].fixed != TRUE && + app_nodes[i].blocked == TRUE) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_work_handler +* Description : node ִУжǷδɵĽڵ㣬ýڵú +* Input : None +* Return : TRUE: ִýڵ +* FALSE: ڵɣֹͣ +*******************************************************************************/ +static BOOL node_work_handler( void ) +{ + node_t *node; + + node = node_unblock_get(); + if (!node) + { + APP_DBG("Unable find Unblocked Node"); + return FALSE; + } + + if (node->retry_cnt -- == 0) + { + APP_DBG("Ran Out of Retransmit"); + goto unblock; + } + + if (!node->cb->stage(node)) + { + return FALSE; + } + +unblock: + + node->fixed = TRUE; + + node = node_block_get(); + if (node) + { + node->blocked = FALSE; + return TRUE; + } + return FALSE; +} + +/******************************************************************************* +* Function Name : node_init +* Description : node ʼ +* Input : None +* Return : None +*******************************************************************************/ +static void node_init(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + app_nodes[i].stage.node = NODE_INIT; + app_nodes[i].node_addr = BLE_MESH_ADDR_UNASSIGNED; + } +} + +/******************************************************************************* +* Function Name : free_node_get +* Description : ȡһյnode +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * free_node_get(void) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr == BLE_MESH_ADDR_UNASSIGNED) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_get +* Description : ȡƥnode +* Input : None +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_get(u16_t node_addr) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr == node_addr) + { + return &app_nodes[i]; + } + } + return NULL; +} + +/******************************************************************************* +* Function Name : node_should_blocked +* Description : жǷnode +* Input : None +* Return : TRUE: nodeδ +* FALSE: nodeѾûҪ +*******************************************************************************/ +static BOOL node_should_blocked(u16_t node_addr) +{ + for (int i = 0; i < ARRAY_SIZE(app_nodes); i++) + { + if (app_nodes[i].node_addr != BLE_MESH_ADDR_UNASSIGNED && + app_nodes[i].node_addr != node_addr && + app_nodes[i].fixed != TRUE && + app_nodes[i].blocked == FALSE) + { + return TRUE; + } + } + return FALSE; +} + +/******************************************************************************* +* Function Name : node_cfg_process +* Description : һеĽڵ㣬ִ +* Input : node +* Return : node_t / NULL +*******************************************************************************/ +static node_t * node_cfg_process(node_t *node, u16_t net_idx, u16_t addr, u8_t num_elem) +{ + if (!node) + { + node = free_node_get(); + if (!node) + { + APP_DBG("No Free Node Object Available"); + return NULL; + } + node->net_idx = net_idx; + node->node_addr = addr; + node->elem_count = num_elem; + } + + node->blocked = node_should_blocked(addr); + + if (!node->blocked) + { + tmos_set_event(App_TaskID, APP_NODE_EVT); + } + return node; +} + +/******************************************************************************* +* Function Name : node_stage_set +* Description : Զnodeõһ׶ +* Input : new_stage: ½׶ +* Return : None +*******************************************************************************/ +static void node_stage_set(node_t *node, node_stage_t new_stage) +{ + node->retry_cnt = 3; + node->stage.node = new_stage; +} + +/******************************************************************************* +* Function Name : local_stage_set +* Description : ñnodeõһ׶ +* Input : new_stage: ½׶ +* Return : None +*******************************************************************************/ +static void local_stage_set(node_t *node, local_stage_t new_stage) +{ + node->retry_cnt = 1; + node->stage.local = new_stage; +} + +/******************************************************************************* +* Function Name : node_rsp +* Description : ÿִһԶ˽ڵ̵Ļص +* Input : p1ҪõԶnode +* p2ǰ״̬ +* Return : None +*******************************************************************************/ +static void node_rsp(void *p1, const void *p2) +{ + node_t *node = p1; + const cfg_cli_status_t *val = p2; + + switch (val->cfgHdr.opcode) + { + case OP_APP_KEY_ADD: + APP_DBG("node Application Key Added"); + node_stage_set(node, NODE_MOD_BIND_SET); + break; + case OP_MOD_APP_BIND: + APP_DBG("node vendor Model Binded"); + node_stage_set(node, NODE_MOD_SUB_SET); + break; + case OP_MOD_SUB_ADD: + APP_DBG("node vendor Model Subscription Set"); + node_stage_set(node, NODE_CONFIGURATIONED); + break; + default: + APP_DBG("Unknown Opcode (0x%04x)", val->cfgHdr.opcode); + return; + } +} + +/******************************************************************************* +* Function Name : local_rsp +* Description : ÿִһؽڵ̵Ļص +* Input : p1Ҫõınode +* p2ǰ״̬ +* Return : None +*******************************************************************************/ +static void local_rsp(void *p1, const void *p2) +{ + node_t *node = p1; + const cfg_cli_status_t *val = p2; + + switch (val->cfgHdr.opcode) + { + case OP_APP_KEY_ADD: + APP_DBG("local Application Key Added"); + local_stage_set(node, LOCAL_MOD_BIND_SET); + break; + case OP_MOD_APP_BIND: + APP_DBG("local vendor Model Binded"); + local_stage_set(node, LOCAL_CONFIGURATIONED); + break; + default: + APP_DBG("Unknown Opcode (0x%04x)", val->cfgHdr.opcode); + return; + } +} + +/******************************************************************************* +* Function Name : node_stage +* Description : Զ˽ڵãapp keyΪԶapp key +* Input : p1Ҫõınode +* Return : TRUE: +*******************************************************************************/ +static BOOL node_stage(void *p1) +{ + int err; + BOOL ret = FALSE; + node_t *node = p1; + + switch (node->stage.node) + { + case NODE_APPKEY_ADD: + err = bt_mesh_cfg_app_key_add(node->net_idx, node->node_addr, self_prov_net_idx, self_prov_app_idx, self_prov_app_key); + if (err) + { + APP_DBG("Unable to adding Application key (err %d)", err); + ret = TRUE; + } + break; + + case NODE_MOD_BIND_SET: + err = bt_mesh_cfg_mod_app_bind_vnd(node->net_idx, node->node_addr, node->node_addr, self_prov_app_idx, BLE_MESH_MODEL_ID_WCH_SRV, CID_WCH); + if (err) + { + APP_DBG("Unable to Binding vendor Model (err %d)", err); + ret = TRUE; + } + break; + + // ģͶ + case NODE_MOD_SUB_SET: + err = bt_mesh_cfg_mod_sub_add_vnd(node->net_idx, node->node_addr, node->node_addr, vendor_sub_addr, BLE_MESH_MODEL_ID_WCH_SRV, CID_WCH); + if (err) + { + APP_DBG("Unable to Set vendor Model Subscription (err %d)", err); + ret = TRUE; + } + break; + + default: + ret = TRUE; + break; + } + + return ret; +} + +/******************************************************************************* +* Function Name : local_stage +* Description : ؽڵãapp keyΪԶͻ˰app key +* Input : None +* Return : None +*******************************************************************************/ +static BOOL local_stage(void *p1) +{ + int err; + BOOL ret = FALSE; + node_t *node = p1; + + switch (node->stage.local) + { + case LOCAL_APPKEY_ADD: + err = bt_mesh_cfg_app_key_add(node->net_idx, node->node_addr, self_prov_net_idx, self_prov_app_idx, self_prov_app_key); + if (err) + { + APP_DBG("Unable to adding Application key (err %d)", err); + ret = 1; + } + break; + + case LOCAL_MOD_BIND_SET: + err = bt_mesh_cfg_mod_app_bind_vnd(node->net_idx, node->node_addr, node->node_addr, self_prov_app_idx, BLE_MESH_MODEL_ID_WCH_CLI,CID_WCH); + if (err) + { + APP_DBG("Unable to Binding vendor Model (err %d)", err); + ret = 1; + } + break; + + default: + ret = 1; + break; + } + + return ret; +} + +static const cfg_cb_t node_cfg_cb = { + node_rsp, + node_stage, +}; + +static const cfg_cb_t local_cfg_cb = { + local_rsp, + local_stage, +}; + +/******************************************************************************* +* Function Name : prov_complete +* Description : ɻصɺʼؽڵ +* Input : Ľڵ +* Return : None +*******************************************************************************/ +static void prov_complete(u16_t net_idx, u16_t addr, u8_t flags, u32_t iv_index) +{ + int err; + node_t *node; + + APP_DBG(""); + + err = bt_mesh_provisioner_enable(BLE_MESH_PROV_ADV); + if (err) + { + APP_DBG("Unabled Enable Provisoner (err:%d)", err); + } + + node = node_get(addr); + if (!node || !node->fixed) + { + node = node_cfg_process(node, net_idx, addr, ARRAY_SIZE(elements)); + if (!node) + { + APP_DBG("Unable allocate node object"); + return; + } + + node->cb = &local_cfg_cb; + local_stage_set(node, LOCAL_APPKEY_ADD); + } +} + +/******************************************************************************* +* Function Name : unprov_recv +* Description : յδݣ +* Input : None +* Return : None +*******************************************************************************/ +static void unprov_recv(bt_mesh_prov_bearer_t bearer, + const u8_t uuid[16], bt_mesh_prov_oob_info_t oob_info, + const unprivison_info_t *info) +{ + APP_DBG(""); + int err; + + if (bearer & BLE_MESH_PROV_ADV) + { + err = bt_mesh_provision_adv(uuid, self_prov_net_idx, BLE_MESH_ADDR_UNASSIGNED, 5); + if (err) + { + APP_DBG("Unable Open PB-ADV Session (err:%d)", err); + } + } +} + +/******************************************************************************* +* Function Name : node_added +* Description : Զ˽ڵɹӵؽڵʼԶ˽ڵ +* Input : None +* Return : None +*******************************************************************************/ +static void node_added(u16_t net_idx, u16_t addr, u8_t num_elem) +{ + node_t *node; + APP_DBG(""); + + node = node_get(addr); + if (!node || !node->fixed) + { + node = node_cfg_process(node, net_idx, addr, num_elem); + if (!node) + { + APP_DBG("Unable allocate node object"); + return; + } + + node->cb = &node_cfg_cb; + node_stage_set(node, NODE_APPKEY_ADD); + } +} + +/******************************************************************************* +* Function Name : cfg_cli_rsp_handler +* Description : յcfgӦص +* Input : None +* Return : None +*******************************************************************************/ +static void cfg_cli_rsp_handler(const cfg_cli_status_t *val) +{ + node_t *node; + APP_DBG(""); + + node = node_unblock_get(); + if (!node) + { + APP_DBG("Unable find Unblocked Node"); + return; + } + + if (val->cfgHdr.status == 0xFF) + { + APP_DBG("Opcode 0x%04x, timeout", val->cfgHdr.opcode); + goto end; + } + + node->cb->rsp(node, val); + +end: + tmos_start_task(App_TaskID, APP_NODE_EVT, K_SECONDS(1)); +} + +/******************************************************************************* +* Function Name : vendor_model_cli_rsp_handler +* Description : vendor_model cli յص +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_cli_rsp_handler(const vendor_model_cli_status_t *val) +{ + if( val->vendor_model_cli_Hdr.status) + { + // Ӧݴ ʱδյӦ + APP_DBG("Timeout opcode 0x%02x",val->vendor_model_cli_Hdr.opcode); + return; + } + if( val->vendor_model_cli_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_MSG ) + { + // յ͸ + APP_DBG("trans len %d, data 0x%02x",val->vendor_model_cli_Event.trans.len, + val->vendor_model_cli_Event.trans.pdata[0]); + // ת() + peripheralChar4Notify(val->vendor_model_cli_Event.trans.pdata, val->vendor_model_cli_Event.trans.len); + } + else if( val->vendor_model_cli_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_IND ) + { + // յindicate + APP_DBG("ind len %d, data 0x%02x",val->vendor_model_cli_Event.ind.len, + val->vendor_model_cli_Event.ind.pdata[0]); + // ת() + peripheralChar4Notify(val->vendor_model_cli_Event.trans.pdata, val->vendor_model_cli_Event.trans.len); + } + else if( val->vendor_model_cli_Hdr.opcode == OP_VENDOR_MESSAGE_TRANSPARENT_WRT ) + { + // յwriteӦ + } + else + { + APP_DBG("Unknow opcode 0x%02x",val->vendor_model_cli_Hdr.opcode); + } +} + +/******************************************************************************* +* Function Name : keyPress +* Description : صڶĽڵ㷢͸ +* Input : keys: İ +* Return : None +*******************************************************************************/ +void keyPress(uint8 keys) +{ + APP_DBG("%d", keys); + + switch (keys) + { + default: + { + if(app_nodes[1].node_addr) + { + uint8 status; + APP_DBG("node1_addr %x",app_nodes[1].node_addr); + struct send_param param = { + .app_idx = self_prov_app_idx, // Ϣʹõapp key + .addr = app_nodes[1].node_addr, // ϢĿĵصַ˴Ϊ1Ľڵ + .trans_cnt = 0x03, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_cli_tid_get(), // tidÿϢѭcliʹ0~127 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + uint8 data[16] = {0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16}; + status = vendor_message_cli_write(¶m, data, 16); // ԶģͿͻ˵Ӧд + if( status ) APP_DBG("write failed %d",status); + } + break; + } + } +} + +/******************************************************************************* +* Function Name : blemesh_on_sync +* Description : ͬmeshöӦܣ޸ +* Input : None +* Return : None +*******************************************************************************/ +void blemesh_on_sync(void) +{ + int err; + mem_info_t info; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ) + { + PRINT("head file error...\n"); + while(1); + } + + info.base_addr = MESH_MEM; + info.mem_len = ARRAY_SIZE(MESH_MEM); +#if (CONFIG_BLE_MESH_FRIEND) + friend_init_register(bt_mesh_friend_init); +#endif /* FRIEND */ +#if (CONFIG_BLE_MESH_LOW_POWER) + lpn_init_register(bt_mesh_lpn_init); +#endif /* LPN */ + GetMACAddress( MACAddr ); + tmos_memcpy(dev_uuid, MACAddr, 6); + err = bt_mesh_cfg_set(&app_mesh_cfg, &app_dev, MACAddr, &info); + if (err) + { + APP_DBG("Unable set configuration (err:%d)", err); + return; + } + hal_rf_init(); + err = bt_mesh_comp_register(&app_comp); + node_init(); + +#if (CONFIG_BLE_MESH_RELAY) + bt_mesh_relay_init(); +#endif /* RELAY */ +#if (CONFIG_BLE_MESH_PROXY || CONFIG_BLE_MESH_PB_GATT) +#if (CONFIG_BLE_MESH_PROXY ) + bt_mesh_proxy_beacon_init_register( (void*) bt_mesh_proxy_beacon_init ); + gatts_notify_register( bt_mesh_gatts_notify ); + proxy_gatt_enable_register( bt_mesh_proxy_gatt_enable ); +#endif /* PROXY */ +#if (CONFIG_BLE_MESH_PB_GATT ) + proxy_prov_enable_register( bt_mesh_proxy_prov_enable ); +#endif /* PB_GATT */ + bt_mesh_proxy_init(); +#endif /* PROXY || PB-GATT */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_client_init(cli); // +#endif /* PROXY_CLI */ + + bt_mesh_prov_retransmit_init(); + +#if (!CONFIG_BLE_MESH_PB_GATT) + adv_link_rx_buf_register(&rx_buf); +#endif /* !PB_GATT */ + err = bt_mesh_prov_init(&app_prov); + + bt_mesh_mod_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + bt_mesh_adv_init(); + +#if ((CONFIG_BLE_MESH_PB_GATT) || (CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_conn_adv_init(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_SETTINGS) + bt_mesh_settings_init(); +#endif /* SETTINGS */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + bt_mesh_proxy_cli_adapt_init(); +#endif /* PROXY_CLI */ + +#if ((CONFIG_BLE_MESH_PROXY) || (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_PROXY_CLI) || (CONFIG_BLE_MESH_OTA)) + bt_mesh_adapt_init(); +#endif /* PROXY || PB-GATT || PROXY_CLI || OTA */ + +#if (CONFIG_BLE_MESH_LOW_POWER) + bt_mesh_lpn_set(TRUE); +#endif /* LPN */ + + if (err) + { + APP_DBG("Initializing mesh failed (err %d)", err); + return; + } + APP_DBG("Bluetooth initialized"); + +#if (CONFIG_BLE_MESH_SETTINGS) + settings_load(); +#endif /* SETTINGS */ + + if (bt_mesh_is_provisioned()) + { + APP_DBG("Mesh network restored from flash"); + } + else + { + err = bt_mesh_provision(self_prov_net_key, self_prov_net_idx, self_prov_flags, + self_prov_iv_index, self_prov_addr, self_prov_dev_key); + if (err) + { + APP_DBG("Self Privisioning (err %d)", err); + return; + } + } + APP_DBG("Mesh initialized"); +} + +/******************************************************************************* +* Function Name : App_Init +* Description : ʼ +* Input : None +* Return : None +*******************************************************************************/ +void App_Init() +{ + GAPRole_PeripheralInit(); + Peripheral_Init(); + + App_TaskID = TMOS_ProcessEventRegister( App_ProcessEvent ); + + blemesh_on_sync(); + + HAL_KeyInit(); + HalKeyConfig( keyPress ); + + // һ񣬶ʱһ豸͸ + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 4800); +} + +/******************************************************************************* +* Function Name : App_ProcessEvent +* Description : +* Input : None +* Return : None +*******************************************************************************/ +static uint16 App_ProcessEvent( uint8 task_id, uint16 events ) +{ + // ڵ¼ + if ( events & APP_NODE_EVT ) + { + if (node_work_handler() ) + return ( events ); + else + return ( events ^ APP_NODE_EVT ); + } + + // ¼ + if ( events & APP_NODE_TEST_EVT ) + { + if(app_nodes[1].node_addr) + { + uint8 status; + APP_DBG("app_nodes[1] ADDR %x",app_nodes[1].node_addr); + struct send_param param = { + .app_idx = self_prov_app_idx, // Ϣʹõapp key + .addr = app_nodes[1].node_addr, // ϢĿĵصַ˴ΪԶ˽ڵ1ĵַ + .trans_cnt = 0x03, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_cli_tid_get(), // tidÿϢѭcliʹ0~127 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + uint8 data[16] = {0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16}; + status = vendor_message_cli_send_trans(¶m, data, 4); // ԶģͿͻ˵͸ + if( status ) APP_DBG("trans failed %d",status); + } + tmos_start_task(App_TaskID, APP_NODE_TEST_EVT, 2400); + return ( events ^ APP_NODE_TEST_EVT ); + } + + // Discard unknown events + return 0; +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_main.c b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_main.c new file mode 100644 index 0000000..f201005 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_main.c @@ -0,0 +1,88 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "app_mesh_config.h" +#include "app.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; + +/******************************************************************************* +* Function Name : MeshTimer_Init +* Description : mesh ʼ +* Input : None +* Return : None +*******************************************************************************/ +u8_t bt_mesh_lib_init(void) +{ + u8_t ret; + + if( tmos_memcmp( VER_MESH_LIB,VER_MESH_FILE,strlen(VER_MESH_FILE)) == FALSE ){ + PRINT("mesh head file error...\n"); + while(1); + } + + ret = RF_RoleInit( ); + +#if ((CONFIG_BLE_MESH_PROXY) || \ + (CONFIG_BLE_MESH_PB_GATT) || \ + (CONFIG_BLE_MESH_OTA)) + ret = GAPRole_PeripheralInit(); +#endif /* PROXY || PB-GATT || OTA */ + +#if (CONFIG_BLE_MESH_PROXY_CLI) + ret = GAPRole_CentralInit(); +#endif /* CONFIG_BLE_MESH_PROXY_CLI */ + + MeshTimer_Init(); + MeshDeamon_Init(); + +#if (CONFIG_BLE_MESH_IV_UPDATE_TEST) + bt_mesh_iv_update_test(TRUE); +#endif + return ret; +} + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#ifdef DEBUG + GPIOA_SetBits( bTXD1 ); + GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); + UART1_DefInit( ); +#endif + { + PRINT("%s\n",VER_LIB); + PRINT("%s\n",VER_MESH_LIB); + } + CH57X_BLEInit( ); + HAL_Init( ); + bt_mesh_lib_init(); + App_Init(); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_mesh_config.c b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_mesh_config.c new file mode 100644 index 0000000..287436b --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_mesh_config.c @@ -0,0 +1,117 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +const ble_mesh_cfg_t app_mesh_cfg = { + .common_cfg.adv_buf_count = CONFIG_MESH_ADV_BUF_COUNT_DEF, + .common_cfg.rpl_count = CONFIG_MESH_RPL_COUNT_DEF, + .common_cfg.allow_same_addr = CONFIG_MESH_ALLOW_SAME_ADDR, + .common_cfg.ivu_divider = CONFIG_MESH_IVU_DIVIDER_DEF, + + .proxy_cfg.pxyfilter_count = CONFIG_MESH_PROXY_FILTER_DEF, + + .net_cfg.msgcache_count = CONFIG_MESH_MSG_CACHE_DEF, + .net_cfg.subnet_count = CONFIG_MESH_SUBNET_COUNT_DEF, + .net_cfg.appkey_count = CONFIG_MESH_APPKEY_COUNT_DEF, + .net_cfg.unseg_length = CONFIG_MESH_UNSEG_LENGTH_DEF, + .net_cfg.txseg_max = CONFIG_MESH_TX_SEG_DEF, + .net_cfg.txseg_count = CONFIG_MESH_TX_SEG_COUNT_DEF, + .net_cfg.rxseg_count = CONFIG_MESH_RX_SEG_COUNT_DEF, + .net_cfg.rxsdu_max = CONFIG_MESH_RX_SDU_DEF, + .net_cfg.label_count = CONFIG_MESH_LABEL_COUNT_DEF, + + .store_cfg.seq_store_rate = CONFIG_MESH_SEQ_STORE_RATE_DEF, + .store_cfg.rpl_store_rate = CONFIG_MESH_RPL_STORE_RATE_DEF, + .store_cfg.store_rate = CONFIG_MESH_STORE_RATE_DEF, + + .friend_cfg.frndseg_rx = CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF, + .friend_cfg.frndsub_size = CONFIG_MESH_FRIEND_SUB_SIZE_DEF, + .friend_cfg.frndlpn_count = CONFIG_MESH_FRIEND_LPN_COUNT_DEF, + .friend_cfg.frndqueue_size = CONFIG_MESH_QUEUE_SIZE_DEF, + .friend_cfg.frndrecv_win = CONFIG_MESH_FRIEND_RECV_WIN_DEF, + + .lpn_cfg.lpnmin_size = CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF, + .lpn_cfg.lpnrssi_factor = 0, + .lpn_cfg.lpnrecv_factor = 0, + .lpn_cfg.lpnpoll_timeout = CONFIG_MESH_LPN_POLLTIMEOUT_DEF, + .lpn_cfg.lpnrecv_delay = CONFIG_MESH_LPN_RECV_DELAY_DEF, + .lpn_cfg.lpnretry_timeout = CONFIG_MESH_RETRY_TIMEOUT_DEF, + + .prov_cfg.node_count = CONFIG_MESH_PROV_NODE_COUNT_DEF, + .rf_cfg.rf_accessAddress = CONFIG_MESH_RF_ACCESSADDRESS, + .rf_cfg.rf_channel_37 = CONFIG_MESH_RF_CHANNEL_37, + .rf_cfg.rf_channel_38 = CONFIG_MESH_RF_CHANNEL_38, + .rf_cfg.rf_channel_39 = CONFIG_MESH_RF_CHANNEL_39, +}; + +int read_flash(int offset, void *data, unsigned int len) +{ + memcpy(data, (const void *)offset, len); + return 0; +} + +int write_flash(int offset, const void *data, unsigned int len) +{ + UINT8 status; + + status = FlashWriteBuf(offset, (PUINT32)data, len); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int erase_flash(int offset, unsigned int len) +{ + UINT8 status; + + status = FlashBlockErase(offset); + if (status != 0) + { + return -EACCES; + } + + return 0; +} + +int flash_write_protection(BOOL enable) +{ + return 0; +} + +const struct device app_dev = { + .api = { + .read = read_flash, + .write = write_flash, + .erase = erase_flash, + .write_protection = flash_write_protection, + }, + .info = { + .nvs_sector_cnt = CONFIG_MESH_SECTOR_COUNT_DEF, + .nvs_write_size = sizeof(int), + .nvs_sector_size = 512, + .nvs_store_baddr = CONFIG_MESH_NVS_ADDR_DEF, + }, +}; + + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_vendor_model_cli.c b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_vendor_model_cli.c new file mode 100644 index 0000000..df92946 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/app_vendor_model_cli.c @@ -0,0 +1,618 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_cli.c +* Author : WCH +* Version : V1.0 +* Date : 2021/03/22 +* Description : +*******************************************************************************/ + + + +/******************************************************************************/ +#include "CONFIG.h" +#include "app_mesh_config.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "app_vendor_model_cli.h" +#include "app_vendor_model_srv.h" + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +// ӦòͳȣְΪCONFIG_MESH_UNSEG_LENGTH_DEFְΪCONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8RAMʹ +#define APP_MAX_TX_SIZE MAX(CONFIG_MESH_UNSEG_LENGTH_DEF,CONFIG_MESH_TX_SEG_DEF*BLE_MESH_APP_SEG_SDU_MAX-8) + +static uint8 vendor_model_cli_TaskID = 0; // Task ID for internal task/event processing +static uint8 cli_send_tid=0; +static s32_t cli_msg_timeout = K_SECONDS(2); //Ӧݴ䳬ʱʱ䣬Ĭ2 + +static struct net_buf cli_trans_buf; +static struct bt_mesh_trans cli_trans = +{ + .buf = &cli_trans_buf, +}; + +static struct net_buf cli_write_buf; +static struct bt_mesh_write cli_write = +{ + .buf = &cli_write_buf, +}; + +static struct bt_mesh_vendor_model_cli *vendor_model_cli; + +static uint16 vendor_model_cli_ProcessEvent( uint8 task_id, uint16 events ); +static void write_reset(struct bt_mesh_write *write, int err); + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + + +/********************************************************************* + * GLOBAL TYPEDEFS + */ + +/******************************************************************************* +* Function Name : vendor_cli_tid_get +* Description : TODO TID selection method +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_cli_tid_get(void) +{ + cli_send_tid++; + if(cli_send_tid > 127) + cli_send_tid = 0; + return cli_send_tid; +} + +/******************************************************************************* +* Function Name : vendor_model_cli_reset +* Description : vendor_model_cli״ִ̬е +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_model_cli_reset(void) +{ + vendor_model_cli->op_pending = 0U; + vendor_model_cli->op_req = 0U; + + tmos_stop_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT); + tmos_stop_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT); +} + +/******************************************************************************* +* Function Name : vendor_model_cli_rsp_recv +* Description : Ӧò㴫Ļص +* Input : val: vendor_model_cli_status_t +* status: status +* Return : None +*******************************************************************************/ +static void vendor_model_cli_rsp_recv(vendor_model_cli_status_t *val, u8_t status) +{ + if (vendor_model_cli == NULL || (!vendor_model_cli->op_req)) + { + return; + } + + val->vendor_model_cli_Hdr.opcode = vendor_model_cli->op_req; + val->vendor_model_cli_Hdr.status = status; + + vendor_model_cli_reset(); + + if (vendor_model_cli->handler) + { + vendor_model_cli->handler(val); + } +} + +/******************************************************************************* +* Function Name : vendor_model_cli_wait +* Description : Ĭ볬ʱ֪ͨӦò +* Input : None +* Return : err: οBLE_LIB err code +*******************************************************************************/ +static int vendor_model_cli_wait(void) +{ + int err; + + err = tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT, cli_msg_timeout); + + return err; +} + +/******************************************************************************* +* Function Name : vendor_model_cli_prepare +* Description : Ԥ +* Input : op_req: ͵ +* op: ķ +* Return : None +*******************************************************************************/ +static int vendor_model_cli_prepare(u32_t op_req, u32_t op) +{ + if (!vendor_model_cli) + { + APP_DBG("No available Configuration Client context!"); + return -EINVAL; + } + + if (vendor_model_cli->op_pending) + { + APP_DBG("Another synchronous operation pending"); + return -EBUSY; + } + + vendor_model_cli->op_req = op_req; + vendor_model_cli->op_pending = op; + + return 0; +} + +/******************************************************************************* +* Function Name : vendor_cli_sync_handler +* Description : ֪ͨӦò㵱ǰop_codeʱ +* Input : None +* Return : None +*******************************************************************************/ +static void vendor_cli_sync_handler( void ) +{ + vendor_model_cli_status_t vendor_model_cli_status; + + tmos_memset(&vendor_model_cli_status, 0, sizeof(vendor_model_cli_status_t)); + + write_reset(&cli_write, -ETIMEDOUT); + + vendor_model_cli_rsp_recv(&vendor_model_cli_status, 0xFF); +} + + +/******************************************************************************* +* Function Name : vendor_message_cli_ack +* Description : vendor_message_cli_ack - ϢVendor Model ClientظVendor Model Server + ڱʾյVendor Model ServerIndication +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_ack(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + u8_t recv_tid; + int err; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("tid 0x%02x ", recv_tid); + + /* Init indication opcode */ + bt_mesh_model_msg_init(&msg, OP_VENDOR_MESSAGE_TRANSPARENT_ACK); + + /* Add tid field */ + net_buf_simple_add_u8(&msg, recv_tid); + + err = bt_mesh_model_send(model, ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("#mesh-onoff STATUS: send status failed: %d", err); + } +} + +/******************************************************************************* +* Function Name : vendor_message_cli_trans +* Description : ͸ +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_trans(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_cli_status_t vendor_model_cli_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + + if( pData[0] != vendor_model_cli->cli_tid.trans_tid ) + { + vendor_model_cli->cli_tid.trans_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_cli_status.vendor_model_cli_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_MSG; + vendor_model_cli_status.vendor_model_cli_Hdr.status = 0; + vendor_model_cli_status.vendor_model_cli_Event.trans.pdata = pData; + vendor_model_cli_status.vendor_model_cli_Event.trans.len = len; + + if (vendor_model_cli->handler) + { + vendor_model_cli->handler(&vendor_model_cli_status); + } + } +} + +/******************************************************************************* +* Function Name : vendor_message_cli_ind +* Description : յVendor Model ServerIndication +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_ind(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + vendor_model_cli_status_t vendor_model_cli_status; + u8_t *pData = buf->data; + u16_t len = buf->len; + APP_DBG("src: 0x%04x dst: 0x%04x rssi: %d app_idx: 0x%x", + ctx->addr, ctx->recv_dst, ctx->recv_rssi, ctx->app_idx); + + if( pData[0] != vendor_model_cli->cli_tid.ind_tid ) + { + vendor_model_cli->cli_tid.ind_tid = pData[0]; + // ͷΪtid + pData++;len--; + vendor_model_cli_status.vendor_model_cli_Hdr.opcode = OP_VENDOR_MESSAGE_TRANSPARENT_IND; + vendor_model_cli_status.vendor_model_cli_Hdr.status = 0; + vendor_model_cli_status.vendor_model_cli_Event.ind.pdata = pData; + vendor_model_cli_status.vendor_model_cli_Event.ind.len = len; + + if (vendor_model_cli->handler) + { + vendor_model_cli->handler(&vendor_model_cli_status); + } + } + vendor_message_cli_ack(model, ctx, buf); +} + +/******************************************************************************* +* Function Name : vendor_message_cli_cfm +* Description : յ vendor_message_cli_cfm - ϢVendor Model ServerظVendor Model Client + ڱʾյVendor Model Client Write +* Input : model: ģͲ +* ctxݲ +* buf: +* Return : None +*******************************************************************************/ +static void vendor_message_cli_cfm(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) +{ + u8_t recv_tid; + vendor_model_cli_status_t vendor_model_cli_status; + + recv_tid = net_buf_simple_pull_u8(buf); + + APP_DBG("src: 0x%04x dst: 0x%04x tid 0x%02x rssi: %d", + ctx->addr, ctx->recv_dst, recv_tid, ctx->recv_rssi); + + if (cli_write.param.tid == recv_tid) + { + write_reset(&cli_write, 0); + vendor_model_cli_rsp_recv(&vendor_model_cli_status, 0); + } +} + + +// opcode ӦĴ +const struct bt_mesh_model_op vnd_model_cli_op[] = { + {OP_VENDOR_MESSAGE_TRANSPARENT_MSG, 0, vendor_message_cli_trans}, + {OP_VENDOR_MESSAGE_TRANSPARENT_IND, 0, vendor_message_cli_ind}, + {OP_VENDOR_MESSAGE_TRANSPARENT_CFM, 0, vendor_message_cli_cfm}, + BLE_MESH_MODEL_OP_END, +}; + +/******************************************************************************* +* Function Name : vendor_message_cli_send_trans +* Description : send_trans ,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_send_trans(struct send_param *param, u8_t *pData, u16_t len) +{ + if(!param->addr) + return -EINVAL; + if( cli_trans.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + cli_trans.buf->__buf = tmos_msg_allocate(len+8); + if( !(cli_trans.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + cli_trans.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(cli_trans.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_MSG); + + /* Add tid field */ + net_buf_simple_add_u8(&(cli_trans.buf->b), param->tid); + + net_buf_simple_add_mem(&(cli_trans.buf->b), pData, len); + + memcpy(&cli_trans.param, param, sizeof(struct send_param)); + + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_TRANS_EVT, param->rand); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_message_cli_write +* Description : write ,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_write(struct send_param *param, u8_t *pData, u16_t len) +{ + if( !param->addr) + return -EINVAL; + if( cli_write.buf->__buf ) + return -EBUSY; + if( len > (APP_MAX_TX_SIZE)) + return -EINVAL; + + cli_write.buf->__buf = tmos_msg_allocate(len+8); + if( !(cli_write.buf->__buf) ) + { + APP_DBG("No enough space!"); + return -ENOMEM; + } + cli_write.buf->size = len+4; + /* Init indication opcode */ + bt_mesh_model_msg_init(&(cli_write.buf->b), OP_VENDOR_MESSAGE_TRANSPARENT_WRT); + + /* Add tid field */ + net_buf_simple_add_u8(&(cli_write.buf->b), param->tid); + + net_buf_simple_add_mem(&(cli_write.buf->b), pData, len); + + memcpy(&cli_write.param, param, sizeof(struct send_param)); + + vendor_model_cli_prepare(OP_VENDOR_MESSAGE_TRANSPARENT_WRT, OP_VENDOR_MESSAGE_TRANSPARENT_CFM); + + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT, param->rand); + + vendor_model_cli_wait(); + return 0; +} + +/******************************************************************************* +* Function Name : adv_cli_trans_send +* Description : ͸ cli_trans +* Input : None +* Return : None +*******************************************************************************/ +static void adv_cli_trans_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = cli_trans.param.app_idx ? cli_trans.param.app_idx : vendor_model_cli->model->keys[0], + .addr = cli_trans.param.addr, + }; + + if (cli_trans.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (cli_trans.param.trans_cnt == 0) + { +// APP_DBG("cli_trans.buf.trans_cnt over"); + tmos_msg_deallocate(cli_trans.buf->__buf); + cli_trans.buf->__buf = NULL; + return; + } + + cli_trans.param.trans_cnt --; + + ctx.send_ttl = cli_trans.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, cli_trans.buf->data, cli_trans.buf->len); + + err = bt_mesh_model_send(vendor_model_cli->model, &ctx, &msg, NULL, NULL); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + tmos_msg_deallocate(cli_trans.buf->__buf); + cli_trans.buf->__buf = NULL; + return; + } + // ش + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_TRANS_EVT, cli_trans.param.period); +} + +/******************************************************************************* +* Function Name : vendor_message_cli_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_cli_trans_reset( void ) +{ + tmos_msg_deallocate(cli_trans.buf->__buf); + cli_trans.buf->__buf = NULL; + tmos_stop_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_TRANS_EVT); +} + +/******************************************************************************* +* Function Name : write_reset +* Description : ӦòwriteɻصͷŻ +* Input : write: +* err: οGlobal_Error_Code +* Return : None +*******************************************************************************/ +static void write_reset(struct bt_mesh_write *write, int err) +{ + if (write->param.cb && write->param.cb->end) + { + write->param.cb->end(err, write->param.cb_data); + } + + tmos_msg_deallocate(write->buf->__buf); + write->buf->__buf = NULL; +} + +/******************************************************************************* +* Function Name : write_start +* Description : write ʼص +* Input : duration: ˷¼¼λ0.625ms +* err: οGlobal_Error_Code +* cb_data: ص +* Return : None +*******************************************************************************/ +static void write_start(u16_t duration, int err, void *cb_data) +{ + struct bt_mesh_write *write = cb_data; + + if (write->buf->__buf == NULL) + { + return; + } + + if (err) + { + APP_DBG("Unable send indicate (err:%d)", err); + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT, K_MSEC(100)); + return; + } +} + +/******************************************************************************* +* Function Name : write_end +* Description : write ص +* Input : err: οGlobal_Error_Code +* cb_data: ص +* Return : None +*******************************************************************************/ +static void write_end(int err, void *cb_data) +{ + struct bt_mesh_write *write = cb_data; + APP_DBG("write_end (err:%d)", err); + + if (write->buf->__buf == NULL) + { + return; + } + + tmos_start_task(vendor_model_cli_TaskID, VENDOR_MODEL_CLI_WRITE_EVT, write->param.period); +} + +// indicate صṹ +const struct bt_mesh_send_cb write_cb = +{ + .start = write_start, + .end = write_end, +}; + +/******************************************************************************* +* Function Name : adv_cli_write_send +* Description : Ӧ cli_write +* Input : None +* Return : None +*******************************************************************************/ +static void adv_cli_write_send( void ) +{ + int err; + NET_BUF_SIMPLE_DEFINE(msg, APP_MAX_TX_SIZE+8); + + struct bt_mesh_msg_ctx ctx = { + .app_idx = cli_write.param.app_idx ? cli_write.param.app_idx : vendor_model_cli->model->keys[0], + .addr = cli_write.param.addr, + }; + + if (cli_write.buf->__buf == NULL) + { + APP_DBG("NULL buf"); + return; + } + + if (cli_write.param.trans_cnt == 0) + { +// APP_DBG("cli_write.buf.trans_cnt over"); + write_reset(&cli_write, -ETIMEDOUT); + return; + } + + cli_write.param.trans_cnt --; + + ctx.send_ttl = cli_write.param.send_ttl; + + /** TODO */ + net_buf_simple_add_mem(&msg, cli_write.buf->data, cli_write.buf->len); + + err = bt_mesh_model_send(vendor_model_cli->model, &ctx, &msg, &write_cb, &cli_write); + if (err) + { + APP_DBG("Unable send model message (err:%d)", err); + + write_reset(&cli_write, err); + return; + } +} + + +/******************************************************************************* +* Function Name : vendor_model_cli_init +* Description : vendor_model_cli ʼ +* Input : model; +* Return : SUCCESS +*******************************************************************************/ +static int vendor_model_cli_init(struct bt_mesh_model *model) +{ + vendor_model_cli = model->user_data; + vendor_model_cli->model = model; + + vendor_model_cli_TaskID = TMOS_ProcessEventRegister( vendor_model_cli_ProcessEvent ); + return 0; +} + +/******************************************************************************* +* Function Name : vendor_model_cli_ProcessEvent +* Description : vendor_model_cli +* Input : task_id, events +* Return : events +*******************************************************************************/ +static uint16 vendor_model_cli_ProcessEvent( uint8 task_id, uint16 events ) +{ + + if ( events & VENDOR_MODEL_CLI_TRANS_EVT ) + { + adv_cli_trans_send(); + return ( events ^ VENDOR_MODEL_CLI_TRANS_EVT ); + } + if ( events & VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT ) + { + vendor_cli_sync_handler(); + return ( events ^ VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT ); + } + if ( events & VENDOR_MODEL_CLI_WRITE_EVT ) + { + adv_cli_write_send(); + return ( events ^ VENDOR_MODEL_CLI_WRITE_EVT ); + } + // Discard unknown events + return 0; +} + + +const struct bt_mesh_model_cb bt_mesh_vendor_model_cli_cb = { + .init = vendor_model_cli_init, +}; + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app.h b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app.h new file mode 100644 index 0000000..afc2952 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app.h @@ -0,0 +1,90 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_H +#define app_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/******************************************************************************/ + +#define APP_NODE_EVT (1<<0) +#define APP_NODE_TEST_EVT (1<<1) + +/******************************************************************************/ +// Զ˽ڵ +typedef enum +{ + NODE_INIT = 0, + NODE_APPKEY_ADD = 1, + NODE_MOD_BIND_SET = 2, + NODE_MOD_SUB_SET = 3, + + NODE_CONFIGURATIONED = 4, +} node_stage_t; + +// ؽڵ +typedef enum +{ + LOCAL_INIT = 0, + LOCAL_APPKEY_ADD = 1, + LOCAL_MOD_BIND_SET = 2, + + LOCAL_CONFIGURATIONED = 4, +} local_stage_t; + +typedef union +{ + node_stage_t node; + local_stage_t local; +}stage_t; + +typedef void (*cfg_rsp_handler_t)(void *node, const void *rsp); +typedef BOOL (*stage_handler_t)(void *node); + +typedef struct +{ + cfg_rsp_handler_t rsp; + stage_handler_t stage; +}cfg_cb_t; + +typedef struct +{ + u16_t node_addr; + u16_t elem_count; + u16_t net_idx; + u16_t retry_cnt:12, + fixed:1, + blocked:1; + + stage_t stage; + const cfg_cb_t *cb; +}node_t; + +extern node_t app_nodes[ 1 + CONFIG_MESH_PROV_NODE_COUNT_DEF ]; +extern const u16_t self_prov_net_idx; +extern const u16_t self_prov_app_idx; +extern const u32_t self_prov_iv_index; +extern const u16_t self_prov_addr; + + +void App_Init(void); + +/******************************************************************************/ + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_mesh_config.h b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_mesh_config.h new file mode 100644 index 0000000..30deebb --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_mesh_config.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_mesh_config.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/24 +* Description : +*******************************************************************************/ + +#ifndef APP_MESH_CONFIG_H +#define APP_MESH_CONFIG_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/**************************,ֱӲοͬ*****************************/ + +// relay +#define CONFIG_BLE_MESH_RELAY 1 +// +#define CONFIG_BLE_MESH_PROXY 0 +// GATT +#define CONFIG_BLE_MESH_PB_GATT 0 +// FLASH洢 +#define CONFIG_BLE_MESH_SETTINGS 1 +// ѽڵ㹦 +#define CONFIG_BLE_MESH_FRIEND 0 +// ͹Ľڵ㹦 +#define CONFIG_BLE_MESH_LOW_POWER 0 +// configģͿͻ˹ +#define CONFIG_BLE_MESH_CFG_CLI 1 +// healthģͿͻ˹ +#define CONFIG_BLE_MESH_HLTH_CLI 1 + + +/******************************************************************************/ + +// Netݻ +#define CONFIG_MESH_ADV_BUF_COUNT_MIN (6) +#define CONFIG_MESH_ADV_BUF_COUNT_DEF (10) +#define CONFIG_MESH_ADV_BUF_COUNT_MAX (40) + +// RPLݻ +#define CONFIG_MESH_RPL_COUNT_MIN (6) +#define CONFIG_MESH_RPL_COUNT_DEF (6) +#define CONFIG_MESH_RPL_COUNT_MAX (20) + +// IV Update State Timer 96HķƵϵ +#define CONFIG_MESH_IVU_DIVIDER_MIN (1) +#define CONFIG_MESH_IVU_DIVIDER_DEF (96) +#define CONFIG_MESH_IVU_DIVIDER_MAX (96) + +// ڰܴ洢 +#define CONFIG_MESH_PROXY_FILTER_MIN (2) +#define CONFIG_MESH_PROXY_FILTER_DEF (5) +#define CONFIG_MESH_PROXY_FILTER_MAX (20) + +// Ϣ +#define CONFIG_MESH_MSG_CACHE_MIN (3) +#define CONFIG_MESH_MSG_CACHE_DEF (20) +#define CONFIG_MESH_MSG_CACHE_MAX (20) + +// +#define CONFIG_MESH_SUBNET_COUNT_MIN (1) +#define CONFIG_MESH_SUBNET_COUNT_DEF (1) +#define CONFIG_MESH_SUBNET_COUNT_MAX (4) + +// APP key +#define CONFIG_MESH_APPKEY_COUNT_MIN (1) +#define CONFIG_MESH_APPKEY_COUNT_DEF (3) +#define CONFIG_MESH_APPKEY_COUNT_MAX (5) + +// ǷһдַͬĽڵ㣨ʹְܺܲã +#define CONFIG_MESH_ALLOW_SAME_ADDR (FALSE) + +// ְϢֵ֧ijȣ˳Ҫְ޸Ĵֵmesh׼ +#define CONFIG_MESH_UNSEG_LENGTH_MIN (7) +#define CONFIG_MESH_UNSEG_LENGTH_DEF (7) +#define CONFIG_MESH_UNSEG_LENGTH_MAX (221) + +// ÿϢְ +#define CONFIG_MESH_TX_SEG_MIN (2) +#define CONFIG_MESH_TX_SEG_DEF (8) +#define CONFIG_MESH_TX_SEG_MAX (32) + +// ͬʱڵķְϢ͸ +#define CONFIG_MESH_TX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_TX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_TX_SEG_COUNT_MAX (4) + +// ͬʱڵķְϢո +#define CONFIG_MESH_RX_SEG_COUNT_MIN (1) +#define CONFIG_MESH_RX_SEG_COUNT_DEF (2) +#define CONFIG_MESH_RX_SEG_COUNT_MAX (4) + +// ÿյķְϢֽ +#define CONFIG_MESH_RX_SDU_MIN (12) +#define CONFIG_MESH_RX_SDU_DEF (192) +#define CONFIG_MESH_RX_SDU_MAX (384) + +// ַ +#define CONFIG_MESH_LABEL_COUNT_MIN (1) +#define CONFIG_MESH_LABEL_COUNT_DEF (2) +#define CONFIG_MESH_LABEL_COUNT_MAX (4) + +// NVS洢ʹ +#define CONFIG_MESH_SECTOR_COUNT_MIN (2) +#define CONFIG_MESH_SECTOR_COUNT_DEF (3) + +// NVS洢׵ַ +#define CONFIG_MESH_NVS_ADDR_DEF (0x3E800) + +// RPLº洢ijʱʱ(s) +#define CONFIG_MESH_RPL_STORE_RATE_MIN (5) +#define CONFIG_MESH_RPL_STORE_RATE_DEF (60) +#define CONFIG_MESH_RPL_STORE_RATE_MAX (3600) + +// SEQº洢ijʱʱ(s) +#define CONFIG_MESH_SEQ_STORE_RATE_MIN (5) +#define CONFIG_MESH_SEQ_STORE_RATE_DEF (60) +#define CONFIG_MESH_SEQ_STORE_RATE_MAX (3600) + +// Ϣº洢ijʱʱ(s) +#define CONFIG_MESH_STORE_RATE_MIN (2) +#define CONFIG_MESH_STORE_RATE_DEF (2) +#define CONFIG_MESH_STORE_RATE_MAX (5) + +// ѽڵֵ֧ÿϢķְ +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_DEF (2) +#define CONFIG_MESH_FRIEND_SEG_RX_COUNT_MAX (4) + +// ѽڵֵ֧Ķĸ +#define CONFIG_MESH_FRIEND_SUB_SIZE_MIN (1) +#define CONFIG_MESH_FRIEND_SUB_SIZE_DEF (4) +#define CONFIG_MESH_FRIEND_SUB_SIZE_MAX (8) + +// ѽڵֵ֧ĵ͹Ľڵ +#define CONFIG_MESH_FRIEND_LPN_COUNT_MIN (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_DEF (1) +#define CONFIG_MESH_FRIEND_LPN_COUNT_MAX (4) + +// ѽڵ洢ϢдС +#define CONFIG_MESH_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_QUEUE_SIZE_DEF (4) +#define CONFIG_MESH_QUEUE_SIZE_MAX (30) + +// ѽڵմڴС(ms) +#define CONFIG_MESH_FRIEND_RECV_WIN_MIN (1) +#define CONFIG_MESH_FRIEND_RECV_WIN_DEF (20) +#define CONFIG_MESH_FRIEND_RECV_WIN_MAX (255) + +// ͹ĽڵϢдС +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MIN (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_DEF (2) +#define CONFIG_MESH_LPN_REQ_QUEUE_SIZE_MAX (20) + +// ͹ĽڵϢʱʱ(10ms) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MIN (30) +#define CONFIG_MESH_LPN_POLLTIMEOUT_DEF (40) +#define CONFIG_MESH_LPN_POLLTIMEOUT_MAX (400) + +// ͹Ľڵֵ֧Ľӳ(ms) +#define CONFIG_MESH_LPN_RECV_DELAY_MIN (100) +#define CONFIG_MESH_LPN_RECV_DELAY_DEF (100) +#define CONFIG_MESH_LPN_RECV_DELAY_MAX (400) + +// ѹϵؽȴʱ(s) +#define CONFIG_MESH_RETRY_TIMEOUT_MIN (3) +#define CONFIG_MESH_RETRY_TIMEOUT_DEF (10) +#define CONFIG_MESH_RETRY_TIMEOUT_MAX (60) + +// ֵ֧豸ڵ +#define CONFIG_MESH_PROV_NODE_COUNT_MIN (1) +#define CONFIG_MESH_PROV_NODE_COUNT_DEF (6) + +// ADV_RF +#define CONFIG_MESH_RF_ACCESSADDRESS (0x8E89BED6) +#define CONFIG_MESH_RF_CHANNEL_37 (37) +#define CONFIG_MESH_RF_CHANNEL_38 (38) +#define CONFIG_MESH_RF_CHANNEL_39 (39) + +#define APP_DBG(X...) \ + if (1) \ + { \ + printf("APP_DBG %s> ", __FUNCTION__); \ + printf(X); \ + printf("\n"); \ + } \ + + +/******************************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_vendor_model_cli.h b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_vendor_model_cli.h new file mode 100644 index 0000000..ca0dc42 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_vendor_model_cli.h @@ -0,0 +1,128 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_generic_onoff_model_cli.h +* Author : WCH +* Version : V1.0 +* Date : 2018/11/12 +* Description : +*******************************************************************************/ + +#ifndef app_generic_onoff_model_cli_H +#define app_generic_onoff_model_cli_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "app_vendor_model_srv.h" + +#define CID_WCH 0x07D7 + +#define OP_VENDOR_MESSAGE_TRANSPARENT_CFM BLE_MESH_MODEL_OP_3(0xCB, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_WRT BLE_MESH_MODEL_OP_3(0xCC, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_ACK BLE_MESH_MODEL_OP_3(0xCD, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_IND BLE_MESH_MODEL_OP_3(0xCE, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_WCH) + +#define BLE_MESH_MODEL_ID_WCH_SRV 0x0000 +#define BLE_MESH_MODEL_ID_WCH_CLI 0x0001 + +#define VENDOR_MODEL_CLI_TRANS_EVT (1<<0) +#define VENDOR_MODEL_CLI_RSP_TIMEOUT_EVT (1<<1) +#define VENDOR_MODEL_CLI_WRITE_EVT (1<<2) + +struct bt_mesh_vendor_model_ind +{ + u8_t *pdata; + u16_t len; +}; + +struct bt_mesh_vendor_model_cli_trans +{ + u8_t *pdata; + u16_t len; +}; + +struct vendor_model_cli_EventHdr +{ + u8_t status; + u32_t opcode; +}; + +union vendor_model_cli_Event_t +{ + struct bt_mesh_vendor_model_cli_trans trans; + struct bt_mesh_vendor_model_ind ind; +}; + +typedef struct +{ + struct vendor_model_cli_EventHdr vendor_model_cli_Hdr; + union vendor_model_cli_Event_t vendor_model_cli_Event; +}vendor_model_cli_status_t; + + +typedef void (*vendor_model_cli_rsp_handler_t)(const vendor_model_cli_status_t *val); + +struct vendor_model_cli_tid +{ + u8_t trans_tid; + u8_t ind_tid; +}; + +/** Mesh vendor_model_cli Model Context */ +struct bt_mesh_vendor_model_cli { + struct bt_mesh_model *model; + u32_t op_req; + u32_t op_pending; + struct vendor_model_cli_tid cli_tid; + + vendor_model_cli_rsp_handler_t handler; + +}; + +extern const struct bt_mesh_model_op vnd_model_cli_op[]; +extern const struct bt_mesh_model_cb bt_mesh_vendor_model_cli_cb; + +/******************************************************************************* +* Function Name : vendor_message_cli_send_trans +* Description : send_trans ,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_send_trans(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_message_cli_write +* Description : write ,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_cli_write(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_cli_tid_get +* Description : TODO TID selection method ÿϢѭcliʹ0~127 +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_cli_tid_get(void); + +/******************************************************************************* +* Function Name : vendor_message_cli_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_cli_trans_reset( void ); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_vendor_model_srv.h b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_vendor_model_srv.h new file mode 100644 index 0000000..83b8329 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/app_vendor_model_srv.h @@ -0,0 +1,199 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : app_vendor_model_srv.h +* Author : WCH +* Version : V1.0 +* Date : 2021/03/23 +* Description : +*******************************************************************************/ + +#ifndef app_vendor_model_srv_H +#define app_vendor_model_srv_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "MESH_LIB.h" + +#define MSG_PIN GPIO_Pin_12 + +#define CID_WCH 0x07D7 + +#define OP_VENDOR_MESSAGE_TRANSPARENT_CFM BLE_MESH_MODEL_OP_3(0xCB, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_WRT BLE_MESH_MODEL_OP_3(0xCC, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_ACK BLE_MESH_MODEL_OP_3(0xCD, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_IND BLE_MESH_MODEL_OP_3(0xCE, CID_WCH) +#define OP_VENDOR_MESSAGE_TRANSPARENT_MSG BLE_MESH_MODEL_OP_3(0xCF, CID_WCH) + +#define BLE_MESH_MODEL_ID_WCH_SRV 0x0000 +#define BLE_MESH_MODEL_ID_WCH_CLI 0x0001 + +#define VENDOR_MODEL_SRV_TRANS_EVT (1<<0) +#define VENDOR_MODEL_SRV_RSP_TIMEOUT_EVT (1<<1) +#define VENDOR_MODEL_SRV_INDICATE_EVT (1<<2) + +struct bt_adv_trans_cb +{ + void (*start)(int err, void *cb_data); + void (*end)(int err, void *cb_data); +}; + + +struct send_param +{ + u16_t net_idx; + u16_t app_idx; + u16_t addr; + u8_t tid; + u8_t trans_cnt; + s32_t period; + s32_t rand; + u8_t send_ttl; + + void *cb_data; + const struct bt_adv_trans_cb *cb; +}; + +struct bt_mesh_indicate +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_trans +{ + struct send_param param; + struct net_buf *buf; +}; + +struct bt_mesh_write +{ + struct send_param param; + struct net_buf *buf; +}; + + +struct bt_mesh_vendor_model_write +{ + u8_t *pdata; + u16_t len; +}; + +struct bt_mesh_vendor_model_srv_trans +{ + u8_t *pdata; + u16_t len; +}; + +struct vendor_model_srv_EventHdr +{ + u8_t status; + u32_t opcode; +}; + +union vendor_model_srv_Event_t +{ + struct bt_mesh_vendor_model_srv_trans trans; + struct bt_mesh_vendor_model_write write; +}; + +typedef struct +{ + struct vendor_model_srv_EventHdr vendor_model_srv_Hdr; + union vendor_model_srv_Event_t vendor_model_srv_Event; +}vendor_model_srv_status_t; + + +typedef void (*vendor_model_srv_rsp_handler_t)(const vendor_model_srv_status_t *val); + +struct vendor_model_srv_tid +{ + u8_t trans_tid; + u8_t write_tid; +}; + +/** Mesh vendor_model_srv Model Context */ +struct bt_mesh_vendor_model_srv { + struct bt_mesh_model *model; + u32_t op_req; + u32_t op_pending; + struct vendor_model_srv_tid srv_tid; + + vendor_model_srv_rsp_handler_t handler; + +}; + + + +extern const struct bt_mesh_model_cb bt_mesh_vendor_model_srv_cb; + +extern const struct bt_mesh_model_op vnd_model_srv_op[]; + + +/******************************************************************************* +* Function Name : read_led_state +* Description : read_led_state +* Input : None +* Return : None +*******************************************************************************/ +BOOL read_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : set_led_state +* Description : set_led_state +* Input : None +* Return : None +*******************************************************************************/ +void set_led_state(u32_t led_pin, BOOL on); + +/******************************************************************************* +* Function Name : toggle_led_state +* Description : toggle_led_state +* Input : None +* Return : None +*******************************************************************************/ +void toggle_led_state(u32_t led_pin); + +/******************************************************************************* +* Function Name : vendor_message_srv_indicate +* Description : indicate,Ӧͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_indicate(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_message_srv_send_trans +* Description : send_trans,͸ͨ +* Input : param: Ͳ +* pData: ָ +* len: ݳ,Ϊ(APP_MAX_TX_SIZE) +* Return : οGlobal_Error_Code +*******************************************************************************/ +int vendor_message_srv_send_trans(struct send_param *param, u8_t *pData, u16_t len); + +/******************************************************************************* +* Function Name : vendor_srv_tid_get +* Description : TODO TID selection method ÿϢѭsrvʹ128~191 +* Input : None +* Return : None +*******************************************************************************/ +u8_t vendor_srv_tid_get(void); + +/******************************************************************************* +* Function Name : vendor_message_srv_trans_reset +* Description : ȡtransݵͷŻ +* Input : None +* Return : None +*******************************************************************************/ +void vendor_message_srv_trans_reset( void ); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/peripheral.h b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/peripheral.h new file mode 100644 index 0000000..c139535 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/include/peripheral.h @@ -0,0 +1,66 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef PERIPHERAL_H +#define PERIPHERAL_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// Peripheral Task Events +#define SBP_START_DEVICE_EVT 0x0001 +#define SBP_PERIODIC_EVT 0x0002 +#define SBP_READ_RSSI_EVT 0x0004 +#define SBP_PARAM_UPDATE_EVT 0x0008 + +/********************************************************************* + * MACROS + */ +typedef struct +{ + uint16 connHandle; // Connection handle of current connection + uint16 connInterval; + uint16 connSlaveLatency; + uint16 connTimeout; +} peripheralConnItem_t; + + +/********************************************************************* + * FUNCTIONS + */ + +/* + * Task Initialization for the BLE Application + */ +extern void Peripheral_Init( void ); + +/* + * Task Event Processor for the BLE Application + */ +extern uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ); +extern void peripheralChar4Notify( uint8 *pValue, uint16 len ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/peripheral.c b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/peripheral.c new file mode 100644 index 0000000..cd2ef57 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/APP/peripheral.c @@ -0,0 +1,692 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ӻӦó򣬳ʼ㲥ӲȻ㲥 +* ӲͨԶ +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "MESH_LIB.h" +#include "CH57x_common.h" +#include "gattprofile.h" +#include "peripheral.h" +#include "app.h" +#include "app_vendor_model_srv.h" +#include "app_vendor_model_cli.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// How often to perform periodic event +#define SBP_PERIODIC_EVT_PERIOD 1600 + +// How often to perform read rssi event +#define SBP_READ_RSSI_EVT_PERIOD 3200 + +// Parameter update delay +#define SBP_PARAM_UPDATE_DELAY 6400 + +// What is the advertising interval when device is discoverable (units of 625us, 80=50ms) +#define DEFAULT_ADVERTISING_INTERVAL 80 + +// Limited discoverable mode advertises for 30.72s, and then stops +// General discoverable mode advertises indefinitely +#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL + +// Minimum connection interval (units of 1.25ms, 20=25ms) +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 20 + +// Maximum connection interval (units of 1.25ms, 100=125ms) +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 100 + +// Slave latency to use parameter update +#define DEFAULT_DESIRED_SLAVE_LATENCY 0 + +// Supervision timeout value (units of 10ms, 100=1s) +#define DEFAULT_DESIRED_CONN_TIMEOUT 100 + +// Company Identifier: WCH +#define WCH_COMPANY_ID 0x07D7 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ +static uint8 Peripheral_TaskID = INVALID_TASK_ID; // Task ID for internal task/event processing + +// GAP - SCAN RSP data (max size = 31 bytes) +static uint8 scanRspData[ ] = +{ + // complete name + 0x12, // length of this data + GAP_ADTYPE_LOCAL_NAME_COMPLETE, + 'S', + 'i', + 'm', + 'p', + 'l', + 'e', + ' ', + 'P', + 'e', + 'r', + 'i', + 'p', + 'h', + 'e', + 'r', + 'a', + 'l', + // connection interval range + 0x05, // length of this data + GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE, + LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), // 100ms + HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), + LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), // 1s + HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), + + // Tx power level + 0x02, // length of this data + GAP_ADTYPE_POWER_LEVEL, + 0 // 0dBm +}; + +// GAP - Advertisement data (max size = 31 bytes, though this is +// best kept short to conserve power while advertising) +static uint8 advertData[] = +{ + // Flags; this sets the device to use limited discoverable + // mode (advertises for 30 seconds at a time) instead of general + // discoverable mode (advertises indefinitely) + 0x02, // length of this data + GAP_ADTYPE_FLAGS, + DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED, + + // service UUID, to notify central devices what services are included + // in this peripheral + 0x03, // length of this data + GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all + LO_UINT16( SIMPLEPROFILE_SERV_UUID ), + HI_UINT16( SIMPLEPROFILE_SERV_UUID ) +}; + +// GAP GATT Attributes +static uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "Simple Peripheral"; + +// Connection item list +static peripheralConnItem_t peripheralConnList; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ); +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent); +static void performPeriodicTask( void ); +static void simpleProfileChangeCB( uint8 paramID, uint8 *pValue, uint16 len ); +static void peripheralParamUpdateCB( uint16 connHandle, uint16 connInterval, + uint16 connSlaveLatency, uint16 connTimeout ); +static void peripheralInitConnItem( peripheralConnItem_t* peripheralConnList ); +static void peripheralRssiCB( uint16 connHandle, int8 rssi ); + +/********************************************************************* + * PROFILE CALLBACKS + */ + +// GAP Role Callbacks +static gapRolesCBs_t Peripheral_PeripheralCBs = +{ + peripheralStateNotificationCB, // Profile State Change Callbacks + peripheralRssiCB, // When a valid RSSI is read from controller (not used by application) + peripheralParamUpdateCB +}; + +// Broadcast Callbacks +static gapRolesBroadcasterCBs_t Broadcaster_BroadcasterCBs = +{ + NULL, // Not used in peripheral role + NULL // Receive scan request callback +}; + +// GAP Bond Manager Callbacks +static gapBondCBs_t Peripheral_BondMgrCBs = +{ + NULL, // Passcode callback (not used by application) + NULL // Pairing / Bonding state Callback (not used by application) +}; + +// Simple GATT Profile Callbacks +static simpleProfileCBs_t Peripheral_SimpleProfileCBs = +{ + simpleProfileChangeCB // Characteristic value change callback +}; +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn Peripheral_Init + * + * @brief Initialization function for the 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 TMOS. This ID should be + * used to send messages and set timers. + * + * @return none + */ +void Peripheral_Init( ) +{ + + Peripheral_TaskID = TMOS_ProcessEventRegister( Peripheral_ProcessEvent ); + + // Setup the GAP Peripheral Role Profile + { + uint8 initial_advertising_enable = TRUE; + uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL; + uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); + GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); + GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval ); + GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval ); + } + + // Set the GAP Characteristics + GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); + + // Set advertising interval + { + uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; + + GAP_SetParamValue( TGAP_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_DISC_ADV_INT_MAX, advInt ); + } + + // Setup the GAP Bond Manager + { + uint32 passkey = 0; // passkey "000000" + uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; + uint8 mitm = TRUE; + uint8 bonding = TRUE; + uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; + GAPBondMgr_SetParameter( GAPBOND_PERI_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); + GAPBondMgr_SetParameter( GAPBOND_PERI_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); + GAPBondMgr_SetParameter( GAPBOND_PERI_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); + GAPBondMgr_SetParameter( GAPBOND_PERI_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); + GAPBondMgr_SetParameter( GAPBOND_PERI_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); + } + + // Initialize GATT attributes + GGS_AddService( GATT_ALL_SERVICES ); // GAP + GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes + SimpleProfile_AddService( GATT_ALL_SERVICES ); // Simple GATT Profile + + // Setup the SimpleProfile Characteristic Values + { + uint8 charValue1[SIMPLEPROFILE_CHAR1_LEN] = { 1 }; + uint8 charValue2[SIMPLEPROFILE_CHAR2_LEN] = { 2 }; + uint8 charValue3[SIMPLEPROFILE_CHAR3_LEN] = { 3 }; + uint8 charValue4[SIMPLEPROFILE_CHAR4_LEN] = { 4 }; + uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 }; + + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, SIMPLEPROFILE_CHAR1_LEN, charValue1 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, SIMPLEPROFILE_CHAR2_LEN, charValue2 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, SIMPLEPROFILE_CHAR3_LEN, charValue3 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, charValue4 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); + } + + // Init Connection Item + peripheralInitConnItem( &peripheralConnList ); + + // Register callback with SimpleGATTprofile + SimpleProfile_RegisterAppCBs( &Peripheral_SimpleProfileCBs ); + + // Register receive scan request callback + GAPRole_BroadcasterSetCB( &Broadcaster_BroadcasterCBs ); + + // Setup a delayed profile startup + tmos_set_event( Peripheral_TaskID, SBP_START_DEVICE_EVT ); +} + +/********************************************************************* + * @fn peripheralInitConnItem + * + * @brief Init Connection Item + * + * @param peripheralConnList - + * + * @return NULL + */ +static void peripheralInitConnItem( peripheralConnItem_t* peripheralConnList ) +{ + peripheralConnList->connHandle = GAP_CONNHANDLE_INIT; + peripheralConnList->connInterval = 0; + peripheralConnList->connSlaveLatency = 0; + peripheralConnList->connTimeout = 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessEvent + * + * @brief 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 TMOS assigned task ID. + * @param events - events to process. This is a bit map and can + * contain more than one event. + * + * @return events not processed + */ +uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ) +{ + +// VOID task_id; // TMOS required parameter that isn't used in this function + + if ( events & SYS_EVENT_MSG ){ + uint8 *pMsg; + + if ( (pMsg = tmos_msg_receive( Peripheral_TaskID )) != NULL ){ + Peripheral_ProcessTMOSMsg( (tmos_event_hdr_t *)pMsg ); + // Release the TMOS message + tmos_msg_deallocate( pMsg ); + } + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } + + if ( events & SBP_START_DEVICE_EVT ){ + // Start the Device + GAPRole_PeripheralStartDevice( Peripheral_TaskID, &Peripheral_BondMgrCBs, &Peripheral_PeripheralCBs ); + return ( events ^ SBP_START_DEVICE_EVT ); + } + + if ( events & SBP_PERIODIC_EVT ) + { + // Restart timer + if ( SBP_PERIODIC_EVT_PERIOD ){ + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + } + // Perform periodic application task + performPeriodicTask(); + return (events ^ SBP_PERIODIC_EVT); + } + + if ( events & SBP_PARAM_UPDATE_EVT ) + { + // Send connect param update request + GAPRole_PeripheralConnParamUpdateReq( peripheralConnList.connHandle, + DEFAULT_DESIRED_MIN_CONN_INTERVAL, + DEFAULT_DESIRED_MAX_CONN_INTERVAL, + DEFAULT_DESIRED_SLAVE_LATENCY, + DEFAULT_DESIRED_CONN_TIMEOUT, + Peripheral_TaskID); + + return (events ^ SBP_PARAM_UPDATE_EVT); + } + + if ( events & SBP_READ_RSSI_EVT ) + { + GAPRole_ReadRssiCmd(peripheralConnList.connHandle); + tmos_start_task( Peripheral_TaskID, SBP_READ_RSSI_EVT, SBP_READ_RSSI_EVT_PERIOD ); + return (events ^ SBP_READ_RSSI_EVT); + } + + // Discard unknown events + return 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessTMOSMsg + * + * @brief Process an incoming task message. + * + * @param pMsg - message to process + * + * @return none + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ) +{ + switch ( pMsg->event ){ + default: + break; + } +} + +/********************************************************************* + * @fn Peripheral_LinkEstablished + * + * @brief Process link established. + * + * @param pEvent - event to process + * + * @return none + */ +static void Peripheral_LinkEstablished( gapRoleEvent_t * pEvent ) +{ + gapEstLinkReqEvent_t *event = (gapEstLinkReqEvent_t *) pEvent; + + // See if already connected + if( peripheralConnList.connHandle != GAP_CONNHANDLE_INIT ) + { + GAPRole_TerminateLink( pEvent->linkCmpl.connectionHandle ); + PRINT( "Connection max...\n" ); + } + else + { + peripheralConnList.connHandle = event->connectionHandle; + peripheralConnList.connInterval = event->connInterval; + peripheralConnList.connSlaveLatency = event->connLatency; + peripheralConnList.connTimeout = event->connTimeout; + + // Set timer for periodic event +// tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + + // Set timer for param update event + tmos_start_task( Peripheral_TaskID, SBP_PARAM_UPDATE_EVT, SBP_PARAM_UPDATE_DELAY ); + + // Start read rssi + tmos_start_task( Peripheral_TaskID, SBP_READ_RSSI_EVT, SBP_READ_RSSI_EVT_PERIOD ); + + PRINT("Conn %x - Int %x \n", event->connectionHandle, event->connInterval); + } +} + +/********************************************************************* + * @fn Peripheral_LinkTerminated + * + * @brief Process link terminated. + * + * @param pEvent - event to process + * + * @return none + */ +static void Peripheral_LinkTerminated( gapRoleEvent_t * pEvent ) +{ + gapTerminateLinkEvent_t *event = (gapTerminateLinkEvent_t *) pEvent; + + if( event->connectionHandle == peripheralConnList.connHandle ) + { + peripheralConnList.connHandle = GAP_CONNHANDLE_INIT; + peripheralConnList.connInterval = 0; + peripheralConnList.connSlaveLatency = 0; + peripheralConnList.connTimeout = 0; + tmos_stop_task( Peripheral_TaskID, SBP_PERIODIC_EVT ); + tmos_stop_task( Peripheral_TaskID, SBP_READ_RSSI_EVT ); + + // Restart advertising + { + uint8 advertising_enable = TRUE; + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &advertising_enable ); + } + } + else + { + PRINT("ERR..\n"); + } +} + +/********************************************************************* + * @fn peripheralRssiCB + * + * @brief RSSI callback. + * + * @param connHandle - connection handle + * @param rssi - RSSI + * + * @return none + */ +static void peripheralRssiCB( uint16 connHandle, int8 rssi ) +{ + PRINT( "RSSI -%d dB Conn %x \n", -rssi, connHandle); +} + +/********************************************************************* + * @fn peripheralParamUpdateCB + * + * @brief Parameter update complete callback + * + * @param connHandle - connect handle + * connInterval - connect interval + * connSlaveLatency - connect slave latency + * connTimeout - connect timeout + * + * @return none + */ +static void peripheralParamUpdateCB( uint16 connHandle, uint16 connInterval, + uint16 connSlaveLatency, uint16 connTimeout ) +{ + if( connHandle == peripheralConnList.connHandle ) + { + peripheralConnList.connInterval = connInterval; + peripheralConnList.connSlaveLatency = connSlaveLatency; + peripheralConnList.connTimeout = connTimeout; + + PRINT("Update %x - Int %x \n", connHandle, connInterval); + } + else + { + PRINT("ERR..\n"); + } +} + +/********************************************************************* + * @fn peripheralStateNotificationCB + * + * @brief Notification from the profile of a state change. + * + * @param newState - new state + * + * @return none + */ +static void peripheralStateNotificationCB( gapRole_States_t newState, gapRoleEvent_t * pEvent ) +{ + switch ( newState ) + { + case GAPROLE_STARTED: + PRINT( "Initialized..\n" ); + break; + + case GAPROLE_ADVERTISING: + if( pEvent->gap.opcode == GAP_LINK_TERMINATED_EVENT ) + { + Peripheral_LinkTerminated( pEvent ); + PRINT( "Disconnected.. Reason:%x\n",pEvent->linkTerminate.reason ); + } + PRINT( "Advertising..\n" ); + break; + + case GAPROLE_CONNECTED: + if( pEvent->gap.opcode == GAP_LINK_ESTABLISHED_EVENT ) + { + Peripheral_LinkEstablished( pEvent ); + } + PRINT( "Connected..\n" ); + break; + + case GAPROLE_CONNECTED_ADV: + PRINT( "Connected Advertising..\n" ); + break; + + case GAPROLE_WAITING: + if( pEvent->gap.opcode == GAP_END_DISCOVERABLE_DONE_EVENT ) + { + PRINT( "Waiting for advertising..\n" ); + } + else if( pEvent->gap.opcode == GAP_LINK_TERMINATED_EVENT ) + { + Peripheral_LinkTerminated( pEvent ); + PRINT( "Disconnected.. Reason:%x\n",pEvent->linkTerminate.reason ); + } + else if( pEvent->gap.opcode == GAP_LINK_ESTABLISHED_EVENT ) + { + if( pEvent->gap.hdr.status != SUCCESS ) + { + PRINT( "Waiting for advertising..\n" ); + } + else + { + PRINT( "Error..\n" ); + } + } + else + { + PRINT( "Error..%x\n",pEvent->gap.opcode ); + } + break; + + case GAPROLE_ERROR: + PRINT( "Error..\n" ); + break; + + default: + break; + } +} + +/********************************************************************* + * @fn performPeriodicTask + * + * @brief Perform a periodic application task. This function gets + * called every five seconds as a result of the SBP_PERIODIC_EVT + * TMOS event. In this example, the value of the third + * characteristic in the SimpleGATTProfile service is retrieved + * from the profile, and then copied into the value of the + * the fourth characteristic. + * + * @param none + * + * @return none + */ +static void performPeriodicTask( void ) +{ + uint8 notiData[SIMPLEPROFILE_CHAR4_LEN] = { 0x88 }; + peripheralChar4Notify( notiData, SIMPLEPROFILE_CHAR4_LEN ); +} + +/********************************************************************* + * @fn peripheralChar4Notify + * + * @brief Prepare and send simpleProfileChar4 notification + * + * @param pValue - data to notify + * len - length of data + * + * @return none + */ +void peripheralChar4Notify( uint8 *pValue, uint16 len ) +{ + attHandleValueNoti_t noti; + noti.len = len; + noti.pValue = GATT_bm_alloc( peripheralConnList.connHandle, ATT_HANDLE_VALUE_NOTI, noti.len, NULL, 0 ); + tmos_memcpy( noti.pValue, pValue, noti.len ); + if( simpleProfile_Notify( peripheralConnList.connHandle, ¬i ) != SUCCESS ) + { + GATT_bm_free( (gattMsg_t *)¬i, ATT_HANDLE_VALUE_NOTI ); + } +} + +/********************************************************************* + * @fn simpleProfileChangeCB + * + * @brief Callback from SimpleBLEProfile indicating a value change + * + * @param paramID - parameter ID of the value that was changed. + * pValue - pointer to data that was changed + * len - length of data + * + * @return none + */ +static void simpleProfileChangeCB( uint8 paramID, uint8 *pValue, uint16 len ) +{ + + switch( paramID ) + { + case SIMPLEPROFILE_CHAR1: + { + uint8 newValue[SIMPLEPROFILE_CHAR1_LEN]; + tmos_memcpy( newValue, pValue, len ); + PRINT("profile ChangeCB CHAR1.. \n"); + APP_DBG("node1_addr %x",app_nodes[1].node_addr); + if(app_nodes[1].node_addr) + { + uint8 status; + struct send_param param = { + .app_idx = self_prov_app_idx, // Ϣʹõapp key + .addr = app_nodes[1].node_addr, // ϢĿĵصַ˴ΪһĽڵ + .trans_cnt = 0x03, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_cli_tid_get(), // tidÿϢѭcliʹ0~127 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + status = vendor_message_cli_write(¶m, newValue, len); // ԶģͿͻ˵Ӧд + if( status ) APP_DBG("write failed %d",status); + } + break; + } + + case SIMPLEPROFILE_CHAR3: + { + uint8 newValue[SIMPLEPROFILE_CHAR3_LEN]; + tmos_memcpy( newValue, pValue, len ); + PRINT("profile ChangeCB CHAR3..\n"); + APP_DBG("node2_addr %x",app_nodes[2].node_addr); + if(app_nodes[2].node_addr) + { + uint8 status; + struct send_param param = { + .app_idx = self_prov_app_idx, // Ϣʹõapp key + .addr = app_nodes[2].node_addr, // ϢĿĵصַ˴ΪڶĽڵ + .trans_cnt = 0x03, // Ϣش + .period = K_MSEC(400), // Ϣشļ鲻С(200+50*TTL)msݽϴӳ + .rand = (0), // Ϣ͵ӳ + .tid = vendor_cli_tid_get(), // tidÿϢѭcliʹ0~127 + .send_ttl = BLE_MESH_TTL_DEFAULT, // ttlضʹĬֵ + }; + status = vendor_message_cli_write(¶m, newValue, len); // ԶģͿͻ˵Ӧд + if( status ) APP_DBG("write failed %d",status); + } + break; + } + + default: + // should not reach here! + break; + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Profile/gattprofile.c b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Profile/gattprofile.c new file mode 100644 index 0000000..e7d852e --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Profile/gattprofile.c @@ -0,0 +1,744 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : gattprofile.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ԶֲͬԵķ񣬰ɶд֪ͨɶдȫɶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "gattprofile.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// Position of simpleProfilechar4 value in attribute array +#define SIMPLEPROFILE_CHAR4_VALUE_POS 11 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// 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: 0xFFF1 +CONST uint8 simpleProfilechar1UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR1_UUID), HI_UINT16(SIMPLEPROFILE_CHAR1_UUID) +}; + +// Characteristic 2 UUID: 0xFFF2 +CONST uint8 simpleProfilechar2UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR2_UUID), HI_UINT16(SIMPLEPROFILE_CHAR2_UUID) +}; + +// Characteristic 3 UUID: 0xFFF3 +CONST uint8 simpleProfilechar3UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR3_UUID), HI_UINT16(SIMPLEPROFILE_CHAR3_UUID) +}; + +// Characteristic 4 UUID: 0xFFF4 +CONST uint8 simpleProfilechar4UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR4_UUID), HI_UINT16(SIMPLEPROFILE_CHAR4_UUID) +}; + +// Characteristic 5 UUID: 0xFFF5 +CONST uint8 simpleProfilechar5UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR5_UUID), HI_UINT16(SIMPLEPROFILE_CHAR5_UUID) +}; + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +static simpleProfileCBs_t *simpleProfile_AppCBs = NULL; + +/********************************************************************* + * Profile Attributes - variables + */ + +// Simple Profile Service attribute +static CONST gattAttrType_t simpleProfileService = { ATT_BT_UUID_SIZE, simpleProfileServUUID }; + + +// Simple Profile Characteristic 1 Properties +static uint8 simpleProfileChar1Props = GATT_PROP_READ | GATT_PROP_WRITE; + +// Characteristic 1 Value +static uint8 simpleProfileChar1[SIMPLEPROFILE_CHAR1_LEN] = { 0 }; + +// Simple Profile Characteristic 1 User Description +static uint8 simpleProfileChar1UserDesp[] = "Characteristic 1\0"; + + +// Simple Profile Characteristic 2 Properties +static uint8 simpleProfileChar2Props = GATT_PROP_READ; + +// Characteristic 2 Value +static uint8 simpleProfileChar2[SIMPLEPROFILE_CHAR2_LEN] = { 0 }; + +// Simple Profile Characteristic 2 User Description +static uint8 simpleProfileChar2UserDesp[] = "Characteristic 2\0"; + + +// Simple Profile Characteristic 3 Properties +static uint8 simpleProfileChar3Props = GATT_PROP_WRITE; + +// Characteristic 3 Value +static uint8 simpleProfileChar3[SIMPLEPROFILE_CHAR3_LEN] = { 0 }; + +// Simple Profile Characteristic 3 User Description +static uint8 simpleProfileChar3UserDesp[] = "Characteristic 3\0"; + + +// Simple Profile Characteristic 4 Properties +static uint8 simpleProfileChar4Props = GATT_PROP_NOTIFY; + +// Characteristic 4 Value +static uint8 simpleProfileChar4[SIMPLEPROFILE_CHAR4_LEN] = { 0 }; + +// Simple Profile Characteristic 4 Configuration Each client has its own +// instantiation of the Client Characteristic Configuration. Reads of the +// Client Characteristic Configuration only shows the configuration for +// that client and writes only affect the configuration of that client. +static gattCharCfg_t simpleProfileChar4Config[4]; + +// Simple Profile Characteristic 4 User Description +static uint8 simpleProfileChar4UserDesp[] = "Characteristic 4\0"; + + +// Simple Profile Characteristic 5 Properties +static uint8 simpleProfileChar5Props = GATT_PROP_READ; + +// Characteristic 5 Value +static uint8 simpleProfileChar5[SIMPLEPROFILE_CHAR5_LEN] = { 0 }; + +// Simple Profile Characteristic 5 User Description +static uint8 simpleProfileChar5UserDesp[] = "Characteristic 5\0"; + + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t simpleProfileAttrTbl[] = +{ + // Simple Profile Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&simpleProfileService /* pValue */ + }, + + // Characteristic 1 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar1Props + }, + + // Characteristic Value 1 + { + { ATT_BT_UUID_SIZE, simpleProfilechar1UUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + simpleProfileChar1 + }, + + // Characteristic 1 User Description + { + { 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, + 0, + simpleProfileChar2 + }, + + // Characteristic 2 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar2UserDesp + }, + + // Characteristic 3 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar3Props + }, + + // Characteristic Value 3 + { + { ATT_BT_UUID_SIZE, simpleProfilechar3UUID }, + GATT_PERMIT_WRITE, + 0, + simpleProfileChar3 + }, + + // Characteristic 3 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar3UserDesp + }, + + // Characteristic 4 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar4Props + }, + + // Characteristic Value 4 + { + { ATT_BT_UUID_SIZE, simpleProfilechar4UUID }, + 0, + 0, + simpleProfileChar4 + }, + + // Characteristic 4 configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8 *)simpleProfileChar4Config + }, + + // Characteristic 4 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar4UserDesp + }, + + // Characteristic 5 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar5Props + }, + + // Characteristic Value 5 + { + { ATT_BT_UUID_SIZE, simpleProfilechar5UUID }, + GATT_PERMIT_AUTHEN_READ, + 0, + simpleProfileChar5 + }, + + // Characteristic 5 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar5UserDesp + }, +}; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ); + +static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); + + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Simple Profile Service Callbacks +gattServiceCBs_t simpleProfileCBs = +{ + simpleProfile_ReadAttrCB, // Read callback function pointer + simpleProfile_WriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn SimpleProfile_AddService + * + * @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. + * + * @return Success or Failure + */ +bStatus_t SimpleProfile_AddService( uint32 services ) +{ + uint8 status = SUCCESS; + + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar4Config ); + + // Register with Link DB to receive link status change callback + 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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &simpleProfileCBs ); + } + + return ( status ); +} + + +/********************************************************************* + * @fn SimpleProfile_RegisterAppCBs + * + * @brief Registers the application callback function. Only call + * this function once. + * + * @param callbacks - pointer to application callbacks. + * + * @return SUCCESS or bleAlreadyInRequestedMode + */ +bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) +{ + if ( appCallbacks ) + { + simpleProfile_AppCBs = appCallbacks; + + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } +} + + +/********************************************************************* + * @fn SimpleProfile_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + if ( len == SIMPLEPROFILE_CHAR1_LEN ) + { + tmos_memcpy( simpleProfileChar1, value, SIMPLEPROFILE_CHAR1_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR2: + if ( len == SIMPLEPROFILE_CHAR2_LEN ) + { + tmos_memcpy( simpleProfileChar2, value, SIMPLEPROFILE_CHAR2_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR3: + if ( len == SIMPLEPROFILE_CHAR3_LEN ) + { + tmos_memcpy( simpleProfileChar3, value, SIMPLEPROFILE_CHAR3_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR4: + if ( len == SIMPLEPROFILE_CHAR4_LEN ) + { + tmos_memcpy( simpleProfileChar4, value, SIMPLEPROFILE_CHAR4_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR5: + if ( len == SIMPLEPROFILE_CHAR5_LEN ) + { + tmos_memcpy( simpleProfileChar5, value, SIMPLEPROFILE_CHAR5_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn SimpleProfile_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + tmos_memcpy( value, simpleProfileChar1, SIMPLEPROFILE_CHAR1_LEN ); + break; + + case SIMPLEPROFILE_CHAR2: + tmos_memcpy( value, simpleProfileChar2, SIMPLEPROFILE_CHAR2_LEN ); + break; + + case SIMPLEPROFILE_CHAR3: + tmos_memcpy( value, simpleProfileChar3, SIMPLEPROFILE_CHAR3_LEN ); + break; + + case SIMPLEPROFILE_CHAR4: + tmos_memcpy( value, simpleProfileChar4, SIMPLEPROFILE_CHAR4_LEN ); + break; + + case SIMPLEPROFILE_CHAR5: + tmos_memcpy( value, simpleProfileChar5, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn simpleProfile_Notify + * + * @brief Send a notification containing a heart rate + * measurement. + * + * @param connHandle - connection handle + * @param pNoti - pointer to notification structure + * + * @return Success or Failure + */ +bStatus_t simpleProfile_Notify( uint16 connHandle, attHandleValueNoti_t *pNoti ) +{ + uint16 value = GATTServApp_ReadCharCfg( connHandle, simpleProfileChar4Config ); + + // If notifications enabled + if ( value & GATT_CLIENT_CFG_NOTIFY ) + { + // Set the handle + pNoti->handle = simpleProfileAttrTbl[SIMPLEPROFILE_CHAR4_VALUE_POS].handle; + + // Send the notification + return GATT_Notification( connHandle, pNoti, FALSE ); + } + return bleIncorrectMode; +} + +/********************************************************************* + * @fn simpleProfile_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + + // If attribute permissions require authorization to read, return error + if ( gattPermitAuthorRead( pAttr->permissions ) ) + { + // 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 + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + // No need for "GATT_SERVICE_UUID" or "GATT_CLIENT_CHAR_CFG_UUID" cases; + // gattserverapp handles those reads + + // characteristics 1 and 2 have read permissions + // characteritisc 3 does not have read permissions; therefore it is not + // included here + // characteristic 4 does not have read permissions, but because it + // can be sent as a notification, it is included here + case SIMPLEPROFILE_CHAR1_UUID: + *pLen = SIMPLEPROFILE_CHAR1_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR1_LEN ); + break; + + case SIMPLEPROFILE_CHAR2_UUID: + *pLen = SIMPLEPROFILE_CHAR2_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR2_LEN ); + break; + + case SIMPLEPROFILE_CHAR4_UUID: + *pLen = SIMPLEPROFILE_CHAR4_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR4_LEN ); + break; + + case SIMPLEPROFILE_CHAR5_UUID: + *pLen = SIMPLEPROFILE_CHAR5_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint8 notifyApp = 0xFF; + + // If attribute permissions require authorization to write, return error + if ( gattPermitAuthorWrite( pAttr->permissions ) ) + { + // Insufficient authorization + return ( ATT_ERR_INSUFFICIENT_AUTHOR ); + } + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + case SIMPLEPROFILE_CHAR1_UUID: + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len > SIMPLEPROFILE_CHAR1_LEN ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + tmos_memcpy( pAttr->pValue, pValue, SIMPLEPROFILE_CHAR1_LEN ); + notifyApp = SIMPLEPROFILE_CHAR1; + } + break; + + case SIMPLEPROFILE_CHAR3_UUID: + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len > SIMPLEPROFILE_CHAR3_LEN ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + tmos_memcpy( pAttr->pValue, pValue, SIMPLEPROFILE_CHAR3_LEN ); + notifyApp = SIMPLEPROFILE_CHAR3; + } + break; + + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); + break; + + default: + // Should never get here! (characteristics 2 and 4 do not have write permissions) + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + status = ATT_ERR_INVALID_HANDLE; + } + + // 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, pValue, len ); + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_HandleConnStatusCB + * + * @brief Simple Profile link status change handler function. + * + * @param connHandle - connection handle + * @param changeType - type of change + * + * @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 ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, simpleProfileChar4Config ); + } + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Profile/include/gattprofile.h b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Profile/include/gattprofile.h new file mode 100644 index 0000000..a5a10b8 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Profile/include/gattprofile.h @@ -0,0 +1,137 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : gattprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef GATTPROFILE_H +#define GATTPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// 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 + +// Simple Profile Service UUID +#define SIMPLEPROFILE_SERV_UUID 0xFFE0 + +// Key Pressed UUID +#define SIMPLEPROFILE_CHAR1_UUID 0xFFE1 +#define SIMPLEPROFILE_CHAR2_UUID 0xFFE2 +#define SIMPLEPROFILE_CHAR3_UUID 0xFFE3 +#define SIMPLEPROFILE_CHAR4_UUID 0xFFE4 +#define SIMPLEPROFILE_CHAR5_UUID 0xFFE5 + +// Simple Keys Profile Services bit fields +#define SIMPLEPROFILE_SERVICE 0x00000001 + +// Length of characteristic in bytes ( Default MTU is 23 ) +#define SIMPLEPROFILE_CHAR1_LEN 21 +#define SIMPLEPROFILE_CHAR2_LEN 1 +#define SIMPLEPROFILE_CHAR3_LEN 21 +#define SIMPLEPROFILE_CHAR4_LEN 19 +#define SIMPLEPROFILE_CHAR5_LEN 5 + +/********************************************************************* + * TYPEDEFS + */ + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// Callback when a characteristic value has changed +typedef void (*simpleProfileChange_t)( uint8 paramID, uint8 *pValue, uint16 len ); + +typedef struct +{ + simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes +} simpleProfileCBs_t; + + + +/********************************************************************* + * API FUNCTIONS + */ + + +/* + * SimpleProfile_AddService- Initializes the Simple GATT 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. + */ + +extern bStatus_t SimpleProfile_AddService( uint32 services ); + +/* + * SimpleProfile_RegisterAppCBs - Registers the application callback function. + * Only call this function once. + * + * 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). + */ +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). + */ +extern bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ); + +/* + * simpleProfile_Notify - Send notification. + * + * connHandle - connect handle + * pNoti - pointer to structure to notify. + */ +extern bStatus_t simpleProfile_Notify( uint16 connHandle, attHandleValueNoti_t *pNoti ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Project/BLE.uvprojx b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Project/BLE.uvprojx new file mode 100644 index 0000000..48236c1 --- /dev/null +++ b/src/EXAM/BLE/MESH/self_provisioner_vendor_with_peripheral/Project/BLE.uvprojx @@ -0,0 +1,587 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,HAL_KEY=1 + + ..\APP\include;..\Profile\include;..\..\..\HAL\include;..\..\..\LIB;..\..\..\..\SRC\CMSIS\Include;..\..\..\..\SRC\StdPeriphDriver\inc;..\..\MESH_LIB + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + app.c + 1 + ..\APP\app.c + + + app_vendor_model_cli.c + 1 + ..\APP\app_vendor_model_cli.c + + + app_main.c + 1 + ..\APP\app_main.c + + + app_mesh_config.c + 1 + ..\APP\app_mesh_config.c + + + app_mesh_config.h + 5 + ..\APP\include\app_mesh_config.h + + + peripheral.c + 1 + ..\APP\peripheral.c + + + gattprofile.c + 1 + ..\Profile\gattprofile.c + + + + + drive + + + CH57x_adc.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + CH57x_clk.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_flash.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_gpio.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_int.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + CH57x_lcd.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_lcd.c + + + CH57x_pwm.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwm.c + + + CH57x_pwr.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_spi0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi0.c + + + CH57x_spi1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_spi1.c + + + CH57x_sys.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_timer0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer0.c + + + CH57x_timer1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer1.c + + + CH57x_timer2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer2.c + + + CH57x_timer3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_timer3.c + + + CH57x_uart0.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart0.c + + + CH57x_uart1.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_uart2.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart2.c + + + CH57x_uart3.c + 1 + ..\..\..\..\SRC\StdPeriphDriver\CH57x_uart3.c + + + startup_ARMCM0.s + 2 + ..\..\..\..\SRC\Startup\startup_ARMCM0.s + + + + + hal + + + KEY.c + 1 + ..\..\..\HAL\KEY.c + + + MCU.c + 1 + ..\..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.lib + 4 + ..\..\..\LIB\CH57xBLE.lib + + + MESH_LIB.lib + 4 + ..\..\MESH_LIB\MESH_LIB.lib + + + + + config + + + config.h + 5 + ..\..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/MultiCentral/APP/multiCentral_main.c b/src/EXAM/BLE/MultiCentral/APP/multiCentral_main.c index 3a5b119..d3cbd52 100644 --- a/src/EXAM/BLE/MultiCentral/APP/multiCentral_main.c +++ b/src/EXAM/BLE/MultiCentral/APP/multiCentral_main.c @@ -31,8 +31,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/MultiCentral/Project/BLE.uvprojx b/src/EXAM/BLE/MultiCentral/Project/BLE.uvprojx index cdc4355..9feec58 100644 --- a/src/EXAM/BLE/MultiCentral/Project/BLE.uvprojx +++ b/src/EXAM/BLE/MultiCentral/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -483,6 +483,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c +
@@ -529,4 +534,10 @@ + + + + + + diff --git a/src/EXAM/BLE/Observer/APP/observer_main.c b/src/EXAM/BLE/Observer/APP/observer_main.c index dc99088..401a02f 100644 --- a/src/EXAM/BLE/Observer/APP/observer_main.c +++ b/src/EXAM/BLE/Observer/APP/observer_main.c @@ -31,8 +31,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/Observer/Project/BLE.uvprojx b/src/EXAM/BLE/Observer/Project/BLE.uvprojx index cfe8497..d7a1e43 100644 --- a/src/EXAM/BLE/Observer/Project/BLE.uvprojx +++ b/src/EXAM/BLE/Observer/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -483,6 +483,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + @@ -529,4 +534,10 @@ + + + + + + diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/OTAnobackup.c b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/OTAnobackup.c new file mode 100644 index 0000000..2d72a50 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/OTAnobackup.c @@ -0,0 +1,682 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : OTAnobackup.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ӻӦó򣬳ʼ㲥ӲȻ㲥ֱͨԶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "devinfoservice.h" +#include "GATTprofile.h" +#include "OTAnobackup.h" +#include "OTA.h" +#include "OTAprofile.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// How often to perform periodic event +#define SBP_PERIODIC_EVT_PERIOD 1000 + +// What is the advertising interval when device is discoverable (units of 625us, 160=100ms) +#define DEFAULT_ADVERTISING_INTERVAL 160 + +// Limited discoverable mode advertises for 30.72s, and then stops +// General discoverable mode advertises indefinitely + +#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL + +// Minimum connection interval (units of 1.25ms, 80=100ms) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 6 + +// Maximum connection interval (units of 1.25ms, 800=1000ms) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 12 + +// Slave latency to use if automatic parameter update request is enabled +#define DEFAULT_DESIRED_SLAVE_LATENCY 0 + +// Supervision timeout value (units of 10ms, 1000=10s) if automatic parameter update request is enabled +#define DEFAULT_DESIRED_CONN_TIMEOUT 1000 + +// Whether to enable automatic parameter update request when a connection is formed +#define DEFAULT_ENABLE_UPDATE_REQUEST TRUE + +// Connection Pause Peripheral time value (in seconds) +#define DEFAULT_CONN_PAUSE_PERIPHERAL 6 + +// Company Identifier: WCH +#define WCH_COMPANY_ID 0x07D7 + +#define INVALID_CONNHANDLE 0xFFFF + +// Length of bd addr as a string +#define B_ADDR_STR_LEN 15 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ +static uint8 Peripheral_TaskID=0xff; // Task ID for internal task/event processing + +// GAP - SCAN RSP data (max size = 31 bytes) +static uint8 scanRspData[31] = +{ + // complete name + 0x12, // length of this data + GAP_ADTYPE_LOCAL_NAME_COMPLETE, + 'O','T','A',' ','O','T','A',' ','O','T','A',' ','O','T','A',' ','!', + // connection interval range + 0x05, // length of this data + GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE, + LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), // 100ms + HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), + LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), // 1s + HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), + + // Tx power level + 0x02, // length of this data + GAP_ADTYPE_POWER_LEVEL, + 0 // 0dBm +}; + +// GAP - Advertisement data (max size = 31 bytes, though this is +// best kept short to conserve power while advertisting) +static uint8 advertData[] = +{ + // Flags; this sets the device to use limited discoverable + // mode (advertises for 30 seconds at a time) instead of general + // discoverable mode (advertises indefinitely) + 0x02, // length of this data + GAP_ADTYPE_FLAGS, + DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED, + + // service UUID, to notify central devices what services are included + // in this peripheral + 0x03, // length of this data + GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all + LO_UINT16( SIMPLEPROFILE_SERV_UUID ), + HI_UINT16( SIMPLEPROFILE_SERV_UUID ) + +}; + +// GAP GATT Attributes +static uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "OTA OTA OTA OTA !"; + +// OTA IAP VARIABLES +/* OTAͨѶ֡ */ +OTA_IAP_CMD_t iap_rec_data; + +/* OTA */ +__align(8) UINT32 OpParaData[4]; +UINT32 OpParaDataLen = 0; +UINT32 OpAdd = 0; + +/* flashһʱ洢 */ +__align(8) uint8 vectors_block_buf[FLASH_BLOCK_SIZE]; + +/* codeflashʱ */ +__align(8) uint8 codeflash_block_buf[FLASH_BLOCK_SIZE]; + +/* Imageתַ */ +typedef int( *pImageTaskFn)( void ); +pImageTaskFn user_image_tasks; + +/* Flash */ +UINT32 EraseAdd = 0; //ַ +UINT32 EraseBlockNum = 0; //ҪĿ +UINT32 EraseBlockCnt = 0; //Ŀ + +/* FLASH У */ +UINT8 VerifyStatus = 0; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ); +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent ); +void OTA_IAPReadDataComplete( unsigned char index ); +void OTA_IAPWriteData( unsigned char index, unsigned char *p_data, unsigned char w_len ); +void Rec_OTA_IAP_DataDeal(void); +void OTA_IAP_SendCMDDealSta(UINT8 deal_status); + +/********************************************************************* + * PROFILE CALLBACKS + */ + +// GAP Role Callbacks +static gapRolesCBs_t Peripheral_PeripheralCBs = +{ + peripheralStateNotificationCB, // Profile State Change Callbacks + NULL, // When a valid RSSI is read from controller (not used by application) + NULL +}; + +// Simple GATT Profile Callbacks +static OTAProfileCBs_t Peripheral_OTA_IAPProfileCBs = +{ + OTA_IAPReadDataComplete, // Charactersitic value change callback + OTA_IAPWriteData +}; + + + +// Callback when the connection parameteres are updated. +void PeripheralParamUpdate(uint16 connInterval,uint16 connSlaveLatency, uint16 connTimeout); + +gapRolesParamUpdateCB_t PeripheralParamUpdate_t = NULL; + + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn Peripheral_Init + * + * @brief Initialization function for the 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 TMOS. This ID should be + * used to send messages and set timers. + * + * @return none + */ +void Peripheral_Init( ) +{ + Peripheral_TaskID = TMOS_ProcessEventRegister(Peripheral_ProcessEvent); + + // Setup the GAP Peripheral Role Profile + { + // For other hardware platforms, device starts advertising upon initialization + uint8 initial_advertising_enable = TRUE; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); + GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); + } + + // Set the GAP Characteristics + GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); + + // Set advertising interval + { + uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; + + GAP_SetParamValue( TGAP_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_DISC_ADV_INT_MAX, advInt ); + } + // Initialize GATT attributes + GGS_AddService( GATT_ALL_SERVICES ); // GAP + GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes + OTAProfile_AddService( GATT_ALL_SERVICES ); + + // Register callback with OTAGATTprofile + OTAProfile_RegisterAppCBs( &Peripheral_OTA_IAPProfileCBs ); + + // Setup a delayed profile startup + tmos_set_event( Peripheral_TaskID, SBP_START_DEVICE_EVT ); + +} + +/********************************************************************* + * @fn Peripheral_ProcessEvent + * + * @brief 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 TMOS assigned task ID. + * @param events - events to process. This is a bit map and can + * contain more than one event. + * + * @return events not processed + */ +uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ) +{ + +// VOID task_id; // TMOS required parameter that isn't used in this function + + if ( events & SYS_EVENT_MSG ){ + uint8 *pMsg; + + if ( (pMsg = tmos_msg_receive( Peripheral_TaskID )) != NULL ){ + Peripheral_ProcessTMOSMsg( (tmos_event_hdr_t *)pMsg ); + // Release the TMOS message + tmos_msg_deallocate( pMsg ); + } + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } + + if ( events & SBP_START_DEVICE_EVT ){ + // Start the Device + GAPRole_PeripheralStartDevice( Peripheral_TaskID, NULL, &Peripheral_PeripheralCBs ); + // Set timer for first periodic event + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + return ( events ^ SBP_START_DEVICE_EVT ); + } + + //OTA_FLASH_ERASE_EVT + if ( events & OTA_FLASH_ERASE_EVT ) + { + UINT8 status; + + PRINT("ERASE:%08x num:%d\r\n",(int)(EraseAdd+EraseBlockCnt*FLASH_BLOCK_SIZE),(int)EraseBlockCnt); + status = FlashBlockErase(EraseAdd+EraseBlockCnt*FLASH_BLOCK_SIZE); + + /* ʧ */ + if(status != SUCCESS) + { + OTA_IAP_SendCMDDealSta(status); + return (events ^ OTA_FLASH_ERASE_EVT); + } + + EraseBlockCnt++; + + /* */ + if( EraseBlockCnt >= EraseBlockNum ) + { + PRINT("ERASE Complete\r\n"); + OTA_IAP_SendCMDDealSta(status); + return (events ^ OTA_FLASH_ERASE_EVT); + } + return (events); + } + + // Discard unknown events + return 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessTMOSMsg + * + * @brief Process an incoming task message. + * + * @param pMsg - message to process + * + * @return none + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ) +{ + switch ( pMsg->event ){ + default: + break; + } +} + +/********************************************************************* + * @fn peripheralStateNotificationCB + * + * @brief Notification from the profile of a state change. + * + * @param newState - new state + * + * @return none + */ +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent ) +{ + switch ( newState ) + { + case GAPROLE_STARTED: + PRINT( "Initialized \n" ); + break; + + case GAPROLE_ADVERTISING: + PRINT( "Advertising \n" ); + break; + + case GAPROLE_CONNECTED: + PRINT( "Connected \n" ); + break; + + case GAPROLE_WAITING: + PRINT( "Disconnected %x\n", pEvent->linkTerminate.reason); + { + uint8 initial_advertising_enable = TRUE; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + } + break; + + default: + break; + + } +} + +/******************************************************************************* +* Function Name : OTA_IAP_SendData +* Description : OTA IAPݣʹʱ20ֽ +* Input : p_send_dataݵָ + send_lenݵij +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_SendData(UINT8 *p_send_data,UINT8 send_len) +{ + OTAProfile_SendData(OTAPROFILE_CHAR ,p_send_data, send_len ); +} + +/******************************************************************************* +* Function Name : OTA_IAP_SendCMDDealSta +* Description : OTA IAPִе״̬ +* Input : deal_statusص״̬ +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_SendCMDDealSta(UINT8 deal_status) +{ + UINT8 send_buf[2]; + + send_buf[0] = deal_status; + send_buf[1] = 0; + OTA_IAP_SendData(send_buf,2); +} + +/******************************************************************************* +* Function Name : OTA_IAP_CMDErrDeal +* Description : OTA IAP쳣봦 +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAP_CMDErrDeal(void) +{ + OTA_IAP_SendCMDDealSta(0xfe); +} + +/******************************************************************************* +* Function Name : CopyOTAFrist512ByteToAPP +* Description : CopyOTAFrist512ByteToAPP +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void CopyOTAFrist512ByteToAPP( ) +{ + UINT8 *p_flash; + UINT16 i; + + /* ȡһ */ + p_flash = (UINT8 *)IMAGE_OTA_START_ADD; + for(i=0; iICER[0] = 0xffffffff; + SysTick->CTRL = 0; //رSysTickж +} + +/******************************************************************************* +* Function Name : GotoResetVector +* Description : ȡתַת +* Input : entry_addResetַ +* Output : none +* Return : none +*******************************************************************************/ +void GotoResetVector(UINT32 entry_add) +{ + user_image_tasks = (pImageTaskFn)(*(UINT32 *)(entry_add)); + (user_image_tasks)(); +} + +/******************************************************************************* +* Function Name : Rec_OTA_IAP_DataDeal +* Description : յOTAݰ +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void Rec_OTA_IAP_DataDeal(void) +{ + switch(iap_rec_data.other.buf[0]) + { + /* */ + case CMD_IAP_PROM: + { + UINT32 i; + UINT8 status; + + OpParaDataLen = iap_rec_data.program.len; + + OpAdd = (UINT32)(iap_rec_data.program.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.program.addr[1]) << 8); + OpAdd = OpAdd * 4; + + PRINT("IAP_PROM: %08x len:%d \r\n",(int)OpAdd,(int)OpParaDataLen); + + for(i=0; i<(OpParaDataLen/4); i++) + { + OpParaData[i] = (UINT32)(iap_rec_data.program.buf[0+4*i]); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[1+4*i]) << 8); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[2+4*i]) << 16); + OpParaData[i] |= ((UINT32)(iap_rec_data.program.buf[3+4*i]) << 24); + } + + /* һ */ + if((OpAdd + OpParaDataLen) <= FLASH_BLOCK_SIZE) + { + for(i = 0; i < OpParaDataLen; i++) + { + vectors_block_buf[OpAdd + i] = iap_rec_data.program.buf[i]; + } + status = SUCCESS; + OTA_IAP_SendCMDDealSta(status); + } + /* */ + else + { + status = FlashWriteBuf(OpAdd, (PUINT32)OpParaData, (UINT16) OpParaDataLen); + OTA_IAP_SendCMDDealSta(status); + } + + break; + } + /* -- */ + case CMD_IAP_ERASE: + { + /* һʼflashIAPĵһflashAPPһflash */ + CopyOTAFrist512ByteToAPP(); + + OpAdd = (UINT32)(iap_rec_data.erase.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.erase.addr[1]) << 8); + OpAdd = OpAdd * 4; + + EraseBlockNum = (UINT32)(iap_rec_data.erase.block_num[0]); + EraseBlockNum |= ((UINT32)(iap_rec_data.erase.block_num[1]) << 8); + EraseAdd = OpAdd; + EraseBlockCnt = 0; + + /* ͷڲ0 */ + VerifyStatus = 0; + + PRINT("IAP_ERASE start:%08x num:%d\r\n",(int)OpAdd,(int)EraseBlockNum); + + EraseBlockNum -= 1; + EraseAdd += FLASH_BLOCK_SIZE; + + /* */ + tmos_set_event( Peripheral_TaskID, OTA_FLASH_ERASE_EVT ); + + break; + } + /* У */ + case CMD_IAP_VERIFY: + { + UINT32 i; + UINT8 *p_flash; + UINT8 status = 0; + + OpParaDataLen = iap_rec_data.verify.len; + + OpAdd = (UINT32)(iap_rec_data.verify.addr[0]); + OpAdd |= ((UINT32)(iap_rec_data.verify.addr[1]) << 8); + OpAdd = OpAdd * 4; + + PRINT("IAP_VERIFY: %08x len:%d \r\n",(int)OpAdd,(int)OpParaDataLen); + + p_flash = (UINT8 *)OpAdd; + + /* һRAMIJԱ */ + if( (OpAdd + OpParaDataLen) <= FLASH_BLOCK_SIZE ) + { + for(i=0; i>8) & 0xff); + send_buf[3] = (UINT8)((IMAGE_APP_SIZE>>16) & 0xff); + send_buf[4] = (UINT8)((IMAGE_APP_SIZE>>24) & 0xff); + + /* BLOCK SIZE */ + send_buf[5] = (UINT8)(FLASH_BLOCK_SIZE & 0xff); + send_buf[6] = (UINT8)((FLASH_BLOCK_SIZE>>8) & 0xff); + + /* Ҫ */ + + /* Ϣ */ + OTA_IAP_SendData(send_buf,20); + + break; + } + + default: + { + OTA_IAP_CMDErrDeal(); + break; + } + } +} + +/******************************************************************************* +* Function Name : OTA_IAPReadDataComplete +* Description : OTA ݶȡɴ +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAPReadDataComplete( unsigned char index ) +{ + PRINT("OTA Send Comp \r\n"); +} + +/******************************************************************************* +* Function Name : OTA_IAPWriteData +* Description : OTA ͨݽɴ +* Input : indexOTA ͨ + p_dataд + w_lenдij +* Output : none +* Return : none +*******************************************************************************/ +void OTA_IAPWriteData( unsigned char index, unsigned char *p_data, unsigned char w_len ) +{ + unsigned char rec_len; + unsigned char *rec_data; + + rec_len = w_len; + rec_data = p_data; + tmos_memcpy( (unsigned char *)&iap_rec_data, rec_data, rec_len ); + Rec_OTA_IAP_DataDeal(); +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/OTAnobackup_main.c b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/OTAnobackup_main.c new file mode 100644 index 0000000..30baae9 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/OTAnobackup_main.c @@ -0,0 +1,59 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.1 +* Date : 2019/11/05 +* Description : ӻӦϵͳʼ +*******************************************************************************/ + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "GATTprofile.h" +#include "OTAnobackup.h" +#include "OTA.h" +#include "OTAprofile.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4] __attribute__((at(0x20003800))); + +#if (defined (BLE_MAC)) && (BLE_MAC == TRUE) +u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; +#endif + +/* ע⣺ڳflashIJִУκжϣֹжϺʧ */ +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) + GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif +#ifdef DEBUG + GPIOA_SetBits(bTXD1); + GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); + UART1_DefInit( ); +#endif + PRINT("%s\n",VER_LIB); + DisableAllIRQ(); + PRINT("Turn in OTA\n"); + CH57X_BLEInit( ); + HAL_Init( ); + GAPRole_PeripheralInit( ); + Peripheral_Init( ); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/include/OTAnobackup.h b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/include/OTAnobackup.h new file mode 100644 index 0000000..0fbe725 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/include/OTAnobackup.h @@ -0,0 +1,65 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef PERIPHERAL_H +#define PERIPHERAL_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + + +// Simple BLE Peripheral Task Events +#define SBP_START_DEVICE_EVT 0x0001 +#define SBP_PERIODIC_EVT 0x0002 +#define OTA_FLASH_ERASE_EVT 0x0004 //OTA Flash + + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * FUNCTIONS + */ + +/* + * Task Initialization for the BLE Application + */ +extern void Peripheral_Init( void ); + +/* + * Task Event Processor for the BLE Application + */ +extern uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ); + +extern void GotoResetVector(UINT32 entry_add); + +extern uint8 ReadSafeFlag(void); + +extern void DisableAllIRQ(void); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/include/ota.h b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/include/ota.h new file mode 100644 index 0000000..53ef264 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/APP/include/ota.h @@ -0,0 +1,108 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : ota.h +* Author : WCH +* Version : V1.10 +* Date : 2018/12/14 +* Description : oadö +*******************************************************************************/ + + +/******************************************************************************/ +#ifndef __OTA_H +#define __OTA_H + + +/* ------------------------------------------------------------------------------------------------ + * OTA FLASH + * ------------------------------------------------------------------------------------------------ + */ + +/* ûcodeֳ飬ǰ146Kͺ8KֱimageAPPimageOTA ʣ96KΪ*/ + +/* FLASH */ +#define FLASH_BLOCK_SIZE 512 + +/* imageAPP */ +#define IMAGE_APP_FLAG 0x01 +#define IMAGE_APP_START_ADD 0 +#define IMAGE_APP_SIZE 0x23800 +#define IMAGE_APP_ENTRY_ADD (IMAGE_APP_START_ADD + 4) + +/* imageOTA */ +#define IMAGE_OTA_FLAG 0x02 +#define IMAGE_OTA_START_ADD (IMAGE_APP_START_ADD + IMAGE_APP_SIZE) +#define IMAGE_OTA_SIZE 0x2000 +#define IMAGE_OTA_ENTRY_ADD (IMAGE_OTA_START_ADD + 4) + + +/* IAP */ +/* ΪIAP */ +#define CMD_IAP_PROM 0x80 // IAP +#define CMD_IAP_ERASE 0x81 // IAP +#define CMD_IAP_VERIFY 0x82 // IAPУ +#define CMD_IAP_END 0x83 // IAP־ +#define CMD_IAP_INFO 0x84 // IAPȡ豸Ϣ + + +/* ֡ȶ */ +#define IAP_LEN 20 + +/* DataFlashOTAϢ */ +typedef struct +{ + unsigned char ImageFlag; //¼ĵǰimage־ + unsigned char Revd[3]; +}OTADataFlashInfo_t; + +/* OTA IAPͨѶЭ鶨 */ +/* ַʹ4ƫ */ +typedef union +{ + struct + { + unsigned char cmd; /* 0x81 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char block_num[2]; /* */ + + } erase; /* */ + struct + { + unsigned char cmd; /* 0x83 */ + unsigned char len; /* ݳ */ + unsigned char status[2]; /* ֽ״̬ */ + } end; /* */ + struct + { + unsigned char cmd; /* 0x82 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* Уַ */ + unsigned char buf[IAP_LEN-4]; /* У */ + } verify; /* У */ + struct + { + unsigned char cmd; /* 0x80 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char buf[IAP_LEN-4]; /* */ + } program; /* */ + struct + { + unsigned char cmd; /* 0x84 */ + unsigned char len; /* ݳ */ + unsigned char buf[IAP_LEN-2]; /* */ + } info; /* */ + struct + { + unsigned char buf[IAP_LEN]; /* ݰ*/ + } other; +} OTA_IAP_CMD_t; + + +/* ¼ǰImage */ +extern unsigned char CurrImageFlag; + + +#endif + +/******************************** endfile @ oad ******************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/OTAprofile.c b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/OTAprofile.c new file mode 100644 index 0000000..21fe7cf --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/OTAprofile.c @@ -0,0 +1,338 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : OTAprofile.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : OTAͨѶӿ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "OTAprofile.h" +#include "CH579SFR.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// Simple GATT Profile Service UUID: 0xFFF0 +CONST uint8 OTAProfileServUUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(OTAPROFILE_SERV_UUID), HI_UINT16(OTAPROFILE_SERV_UUID) +}; + +// Characteristic 1 UUID: 0xFFF1 +CONST uint8 OTAProfilechar1UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(OTAPROFILE_CHAR_UUID), HI_UINT16(OTAPROFILE_CHAR_UUID) +}; + + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +static OTAProfileCBs_t *OTAProfile_AppCBs = NULL; + +/********************************************************************* + * Profile Attributes - variables + */ + +// Simple Profile Service attribute +static CONST gattAttrType_t OTAProfileService = { ATT_BT_UUID_SIZE, OTAProfileServUUID }; + + +// Simple Profile Characteristic 1 Properties +static uint8 OTAProfileCharProps = GATT_PROP_READ | GATT_PROP_WRITE | GATT_PROP_WRITE_NO_RSP; + +// Characteristic 1 Value +static uint8 OTAProfileChar = 0; + +// Simple Profile Characteristic 1 User Description +static uint8 OTAProfileCharUserDesp[12] = "OTA Channel"; + +// write and read buffer +static uint8 OTAProfileReadLen; +static uint8 OTAProfileReadBuf[20]; +static uint8 OTAProfileWriteLen; +static uint8 OTAProfileWriteBuf[20]; + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t OTAProfileAttrTbl[4] = +{ + // Simple Profile Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&OTAProfileService /* pValue */ + }, + + // Characteristic Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &OTAProfileCharProps + }, + + // Characteristic Value + { + { ATT_BT_UUID_SIZE, OTAProfilechar1UUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + &OTAProfileChar + }, + + // Characteristic User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + OTAProfileCharUserDesp + }, +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t OTAProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); +static bStatus_t OTAProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ); + +/********************************************************************* + * PROFILE CALLBACKS + */ +// OTA Profile Service Callbacks +gattServiceCBs_t OTAProfileCBs = +{ + OTAProfile_ReadAttrCB, // Read callback function pointer + OTAProfile_WriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + + +/******************************************************************************* +* Function Name : OTAProfile_AddService +* Description : OTA Profileʼ +* Input : services +* Output : None +* Return : ʼ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_AddService( uint32 services ) +{ + uint8 status = SUCCESS; + + if ( services & OTAPROFILE_SERVICE ) + { + // Register GATT attribute list and CBs with GATT Server App + status = GATTServApp_RegisterService( OTAProfileAttrTbl, + GATT_NUM_ATTRS( OTAProfileAttrTbl ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &OTAProfileCBs ); + } + + return ( status ); +} + +/******************************************************************************* +* Function Name : OTAProfile_RegisterAppCBs +* Description : OTA Profileдصע +* Input : appCallbacksṹָ +* Output : None +* Return : ִе״̬ +*******************************************************************************/ +bStatus_t OTAProfile_RegisterAppCBs( OTAProfileCBs_t *appCallbacks ) +{ + if ( appCallbacks ) + { + OTAProfile_AppCBs = appCallbacks; + + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } +} + + +/********************************************************************* + * @fn OTAProfile_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t OTAProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch ( uuid ) + { + case OTAPROFILE_CHAR_UUID: + { + *pLen = 0; + if( OTAProfileReadLen ) + { + *pLen = OTAProfileReadLen; + tmos_memcpy( pValue, OTAProfileReadBuf, OTAProfileReadLen ); + OTAProfileReadLen = 0; + if( OTAProfile_AppCBs && OTAProfile_AppCBs->pfnOTAProfileRead ) + { + OTAProfile_AppCBs->pfnOTAProfileRead(OTAPROFILE_CHAR); + } + } + break; + } + default: + { + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn OTAProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t OTAProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + //uint8 notifyApp = 0xFF; + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch ( uuid ) + { + case OTAPROFILE_CHAR_UUID: + { + //Write the value + if ( status == SUCCESS ) + { + uint16 i; + uint8 *p_rec_buf; + + OTAProfileWriteLen = len; + p_rec_buf = pValue; + for(i=0; ipfnOTAProfileWrite) + { + OTAProfile_AppCBs->pfnOTAProfileWrite(OTAPROFILE_CHAR,OTAProfileWriteBuf,OTAProfileWriteLen); + OTAProfileWriteLen = 0; + } + + return ( status ); +} + +/******************************************************************************* +* Function Name : OTAProfile_SendData +* Description : OTA Profileͨ +* Input : paramIDOTAͨѡ + p_dataָ + send_lenݳ +* Output : None +* Return : ִ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_SendData(unsigned char paramID ,unsigned char *p_data, unsigned char send_len ) +{ + bStatus_t status = SUCCESS; + + /* ݳȳΧ */ + if( send_len > 20 ) return 0xfe; + + OTAProfileReadLen = send_len; + tmos_memcpy( OTAProfileReadBuf, p_data, OTAProfileReadLen ); + + return status; +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/devinfoservice.c b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/devinfoservice.c new file mode 100644 index 0000000..c63f6a7 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/devinfoservice.c @@ -0,0 +1,631 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.c +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : 豸Ϣ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "devinfoservice.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// Device information service +CONST uint8 devInfoServUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Model Number String +CONST uint8 devInfoModelNumberUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Firmware Revision String +CONST uint8 devInfoFirmwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Software Revision String +CONST uint8 devInfoSoftwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// 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) +}; + +// PnP ID +CONST uint8 devInfoPnpIdUUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(PNP_ID_UUID), HI_UINT16(PNP_ID_UUID) +}; + + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +/********************************************************************* + * Profile Attributes - variables + */ + +// Device Information Service attribute +static CONST gattAttrType_t devInfoService = { ATT_BT_UUID_SIZE, devInfoServUUID }; + +// System ID characteristic +static uint8 devInfoSystemIdProps = GATT_PROP_READ; +static uint8 devInfoSystemId[DEVINFO_SYSTEM_ID_LEN] = {0, 0, 0, 0, 0, 0, 0, 0}; + +// Model Number String characteristic +static uint8 devInfoModelNumberProps = GATT_PROP_READ; +static const uint8 devInfoModelNumber[] = "Model Number"; + +// Serial Number String characteristic +static uint8 devInfoSerialNumberProps = GATT_PROP_READ; +static const uint8 devInfoSerialNumber[] = "Serial Number"; + +// Firmware Revision String characteristic +static uint8 devInfoFirmwareRevProps = GATT_PROP_READ; +static const uint8 devInfoFirmwareRev[] = "Firmware Revision"; + +// Hardware Revision String characteristic +static uint8 devInfoHardwareRevProps = GATT_PROP_READ; +static const uint8 devInfoHardwareRev[] = "Hardware Revision"; + +// Software Revision String characteristic +static uint8 devInfoSoftwareRevProps = GATT_PROP_READ; +static const uint8 devInfoSoftwareRev[] = "Software Revision"; + +// Manufacturer Name String characteristic +static uint8 devInfoMfrNameProps = GATT_PROP_READ; +static const uint8 devInfoMfrName[] = "Manufacturer Name"; + +// IEEE 11073-20601 Regulatory Certification Data List characteristic +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: + 'e', 'x', 'p', 'e', 'r', 'i', 'm', 'e', 'n', 't', 'a', 'l' +}; + +// System ID characteristic +static uint8 devInfoPnpIdProps = GATT_PROP_READ; +static uint8 devInfoPnpId[DEVINFO_PNP_ID_LEN] = +{ + 1, // Vendor ID source (1=Bluetooth SIG) + LO_UINT16(0x07D7), HI_UINT16(0x07D7), // Vendor ID (WCH) + LO_UINT16(0x0000), HI_UINT16(0x0000), // Product ID (vendor-specific) + LO_UINT16(0x0110), HI_UINT16(0x0110) // Product version (JJ.M.N) +}; + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t devInfoAttrTbl[] = +{ + // Device Information Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&devInfoService /* pValue */ + }, + + // System ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSystemIdProps + }, + + // System ID Value + { + { ATT_BT_UUID_SIZE, devInfoSystemIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSystemId + }, + + // Model Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoModelNumberProps + }, + + // Model Number Value + { + { ATT_BT_UUID_SIZE, devInfoModelNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoModelNumber + }, + + // Serial Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSerialNumberProps + }, + + // Serial Number Value + { + { ATT_BT_UUID_SIZE, devInfoSerialNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSerialNumber + }, + + // Firmware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoFirmwareRevProps + }, + + // Firmware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoFirmwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoFirmwareRev + }, + + // Hardware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoHardwareRevProps + }, + + // Hardware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoHardwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoHardwareRev + }, + + // Software Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSoftwareRevProps + }, + + // Software Revision Value + { + { ATT_BT_UUID_SIZE, devInfoSoftwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSoftwareRev + }, + + // Manufacturer Name String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoMfrNameProps + }, + + // Manufacturer Name Value + { + { ATT_BT_UUID_SIZE, devInfoMfrNameUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoMfrName + }, + + // IEEE 11073-20601 Regulatory Certification Data List Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfo11073CertProps + }, + + // IEEE 11073-20601 Regulatory Certification Data List Value + { + { ATT_BT_UUID_SIZE, devInfo11073CertUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfo11073Cert + }, + + // PnP ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoPnpIdProps + }, + + // PnP ID Value + { + { ATT_BT_UUID_SIZE, devInfoPnpIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoPnpId + } +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Device Info Service Callbacks +gattServiceCBs_t devInfoCBs = +{ + devInfo_ReadAttrCB, // Read callback function pointer + NULL, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * NETWORK LAYER CALLBACKS + */ + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn DevInfo_AddService + * + * @brief Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + * @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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &devInfoCBs ); +} + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(devInfoSystemId, value, len); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn DevInfo_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(value, devInfoSystemId, sizeof(devInfoSystemId)); + break; + + case DEVINFO_MODEL_NUMBER: + tmos_memcpy(value, devInfoModelNumber, sizeof(devInfoModelNumber)); + break; + case DEVINFO_SERIAL_NUMBER: + tmos_memcpy(value, devInfoSerialNumber, sizeof(devInfoSerialNumber)); + break; + + case DEVINFO_FIRMWARE_REV: + tmos_memcpy(value, devInfoFirmwareRev, sizeof(devInfoFirmwareRev)); + break; + + case DEVINFO_HARDWARE_REV: + tmos_memcpy(value, devInfoHardwareRev, sizeof(devInfoHardwareRev)); + break; + + case DEVINFO_SOFTWARE_REV: + tmos_memcpy(value, devInfoSoftwareRev, sizeof(devInfoSoftwareRev)); + break; + + case DEVINFO_MANUFACTURER_NAME: + tmos_memcpy(value, devInfoMfrName, sizeof(devInfoMfrName)); + break; + + case DEVINFO_11073_CERT_DATA: + tmos_memcpy(value, devInfo11073Cert, sizeof(devInfo11073Cert)); + break; + + case DEVINFO_PNP_ID: + tmos_memcpy(value, devInfoPnpId, sizeof(devInfoPnpId)); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn devInfo_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch (uuid) + { + case SYSTEM_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoSystemId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoSystemId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSystemId[offset], *pLen); + } + break; + + case MODEL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoModelNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoModelNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoModelNumber[offset], *pLen); + } + break; + + case SERIAL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoSerialNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSerialNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSerialNumber[offset], *pLen); + } + break; + + case FIRMWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoFirmwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoFirmwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoFirmwareRev[offset], *pLen); + } + break; + + case HARDWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoHardwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoHardwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoHardwareRev[offset], *pLen); + } + break; + + case SOFTWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoSoftwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSoftwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSoftwareRev[offset], *pLen); + } + break; + + case MANUFACTURER_NAME_UUID: + // verify offset + if (offset >= (sizeof(devInfoMfrName) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoMfrName) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoMfrName[offset], *pLen); + } + break; + + case IEEE_11073_CERT_DATA_UUID: + // verify offset + if (offset >= sizeof(devInfo11073Cert)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfo11073Cert) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfo11073Cert[offset], *pLen); + } + break; + + case PNP_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoPnpId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoPnpId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoPnpId[offset], *pLen); + } + break; + + default: + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + + return ( status ); +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/gattprofile.c b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/gattprofile.c new file mode 100644 index 0000000..27c745c --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/gattprofile.c @@ -0,0 +1,702 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : GATTprofile.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ԶֲͬԵķ񣬰ɶд֪ͨɶдȫɶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "GATTprofile.h" + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +#define SERVAPP_NUM_ATTR_SUPPORTED 17 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// 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: 0xFFF1 +CONST uint8 simpleProfilechar1UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR1_UUID), HI_UINT16(SIMPLEPROFILE_CHAR1_UUID) +}; + +// Characteristic 2 UUID: 0xFFF2 +CONST uint8 simpleProfilechar2UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR2_UUID), HI_UINT16(SIMPLEPROFILE_CHAR2_UUID) +}; + +// Characteristic 3 UUID: 0xFFF3 +CONST uint8 simpleProfilechar3UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR3_UUID), HI_UINT16(SIMPLEPROFILE_CHAR3_UUID) +}; + +// Characteristic 4 UUID: 0xFFF4 +CONST uint8 simpleProfilechar4UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR4_UUID), HI_UINT16(SIMPLEPROFILE_CHAR4_UUID) +}; + +// Characteristic 5 UUID: 0xFFF5 +CONST uint8 simpleProfilechar5UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR5_UUID), HI_UINT16(SIMPLEPROFILE_CHAR5_UUID) +}; + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +static simpleProfileCBs_t *simpleProfile_AppCBs = NULL; + +/********************************************************************* + * Profile Attributes - variables + */ + +// Simple Profile Service attribute +static CONST gattAttrType_t simpleProfileService = { ATT_BT_UUID_SIZE, simpleProfileServUUID }; + + +// Simple Profile Characteristic 1 Properties +static uint8 simpleProfileChar1Props = GATT_PROP_READ | GATT_PROP_WRITE; + +// Characteristic 1 Value +static uint8 simpleProfileChar1 = 0; + +// Simple Profile Characteristic 1 User Description +static uint8 simpleProfileChar1UserDesp[17] = "Characteristic 1\0"; + + +// Simple Profile Characteristic 2 Properties +static uint8 simpleProfileChar2Props = GATT_PROP_READ; + +// Characteristic 2 Value +static uint8 simpleProfileChar2 = 0; + +// Simple Profile Characteristic 2 User Description +static uint8 simpleProfileChar2UserDesp[17] = "Characteristic 2\0"; + + +// Simple Profile Characteristic 3 Properties +static uint8 simpleProfileChar3Props = GATT_PROP_WRITE; + +// Characteristic 3 Value +static uint8 simpleProfileChar3 = 0; + +// Simple Profile Characteristic 3 User Description +static uint8 simpleProfileChar3UserDesp[17] = "Characteristic 3\0"; + + +// Simple Profile Characteristic 4 Properties +static uint8 simpleProfileChar4Props = GATT_PROP_NOTIFY; + +// Characteristic 4 Value +static uint8 simpleProfileChar4 = 0; + +// Simple Profile Characteristic 4 Configuration Each client has its own +// instantiation of the Client Characteristic Configuration. Reads of the +// Client Characteristic Configuration only shows the configuration for +// that client and writes only affect the configuration of that client. +static gattCharCfg_t simpleProfileChar4Config[4]; + +// Simple Profile Characteristic 4 User Description +static uint8 simpleProfileChar4UserDesp[17] = "Characteristic 4\0"; + + +// Simple Profile Characteristic 5 Properties +static uint8 simpleProfileChar5Props = GATT_PROP_READ; + +// Characteristic 5 Value +static uint8 simpleProfileChar5[SIMPLEPROFILE_CHAR5_LEN] = { 0, 0, 0, 0, 0 }; + +// Simple Profile Characteristic 5 User Description +static uint8 simpleProfileChar5UserDesp[17] = "Characteristic 5\0"; + + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t simpleProfileAttrTbl[SERVAPP_NUM_ATTR_SUPPORTED] = +{ + // Simple Profile Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&simpleProfileService /* pValue */ + }, + + // Characteristic 1 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar1Props + }, + + // Characteristic Value 1 + { + { ATT_BT_UUID_SIZE, simpleProfilechar1UUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + &simpleProfileChar1 + }, + + // Characteristic 1 User Description + { + { 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, + 0, + &simpleProfileChar2 + }, + + // Characteristic 2 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar2UserDesp + }, + + // Characteristic 3 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar3Props + }, + + // Characteristic Value 3 + { + { ATT_BT_UUID_SIZE, simpleProfilechar3UUID }, + GATT_PERMIT_WRITE, + 0, + &simpleProfileChar3 + }, + + // Characteristic 3 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar3UserDesp + }, + + // Characteristic 4 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar4Props + }, + + // Characteristic Value 4 + { + { ATT_BT_UUID_SIZE, simpleProfilechar4UUID }, + 0, + 0, + &simpleProfileChar4 + }, + + // Characteristic 4 configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8 *)simpleProfileChar4Config + }, + + // Characteristic 4 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar4UserDesp + }, + + // Characteristic 5 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar5Props + }, + + // Characteristic Value 5 + { + { ATT_BT_UUID_SIZE, simpleProfilechar5UUID }, + GATT_PERMIT_AUTHEN_READ, + 0, + simpleProfileChar5 + }, + + // Characteristic 5 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar5UserDesp + }, + + +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ); + +static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); + + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Simple Profile Service Callbacks +gattServiceCBs_t simpleProfileCBs = +{ + simpleProfile_ReadAttrCB, // Read callback function pointer + simpleProfile_WriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn SimpleProfile_AddService + * + * @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. + * + * @return Success or Failure + */ +bStatus_t SimpleProfile_AddService( uint32 services ) +{ + uint8 status = SUCCESS; + + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar4Config ); + + // Register with Link DB to receive link status change callback + 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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &simpleProfileCBs ); + } + + return ( status ); +} + + +/********************************************************************* + * @fn SimpleProfile_RegisterAppCBs + * + * @brief Registers the application callback function. Only call + * this function once. + * + * @param callbacks - pointer to application callbacks. + * + * @return SUCCESS or bleAlreadyInRequestedMode + */ +bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) +{ + if ( appCallbacks ) + { + simpleProfile_AppCBs = appCallbacks; + + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } +} + + +/********************************************************************* + * @fn SimpleProfile_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar1 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR2: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar2 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR3: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar3 = *((uint8*)value); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR4: + if ( len == sizeof ( uint8 ) ) + { + simpleProfileChar4 = *((uint8*)value); + + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR5: + if ( len == SIMPLEPROFILE_CHAR5_LEN ) + { + tmos_memcpy( simpleProfileChar5, value, SIMPLEPROFILE_CHAR5_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn SimpleProfile_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + *((uint8*)value) = simpleProfileChar1; + break; + + case SIMPLEPROFILE_CHAR2: + *((uint8*)value) = simpleProfileChar2; + break; + + case SIMPLEPROFILE_CHAR3: + *((uint8*)value) = simpleProfileChar3; + break; + + case SIMPLEPROFILE_CHAR4: + *((uint8*)value) = simpleProfileChar4; + break; + + case SIMPLEPROFILE_CHAR5: + tmos_memcpy( value, simpleProfileChar5, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn simpleProfile_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + + // If attribute permissions require authorization to read, return error + if ( gattPermitAuthorRead( pAttr->permissions ) ) + { + // 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 + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + // No need for "GATT_SERVICE_UUID" or "GATT_CLIENT_CHAR_CFG_UUID" cases; + // gattserverapp handles those reads + + // characteristics 1 and 2 have read permissions + // characteritisc 3 does not have read permissions; therefore it is not + // included here + // characteristic 4 does not have read permissions, but because it + // can be sent as a notification, it is included here + case SIMPLEPROFILE_CHAR1_UUID: + case SIMPLEPROFILE_CHAR2_UUID: + case SIMPLEPROFILE_CHAR4_UUID: + *pLen = 1; + pValue[0] = *pAttr->pValue; + break; + + case SIMPLEPROFILE_CHAR5_UUID: + *pLen = SIMPLEPROFILE_CHAR5_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint8 notifyApp = 0xFF; + + // If attribute permissions require authorization to write, return error + if ( gattPermitAuthorWrite( pAttr->permissions ) ) + { + // Insufficient authorization + return ( ATT_ERR_INSUFFICIENT_AUTHOR ); + } + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + case SIMPLEPROFILE_CHAR1_UUID: + case SIMPLEPROFILE_CHAR3_UUID: + + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len != 1 ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + uint8 *pCurValue = (uint8 *)pAttr->pValue; + *pCurValue = pValue[0]; + + if( pAttr->pValue == &simpleProfileChar1 ) + { + notifyApp = SIMPLEPROFILE_CHAR1; + } + else + { + notifyApp = SIMPLEPROFILE_CHAR3; + } + } + + break; + + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); + break; + + default: + // Should never get here! (characteristics 2 and 4 do not have write permissions) + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + status = ATT_ERR_INVALID_HANDLE; + } + + // 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 ); + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_HandleConnStatusCB + * + * @brief Simple Profile link status change handler function. + * + * @param connHandle - connection handle + * @param changeType - type of change + * + * @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 ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, simpleProfileChar4Config ); + } + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/OTAprofile.h b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/OTAprofile.h new file mode 100644 index 0000000..b786bd3 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/OTAprofile.h @@ -0,0 +1,98 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : OTAprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : +*******************************************************************************/ + +#ifndef OTAPROFILE_H +#define OTAPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// OTA ProfileͨIndex +#define OTAPROFILE_CHAR 0 + +// OTA UUID +#define OTAPROFILE_SERV_UUID 0xFEE0 + +// OTA ͨѶͨUUID +#define OTAPROFILE_CHAR_UUID 0xFEE1 + +// Simple Keys Profile Services bit fields +#define OTAPROFILE_SERVICE 0x00000001 + + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// дص +typedef void (*OTAProfileRead_t)( unsigned char paramID ); +typedef void (*OTAProfileWrite_t)( unsigned char paramID ,unsigned char *p_data, unsigned char w_len); + +typedef struct +{ + OTAProfileRead_t pfnOTAProfileRead; + OTAProfileWrite_t pfnOTAProfileWrite; +} OTAProfileCBs_t; + +/********************************************************************* + * API FUNCTIONS + */ + +/******************************************************************************* +* Function Name : OTAProfile_AddService +* Description : OTA Profileʼ +* Input : services +* Output : None +* Return : ʼ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_AddService( uint32 services ); +/******************************************************************************* +* Function Name : OTAProfile_RegisterAppCBs +* Description : OTA Profileдصע +* Input : appCallbacksṹָ +* Output : None +* Return : ִе״̬ +*******************************************************************************/ +bStatus_t OTAProfile_RegisterAppCBs( OTAProfileCBs_t *appCallbacks ); +/******************************************************************************* +* Function Name : OTAProfile_SendData +* Description : OTA Profileͨ +* Input : paramIDOTAͨѡ + p_dataָ + send_lenݳ +* Output : None +* Return : ִ״̬ +*******************************************************************************/ +bStatus_t OTAProfile_SendData(unsigned char paramID ,unsigned char *p_data, unsigned char send_len ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/devinfoservice.h b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/devinfoservice.h new file mode 100644 index 0000000..a808937 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/devinfoservice.h @@ -0,0 +1,108 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef DEVINFOSERVICE_H +#define DEVINFOSERVICE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * 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 + +// 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 + +// System ID length +#define DEVINFO_SYSTEM_ID_LEN 8 + + // PnP ID length +#define DEVINFO_PNP_ID_LEN 7 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + + +/********************************************************************* + * API FUNCTIONS + */ + +/* + * DevInfo_AddService- Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + */ + +extern bStatus_t DevInfo_AddService( void ); + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ); + +/* + * 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). + */ +extern bStatus_t DevInfo_GetParameter( uint8 param, void *value ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif /* DEVINFOSERVICE_H */ diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/gattprofile.h b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/gattprofile.h new file mode 100644 index 0000000..ad9e613 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/Profile/include/gattprofile.h @@ -0,0 +1,127 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : GATTprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef GATTPROFILE_H +#define GATTPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// 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 + +// Simple Profile Service UUID +#define SIMPLEPROFILE_SERV_UUID 0xFFE0 + +// Key Pressed UUID +#define SIMPLEPROFILE_CHAR1_UUID 0xFFE1 +#define SIMPLEPROFILE_CHAR2_UUID 0xFFE2 +#define SIMPLEPROFILE_CHAR3_UUID 0xFFE3 +#define SIMPLEPROFILE_CHAR4_UUID 0xFFE4 +#define SIMPLEPROFILE_CHAR5_UUID 0xFFE5 + +// Simple Keys Profile Services bit fields +#define SIMPLEPROFILE_SERVICE 0x00000001 + +// Length of Characteristic 5 in bytes +#define SIMPLEPROFILE_CHAR4_LEN 8 +#define SIMPLEPROFILE_CHAR5_LEN 5 + +/********************************************************************* + * TYPEDEFS + */ + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// Callback when a characteristic value has changed +typedef void (*simpleProfileChange_t)( uint8 paramID ); + +typedef struct +{ + simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes +} simpleProfileCBs_t; + + + +/********************************************************************* + * API FUNCTIONS + */ + + +/* + * SimpleProfile_AddService- Initializes the Simple GATT 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. + */ + +extern bStatus_t SimpleProfile_AddService( uint32 services ); + +/* + * SimpleProfile_RegisterAppCBs - Registers the application callback function. + * Only call this function once. + * + * 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). + */ +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). + */ +extern bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ); + + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/OnlyUpdateApp_IAP/Project/BLE.uvprojx b/src/EXAM/BLE/OnlyUpdateApp_IAP/Project/BLE.uvprojx new file mode 100644 index 0000000..ce5f666 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_IAP/Project/BLE.uvprojx @@ -0,0 +1,752 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\ImageOTA\obj\ + ImageOTA + 1 + 0 + 1 + 1 + 1 + .\ImageOTA\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x23800 + 0x2000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20006000 + 0x2000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,CH57xBLE_ROM + + ..\APP\include;..\Profile\include;..\..\HAL\include;..\..\LIB;..\..\..\SRC\CMSIS\Include;..\..\..\SRC\StdPeriphDriver\inc + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + ..\APP\include\ImageOTA.sct + + + + + + + + + + + app + + + OTAnobackup.c + 1 + ..\APP\OTAnobackup.c + + + OTAnobackup_main.c + 1 + ..\APP\OTAnobackup_main.c + + + + + profile + + + OTAprofile.c + 1 + ..\Profile\OTAprofile.c + + + + + drive + + + startup_ARMCM0.s + 2 + ..\..\..\SRC\Startup\startup_ARMCM0.s + + + CH57x_clk.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + 2 + 0 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 1 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_gpio.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + 2 + 0 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 1 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_sys.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + 2 + 0 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 1 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_uart1.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + 2 + 0 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 1 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_int.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + 2 + 9 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_pwr.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_flash.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_flash.c + + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + + + hal + + + MCU.c + 1 + ..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\HAL\SLEEP.c + + + + + config + + + config.h + 5 + ..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/include/ota.h b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/include/ota.h new file mode 100644 index 0000000..53ef264 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/include/ota.h @@ -0,0 +1,108 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : ota.h +* Author : WCH +* Version : V1.10 +* Date : 2018/12/14 +* Description : oadö +*******************************************************************************/ + + +/******************************************************************************/ +#ifndef __OTA_H +#define __OTA_H + + +/* ------------------------------------------------------------------------------------------------ + * OTA FLASH + * ------------------------------------------------------------------------------------------------ + */ + +/* ûcodeֳ飬ǰ146Kͺ8KֱimageAPPimageOTA ʣ96KΪ*/ + +/* FLASH */ +#define FLASH_BLOCK_SIZE 512 + +/* imageAPP */ +#define IMAGE_APP_FLAG 0x01 +#define IMAGE_APP_START_ADD 0 +#define IMAGE_APP_SIZE 0x23800 +#define IMAGE_APP_ENTRY_ADD (IMAGE_APP_START_ADD + 4) + +/* imageOTA */ +#define IMAGE_OTA_FLAG 0x02 +#define IMAGE_OTA_START_ADD (IMAGE_APP_START_ADD + IMAGE_APP_SIZE) +#define IMAGE_OTA_SIZE 0x2000 +#define IMAGE_OTA_ENTRY_ADD (IMAGE_OTA_START_ADD + 4) + + +/* IAP */ +/* ΪIAP */ +#define CMD_IAP_PROM 0x80 // IAP +#define CMD_IAP_ERASE 0x81 // IAP +#define CMD_IAP_VERIFY 0x82 // IAPУ +#define CMD_IAP_END 0x83 // IAP־ +#define CMD_IAP_INFO 0x84 // IAPȡ豸Ϣ + + +/* ֡ȶ */ +#define IAP_LEN 20 + +/* DataFlashOTAϢ */ +typedef struct +{ + unsigned char ImageFlag; //¼ĵǰimage־ + unsigned char Revd[3]; +}OTADataFlashInfo_t; + +/* OTA IAPͨѶЭ鶨 */ +/* ַʹ4ƫ */ +typedef union +{ + struct + { + unsigned char cmd; /* 0x81 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char block_num[2]; /* */ + + } erase; /* */ + struct + { + unsigned char cmd; /* 0x83 */ + unsigned char len; /* ݳ */ + unsigned char status[2]; /* ֽ״̬ */ + } end; /* */ + struct + { + unsigned char cmd; /* 0x82 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* Уַ */ + unsigned char buf[IAP_LEN-4]; /* У */ + } verify; /* У */ + struct + { + unsigned char cmd; /* 0x80 */ + unsigned char len; /* ݳ */ + unsigned char addr[2]; /* ַ */ + unsigned char buf[IAP_LEN-4]; /* */ + } program; /* */ + struct + { + unsigned char cmd; /* 0x84 */ + unsigned char len; /* ݳ */ + unsigned char buf[IAP_LEN-2]; /* */ + } info; /* */ + struct + { + unsigned char buf[IAP_LEN]; /* ݰ*/ + } other; +} OTA_IAP_CMD_t; + + +/* ¼ǰImage */ +extern unsigned char CurrImageFlag; + + +#endif + +/******************************** endfile @ oad ******************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/include/peripheral.h b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/include/peripheral.h new file mode 100644 index 0000000..d8596ef --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/include/peripheral.h @@ -0,0 +1,65 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef PERIPHERAL_H +#define PERIPHERAL_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// Peripheral Task Events +#define SBP_START_DEVICE_EVT 0x0001 +#define SBP_PERIODIC_EVT 0x0002 +#define SBP_READ_RSSI_EVT 0x0004 +#define SBP_PARAM_UPDATE_EVT 0x0008 + +/********************************************************************* + * MACROS + */ +typedef struct +{ + uint16 connHandle; // Connection handle of current connection + uint16 connInterval; + uint16 connSlaveLatency; + uint16 connTimeout; +} peripheralConnItem_t; + + +/********************************************************************* + * FUNCTIONS + */ + +/* + * Task Initialization for the BLE Application + */ +extern void Peripheral_Init( void ); + +/* + * Task Event Processor for the BLE Application + */ +extern uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/peripheral.c b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/peripheral.c new file mode 100644 index 0000000..5abed56 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/peripheral.c @@ -0,0 +1,691 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : peripheral.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ӻӦó򣬳ʼ㲥ӲȻ㲥 +* ӲͨԶ +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "devinfoservice.h" +#include "gattprofile.h" +#include "peripheral.h" +#include "ota.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// How often to perform periodic event +#define SBP_PERIODIC_EVT_PERIOD 1600 + +// How often to perform read rssi event +#define SBP_READ_RSSI_EVT_PERIOD 3200 + +// Parameter update delay +#define SBP_PARAM_UPDATE_DELAY 6400 + +// What is the advertising interval when device is discoverable (units of 625us, 80=50ms) +#define DEFAULT_ADVERTISING_INTERVAL 80 + +// Limited discoverable mode advertises for 30.72s, and then stops +// General discoverable mode advertises indefinitely +#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL + +// Minimum connection interval (units of 1.25ms, 20=25ms) +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 20 + +// Maximum connection interval (units of 1.25ms, 100=125ms) +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 100 + +// Slave latency to use parameter update +#define DEFAULT_DESIRED_SLAVE_LATENCY 0 + +// Supervision timeout value (units of 10ms, 100=1s) +#define DEFAULT_DESIRED_CONN_TIMEOUT 100 + +// Company Identifier: WCH +#define WCH_COMPANY_ID 0x07D7 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ +static uint8 Peripheral_TaskID = INVALID_TASK_ID; // Task ID for internal task/event processing + +// GAP - SCAN RSP data (max size = 31 bytes) +static uint8 scanRspData[ ] = +{ + // complete name + 0x12, // length of this data + GAP_ADTYPE_LOCAL_NAME_COMPLETE, + 'S', + 'i', + 'm', + 'p', + 'l', + 'e', + ' ', + 'P', + 'e', + 'r', + 'i', + 'p', + 'h', + 'e', + 'r', + 'a', + 'l', + // connection interval range + 0x05, // length of this data + GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE, + LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), // 100ms + HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ), + LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), // 1s + HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ), + + // Tx power level + 0x02, // length of this data + GAP_ADTYPE_POWER_LEVEL, + 0 // 0dBm +}; + +// GAP - Advertisement data (max size = 31 bytes, though this is +// best kept short to conserve power while advertisting) +static uint8 advertData[] = +{ + // Flags; this sets the device to use limited discoverable + // mode (advertises for 30 seconds at a time) instead of general + // discoverable mode (advertises indefinitely) + 0x02, // length of this data + GAP_ADTYPE_FLAGS, + DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED, + + // service UUID, to notify central devices what services are included + // in this peripheral + 0x03, // length of this data + GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all + LO_UINT16( SIMPLEPROFILE_SERV_UUID ), + HI_UINT16( SIMPLEPROFILE_SERV_UUID ) +}; + +// GAP GATT Attributes +static uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "Simple Peripheral"; + +// Connection item list +static peripheralConnItem_t peripheralConnList; + +/* Imageתַ */ +typedef int( *pImageTaskFn)( void ); +pImageTaskFn user_image_tasks; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ); +static void peripheralStateNotificationCB( gapRole_States_t newState ,gapRoleEvent_t * pEvent); +static void performPeriodicTask( void ); +static void simpleProfileChangeCB( uint8 paramID ); +static void peripheralParamUpdateCB( uint16 connHandle, uint16 connInterval, + uint16 connSlaveLatency, uint16 connTimeout ); +static void peripheralInitConnItem( peripheralConnItem_t* peripheralConnList ); +static void peripheralRssiCB( uint16 connHandle, int8 rssi ); +static void peripheralChar4Notify( uint8 *pValue, uint16 len ); +static void GotoResetVector(UINT32 entry_add); + +/********************************************************************* + * PROFILE CALLBACKS + */ + +// GAP Role Callbacks +static gapRolesCBs_t Peripheral_PeripheralCBs = +{ + peripheralStateNotificationCB, // Profile State Change Callbacks + peripheralRssiCB, // When a valid RSSI is read from controller (not used by application) + peripheralParamUpdateCB +}; + +// Broadcast Callbacks +static gapRolesBroadcasterCBs_t Broadcaster_BroadcasterCBs = +{ + NULL, // Not used in peripheral role + NULL // Receive scan request callback +}; + +// GAP Bond Manager Callbacks +static gapBondCBs_t Peripheral_BondMgrCBs = +{ + NULL, // Passcode callback (not used by application) + NULL // Pairing / Bonding state Callback (not used by application) +}; + +// Simple GATT Profile Callbacks +static simpleProfileCBs_t Peripheral_SimpleProfileCBs = +{ + simpleProfileChangeCB // Charactersitic value change callback +}; +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn Peripheral_Init + * + * @brief Initialization function for the 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 TMOS. This ID should be + * used to send messages and set timers. + * + * @return none + */ +void Peripheral_Init( ) +{ + Peripheral_TaskID = TMOS_ProcessEventRegister( Peripheral_ProcessEvent ); + + // Setup the GAP Peripheral Role Profile + { + uint8 initial_advertising_enable = TRUE; + uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL; + uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL; + + // Set the GAP Role Parameters + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); + GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); + GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); + GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval ); + GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval ); + } + + // Set the GAP Characteristics + GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); + + // Set advertising interval + { + uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; + + GAP_SetParamValue( TGAP_DISC_ADV_INT_MIN, advInt ); + GAP_SetParamValue( TGAP_DISC_ADV_INT_MAX, advInt ); + } + + // Setup the GAP Bond Manager + { + uint32 passkey = 0; // passkey "000000" + uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; + uint8 mitm = TRUE; + uint8 bonding = TRUE; + uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; + GAPBondMgr_SetParameter( GAPBOND_PERI_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); + GAPBondMgr_SetParameter( GAPBOND_PERI_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); + GAPBondMgr_SetParameter( GAPBOND_PERI_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); + GAPBondMgr_SetParameter( GAPBOND_PERI_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); + GAPBondMgr_SetParameter( GAPBOND_PERI_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); + } + + // 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 + + // Setup the SimpleProfile Characteristic Values + { + uint8 charValue1[SIMPLEPROFILE_CHAR1_LEN] = { 1 }; + uint8 charValue2[SIMPLEPROFILE_CHAR2_LEN] = { 2 }; + uint8 charValue3[SIMPLEPROFILE_CHAR3_LEN] = { 3 }; + uint8 charValue4[SIMPLEPROFILE_CHAR4_LEN] = { 4 }; + uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 }; + + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, SIMPLEPROFILE_CHAR1_LEN, charValue1 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, SIMPLEPROFILE_CHAR2_LEN, charValue2 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, SIMPLEPROFILE_CHAR3_LEN, charValue3 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, charValue4 ); + SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); + } + + // Init Connection Item + peripheralInitConnItem( &peripheralConnList ); + + // Register callback with SimpleGATTprofile + SimpleProfile_RegisterAppCBs( &Peripheral_SimpleProfileCBs ); + + // Register receive scan request callback + GAPRole_BroadcasterSetCB( &Broadcaster_BroadcasterCBs ); + + // Setup a delayed profile startup + tmos_set_event( Peripheral_TaskID, SBP_START_DEVICE_EVT ); +} + +/********************************************************************* + * @fn peripheralInitConnItem + * + * @brief Init Connection Item + * + * @param peripheralConnList - + * + * @return NULL + */ +static void peripheralInitConnItem( peripheralConnItem_t* peripheralConnList ) +{ + peripheralConnList->connHandle = GAP_CONNHANDLE_INIT; + peripheralConnList->connInterval = 0; + peripheralConnList->connSlaveLatency = 0; + peripheralConnList->connTimeout = 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessEvent + * + * @brief 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 TMOS assigned task ID. + * @param events - events to process. This is a bit map and can + * contain more than one event. + * + * @return events not processed + */ +uint16 Peripheral_ProcessEvent( uint8 task_id, uint16 events ) +{ + +// VOID task_id; // TMOS required parameter that isn't used in this function + + if ( events & SYS_EVENT_MSG ){ + uint8 *pMsg; + + if ( (pMsg = tmos_msg_receive( Peripheral_TaskID )) != NULL ){ + Peripheral_ProcessTMOSMsg( (tmos_event_hdr_t *)pMsg ); + // Release the TMOS message + tmos_msg_deallocate( pMsg ); + } + // return unprocessed events + return (events ^ SYS_EVENT_MSG); + } + + if ( events & SBP_START_DEVICE_EVT ){ + // Start the Device + GAPRole_PeripheralStartDevice( Peripheral_TaskID, &Peripheral_BondMgrCBs, &Peripheral_PeripheralCBs ); + return ( events ^ SBP_START_DEVICE_EVT ); + } + + if ( events & SBP_PERIODIC_EVT ) + { + // Restart timer + if ( SBP_PERIODIC_EVT_PERIOD ){ + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + } + // Perform periodic application task + performPeriodicTask(); + return (events ^ SBP_PERIODIC_EVT); + } + + if ( events & SBP_PARAM_UPDATE_EVT ) + { + // Send connect param update request + GAPRole_PeripheralConnParamUpdateReq( peripheralConnList.connHandle, + DEFAULT_DESIRED_MIN_CONN_INTERVAL, + DEFAULT_DESIRED_MAX_CONN_INTERVAL, + DEFAULT_DESIRED_SLAVE_LATENCY, + DEFAULT_DESIRED_CONN_TIMEOUT, + Peripheral_TaskID); + + return (events ^ SBP_PARAM_UPDATE_EVT); + } + + if ( events & SBP_READ_RSSI_EVT ) + { + GAPRole_ReadRssiCmd(peripheralConnList.connHandle); + tmos_start_task( Peripheral_TaskID, SBP_READ_RSSI_EVT, SBP_READ_RSSI_EVT_PERIOD ); + return (events ^ SBP_READ_RSSI_EVT); + } + + // Discard unknown events + return 0; +} + +/********************************************************************* + * @fn Peripheral_ProcessTMOSMsg + * + * @brief Process an incoming task message. + * + * @param pMsg - message to process + * + * @return none + */ +static void Peripheral_ProcessTMOSMsg( tmos_event_hdr_t *pMsg ) +{ + switch ( pMsg->event ){ + default: + break; + } +} + +/********************************************************************* + * @fn Peripheral_LinkEstablished + * + * @brief Process link established. + * + * @param pEvent - event to process + * + * @return none + */ +static void Peripheral_LinkEstablished( gapRoleEvent_t * pEvent ) +{ + gapEstLinkReqEvent_t *event = (gapEstLinkReqEvent_t *) pEvent; + + // See if already connected + if( peripheralConnList.connHandle != GAP_CONNHANDLE_INIT ) + { + GAPRole_TerminateLink( pEvent->linkCmpl.connectionHandle ); + PRINT( "Connection max...\n" ); + } + else + { + peripheralConnList.connHandle = event->connectionHandle; + peripheralConnList.connInterval = event->connInterval; + peripheralConnList.connSlaveLatency = event->connLatency; + peripheralConnList.connTimeout = event->connTimeout; + + // Set timer for periodic event + tmos_start_task( Peripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); + + // Set timer for param update event + tmos_start_task( Peripheral_TaskID, SBP_PARAM_UPDATE_EVT, SBP_PARAM_UPDATE_DELAY ); + + // Start read rssi + tmos_start_task( Peripheral_TaskID, SBP_READ_RSSI_EVT, SBP_READ_RSSI_EVT_PERIOD ); + + PRINT("Conn %x - Int %x \n", event->connectionHandle, event->connInterval); + } +} + +/********************************************************************* + * @fn Peripheral_LinkTerminated + * + * @brief Process link terminated. + * + * @param pEvent - event to process + * + * @return none + */ +static void Peripheral_LinkTerminated( gapRoleEvent_t * pEvent ) +{ + gapTerminateLinkEvent_t *event = (gapTerminateLinkEvent_t *) pEvent; + + if( event->connectionHandle == peripheralConnList.connHandle ) + { + peripheralConnList.connHandle = GAP_CONNHANDLE_INIT; + peripheralConnList.connInterval = 0; + peripheralConnList.connSlaveLatency = 0; + peripheralConnList.connTimeout = 0; + tmos_stop_task( Peripheral_TaskID, SBP_PERIODIC_EVT ); + tmos_stop_task( Peripheral_TaskID, SBP_READ_RSSI_EVT ); + + // Restart advertising + { + uint8 advertising_enable = TRUE; + GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &advertising_enable ); + } + } + else + { + PRINT("ERR..\n"); + } +} + +/********************************************************************* + * @fn peripheralRssiCB + * + * @brief RSSI callback. + * + * @param connHandle - connection handle + * @param rssi - RSSI + * + * @return none + */ +static void peripheralRssiCB( uint16 connHandle, int8 rssi ) +{ + PRINT( "RSSI -%d dB Conn %x \n", -rssi, connHandle); +} + +/********************************************************************* + * @fn peripheralParamUpdateCB + * + * @brief Parameter update complete callback + * + * @param connHandle - connect handle + * connInterval - connect interval + * connSlaveLatency - connect slave latency + * connTimeout - connect timeout + * + * @return none + */ +static void peripheralParamUpdateCB( uint16 connHandle, uint16 connInterval, + uint16 connSlaveLatency, uint16 connTimeout ) +{ + if( connHandle == peripheralConnList.connHandle ) + { + peripheralConnList.connInterval = connInterval; + peripheralConnList.connSlaveLatency = connSlaveLatency; + peripheralConnList.connTimeout = connTimeout; + + PRINT("Update %x - Int %x \n", connHandle, connInterval); + } + else + { + PRINT("ERR..\n"); + } +} + +/********************************************************************* + * @fn peripheralStateNotificationCB + * + * @brief Notification from the profile of a state change. + * + * @param newState - new state + * + * @return none + */ +static void peripheralStateNotificationCB( gapRole_States_t newState, gapRoleEvent_t * pEvent ) +{ + switch ( newState ) + { + case GAPROLE_STARTED: + PRINT( "Initialized..\n" ); + break; + + case GAPROLE_ADVERTISING: + if( pEvent->gap.opcode == GAP_LINK_TERMINATED_EVENT ) + { + Peripheral_LinkTerminated( pEvent ); + PRINT( "Disconnected.. Reason:%x\n",pEvent->linkTerminate.reason ); + } + PRINT( "Advertising..\n" ); + break; + + case GAPROLE_CONNECTED: + if( pEvent->gap.opcode == GAP_LINK_ESTABLISHED_EVENT ) + { + Peripheral_LinkEstablished( pEvent ); + } + PRINT( "Connected..\n" ); + break; + + case GAPROLE_CONNECTED_ADV: + PRINT( "Connected Advertising..\n" ); + break; + + case GAPROLE_WAITING: + if( pEvent->gap.opcode == GAP_END_DISCOVERABLE_DONE_EVENT ) + { + PRINT( "Waiting for advertising..\n" ); + } + else if( pEvent->gap.opcode == GAP_LINK_TERMINATED_EVENT ) + { + Peripheral_LinkTerminated( pEvent ); + PRINT( "Disconnected.. Reason:%x\n",pEvent->linkTerminate.reason ); + } + else if( pEvent->gap.opcode == GAP_LINK_ESTABLISHED_EVENT ) + { + if( pEvent->gap.hdr.status != SUCCESS ) + { + PRINT( "Waiting for advertising..\n" ); + } + else + { + PRINT( "Error..\n" ); + } + } + else + { + PRINT( "Error..%x\n",pEvent->gap.opcode ); + } + break; + + case GAPROLE_ERROR: + PRINT( "Error..\n" ); + break; + + default: + break; + } +} + +/********************************************************************* + * @fn performPeriodicTask + * + * @brief Perform a periodic application task. This function gets + * called every five seconds as a result of the SBP_PERIODIC_EVT + * TMOS event. In this example, the value of the third + * characteristic in the SimpleGATTProfile service is retrieved + * from the profile, and then copied into the value of the + * the fourth characteristic. + * + * @param none + * + * @return none + */ +static void performPeriodicTask( void ) +{ + uint8 notiData[SIMPLEPROFILE_CHAR4_LEN] = { 0x88 }; + peripheralChar4Notify( notiData, SIMPLEPROFILE_CHAR4_LEN ); +} + +/********************************************************************* + * @fn peripheralChar4Notify + * + * @brief Prepare and send simpleProfileChar4 notification + * + * @param pValue - data to notify + * len - length of data + * + * @return none + */ +static void peripheralChar4Notify( uint8 *pValue, uint16 len ) +{ + attHandleValueNoti_t noti; + noti.len = len; + noti.pValue = GATT_bm_alloc( peripheralConnList.connHandle, ATT_HANDLE_VALUE_NOTI, noti.len, NULL, 0 ); + tmos_memcpy( noti.pValue, pValue, noti.len ); + if( simpleProfile_Notify( peripheralConnList.connHandle, ¬i ) != SUCCESS ) + { + GATT_bm_free( (gattMsg_t *)¬i, ATT_HANDLE_VALUE_NOTI ); + } +} + +/********************************************************************* + * @fn simpleProfileChangeCB + * + * @brief Callback from SimpleBLEProfile indicating a value change + * + * @param paramID - parameter ID of the value that was changed. + * + * @return none + */ +static void simpleProfileChangeCB( uint8 paramID ) +{ + + switch( paramID ) + { + case SIMPLEPROFILE_CHAR1: + { + uint8 newValue[SIMPLEPROFILE_CHAR1_LEN]; + SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, newValue ); + PRINT("profile ChangeCB CHAR1.. \n"); + PRINT("Go to OTA.. \n"); + GotoResetVector( IMAGE_OTA_ENTRY_ADD ); + break; + } + + case SIMPLEPROFILE_CHAR3: + { + uint8 newValue[SIMPLEPROFILE_CHAR3_LEN]; + SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, newValue ); + PRINT("profile ChangeCB CHAR3..\n"); + break; + } + + default: + // should not reach here! + break; + } +} + +/******************************************************************************* +* Function Name : DisableAllIRQ +* Description : رеж +* Input : none +* Output : none +* Return : none +*******************************************************************************/ +void DisableAllIRQ(void) +{ + NVIC->ICER[0] = 0xffffffff; + SysTick->CTRL = 0; //رSysTickж +} + +/******************************************************************************* +* Function Name : GotoResetVector +* Description : ȡתַת +* Input : entry_addResetַ +* Output : none +* Return : none +*******************************************************************************/ +void GotoResetVector(UINT32 entry_add) +{ + DisableAllIRQ(); + user_image_tasks = (pImageTaskFn)(*(UINT32 *)(entry_add)); + (user_image_tasks)(); +} + + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/peripheral_main.c b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/peripheral_main.c new file mode 100644 index 0000000..13896f0 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/APP/peripheral_main.c @@ -0,0 +1,54 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : main.c +* Author : WCH +* Version : V1.1 +* Date : 2019/11/05 +* Description : ӻӦϵͳʼ +*******************************************************************************/ + +/******************************************************************************/ +/* ͷļ */ +#include "CONFIG.h" +#include "CH57x_common.h" +#include "HAL.h" +#include "gattprofile.h" +#include "peripheral.h" + +/********************************************************************* + * GLOBAL TYPEDEFS + */ +__align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4] __attribute__((at(0x20003800))); + +#if (defined (BLE_MAC)) && (BLE_MAC == TRUE) +u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; +#endif + +/******************************************************************************* +* Function Name : main +* Description : +* Input : None +* Output : None +* Return : None +*******************************************************************************/ +int main( void ) +{ +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) + GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif +#ifdef DEBUG + GPIOA_SetBits(bTXD1); + GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); + UART1_DefInit( ); +#endif + PRINT("%s\n",VER_LIB); + CH57X_BLEInit( ); + HAL_Init( ); + GAPRole_PeripheralInit( ); + Peripheral_Init( ); + while(1){ + TMOS_SystemProcess( ); + } +} + +/******************************** endfile @ main ******************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/devinfoservice.c b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/devinfoservice.c new file mode 100644 index 0000000..c63f6a7 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/devinfoservice.c @@ -0,0 +1,631 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.c +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : 豸Ϣ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "devinfoservice.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// Device information service +CONST uint8 devInfoServUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Model Number String +CONST uint8 devInfoModelNumberUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Firmware Revision String +CONST uint8 devInfoFirmwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// Software Revision String +CONST uint8 devInfoSoftwareRevUUID[ATT_BT_UUID_SIZE] = +{ + 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) +}; + +// 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) +}; + +// PnP ID +CONST uint8 devInfoPnpIdUUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(PNP_ID_UUID), HI_UINT16(PNP_ID_UUID) +}; + + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +/********************************************************************* + * Profile Attributes - variables + */ + +// Device Information Service attribute +static CONST gattAttrType_t devInfoService = { ATT_BT_UUID_SIZE, devInfoServUUID }; + +// System ID characteristic +static uint8 devInfoSystemIdProps = GATT_PROP_READ; +static uint8 devInfoSystemId[DEVINFO_SYSTEM_ID_LEN] = {0, 0, 0, 0, 0, 0, 0, 0}; + +// Model Number String characteristic +static uint8 devInfoModelNumberProps = GATT_PROP_READ; +static const uint8 devInfoModelNumber[] = "Model Number"; + +// Serial Number String characteristic +static uint8 devInfoSerialNumberProps = GATT_PROP_READ; +static const uint8 devInfoSerialNumber[] = "Serial Number"; + +// Firmware Revision String characteristic +static uint8 devInfoFirmwareRevProps = GATT_PROP_READ; +static const uint8 devInfoFirmwareRev[] = "Firmware Revision"; + +// Hardware Revision String characteristic +static uint8 devInfoHardwareRevProps = GATT_PROP_READ; +static const uint8 devInfoHardwareRev[] = "Hardware Revision"; + +// Software Revision String characteristic +static uint8 devInfoSoftwareRevProps = GATT_PROP_READ; +static const uint8 devInfoSoftwareRev[] = "Software Revision"; + +// Manufacturer Name String characteristic +static uint8 devInfoMfrNameProps = GATT_PROP_READ; +static const uint8 devInfoMfrName[] = "Manufacturer Name"; + +// IEEE 11073-20601 Regulatory Certification Data List characteristic +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: + 'e', 'x', 'p', 'e', 'r', 'i', 'm', 'e', 'n', 't', 'a', 'l' +}; + +// System ID characteristic +static uint8 devInfoPnpIdProps = GATT_PROP_READ; +static uint8 devInfoPnpId[DEVINFO_PNP_ID_LEN] = +{ + 1, // Vendor ID source (1=Bluetooth SIG) + LO_UINT16(0x07D7), HI_UINT16(0x07D7), // Vendor ID (WCH) + LO_UINT16(0x0000), HI_UINT16(0x0000), // Product ID (vendor-specific) + LO_UINT16(0x0110), HI_UINT16(0x0110) // Product version (JJ.M.N) +}; + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t devInfoAttrTbl[] = +{ + // Device Information Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&devInfoService /* pValue */ + }, + + // System ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSystemIdProps + }, + + // System ID Value + { + { ATT_BT_UUID_SIZE, devInfoSystemIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSystemId + }, + + // Model Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoModelNumberProps + }, + + // Model Number Value + { + { ATT_BT_UUID_SIZE, devInfoModelNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoModelNumber + }, + + // Serial Number String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSerialNumberProps + }, + + // Serial Number Value + { + { ATT_BT_UUID_SIZE, devInfoSerialNumberUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSerialNumber + }, + + // Firmware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoFirmwareRevProps + }, + + // Firmware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoFirmwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoFirmwareRev + }, + + // Hardware Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoHardwareRevProps + }, + + // Hardware Revision Value + { + { ATT_BT_UUID_SIZE, devInfoHardwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoHardwareRev + }, + + // Software Revision String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoSoftwareRevProps + }, + + // Software Revision Value + { + { ATT_BT_UUID_SIZE, devInfoSoftwareRevUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoSoftwareRev + }, + + // Manufacturer Name String Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoMfrNameProps + }, + + // Manufacturer Name Value + { + { ATT_BT_UUID_SIZE, devInfoMfrNameUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoMfrName + }, + + // IEEE 11073-20601 Regulatory Certification Data List Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfo11073CertProps + }, + + // IEEE 11073-20601 Regulatory Certification Data List Value + { + { ATT_BT_UUID_SIZE, devInfo11073CertUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfo11073Cert + }, + + // PnP ID Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &devInfoPnpIdProps + }, + + // PnP ID Value + { + { ATT_BT_UUID_SIZE, devInfoPnpIdUUID }, + GATT_PERMIT_READ, + 0, + (uint8 *) devInfoPnpId + } +}; + + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Device Info Service Callbacks +gattServiceCBs_t devInfoCBs = +{ + devInfo_ReadAttrCB, // Read callback function pointer + NULL, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * NETWORK LAYER CALLBACKS + */ + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn DevInfo_AddService + * + * @brief Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + * @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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &devInfoCBs ); +} + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(devInfoSystemId, value, len); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn DevInfo_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + + switch ( param ) + { + case DEVINFO_SYSTEM_ID: + tmos_memcpy(value, devInfoSystemId, sizeof(devInfoSystemId)); + break; + + case DEVINFO_MODEL_NUMBER: + tmos_memcpy(value, devInfoModelNumber, sizeof(devInfoModelNumber)); + break; + case DEVINFO_SERIAL_NUMBER: + tmos_memcpy(value, devInfoSerialNumber, sizeof(devInfoSerialNumber)); + break; + + case DEVINFO_FIRMWARE_REV: + tmos_memcpy(value, devInfoFirmwareRev, sizeof(devInfoFirmwareRev)); + break; + + case DEVINFO_HARDWARE_REV: + tmos_memcpy(value, devInfoHardwareRev, sizeof(devInfoHardwareRev)); + break; + + case DEVINFO_SOFTWARE_REV: + tmos_memcpy(value, devInfoSoftwareRev, sizeof(devInfoSoftwareRev)); + break; + + case DEVINFO_MANUFACTURER_NAME: + tmos_memcpy(value, devInfoMfrName, sizeof(devInfoMfrName)); + break; + + case DEVINFO_11073_CERT_DATA: + tmos_memcpy(value, devInfo11073Cert, sizeof(devInfo11073Cert)); + break; + + case DEVINFO_PNP_ID: + tmos_memcpy(value, devInfoPnpId, sizeof(devInfoPnpId)); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn devInfo_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t devInfo_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + + switch (uuid) + { + case SYSTEM_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoSystemId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoSystemId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSystemId[offset], *pLen); + } + break; + + case MODEL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoModelNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoModelNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoModelNumber[offset], *pLen); + } + break; + + case SERIAL_NUMBER_UUID: + // verify offset + if (offset >= (sizeof(devInfoSerialNumber) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSerialNumber) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSerialNumber[offset], *pLen); + } + break; + + case FIRMWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoFirmwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoFirmwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoFirmwareRev[offset], *pLen); + } + break; + + case HARDWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoHardwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoHardwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoHardwareRev[offset], *pLen); + } + break; + + case SOFTWARE_REV_UUID: + // verify offset + if (offset >= (sizeof(devInfoSoftwareRev) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoSoftwareRev) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoSoftwareRev[offset], *pLen); + } + break; + + case MANUFACTURER_NAME_UUID: + // verify offset + if (offset >= (sizeof(devInfoMfrName) - 1)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length (exclude null terminating character) + *pLen = MIN(maxLen, ((sizeof(devInfoMfrName) - 1) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoMfrName[offset], *pLen); + } + break; + + case IEEE_11073_CERT_DATA_UUID: + // verify offset + if (offset >= sizeof(devInfo11073Cert)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfo11073Cert) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfo11073Cert[offset], *pLen); + } + break; + + case PNP_ID_UUID: + // verify offset + if (offset >= sizeof(devInfoPnpId)) + { + status = ATT_ERR_INVALID_OFFSET; + } + else + { + // determine read length + *pLen = MIN(maxLen, (sizeof(devInfoPnpId) - offset)); + + // copy data + tmos_memcpy(pValue, &devInfoPnpId[offset], *pLen); + } + break; + + default: + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + + return ( status ); +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/gattprofile.c b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/gattprofile.c new file mode 100644 index 0000000..8edb945 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/gattprofile.c @@ -0,0 +1,744 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : gattprofile.C +* Author : WCH +* Version : V1.0 +* Date : 2018/12/10 +* Description : ԶֲͬԵķ񣬰ɶд֪ͨɶдȫɶ + +*******************************************************************************/ + +/********************************************************************* + * INCLUDES + */ +#include "CONFIG.h" +#include "gattprofile.h" + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * CONSTANTS + */ + +// Position of simpleProfilechar4 value in attribute array +#define SIMPLEPROFILE_CHAR4_VALUE_POS 11 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * GLOBAL VARIABLES + */ +// 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: 0xFFF1 +CONST uint8 simpleProfilechar1UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR1_UUID), HI_UINT16(SIMPLEPROFILE_CHAR1_UUID) +}; + +// Characteristic 2 UUID: 0xFFF2 +CONST uint8 simpleProfilechar2UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR2_UUID), HI_UINT16(SIMPLEPROFILE_CHAR2_UUID) +}; + +// Characteristic 3 UUID: 0xFFF3 +CONST uint8 simpleProfilechar3UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR3_UUID), HI_UINT16(SIMPLEPROFILE_CHAR3_UUID) +}; + +// Characteristic 4 UUID: 0xFFF4 +CONST uint8 simpleProfilechar4UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR4_UUID), HI_UINT16(SIMPLEPROFILE_CHAR4_UUID) +}; + +// Characteristic 5 UUID: 0xFFF5 +CONST uint8 simpleProfilechar5UUID[ATT_BT_UUID_SIZE] = +{ + LO_UINT16(SIMPLEPROFILE_CHAR5_UUID), HI_UINT16(SIMPLEPROFILE_CHAR5_UUID) +}; + +/********************************************************************* + * EXTERNAL VARIABLES + */ + +/********************************************************************* + * EXTERNAL FUNCTIONS + */ + +/********************************************************************* + * LOCAL VARIABLES + */ + +static simpleProfileCBs_t *simpleProfile_AppCBs = NULL; + +/********************************************************************* + * Profile Attributes - variables + */ + +// Simple Profile Service attribute +static CONST gattAttrType_t simpleProfileService = { ATT_BT_UUID_SIZE, simpleProfileServUUID }; + + +// Simple Profile Characteristic 1 Properties +static uint8 simpleProfileChar1Props = GATT_PROP_READ | GATT_PROP_WRITE; + +// Characteristic 1 Value +static uint8 simpleProfileChar1[SIMPLEPROFILE_CHAR1_LEN] = { 0 }; + +// Simple Profile Characteristic 1 User Description +static uint8 simpleProfileChar1UserDesp[] = "Characteristic 1\0"; + + +// Simple Profile Characteristic 2 Properties +static uint8 simpleProfileChar2Props = GATT_PROP_READ; + +// Characteristic 2 Value +static uint8 simpleProfileChar2[SIMPLEPROFILE_CHAR2_LEN] = { 0 }; + +// Simple Profile Characteristic 2 User Description +static uint8 simpleProfileChar2UserDesp[] = "Characteristic 2\0"; + + +// Simple Profile Characteristic 3 Properties +static uint8 simpleProfileChar3Props = GATT_PROP_WRITE; + +// Characteristic 3 Value +static uint8 simpleProfileChar3[SIMPLEPROFILE_CHAR3_LEN] = { 0 }; + +// Simple Profile Characteristic 3 User Description +static uint8 simpleProfileChar3UserDesp[] = "Characteristic 3\0"; + + +// Simple Profile Characteristic 4 Properties +static uint8 simpleProfileChar4Props = GATT_PROP_NOTIFY; + +// Characteristic 4 Value +static uint8 simpleProfileChar4[SIMPLEPROFILE_CHAR4_LEN] = { 0 }; + +// Simple Profile Characteristic 4 Configuration Each client has its own +// instantiation of the Client Characteristic Configuration. Reads of the +// Client Characteristic Configuration only shows the configuration for +// that client and writes only affect the configuration of that client. +static gattCharCfg_t simpleProfileChar4Config[4]; + +// Simple Profile Characteristic 4 User Description +static uint8 simpleProfileChar4UserDesp[] = "Characteristic 4\0"; + + +// Simple Profile Characteristic 5 Properties +static uint8 simpleProfileChar5Props = GATT_PROP_READ; + +// Characteristic 5 Value +static uint8 simpleProfileChar5[SIMPLEPROFILE_CHAR5_LEN] = { 0 }; + +// Simple Profile Characteristic 5 User Description +static uint8 simpleProfileChar5UserDesp[] = "Characteristic 5\0"; + + +/********************************************************************* + * Profile Attributes - Table + */ + +static gattAttribute_t simpleProfileAttrTbl[] = +{ + // Simple Profile Service + { + { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ + GATT_PERMIT_READ, /* permissions */ + 0, /* handle */ + (uint8 *)&simpleProfileService /* pValue */ + }, + + // Characteristic 1 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar1Props + }, + + // Characteristic Value 1 + { + { ATT_BT_UUID_SIZE, simpleProfilechar1UUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + simpleProfileChar1 + }, + + // Characteristic 1 User Description + { + { 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, + 0, + simpleProfileChar2 + }, + + // Characteristic 2 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar2UserDesp + }, + + // Characteristic 3 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar3Props + }, + + // Characteristic Value 3 + { + { ATT_BT_UUID_SIZE, simpleProfilechar3UUID }, + GATT_PERMIT_WRITE, + 0, + simpleProfileChar3 + }, + + // Characteristic 3 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar3UserDesp + }, + + // Characteristic 4 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar4Props + }, + + // Characteristic Value 4 + { + { ATT_BT_UUID_SIZE, simpleProfilechar4UUID }, + 0, + 0, + simpleProfileChar4 + }, + + // Characteristic 4 configuration + { + { ATT_BT_UUID_SIZE, clientCharCfgUUID }, + GATT_PERMIT_READ | GATT_PERMIT_WRITE, + 0, + (uint8 *)simpleProfileChar4Config + }, + + // Characteristic 4 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar4UserDesp + }, + + // Characteristic 5 Declaration + { + { ATT_BT_UUID_SIZE, characterUUID }, + GATT_PERMIT_READ, + 0, + &simpleProfileChar5Props + }, + + // Characteristic Value 5 + { + { ATT_BT_UUID_SIZE, simpleProfilechar5UUID }, + GATT_PERMIT_AUTHEN_READ, + 0, + simpleProfileChar5 + }, + + // Characteristic 5 User Description + { + { ATT_BT_UUID_SIZE, charUserDescUUID }, + GATT_PERMIT_READ, + 0, + simpleProfileChar5UserDesp + }, +}; + +/********************************************************************* + * LOCAL FUNCTIONS + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ); +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ); + +static void simpleProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); + + +/********************************************************************* + * PROFILE CALLBACKS + */ +// Simple Profile Service Callbacks +gattServiceCBs_t simpleProfileCBs = +{ + simpleProfile_ReadAttrCB, // Read callback function pointer + simpleProfile_WriteAttrCB, // Write callback function pointer + NULL // Authorization callback function pointer +}; + +/********************************************************************* + * PUBLIC FUNCTIONS + */ + +/********************************************************************* + * @fn SimpleProfile_AddService + * + * @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. + * + * @return Success or Failure + */ +bStatus_t SimpleProfile_AddService( uint32 services ) +{ + uint8 status = SUCCESS; + + // Initialize Client Characteristic Configuration attributes + GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar4Config ); + + // Register with Link DB to receive link status change callback + 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 ), + GATT_MAX_ENCRYPT_KEY_SIZE, + &simpleProfileCBs ); + } + + return ( status ); +} + + +/********************************************************************* + * @fn SimpleProfile_RegisterAppCBs + * + * @brief Registers the application callback function. Only call + * this function once. + * + * @param callbacks - pointer to application callbacks. + * + * @return SUCCESS or bleAlreadyInRequestedMode + */ +bStatus_t SimpleProfile_RegisterAppCBs( simpleProfileCBs_t *appCallbacks ) +{ + if ( appCallbacks ) + { + simpleProfile_AppCBs = appCallbacks; + + return ( SUCCESS ); + } + else + { + return ( bleAlreadyInRequestedMode ); + } +} + + +/********************************************************************* + * @fn SimpleProfile_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + if ( len == SIMPLEPROFILE_CHAR1_LEN ) + { + tmos_memcpy( simpleProfileChar1, value, SIMPLEPROFILE_CHAR1_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR2: + if ( len == SIMPLEPROFILE_CHAR2_LEN ) + { + tmos_memcpy( simpleProfileChar2, value, SIMPLEPROFILE_CHAR2_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR3: + if ( len == SIMPLEPROFILE_CHAR3_LEN ) + { + tmos_memcpy( simpleProfileChar3, value, SIMPLEPROFILE_CHAR3_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR4: + if ( len == SIMPLEPROFILE_CHAR4_LEN ) + { + tmos_memcpy( simpleProfileChar4, value, SIMPLEPROFILE_CHAR4_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + case SIMPLEPROFILE_CHAR5: + if ( len == SIMPLEPROFILE_CHAR5_LEN ) + { + tmos_memcpy( simpleProfileChar5, value, SIMPLEPROFILE_CHAR5_LEN ); + } + else + { + ret = bleInvalidRange; + } + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn SimpleProfile_GetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ) +{ + bStatus_t ret = SUCCESS; + switch ( param ) + { + case SIMPLEPROFILE_CHAR1: + tmos_memcpy( value, simpleProfileChar1, SIMPLEPROFILE_CHAR1_LEN ); + break; + + case SIMPLEPROFILE_CHAR2: + tmos_memcpy( value, simpleProfileChar2, SIMPLEPROFILE_CHAR2_LEN ); + break; + + case SIMPLEPROFILE_CHAR3: + tmos_memcpy( value, simpleProfileChar3, SIMPLEPROFILE_CHAR3_LEN ); + break; + + case SIMPLEPROFILE_CHAR4: + tmos_memcpy( value, simpleProfileChar4, SIMPLEPROFILE_CHAR4_LEN ); + break; + + case SIMPLEPROFILE_CHAR5: + tmos_memcpy( value, simpleProfileChar5, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + ret = INVALIDPARAMETER; + break; + } + + return ( ret ); +} + +/********************************************************************* + * @fn simpleProfile_Notify + * + * @brief Send a notification containing a heart rate + * measurement. + * + * @param connHandle - connection handle + * @param pNoti - pointer to notification structure + * + * @return Success or Failure + */ +bStatus_t simpleProfile_Notify( uint16 connHandle, attHandleValueNoti_t *pNoti ) +{ + uint16 value = GATTServApp_ReadCharCfg( connHandle, simpleProfileChar4Config ); + + // If notifications enabled + if ( value & GATT_CLIENT_CFG_NOTIFY ) + { + // Set the handle + pNoti->handle = simpleProfileAttrTbl[SIMPLEPROFILE_CHAR4_VALUE_POS].handle; + + // Send the notification + return GATT_Notification( connHandle, pNoti, FALSE ); + } + return bleIncorrectMode; +} + +/********************************************************************* + * @fn simpleProfile_ReadAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 *pLen, uint16 offset, uint16 maxLen,uint8 method ) +{ + bStatus_t status = SUCCESS; + + // If attribute permissions require authorization to read, return error + if ( gattPermitAuthorRead( pAttr->permissions ) ) + { + // 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 + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + // No need for "GATT_SERVICE_UUID" or "GATT_CLIENT_CHAR_CFG_UUID" cases; + // gattserverapp handles those reads + + // characteristics 1 and 2 have read permissions + // characteritisc 3 does not have read permissions; therefore it is not + // included here + // characteristic 4 does not have read permissions, but because it + // can be sent as a notification, it is included here + case SIMPLEPROFILE_CHAR1_UUID: + *pLen = SIMPLEPROFILE_CHAR1_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR1_LEN ); + break; + + case SIMPLEPROFILE_CHAR2_UUID: + *pLen = SIMPLEPROFILE_CHAR2_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR2_LEN ); + break; + + case SIMPLEPROFILE_CHAR4_UUID: + *pLen = SIMPLEPROFILE_CHAR4_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR4_LEN ); + break; + + case SIMPLEPROFILE_CHAR5_UUID: + *pLen = SIMPLEPROFILE_CHAR5_LEN; + tmos_memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR5_LEN ); + break; + + default: + // Should never get here! (characteristics 3 and 4 do not have read permissions) + *pLen = 0; + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + *pLen = 0; + status = ATT_ERR_INVALID_HANDLE; + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_WriteAttrCB + * + * @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 + * + * @return Success or Failure + */ +static bStatus_t simpleProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, + uint8 *pValue, uint16 len, uint16 offset,uint8 method ) +{ + bStatus_t status = SUCCESS; + uint8 notifyApp = 0xFF; + + // If attribute permissions require authorization to write, return error + if ( gattPermitAuthorWrite( pAttr->permissions ) ) + { + // Insufficient authorization + return ( ATT_ERR_INSUFFICIENT_AUTHOR ); + } + + if ( pAttr->type.len == ATT_BT_UUID_SIZE ) + { + // 16-bit UUID + uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); + switch ( uuid ) + { + case SIMPLEPROFILE_CHAR1_UUID: + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len > SIMPLEPROFILE_CHAR1_LEN ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + tmos_memcpy( pAttr->pValue, pValue, SIMPLEPROFILE_CHAR1_LEN ); + notifyApp = SIMPLEPROFILE_CHAR1; + } + break; + + case SIMPLEPROFILE_CHAR3_UUID: + //Validate the value + // Make sure it's not a blob oper + if ( offset == 0 ) + { + if ( len > SIMPLEPROFILE_CHAR3_LEN ) + { + status = ATT_ERR_INVALID_VALUE_SIZE; + } + } + else + { + status = ATT_ERR_ATTR_NOT_LONG; + } + + //Write the value + if ( status == SUCCESS ) + { + tmos_memcpy( pAttr->pValue, pValue, SIMPLEPROFILE_CHAR3_LEN ); + notifyApp = SIMPLEPROFILE_CHAR3; + } + break; + + case GATT_CLIENT_CHAR_CFG_UUID: + status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, + offset, GATT_CLIENT_CFG_NOTIFY ); + break; + + default: + // Should never get here! (characteristics 2 and 4 do not have write permissions) + status = ATT_ERR_ATTR_NOT_FOUND; + break; + } + } + else + { + // 128-bit UUID + status = ATT_ERR_INVALID_HANDLE; + } + + // 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 ); + } + + return ( status ); +} + +/********************************************************************* + * @fn simpleProfile_HandleConnStatusCB + * + * @brief Simple Profile link status change handler function. + * + * @param connHandle - connection handle + * @param changeType - type of change + * + * @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 ) ) ) ) + { + GATTServApp_InitCharCfg( connHandle, simpleProfileChar4Config ); + } + } +} + +/********************************************************************* +*********************************************************************/ diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/include/devinfoservice.h b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/include/devinfoservice.h new file mode 100644 index 0000000..a808937 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/include/devinfoservice.h @@ -0,0 +1,108 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : devinfoservice.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef DEVINFOSERVICE_H +#define DEVINFOSERVICE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * 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 + +// 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 + +// System ID length +#define DEVINFO_SYSTEM_ID_LEN 8 + + // PnP ID length +#define DEVINFO_PNP_ID_LEN 7 + +/********************************************************************* + * TYPEDEFS + */ + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + + +/********************************************************************* + * API FUNCTIONS + */ + +/* + * DevInfo_AddService- Initializes the Device Information service by registering + * GATT attributes with the GATT server. + * + */ + +extern bStatus_t DevInfo_AddService( void ); + +/********************************************************************* + * @fn DevInfo_SetParameter + * + * @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). + * + * @return bStatus_t + */ +bStatus_t DevInfo_SetParameter( uint8 param, uint8 len, void *value ); + +/* + * 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). + */ +extern bStatus_t DevInfo_GetParameter( uint8 param, void *value ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif /* DEVINFOSERVICE_H */ diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/include/gattprofile.h b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/include/gattprofile.h new file mode 100644 index 0000000..10f8a49 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Profile/include/gattprofile.h @@ -0,0 +1,137 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : gattprofile.h +* Author : WCH +* Version : V1.0 +* Date : 2018/12/11 +* Description : + +*******************************************************************************/ + +#ifndef GATTPROFILE_H +#define GATTPROFILE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/********************************************************************* + * INCLUDES + */ + +/********************************************************************* + * CONSTANTS + */ + +// 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 + +// Simple Profile Service UUID +#define SIMPLEPROFILE_SERV_UUID 0xFFE0 + +// Key Pressed UUID +#define SIMPLEPROFILE_CHAR1_UUID 0xFFE1 +#define SIMPLEPROFILE_CHAR2_UUID 0xFFE2 +#define SIMPLEPROFILE_CHAR3_UUID 0xFFE3 +#define SIMPLEPROFILE_CHAR4_UUID 0xFFE4 +#define SIMPLEPROFILE_CHAR5_UUID 0xFFE5 + +// Simple Keys Profile Services bit fields +#define SIMPLEPROFILE_SERVICE 0x00000001 + +// Length of characteristic in bytes ( Default MTU is 23 ) +#define SIMPLEPROFILE_CHAR1_LEN 1 +#define SIMPLEPROFILE_CHAR2_LEN 1 +#define SIMPLEPROFILE_CHAR3_LEN 1 +#define SIMPLEPROFILE_CHAR4_LEN 1 +#define SIMPLEPROFILE_CHAR5_LEN 5 + +/********************************************************************* + * TYPEDEFS + */ + + +/********************************************************************* + * MACROS + */ + +/********************************************************************* + * Profile Callbacks + */ + +// Callback when a characteristic value has changed +typedef void (*simpleProfileChange_t)( uint8 paramID ); + +typedef struct +{ + simpleProfileChange_t pfnSimpleProfileChange; // Called when characteristic value changes +} simpleProfileCBs_t; + + + +/********************************************************************* + * API FUNCTIONS + */ + + +/* + * SimpleProfile_AddService- Initializes the Simple GATT 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. + */ + +extern bStatus_t SimpleProfile_AddService( uint32 services ); + +/* + * SimpleProfile_RegisterAppCBs - Registers the application callback function. + * Only call this function once. + * + * 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). + */ +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). + */ +extern bStatus_t SimpleProfile_GetParameter( uint8 param, void *value ); + +/* + * simpleProfile_Notify - Send notification. + * + * connHandle - connect handle + * pNoti - pointer to structure to notify. + */ +extern bStatus_t simpleProfile_Notify( uint16 connHandle, attHandleValueNoti_t *pNoti ); + +/********************************************************************* +*********************************************************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Project/BLE.uvprojx b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Project/BLE.uvprojx new file mode 100644 index 0000000..97b6344 --- /dev/null +++ b/src/EXAM/BLE/OnlyUpdateApp_Peripheral/Project/BLE.uvprojx @@ -0,0 +1,558 @@ + + + + 2.1 + +
### uVision Project, (C) Keil Software
+ + + + CH57x + 0x4 + ARM-ADS + 5060750::V5.06 update 6 (build 750)::ARMCC + 0 + + + CH579F + WCH + Keil.WCH57x_DFP.1.1.0 + http://wch.cn/pack + IRAM(0x20000000,0x8000) IROM(0x00000000,0x3E800) CPUTYPE("Cortex-M0") CLOCK(12000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0CH57x -FS00 -FL03F000 -FP0($$Device:CH579F$CMSIS\Flash\CH57x.FLM)) + 0 + $$Device:CH579F$Drivers\CMSIS\Device\WCH\CH57x\Include\CH579SFR.h + + + + + + + + + + $$Device:CH579F$CMSIS\SVD\CH579SFR.svd + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\obj\ + BLE + 1 + 0 + 1 + 1 + 1 + .\listing\ + 1 + 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 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + + + 1 + 0 + 0 + 1 + 1 + -1 + + 1 + BIN\UL2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 0 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x8000 + + + 1 + 0x0 + 0x3e800 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x23800 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20006000 + 0x2000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + + + DEBUG,CH57xBLE_ROM + + ..\APP\include;..\Profile\include;..\..\HAL\include;..\..\LIB;..\..\..\SRC\CMSIS\Include;..\..\..\SRC\StdPeriphDriver\inc + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0x00000000 + 0x20000000 + + BLE.sct + + + + + + + + + + + app + + + peripheral.c + 1 + ..\APP\peripheral.c + + + peripheral_main.c + 1 + ..\APP\peripheral_main.c + + + + + profile + + + devinfoservice.c + 1 + ..\Profile\devinfoservice.c + + + gattprofile.c + 1 + ..\Profile\gattprofile.c + + + + + drive + + + startup_ARMCM0.s + 2 + ..\..\..\SRC\Startup\startup_ARMCM0.s + + + CH57x_clk.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_clk.c + + + CH57x_gpio.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_gpio.c + + + CH57x_pwr.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_pwr.c + + + CH57x_sys.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_sys.c + + + CH57x_uart1.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_uart1.c + + + CH57x_int.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_int.c + + + 2 + 9 + 0 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + 11 + + + 1 + + + + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 0 + 2 + 2 + 2 + 2 + 2 + 0 + 0 + 2 + 2 + 2 + 2 + 2 + + + + + + + + + + + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + + + + + hal + + + MCU.c + 1 + ..\..\HAL\MCU.c + + + RTC.c + 1 + ..\..\HAL\RTC.c + + + SLEEP.c + 1 + ..\..\HAL\SLEEP.c + + + + + lib + + + CH57xBLE.LIB + 4 + ..\..\LIB\CH57xBLE.LIB + + + + + config + + + config.h + 5 + ..\..\HAL\include\config.h + + + + + + + + + + + + + +
diff --git a/src/EXAM/BLE/Peripheral/APP/peripheral_main.c b/src/EXAM/BLE/Peripheral/APP/peripheral_main.c index 1d90401..3efe4ba 100644 --- a/src/EXAM/BLE/Peripheral/APP/peripheral_main.c +++ b/src/EXAM/BLE/Peripheral/APP/peripheral_main.c @@ -32,8 +32,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/Peripheral/Project/BLE.uvprojx b/src/EXAM/BLE/Peripheral/Project/BLE.uvprojx index b8bcb01..df6b8f5 100644 --- a/src/EXAM/BLE/Peripheral/Project/BLE.uvprojx +++ b/src/EXAM/BLE/Peripheral/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -498,6 +498,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c +
diff --git a/src/EXAM/BLE/RF_PHY/APP/RF_main.c b/src/EXAM/BLE/RF_PHY/APP/RF_main.c index 36428c2..885e745 100644 --- a/src/EXAM/BLE/RF_PHY/APP/RF_main.c +++ b/src/EXAM/BLE/RF_PHY/APP/RF_main.c @@ -29,8 +29,10 @@ __align(4) u32 MEM_BUF[BLE_MEMHEAP_SIZE/4]; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits( bTXD1 ); GPIOA_ModeCfg( bTXD1, GPIO_ModeOut_PP_5mA ); diff --git a/src/EXAM/BLE/RF_PHY/Project/BLE.uvprojx b/src/EXAM/BLE/RF_PHY/Project/BLE.uvprojx index 1301dc5..6b060de 100644 --- a/src/EXAM/BLE/RF_PHY/Project/BLE.uvprojx +++ b/src/EXAM/BLE/RF_PHY/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -534,4 +534,10 @@ + + + + + + diff --git a/src/EXAM/BLE/RunningSensor/APP/runningsensor.c b/src/EXAM/BLE/RunningSensor/APP/runningsensor.c index bbda620..e583ee0 100644 --- a/src/EXAM/BLE/RunningSensor/APP/runningsensor.c +++ b/src/EXAM/BLE/RunningSensor/APP/runningsensor.c @@ -47,10 +47,10 @@ #define DEFAULT_RSC_PERIOD 2000 // Minimum connection interval (units of 1.25ms) -#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 200 +#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 20 // Maximum connection interval (units of 1.25ms) -#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 1600 +#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 160 // Slave latency to use if parameter update request #define DEFAULT_DESIRED_SLAVE_LATENCY 0 diff --git a/src/EXAM/BLE/RunningSensor/APP/runningsensor_main.c b/src/EXAM/BLE/RunningSensor/APP/runningsensor_main.c index 02347ca..440cbf8 100644 --- a/src/EXAM/BLE/RunningSensor/APP/runningsensor_main.c +++ b/src/EXAM/BLE/RunningSensor/APP/runningsensor_main.c @@ -31,8 +31,10 @@ u8C MacAddr[6] = {0x84,0xC2,0xE4,0x03,0x02,0x02}; *******************************************************************************/ int main( void ) { +#if (defined (HAL_SLEEP)) && (HAL_SLEEP == TRUE) GPIOA_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); - GPIOB_ModeCfg( GPIO_Pin_All&(~(GPIO_Pin_11|GPIO_Pin_10)), GPIO_ModeIN_PU ); + GPIOB_ModeCfg( GPIO_Pin_All, GPIO_ModeIN_PU ); +#endif #ifdef DEBUG GPIOA_SetBits(bTXD1); GPIOA_ModeCfg(bTXD1, GPIO_ModeOut_PP_5mA); diff --git a/src/EXAM/BLE/RunningSensor/Project/BLE.uvprojx b/src/EXAM/BLE/RunningSensor/Project/BLE.uvprojx index e05b1b9..64ad64c 100644 --- a/src/EXAM/BLE/RunningSensor/Project/BLE.uvprojx +++ b/src/EXAM/BLE/RunningSensor/Project/BLE.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -503,6 +503,11 @@ + + CH57x_adc.c + 1 + ..\..\..\SRC\StdPeriphDriver\CH57x_adc.c + diff --git a/src/EXAM/FLASH/CH57x.uvprojx b/src/EXAM/FLASH/CH57x.uvprojx index e9d41bd..16c33d5 100644 --- a/src/EXAM/FLASH/CH57x.uvprojx +++ b/src/EXAM/FLASH/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 diff --git a/src/EXAM/LCD/CH57x.uvprojx b/src/EXAM/LCD/CH57x.uvprojx index c89afa2..d11f553 100644 --- a/src/EXAM/LCD/CH57x.uvprojx +++ b/src/EXAM/LCD/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 diff --git a/src/EXAM/NET/DHCP_Client/DHCP.uvprojx b/src/EXAM/NET/DHCP_Client/DHCP.uvprojx index e826a1b..7884fe2 100644 --- a/src/EXAM/NET/DHCP_Client/DHCP.uvprojx +++ b/src/EXAM/NET/DHCP_Client/DHCP.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 diff --git a/src/EXAM/NET/DNS/DNS.uvprojx b/src/EXAM/NET/DNS/DNS.uvprojx index 322ae64..cbabc56 100644 --- a/src/EXAM/NET/DNS/DNS.uvprojx +++ b/src/EXAM/NET/DNS/DNS.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -509,4 +509,10 @@ + + + + + + diff --git a/src/EXAM/NET/FTP_Client/FTP_Client.uvprojx b/src/EXAM/NET/FTP_Client/FTP_Client.uvprojx index 6e1488e..f15f4aa 100644 --- a/src/EXAM/NET/FTP_Client/FTP_Client.uvprojx +++ b/src/EXAM/NET/FTP_Client/FTP_Client.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -509,4 +509,10 @@ + + + + + + diff --git a/src/EXAM/NET/FTP_Server/FTP_Server.uvprojx b/src/EXAM/NET/FTP_Server/FTP_Server.uvprojx index 53c5266..8575dfd 100644 --- a/src/EXAM/NET/FTP_Server/FTP_Server.uvprojx +++ b/src/EXAM/NET/FTP_Server/FTP_Server.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -509,4 +509,10 @@ + + + + + + diff --git a/src/EXAM/NET/IP_Raw/IP_Raw.uvprojx b/src/EXAM/NET/IP_Raw/IP_Raw.uvprojx index e47fee3..4fb7ee5 100644 --- a/src/EXAM/NET/IP_Raw/IP_Raw.uvprojx +++ b/src/EXAM/NET/IP_Raw/IP_Raw.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -504,4 +504,10 @@ + + + + + + diff --git a/src/EXAM/NET/MQTT/MQTT_Pub/MQTT_Pub.uvprojx b/src/EXAM/NET/MQTT/MQTT_Pub/MQTT_Pub.uvprojx index d760389..448f481 100644 --- a/src/EXAM/NET/MQTT/MQTT_Pub/MQTT_Pub.uvprojx +++ b/src/EXAM/NET/MQTT/MQTT_Pub/MQTT_Pub.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -549,4 +549,10 @@ + + + + + + diff --git a/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.c b/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.c index dcc7917..04d70ee 100644 --- a/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.c +++ b/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.c @@ -56,14 +56,14 @@ __align(4)UINT8 Mem_ArpTable[CH57xNET_RAM_ARP_TABLE_SIZE]; /* TCPЭջûڽأֵΪsocketĽջȡ趨 */ /* RX_QUEUE_ENTRIESʱҪMSSʹ֮Ĺϵ細ֵΪ4*MSSԶһλᷢ */ /* 4TCPRX_QUEUE_ENTRIESС4ȻᵼݰʧӶͨѶЧʽ */ -/* RX_QUEUE_ENTRIESҪ( /MSS ),socketͬʱдݣ */ +/* RX_QUEUE_ENTRIESҪ( /MSS ),socketͬʱдݣ */ /* RX_QUEUE_ENTRIESҪ(( /MSS )*socket) ڶsocketͬʱдշʱ */ /* Ϊ˽ԼRAM뽫ջijΪMSS */ /* CH579MQTTض壬Ҫʵ޸ */ UINT8 MACAddr[6] = {0x84,0xc2,0xe4,0x02,0x03,0x04}; /* CH579MACַ */ -UINT8 IPAddr[4] = {192,168,10,200}; /* CH579IPַ */ -UINT8 GWIPAddr[4]= {192,168,10,1}; /* CH579 */ +UINT8 IPAddr[4] = {192,168,1,200}; /* CH579IPַ */ +UINT8 GWIPAddr[4]= {192,168,1,1}; /* CH579 */ UINT8 IPMask[4] = {255,255,255,0}; /* CH579 */ UINT8 DESIP[4] = {58,213,74,190}; /* ĿIPַ */ UINT16 aport=1000; /* CH579Դ˿ */ @@ -71,7 +71,7 @@ __align(4)UINT8 Mem_ArpTable[CH57xNET_RAM_ARP_TABLE_SIZE]; /* ڵƶ PBڵʮλЧ */ UINT16 CH57xNET_LEDCONN=0x0010; /* ָʾ PB4 */ -UINT16 CH57xNET_LEDDATA=0x0080; /* ͨѶָʾ PB7 */ +UINT16 CH57xNET_LEDDATA=0x0080; /* ͨѶָʾ PB7 */ char *username = ""; /* 豸ÿ豸Ψһá/ּ */ char *password = ""; /* ½ */ @@ -132,7 +132,7 @@ void mStopIfError(UINT8 iError) *******************************************************************************/ UINT8 Transport_Open() { - UINT8 i; + UINT8 i; SOCK_INF TmpSocketInf; /* ʱsocket */ memset((void *)&TmpSocketInf,0,sizeof(SOCK_INF)); /* ڲὫ˱ƣýʱȫ */ @@ -144,7 +144,7 @@ UINT8 Transport_Open() TmpSocketInf.RecvBufLen = RECE_BUF_LEN ; /* ýջĽճ */ i = CH57xNET_SocketCreat(&SocketId,&TmpSocketInf); /* socketصsocketSocketId */ mStopIfError(i); /* */ - + i = CH57xNET_SocketConnect(SocketId); /* TCP */ mStopIfError(i); /* */ return SocketId; @@ -179,7 +179,7 @@ void Transport_SendPacket(UINT8 *buf,UINT32 len) { UINT32 totallen; UINT8 *p=buf; - + totallen=len; while(1) { @@ -210,11 +210,11 @@ void MQTT_Connect(char *username,char *password) data.clientID.cstring = "11"; data.keepAliveInterval = 20; data.cleansession = 1; - data.username.cstring = username; + data.username.cstring = username; data.password.cstring = password; - - len=MQTTSerialize_connect(buf,sizeof(buf),&data); - Transport_SendPacket(buf,len); + + len=MQTTSerialize_connect(buf,sizeof(buf),&data); + Transport_SendPacket(buf,len); } @@ -232,7 +232,7 @@ void MQTT_Subscribe( char *topic) UINT32 len; UINT32 msgid=1; UINT8 buf[200]; - + topicString.cstring=topic; len=MQTTSerialize_subscribe(buf,sizeof(buf),0,msgid,1,&topicString,&req_qos); Transport_SendPacket(buf,len); @@ -252,7 +252,7 @@ void MQTT_Unsubscribe(char *topic) UINT32 len; UINT32 msgid=1; UINT8 buf[200]; - + topicString.cstring=topic; len=MQTTSerialize_unsubscribe(buf,sizeof(buf),0,msgid,1,&topicString); Transport_SendPacket(buf,len); @@ -272,10 +272,10 @@ void MQTT_Publish(char *topic,char *payload) UINT32 payloadlen; UINT32 len; UINT8 buf[1024]; - - topicString.cstring=topic; + + topicString.cstring=topic; payloadlen=strlen(payload); - len= MQTTSerialize_publish(buf,sizeof(buf),0,0,0,packetid++,topicString,payload,payloadlen); + len= MQTTSerialize_publish(buf,sizeof(buf),0,0,0,packetid++,topicString,payload,payloadlen); Transport_SendPacket(buf,len); } @@ -291,7 +291,7 @@ void MQTT_Pingreq() { UINT32 len; UINT8 buf[200]; - + len=MQTTSerialize_pingreq(buf,sizeof(buf)); Transport_SendPacket(buf,len); } @@ -323,12 +323,12 @@ void MQTT_Disconnect() *******************************************************************************/ void CH57xNET_CreatTcpSocket(void) { - UINT8 i; + UINT8 i; SOCK_INF TmpSocketInf; /* ʱsocket */ memset((void *)&TmpSocketInf,0,sizeof(SOCK_INF)); /* ڲὫ˱ƣýʱȫ */ memcpy((void *)TmpSocketInf.IPAddr,DESIP,4); /* ĿIPַ */ - TmpSocketInf.DesPort = 1000; + TmpSocketInf.DesPort = 1000; TmpSocketInf.SourPort = 2000; /* Դ˿ */ TmpSocketInf.ProtoType = PROTO_TYPE_TCP; /* socekt */ TmpSocketInf.RecvStartPoint = (UINT32)SocketRecvBuf; /* ýջĽջ */ @@ -349,7 +349,7 @@ void CH57xNET_CreatTcpSocket(void) /******************************************************************************* * Function Name : net_initkeeplive * Description : keepliveʼ -* Input : None +* Input : None * Output : None * Return : None *******************************************************************************/ @@ -371,7 +371,7 @@ void net_initkeeplive(void) * Input : ip ipַָ * gwip ipַָ * : mask ָ -* : macaddr MACַָ +* : macaddr MACַָ * Output : None * Return : ִ״̬ *******************************************************************************/ @@ -382,7 +382,7 @@ UINT8 CH57xNET_LibInit(/*const*/ UINT8 *ip,/*const*/ UINT8 *gwip,/*const*/ UINT8 if(CH57xNET_GetVer() != CH57xNET_LIB_VER)return 0xfc; /* ȡİ汾ţǷͷļһ */ CH57xNETConfig = LIB_CFG_VALUE; /* Ϣݸñ */ - cfg.RxBufSize = RX_BUF_SIZE; + cfg.RxBufSize = RX_BUF_SIZE; cfg.TCPMss = CH57xNET_TCP_MSS; cfg.HeapSize = CH57x_MEM_HEAP_SIZE; cfg.ARPTableNum = CH57xNET_NUM_ARP_TABLE; @@ -392,7 +392,7 @@ UINT8 CH57xNET_LibInit(/*const*/ UINT8 *ip,/*const*/ UINT8 *gwip,/*const*/ UINT8 #ifdef KEEPLIVE_ENABLE net_initkeeplive( ); #endif - return (i); + return (i); } /******************************************************************************* @@ -440,7 +440,7 @@ void CH57xNET_HandleSockInt(UINT8 sockeid,UINT8 initstat) } PRINT("\r\n"); break; - + case FLAG_SUBACK: sub_flag=1; PRINT("suback\r\n"); @@ -453,8 +453,8 @@ void CH57xNET_HandleSockInt(UINT8 sockeid,UINT8 initstat) } if(initstat & SINT_STAT_CONNECT) /* TCPж */ { /* жϱʾTCPѾӣԽշ */ - PRINT("TCP Connect Success\n"); - MQTT_Connect(username, password); + PRINT("TCP Connect Success\n"); + MQTT_Connect(username, password); } if(initstat & SINT_STAT_DISCONNECT) /* TCPϿж */ { /* жϣCH579ڲὫsocketΪر*/ @@ -486,24 +486,24 @@ void CH57xNET_HandleGlobalInt(void) { PRINT("UnreachCode %d\n",CH57xInf.UnreachCode); /* 鿴ɴ */ PRINT("UnreachProto %d\n",CH57xInf.UnreachProto); /* 鿴ɴЭ */ - PRINT("UnreachPort %d\n",CH57xInf.UnreachPort); /* ѯɴ˿ */ + PRINT("UnreachPort %d\n",CH57xInf.UnreachPort); /* ѯɴ˿ */ } if(initstat & GINT_STAT_IP_CONFLI) /* IPͻж */ { - + } if(initstat & GINT_STAT_PHY_CHANGE) /* PHYıж */ { i = CH57xNET_GetPHYStatus(); /* ȡPHY״̬ */ - PRINT("GINT_STAT_PHY_CHANGE %02x\n",i); + PRINT("GINT_STAT_PHY_CHANGE %02x\n",i); } if(initstat & GINT_STAT_SOCKET) /* Socketж */ { - for(i = 0; i < CH57xNET_MAX_SOCKET_NUM; i ++) + for(i = 0; i < CH57xNET_MAX_SOCKET_NUM; i ++) { socketinit = CH57xNET_GetSocketInt(i); /* socketжϲ */ if(socketinit)CH57xNET_HandleSockInt(i,socketinit); /* ж */ - } + } } } @@ -522,7 +522,7 @@ void Timer0Init(UINT32 time) R8_TMR0_INT_FLAG = R8_TMR0_INT_FLAG; /* ־ */ R8_TMR0_INTER_EN = RB_TMR_IE_CYC_END; /* ʱж */ R8_TMR0_CTRL_MOD |= RB_TMR_COUNT_EN; - NVIC_EnableIRQ(TMR0_IRQn); + NVIC_EnableIRQ(TMR0_IRQn); } /******************************************************************************* @@ -535,7 +535,7 @@ void Timer0Init(UINT32 time) void SystemClock_UART1_init(void) { PWR_UnitModCfg(ENABLE, UNIT_SYS_PLL); /* PLLϵ */ - DelayMs(3); + DelayMs(3); SetSysClock(CLK_SOURCE_HSE_32MHz); /* ⲿ PLL 32MHz */ GPIOA_SetBits( GPIO_Pin_9 ); GPIOA_ModeCfg( GPIO_Pin_9, GPIO_ModeOut_PP_5mA ); /* 1IO */ @@ -552,12 +552,12 @@ void SystemClock_UART1_init(void) void GetMacAddr(UINT8 *pMAC) { UINT8 transbuf[6],i; - + GetMACAddress(transbuf); for(i=0;i<6;i++) { pMAC[5-i]=transbuf[i]; - + } } @@ -568,7 +568,7 @@ void GetMacAddr(UINT8 *pMAC) * Output : None * Return : None *******************************************************************************/ -int main(void) +int main(void) { UINT32 i = 0; @@ -576,15 +576,15 @@ int main(void) GetMacAddr(MACAddr); i = CH57xNET_LibInit(IPAddr,GWIPAddr,IPMask,MACAddr); /* ʼ */ mStopIfError(i); /* */ - PRINT("CH57xNETLibInit Success\r\n"); + PRINT("CH57xNETLibInit Success\r\n"); Timer0Init( 10000 ); /* ʼʱ:10ms */ NVIC_EnableIRQ(ETH_IRQn); Transport_Open(); - + while ( CH57xInf.PHYStat < 2 ) { DelayMs(50); - } - PRINT("CH579 MQTT socket create!Subscribed\r\n"); + } + PRINT("CH579 MQTT socket create!Subscribed\r\n"); while(1) { CH57xNET_MainTask(); /* CH57xNETҪѭвϵ */ diff --git a/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.uvprojx b/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.uvprojx index 15367f0..953d45b 100644 --- a/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.uvprojx +++ b/src/EXAM/NET/MQTT/MQTT_Sub/MQTT_Sub.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -185,7 +185,6 @@ 0 0 0 - 0 0 0 8 @@ -352,7 +351,7 @@ 0 0 0 - 4 + 0 diff --git a/src/EXAM/NET/TCP_Client/TCP_MultipleClients/TCP_MultipleClients.uvprojx b/src/EXAM/NET/TCP_Client/TCP_MultipleClients/TCP_MultipleClients.uvprojx index 3ebcdb3..b77a741 100644 --- a/src/EXAM/NET/TCP_Client/TCP_MultipleClients/TCP_MultipleClients.uvprojx +++ b/src/EXAM/NET/TCP_Client/TCP_MultipleClients/TCP_MultipleClients.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -504,4 +504,10 @@ + + + + + + diff --git a/src/EXAM/NET/TCP_Client/TCP_SingleClient/TCP_Client.uvprojx b/src/EXAM/NET/TCP_Client/TCP_SingleClient/TCP_Client.uvprojx index bddb57e..93805cd 100644 --- a/src/EXAM/NET/TCP_Client/TCP_SingleClient/TCP_Client.uvprojx +++ b/src/EXAM/NET/TCP_Client/TCP_SingleClient/TCP_Client.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -504,4 +504,10 @@ + + + + + + diff --git a/src/EXAM/NET/TCP_Server/TCP_Server.uvprojx b/src/EXAM/NET/TCP_Server/TCP_Server.uvprojx index 3d164a6..98f0ac7 100644 --- a/src/EXAM/NET/TCP_Server/TCP_Server.uvprojx +++ b/src/EXAM/NET/TCP_Server/TCP_Server.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -509,4 +509,10 @@ + + + + + + diff --git a/src/EXAM/NET/UDP_Client/UDP_Client.uvprojx b/src/EXAM/NET/UDP_Client/UDP_Client.uvprojx index 0d6d30c..2d82c07 100644 --- a/src/EXAM/NET/UDP_Client/UDP_Client.uvprojx +++ b/src/EXAM/NET/UDP_Client/UDP_Client.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -504,4 +504,10 @@ + + + + + + diff --git a/src/EXAM/NET/UDP_Server/UDP_Server.uvprojx b/src/EXAM/NET/UDP_Server/UDP_Server.uvprojx index 6b025cf..3d4774a 100644 --- a/src/EXAM/NET/UDP_Server/UDP_Server.uvprojx +++ b/src/EXAM/NET/UDP_Server/UDP_Server.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -137,7 +137,7 @@ 4101 1 - STLink\ST-LINKIII-KEIL_SWO.dll + BIN\UL2CM3.DLL "" () @@ -504,4 +504,10 @@ + + + + + + diff --git a/src/EXAM/PM/CH57x.uvprojx b/src/EXAM/PM/CH57x.uvprojx index e9d41bd..16c33d5 100644 --- a/src/EXAM/PM/CH57x.uvprojx +++ b/src/EXAM/PM/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 diff --git a/src/EXAM/PWMX/CH57x.uvprojx b/src/EXAM/PWMX/CH57x.uvprojx index 6e4b131..b2ca71b 100644 --- a/src/EXAM/PWMX/CH57x.uvprojx +++ b/src/EXAM/PWMX/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -519,4 +519,10 @@ + + + + + + diff --git a/src/EXAM/SPI0/SPI0_MASTER&SLAVE/CH57x.uvprojx b/src/EXAM/SPI0/SPI0_MASTER&SLAVE/CH57x.uvprojx index 8378806..3845e19 100644 --- a/src/EXAM/SPI0/SPI0_MASTER&SLAVE/CH57x.uvprojx +++ b/src/EXAM/SPI0/SPI0_MASTER&SLAVE/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -519,4 +519,10 @@ + + + + + + diff --git a/src/EXAM/SPI1/SPI1_FLASH/CH57x.uvprojx b/src/EXAM/SPI1/SPI1_FLASH/CH57x.uvprojx index fa599b7..9bfa5bb 100644 --- a/src/EXAM/SPI1/SPI1_FLASH/CH57x.uvprojx +++ b/src/EXAM/SPI1/SPI1_FLASH/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -529,4 +529,10 @@ + + + + + + diff --git a/src/EXAM/SPI1/SPI1_MASTER/CH57x.uvprojx b/src/EXAM/SPI1/SPI1_MASTER/CH57x.uvprojx index 1614195..9c2501c 100644 --- a/src/EXAM/SPI1/SPI1_MASTER/CH57x.uvprojx +++ b/src/EXAM/SPI1/SPI1_MASTER/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -524,4 +524,10 @@ + + + + + + diff --git a/src/EXAM/SRC/StdPeriphDriver/CH57x_clk.c b/src/EXAM/SRC/StdPeriphDriver/CH57x_clk.c index 0e30010..bebbde7 100644 --- a/src/EXAM/SRC/StdPeriphDriver/CH57x_clk.c +++ b/src/EXAM/SRC/StdPeriphDriver/CH57x_clk.c @@ -19,6 +19,7 @@ void SystemInit(void) R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG1; R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG2; R16_CLK_SYS_CFG = (2<<6)|0x08; // 32M -> Fsys + *((PUINT16V)0x40001048) |= 4; R8_SAFE_ACCESS_SIG = 0; mDelayuS(10); @@ -373,6 +374,7 @@ void RTC_InitTime( UINT16 y, UINT16 mon, UINT16 d, UINT16 h, UINT16 m, UINT16 s { UINT32 t; UINT16 year, month, day, sec2, t32k; + UINT8V clk_pin; year = y; month = mon; @@ -394,6 +396,11 @@ void RTC_InitTime( UINT16 y, UINT16 mon, UINT16 d, UINT16 h, UINT16 m, UINT16 s t = sec2; t = t<<16 | t32k; + do{ + clk_pin = (R8_CK32K_CONFIG&RB_32K_CLK_PIN); + }while( (clk_pin != (R8_CK32K_CONFIG&RB_32K_CLK_PIN)) || (!clk_pin) ); + + R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG1; R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG2; R32_RTC_TRIG = day; @@ -460,6 +467,12 @@ void RTC_GetTime( PUINT16 py, PUINT16 pmon, PUINT16 pd, PUINT16 ph, PUINT16 pm, *******************************************************************************/ void RTC_SetCycle32k( UINT32 cyc ) { + UINT8V clk_pin; + + do{ + clk_pin = (R8_CK32K_CONFIG&RB_32K_CLK_PIN); + }while( (clk_pin != (R8_CK32K_CONFIG&RB_32K_CLK_PIN)) || (!clk_pin) ); + R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG1; R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG2; R32_RTC_TRIG = cyc; diff --git a/src/EXAM/SRC/StdPeriphDriver/CH57x_int.c b/src/EXAM/SRC/StdPeriphDriver/CH57x_int.c index a317b7b..4f465d8 100644 --- a/src/EXAM/SRC/StdPeriphDriver/CH57x_int.c +++ b/src/EXAM/SRC/StdPeriphDriver/CH57x_int.c @@ -236,6 +236,7 @@ void LowPower_Shutdown( UINT8 rm ) R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG1; R8_SAFE_ACCESS_SIG = SAFE_ACCESS_SIG2; R8_BAT_DET_CTRL = RB_BAT_LOW_IE|RB_BAT_LOWER_IE|RB_BAT_DET_EN; + R8_RST_WDOG_CTRL |= RB_SOFTWARE_RESET; R8_SAFE_ACCESS_SIG = 0; } diff --git a/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_clk.h b/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_clk.h index db17c52..4b87352 100644 --- a/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_clk.h +++ b/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_clk.h @@ -87,7 +87,7 @@ typedef enum #define BEGYEAR 2020 #define IsLeapYear(yr) (!((yr) % 400) || (((yr) % 100) && !((yr) % 4))) #define YearLength(yr) (IsLeapYear(yr) ? 366 : 365) -#define monthLength(lpyr,mon) ((mon==1) ? (28+lpyr) : ((mon>6) ? ((mon&1)?30:31) : ((mon&1)?31:30))) +#define monthLength(lpyr,mon) ((mon==1) ? (28+lpyr) : ((mon>6) ? ((mon&1)?31:30) : ((mon&1)?30:31))) /** * @brief rtc timer mode period define diff --git a/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_timer.h b/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_timer.h index 82c8f89..896b9ae 100644 --- a/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_timer.h +++ b/src/EXAM/SRC/StdPeriphDriver/inc/CH57x_timer.h @@ -82,6 +82,7 @@ typedef enum #define TMR0_Disable() (R8_TMR0_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* ر TMR0 */ +#define TMR0_Enable() (R8_TMR0_CTRL_MOD |= RB_TMR_COUNT_EN) /* TMR0 */ // refer to TMR0 interrupt bit define #define TMR0_ITCfg(s,f) ((s)?(R8_TMR0_INTER_EN|=f):(R8_TMR0_INTER_EN&=~f)) /* TMR0 Ӧжλر */ // refer to TMR0 interrupt bit define @@ -114,6 +115,7 @@ typedef enum void TMR1_DMACfg( UINT8 s, UINT16 startAddr, UINT16 endAddr, DMAModeTypeDef m ); /* DMA */ #define TMR1_Disable() (R8_TMR1_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* ر TMR1 */ +#define TMR1_Enable() (R8_TMR1_CTRL_MOD |= RB_TMR_COUNT_EN) /* TMR1 */ // refer to TMR1 interrupt bit define #define TMR1_ITCfg(s,f) ((s)?(R8_TMR1_INTER_EN|=f):(R8_TMR1_INTER_EN&=~f)) /* TMR1 Ӧжλر */ // refer to TMR1 interrupt bit define @@ -146,6 +148,7 @@ typedef enum void TMR2_DMACfg( UINT8 s, UINT16 startAddr, UINT16 endAddr, DMAModeTypeDef m ); /* DMA */ #define TMR2_Disable() (R8_TMR2_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* ر TMR2 */ +#define TMR2_Enable() (R8_TMR2_CTRL_MOD |= RB_TMR_COUNT_EN) /* TMR2 */ // refer to TMR2 interrupt bit define #define TMR2_ITCfg(s,f) ((s)?(R8_TMR2_INTER_EN|=f):(R8_TMR2_INTER_EN&=~f)) /* TMR2 Ӧжλر */ // refer to TMR2 interrupt bit define @@ -177,6 +180,7 @@ typedef enum #define TMR3_Disable() (R8_TMR3_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* ر TMR3 */ +#define TMR3_Enable() (R8_TMR3_CTRL_MOD |= RB_TMR_COUNT_EN) /* TMR3 */ // refer to TMR3 interrupt bit define #define TMR3_ITCfg(s,f) ((s)?(R8_TMR3_INTER_EN|=f):(R8_TMR3_INTER_EN&=~f)) /* TMR3 Ӧжλر */ // refer to TMR3 interrupt bit define diff --git a/src/EXAM/TMR/CH57x.uvprojx b/src/EXAM/TMR/CH57x.uvprojx index 215c94a..0c441ef 100644 --- a/src/EXAM/TMR/CH57x.uvprojx +++ b/src/EXAM/TMR/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 diff --git a/src/EXAM/TMR/Main.c b/src/EXAM/TMR/Main.c index dfc37bc..ae3999e 100644 --- a/src/EXAM/TMR/Main.c +++ b/src/EXAM/TMR/Main.c @@ -45,8 +45,10 @@ int main() GPIOA_ModeCfg( GPIO_Pin_2, GPIO_ModeOut_PP_5mA ); TMR3_PWMInit( High_Level, PWM_Times_1 ); - TMR3_PWMCycleCfg( 3200 ); // 100ms - TMR3_PWMActDataWidth( 1000 ); // ռձ 50% + TMR3_PWMCycleCfg( 3200 ); // 100us + TMR3_Disable(); + TMR3_PWMActDataWidth( 1000 ); // ռձ , ޸ռձȱʱرնʱ + TMR3_Enable(); #endif @@ -58,6 +60,7 @@ int main() TMR1_CapInit( Edge_To_Edge ); TMR1_CAPTimeoutCfg( 0xFFFFFFFF ); // ò׽ʱʱ TMR1_DMACfg( ENABLE, (UINT16)&CapBuf[0], (UINT16)&CapBuf[100], Mode_Single ); + TMR1_ClearITFlag( TMR1_2_IT_DMA_END ); // жϱ־ TMR1_ITCfg(ENABLE, TMR1_2_IT_DMA_END); // DMAж NVIC_EnableIRQ( TMR1_IRQn ); diff --git a/src/EXAM/UART1/CH57x.uvprojx b/src/EXAM/UART1/CH57x.uvprojx index 79ab6a8..b2ca71b 100644 --- a/src/EXAM/UART1/CH57x.uvprojx +++ b/src/EXAM/UART1/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -185,7 +185,6 @@ 0 0 0 - 0 0 0 8 @@ -352,7 +351,7 @@ 0 0 0 - 4 + 0 diff --git a/src/EXAM/USB/Device/CompoundDev/CH57x.uvprojx b/src/EXAM/USB/Device/CompoundDev/CH57x.uvprojx index b4fc8b5..7901052 100644 --- a/src/EXAM/USB/Device/CompoundDev/CH57x.uvprojx +++ b/src/EXAM/USB/Device/CompoundDev/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -185,7 +185,6 @@ 0 0 0 - 0 0 0 8 @@ -352,7 +351,7 @@ 0 0 0 - 4 + 0 diff --git a/src/EXAM/USB/Device/VendorDefinedDev/CH57x.uvprojx b/src/EXAM/USB/Device/VendorDefinedDev/CH57x.uvprojx index 00c5ab7..7901052 100644 --- a/src/EXAM/USB/Device/VendorDefinedDev/CH57x.uvprojx +++ b/src/EXAM/USB/Device/VendorDefinedDev/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -524,4 +524,10 @@ + + + + + + diff --git a/src/EXAM/USB/Host/HostAOA/CH57x.uvprojx b/src/EXAM/USB/Host/HostAOA/CH57x.uvprojx index 6317964..d9af64d 100644 --- a/src/EXAM/USB/Host/HostAOA/CH57x.uvprojx +++ b/src/EXAM/USB/Host/HostAOA/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 diff --git a/src/EXAM/USB/Host/HostEnum/CH57x.uvprojx b/src/EXAM/USB/Host/HostEnum/CH57x.uvprojx index 6317964..d9af64d 100644 --- a/src/EXAM/USB/Host/HostEnum/CH57x.uvprojx +++ b/src/EXAM/USB/Host/HostEnum/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 diff --git a/src/EXAM/USB/Host/U_DISK/EXAM1/CH57x.uvprojx b/src/EXAM/USB/Host/U_DISK/EXAM1/CH57x.uvprojx index dda8582..01f0df0 100644 --- a/src/EXAM/USB/Host/U_DISK/EXAM1/CH57x.uvprojx +++ b/src/EXAM/USB/Host/U_DISK/EXAM1/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -514,4 +514,10 @@ + + + + + + diff --git a/src/EXAM/USB/Host/U_DISK/EXAM10/CH57x.uvprojx b/src/EXAM/USB/Host/U_DISK/EXAM10/CH57x.uvprojx index eca71a5..53508ab 100644 --- a/src/EXAM/USB/Host/U_DISK/EXAM10/CH57x.uvprojx +++ b/src/EXAM/USB/Host/U_DISK/EXAM10/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -514,4 +514,10 @@ + + + + + + diff --git a/src/EXAM/USB/Host/U_DISK/EXAM11/CH57x.uvprojx b/src/EXAM/USB/Host/U_DISK/EXAM11/CH57x.uvprojx index 9065885..aa566e2 100644 --- a/src/EXAM/USB/Host/U_DISK/EXAM11/CH57x.uvprojx +++ b/src/EXAM/USB/Host/U_DISK/EXAM11/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -514,4 +514,10 @@ + + + + + + diff --git a/src/EXAM/USB/Host/U_DISK/EXAM13/CH57x.uvprojx b/src/EXAM/USB/Host/U_DISK/EXAM13/CH57x.uvprojx index 0449e95..144e71e 100644 --- a/src/EXAM/USB/Host/U_DISK/EXAM13/CH57x.uvprojx +++ b/src/EXAM/USB/Host/U_DISK/EXAM13/CH57x.uvprojx @@ -10,7 +10,7 @@ CH57x 0x4 ARM-ADS - 5060960::V5.06 update 7 (build 960)::ARMCC + 5060750::V5.06 update 6 (build 750)::ARMCC 0 @@ -53,7 +53,7 @@ 1 0 1 - 0 + 1 1 .\list\ 1 @@ -514,4 +514,10 @@ + + + + + + diff --git a/src/PUB/CH579SCH.PDF b/src/PUB/CH579SCH.PDF index 502dc8d..2822470 100644 Binary files a/src/PUB/CH579SCH.PDF and b/src/PUB/CH579SCH.PDF differ diff --git "a/src/PUB/CH579\350\257\204\344\274\260\347\211\210\350\257\264\346\230\216\344\271\246.PDF" "b/src/PUB/CH579\350\257\204\344\274\260\347\211\210\350\257\264\346\230\216\344\271\246.PDF" index 4fbe283..f618aba 100644 Binary files "a/src/PUB/CH579\350\257\204\344\274\260\347\211\210\350\257\264\346\230\216\344\271\246.PDF" and "b/src/PUB/CH579\350\257\204\344\274\260\347\211\210\350\257\264\346\230\216\344\271\246.PDF" differ