hpw422移植新的sdk

This commit is contained in:
xushaoxiang
2026-07-03 18:08:25 +08:00
commit 945a5a5b0b
2583 changed files with 713209 additions and 0 deletions
@@ -0,0 +1,348 @@
/**
****************************************************************************************
*
* @file app_task.h
*
* @brief Header file - APPTASK.
*
* Copyright (C) RivieraWaves 2009-2015
*
*
****************************************************************************************
*/
#ifndef APP_TASK_H_
#define APP_TASK_H_
/**
****************************************************************************************
* @addtogroup APPTASK Task
* @ingroup APP
* @brief Routes ALL messages to/from APP block.
*
* The APPTASK is the block responsible for bridging the final application with
*the RWBLE software host stack. It communicates with the different modules of
*the BLE host, i.e. @ref SMP, @ref GAP and @ref GATT.
*
* @{
****************************************************************************************
*/
#include "app_sec.h"
#include "co_bt_defines.h"
#include "dbg.h"
#include "gapm_int.h"
#include "gatt_msg_int.h" // GATTC Definitions
#include "ke_task.h" // Kernel Task
#include "rwip_task.h" // Task definitions
#include "usr_client.h"
#include "xc_gap_api.h"
#include <stdbool.h>
#include <stdint.h> // Standard Integer Definition
#include <stdio.h>
#define BOND_TEST 0
#define MULTI_ROLE_TEST 1
#define WHITE_LIST_TEST 0
#define CONNECT_DEV_NUM 5
extern struct app_env_tag app_env;
#if (NVDS_SUPPORT)
#include "nvds.h"
#endif // (NVDS_SUPPORT)
#define APP_HANDLERS(subtask) \
{ \
&subtask##_msg_handler_list[0], ARRAY_LEN(subtask##_msg_handler_list) \
}
#define APP_DEVICE_NAME_MAX_LEN (18)
#if !(defined(CONFIG_XINCHIP) && CONFIG_XINCHIP)
#define APP_DFLT_DEVICE_NAME ("XinChipTest")
#define APP_DFLT_DEVICE_NAME_LEN (sizeof(APP_DFLT_DEVICE_NAME))//must not be greater than APP_DEVICE_NAME_MAX_LEN
#else
#define APP_DFLT_DEVICE_NAME ((char *)g_config_file.ble_name)
#define APP_DFLT_DEVICE_NAME_LEN (strlen((char *)g_config_file.ble_name))
#endif
/// Maximal length of the Device Name value
#define APP_DEVICE_NAME_MAX_LEN (18)
#define APP_MAX_TX_POWER (0)
// Advertising channel map - 37, 38, 39
#define APP_ADV_CHMAP (0x07)
// Advertising minimum interval - 40ms (64*0.625ms)
#define APP_ADV_INT_MIN (64)
// Advertising maximum interval - 40ms (64*0.625ms)
#define APP_ADV_INT_MAX (64)
#define ADV_DATA_MAX_LENGTH 28
#define MANUFACTURER_DATA "\x09\xFF\x00\x60\x52\x57\x2D\x42\x4C\x45"
#define MANUFACTURER_DATA_LEN 10
/// Advertising duration (in unit of 10ms). 0 means that advertising continues
/// until the host disable it
#define ADV_DURATION 0
#define APP_SCAN_INTERVAL (0xa0)
#define APP_SCAN_WINDOW (0x50)
#define APP_CONN_EST_TIME_OUT (0)
#define APP_CONN_SCNA_INTV (32)
#define APP_CONN_SCAN_WD (20)
#define APP_CONN_INTV_MIN (80)
#define APP_CONN_INV_MAX (80)
#define APP_CONN_LATENCY (0)
#define APP_CONN_TIME_OUT (500)
/// Number of APP Task Instances
#define APP_IDX_MAX 1
#define DEV_APPEARANCE 0
#define BLE_UAPDATA_MIN_INTVALUE 8
#define BLE_UAPDATA_MAX_INTVALUE 10
#define BLE_UAPDATA_LATENCY 0
#define BLE_UAPDATA_TIMEOUT 200
#define INVALID_DATA 0xFF
// #define TAGET_DEVICE_ADDR ("\x02\x6e\x00\x05\x21\x41")
#define TAGET_DEVICE_ADDR ("\x41\x21\x05\x00\x6e\x02")
/// Application environment structure
struct app_env_tag
{
/// Connection handle
uint16_t conhdl;
/// Connection Index
uint8_t conidx;
/// Current advertising state (@see enum app_adv_state)
uint8_t adv_state;
/// Current advertising state (@see enum app_adv_state)
uint8_t scan_state;
/// Current advertising state (@see enum app_adv_state)
uint8_t init_state;
/// Next expected operation completed event
uint8_t adv_op;
/// Last initialized profile
uint8_t next_svc;
/// Bonding status
bool bonded;
/// Device Name length
uint8_t dev_name_len;
/// Device Name
uint8_t dev_name[APP_DEVICE_NAME_MAX_LEN];
/// Local device IRK
uint8_t loc_irk[KEY_LEN];
/// Secure Connections on current link
bool sec_con_enabled;
/// Counter used to generate IRK
uint8_t rand_cnt;
/// Demonstration type length
uint8_t demo_type_len;
/// Demonstration type
uint8_t demo_type;
/// GATT user local identifier
uint8_t user_lid;
uint8_t adv_actv_idx;
uint8_t scan_actv_idx;
uint8_t init_actv_idx;
uint8_t slave_conidx;
uint8_t master_conidx;
bool slave_connected;
bool master_connected;
};
struct conn_dev_info
{
uint8_t conidx;
uint8_t addr[6];
bool connnectd;
bool role;
};
struct ADV_INFO{
uint8_t addr[6];
uint8_t name_length;
uint8_t name[21];
};
#if (NVDS_SUPPORT)
/// List of Application NVDS TAG identifiers
enum app_nvds_tag
{
/// Device Name
NVDS_TAG_DEVICE_NAME = 0x02,
NVDS_LEN_DEVICE_NAME = 62,
/// BD Address
NVDS_TAG_BD_ADDRESS = 0x01,
NVDS_LEN_BD_ADDRESS = 6,
/// Local device Identity resolving key
NVDS_TAG_LOC_IRK = 0xA0,
NVDS_LEN_LOC_IRK = KEY_LEN,
#if (BLE_APP_PRF)
/// BLE Application Advertising data
NVDS_TAG_APP_BLE_ADV_DATA = 0x0B,
NVDS_LEN_APP_BLE_ADV_DATA = 32,
/// BLE Application Scan response data
NVDS_TAG_APP_BLE_SCAN_RESP_DATA = 0x0C,
NVDS_LEN_APP_BLE_SCAN_RESP_DATA = 32,
/// Mouse Sample Rate
NVDS_TAG_MOUSE_SAMPLE_RATE = 0x38,
NVDS_LEN_MOUSE_SAMPLE_RATE = 1,
/// Peripheral Bonded
NVDS_TAG_PERIPH_BONDED = 0x39,
NVDS_LEN_PERIPH_BONDED = 1,
/// Mouse NTF Cfg
NVDS_TAG_MOUSE_NTF_CFG = 0x3A,
NVDS_LEN_MOUSE_NTF_CFG = 2,
/// Mouse Timeout value
NVDS_TAG_MOUSE_TIMEOUT = 0x3B,
NVDS_LEN_MOUSE_TIMEOUT = 2,
/// Peer Device BD Address
NVDS_TAG_PEER_BD_ADDRESS = 0x3C,
NVDS_LEN_PEER_BD_ADDRESS = 7,
/// Mouse Energy Safe
NVDS_TAG_MOUSE_ENERGY_SAFE = 0x3D,
NVDS_LEN_MOUSE_SAFE_ENERGY = 2,
/// EDIV (2bytes), RAND NB (8bytes), LTK (16 bytes), Key Size (1 byte)
NVDS_TAG_LTK = 0x3E,
NVDS_LEN_LTK = 28,
/// PAIRING
NVDS_TAG_PAIRING = 0x3F,
NVDS_LEN_PAIRING = 54,
/// Audio mode 0 task
NVDS_TAG_AM0_FIRST = 0x90,
NVDS_TAG_AM0_LAST = 0x9F,
/// Peer device Resolving identity key (+identity address)
NVDS_TAG_PEER_IRK = 0xA1,
NVDS_LEN_PEER_IRK = sizeof(struct gapc_irk),
#endif //(BLE_APP_PRF)
};
#endif // (NVDS_SUPPORT)
/// Advertising state machine
enum app_adv_state
{
/// Advertising activity does not exists
APP_ADV_STATE_IDLE = 0,
#if BLE_APP_PRF
/// Creating advertising activity
APP_ADV_STATE_CREATING,
/// Setting advertising data
APP_ADV_STATE_SETTING_ADV_DATA,
/// Setting scan response data
APP_ADV_STATE_SETTING_SCAN_RSP_DATA,
/// Advertising activity created
APP_ADV_STATE_CREATED,
/// Starting advertising activity
APP_ADV_STATE_STARTING,
/// Advertising activity started
APP_ADV_STATE_STARTED,
/// Stopping advertising activity
APP_ADV_STATE_STOPPING,
APP_ADV_STATE_STOPPED,
#endif //(BLE_APP_PRF)
};
/// Scanning state machine
enum app_scan_state
{
APP_SCAN_STATE_IDLE = 0,
APP_SCAN_STATE_CREATING,
APP_SCAN_STATE_CREATED,
APP_SCAN_STATE_STARTING,
APP_SCAN_STATE_STARTED,
APP_SCAN_STATE_STOPPING,
APP_SCAN_STATE_STOPPED,
};
/// initting state machine
enum app_init_state
{
APP_INIT_STATE_IDLE = 0,
APP_INIT_STATE_CREATING,
APP_INIT_STATE_CREATED,
APP_INIT_STATE_STARTING,
APP_INIT_STATE_STARTED,
APP_INIT_STATE_STOPPING,
APP_INIT_STATE_STOPPED,
};
/// States of APP task
enum app_state
{
/// Initialization state
APP_INIT,
/// Database create state
APP_CREATE_DB,
/// Ready State
APP_READY,
/// Connected state
APP_CONNECTED,
/// Number of defined states.
APP_STATE_MAX
};
/// APP Task messages
/*@TRACE*/
enum app_msg_id
{
APP_DUMMY_MSG = TASK_FIRST_MSG(TASK_ID_APP),
#if (BLE_APP_PRF)
#if (BLE_APP_HT)
/// Timer used to refresh the temperature measurement value
APP_HT_MEAS_INTV_TIMER,
#endif //(BLE_APP_HT)
#if (BLE_APP_HID)
/// Timer used to disconnect the moue if no activity is detecter
APP_HID_MOUSE_TIMEOUT_TIMER,
#endif //(BLE_APP_HID)
#endif //(BLE_APP_PRF)
#if (FLASH_TEST_IN_TASK || FLASH_TEST_IN_BLUETOOTH_GAP)
ONE_SEC_TIMER_MSG,
#endif // (FLASH_TEST_IN_TASK || FLASH_TEST_IN_BLUETOOTH_GAP)
#if (CENTRAL_SEND_TEST_DATA)
CENTRAL_SEND_DATA_TIMER,
#endif // (CENTRAL_SEND_TEST_DATA)
};
struct app_subtask_handlers
{
/// Pointer to the message handler table
const struct ke_msg_handler *p_msg_handler_tab;
/// Number of messages handled
uint16_t msg_cnt;
};
/**
****************************************************************************************
* @brief Initialize the BLE demo application.
****************************************************************************************
*/
void app_init(void);
struct app_env_tag *get_app_env(void);
/// @} APPTASK
#endif // APP_TASK_H_
@@ -0,0 +1,91 @@
/**
****************************************************************************************
*
* @file rwapp_config.h
*
* @brief Application configuration definition
*
* Copyright (C) RivieraWaves 2009-2016
*
****************************************************************************************
*/
#ifndef _RWAPP_CONFIG_H_
#define _RWAPP_CONFIG_H_
/**
****************************************************************************************
* @addtogroup app
* @brief Application configuration definition
*
* @{
****************************************************************************************
*/
/*
* INCLUDE FILES
****************************************************************************************
*/
/*
* DEFINES
****************************************************************************************
*/
#define CFG_APP_BATT
/******************************************************************************************/
/* ------------------------- BLE APPLICATION SETTINGS
* -----------------------------*/
/******************************************************************************************/
/// Application Profile
#if defined(CFG_APP_PRF)
#define BLE_APP_PRF 1
#else // defined(CFG_APP_PRF)
#define BLE_APP_PRF 0
#endif // defined(CFG_APP_PRF)
/// Health Thermometer Application
#if defined(CFG_APP_HT)
#define BLE_APP_HT 1
#else // defined(CFG_APP_HT)
#define BLE_APP_HT 0
#endif // defined(CFG_APP_HT)
/// HID Application
#if defined(CFG_APP_HID)
#define BLE_APP_HID 1
#else // defined(CFG_APP_HID)
#define BLE_APP_HID 0
#endif // defined(CFG_APP_HID)
/// DIS Application
#if defined(CFG_APP_DIS)
#define BLE_APP_DIS 1
#else // defined(CFG_APP_DIS)
#define BLE_APP_DIS 0
#endif // defined(CFG_APP_DIS)
/// Battery Service Application
#if defined(CFG_APP_BATT)
#define BLE_APP_BATT 1
#else
#define BLE_APP_BATT 0
#endif //(BLE_APP_BATT)
// There are 3 modes of flash operation, turn on one of them according to your needs.
// This method can be operated at any time without affecting the Bluetooth send and receive packets.
#define FLASH_TEST_IN_INTERRUPT (0)
// This method can be operated at any time, and will affect the Bluetooth send and receive packets.
#define FLASH_TEST_IN_TASK (0)
// This way operates in the gap of Bluetooth and will not affect the Bluetooth sending and receiving packets,
// but the flash operation may not be successful immediately.
#define FLASH_TEST_IN_BLUETOOTH_GAP (0)
// The master sends test data to the slave once per second.
#define CENTRAL_SEND_TEST_DATA (0)
/// @} rwapp_config
#endif /* _RWAPP_CONFIG_H_ */
@@ -0,0 +1,152 @@
#ifndef SDK_DRIVER_CONFIG_H
#define SDK_DRIVER_CONFIG_H
// <<< Use Configuration Wizard in Context Menu >>>\n
#ifdef USE_APP_CONFIG
#include "app_config.h"
#endif
// <h> XC_Drivers
// <e> XC_CLOCK_ENABLED
//==========================================================
#ifndef XC_CLOCK_ENABLED
#define XC_CLOCK_ENABLED 1
#endif
// </e>
// <e> XC_PWR_ENABLED
//==========================================================
#ifndef XC_PWR_ENABLED
#define XC_PWR_ENABLED 1
#endif
// </e>
// <e> XC_WDT_ENABLED
//==========================================================
#ifndef XC_WDT_ENABLED
#define XC_WDT_ENABLED 1
#endif
// </e>
// <e> XC_BOR_ENABLED
//==========================================================
#ifndef XC_BOR_ENABLED
#define XC_BOR_ENABLED 1
#endif
// </e>
// <e> XC_SYSTICK_ENABLED
//==========================================================
#ifndef XC_SYSTICK_ENABLED
#define XC_SYSTICK_ENABLED 1
#endif
// </e>
// <e> XC_TIMER_ENABLED
//==========================================================
#ifndef XC_TIMER_ENABLED
#define XC_TIMER_ENABLED 0
#endif
// </e>
// <e> XC_AOTIMER_ENABLED
//==========================================================
#ifndef XC_AOTIMER_ENABLED
#define XC_AOTIMER_ENABLED 0
#endif
// </e>
// <e> XC_GPIO_ENABLED
//==========================================================
#ifndef XC_GPIO_ENABLED
#define XC_GPIO_ENABLED 1
#endif
// </e>
// <e> XC_ADC_ENABLED
//==========================================================
#ifndef XC_ADC_ENABLED
#define XC_ADC_ENABLED 1
#endif
// </e>
// <e> XC_UART_ENABLED
//==========================================================
#ifndef XC_UART_ENABLED
#define XC_UART_ENABLED 1
#endif
// </e>
// <e> XC_PWM_ENABLED
//==========================================================
#ifndef XC_PWM_ENABLED
#define XC_PWM_ENABLED 1
#endif
// </e>
// <e> XC_FMC_SPI_ENABLED
//==========================================================
#ifndef XC_FMC_SPI_ENABLED
#define XC_FMC_SPI_ENABLED 1
#endif
// </e>
// <e> XC_SPI_ENABLED
//==========================================================
#ifndef XC_SPI_ENABLED
#define XC_SPI_ENABLED 0
#endif
// </e>
// <e> XC_IIC_ENABLED
//==========================================================
#ifndef XC_IIC_ENABLED
#define XC_IIC_ENABLED 0
#endif
// </e>
// <e> XC_RTC_ENABLED
//==========================================================
#ifndef XC_RTC_ENABLED
#define XC_RTC_ENABLED 1
#endif
//==========================================================
// <q> XC_RTC_DATE_INT_ENABLED
#ifndef XC_RTC_DATE_INT_ENABLED
#define XC_RTC_DATE_INT_ENABLED 0
#endif
// </e>
// <e> XC_DMA_ENABLED
//==========================================================
#ifndef XC_DMA_ENABLED
#define XC_DMA_ENABLED 0
#endif
// </e>
// <e> XC_PGA_ENABLED
//==========================================================
#ifndef XC_PGA_ENABLED
#define XC_PGA_ENABLED 0
#endif
// </e>
// <e> XC_QDEC_ENABLED
//==========================================================
#ifndef XC_QDEC_ENABLED
#define XC_QDEC_ENABLED 0
#endif
// </e>
// <e> XC_CALIB_ENABLED
//==========================================================
#ifndef XC_CALIB_ENABLED
#define XC_CALIB_ENABLED 1
#endif
// </e>
// <<< end of configuration section >>>
#endif //SDK_DRIVER_CONFIG_H
@@ -0,0 +1,57 @@
/**
******************************************************************************
*
* COPYRIGHT(c) 2021 Shanghai XinMiaoLink Technology Co.,Ltd.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#ifndef _XM_DEBUG_H_
#define _XM_DEBUG_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Print debug information through debug uart.
*/
#define xm_debug printf
/**
* @brief Print hexadecimal data through debug uart.
*
* @param data - hexadecimal data.
* @param len - the length of hexadecimal data.
*/
void xm_debug_hex(void *data, int len);
#ifdef __cplusplus
}
#endif
#endif/* _XM_DEBUG_H_ */
@@ -0,0 +1,78 @@
#ifndef _XC_ATCMD_H_
#define _XC_ATCMD_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief AT command result.
*/
#define AT_RESULT_ERROR (-1)
#define AT_RESULT_WRONG (-2)
#define AT_RESULT_DENY (-3)
#define AT_RESULT_OK (0)
#define AT_RESULT_NONE (1)
/**
* @brief AT command response.
*/
#define AT_RESPONSE_OK "+ok"
#define AT_RESPONSE_ERROR "+ok=error"
#define AT_RESPONSE_WRONG "+ok=wrong"
#define AT_RESPONSE_DENY "+ok=unsupport"
#define AT_RESPONSE_EOF "\r\n\r\n"
/**
* @brief AT command structure.
*/
typedef struct
{
const char * name;
int (*func)(char *, int, char *, int);
const char * doc;
} at_cmd_t;
/**
* @brief AT command response function definition.
*
* @param data - AT command response data.
* @param len - the length of AT command response data.
*
* @return None.
*/
typedef int (*at_rsp_func_t)(uint8_t *data, int len);
/**
* @brief AT command process.
*
* @param data - AT command data.
* @param len - the length of AT command data.
* @param rsp - buffer to store AT command response.
* @param rsp_buf_len - the size of buffer to store AT command response.
*
* @return AT command result.
*/
int xc_at_process_cmd(uint8_t *data, int len, char *rsp, int rsp_buf_len);
/**
* @brief AT command execute.
*
* @param data - AT command data.
* @param len - the length of AT command data.
* @param rsp_func - response function.
*
* @return XC_SUCCESS if successful.
*/
int xc_at_data_handle(uint8_t *data, int len, at_rsp_func_t rsp_func);
#ifdef __cplusplus
}
#endif
#endif/* _XC_ATCMD_H_ */
@@ -0,0 +1,116 @@
#ifndef _XC_BLE_H_
#define _XC_BLE_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief BLE event types.
*/
enum BLE_EVENT_E
{
BLE_EVENT_INIT = 0x20,
BLE_EVENT_ADV_START,
BLE_EVENT_ADV_STOP,
BLE_EVENT_CONNECTED,
BLE_EVENT_DISCONNECTED,
BLE_EVENT_NTF_ENABLE,
BLE_EVENT_NTF_DISABLE,
BLE_EVENT_NTF_DATA
};
/**
* @brief BLE event handler definition.
*
* @param event - BLE event id.
* @param data - BLE event data.
* @param len - the length of BLE event data.
*
* @return None.
*/
typedef int (*ble_event_callback_t)(uint32_t event, void *data, uint32_t len);
/**
* @brief Register BLE callback.
*
* @param p_callback - callback function.
*
* @return XC_SUCCESS if successful.
*/
int xc_ble_register_callback(ble_event_callback_t p_callback);
/**
* @brief Check if BLE is started.
*
* @return TRUE if started.
*/
int xc_ble_is_start(void);
/**
* @brief Check if BLE is connected.
*
* @return TRUE if connected.
*/
int xc_ble_is_connected(void);
/**
* @brief Send data through BLE.
*
* @param data - data to be sent.
* @param bytes - the length of data.
*
* @return the length of data sent.
*/
int xc_ble_data_send(void *data, uint32_t bytes);
/**
* @brief Get the MTU size of the BLE connection.
*
* @return the MTU size.
*/
int xc_ble_get_mtu_size(void);
/**
* @brief Get BLE mac address.
*
* @param mac - buffer to store mac address.
*
* @return the mac address.
*/
uint8_t *xc_ble_get_mac(uint8_t *mac);
/**
* @brief Get Slave mac address.
*
* @param mac - buffer to store mac address.
*
* @return the mac address.
*/
uint8_t *xc_ble_slave_mac(uint8_t *mac);
/**
* @brief Get Scan mac address.
*
* @param mac - buffer to store mac address.
*
* @return the mac address.
*/
uint8_t *xc_ble_scan_mac(uint8_t *mac);
/**
* @brief Disconnect BLE connection.
*
* @return XC_SUCCESS if successful.
*/
int xc_disconnect(void);
#ifdef __cplusplus
}
#endif
#endif/* _XC_BLE_H_ */
@@ -0,0 +1,107 @@
#ifndef _XC_CONFIG_H_
#define _XC_CONFIG_H_
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdio.h>
#include <stdint.h>
/**
* @brief Configuration magic flag.
*/
#define CONFIG_MAGIC_FLAG 0x55
/**
* @brief Configuration erase and write flag.
*/
#define CONFIG_ERASE_FLAG (0x01)
#define CONFIG_WRITE_FLAG (0x02)
/**
* @brief Configuration structure.
*/
#pragma pack(push) // 1-byte alignment
#pragma pack(1)
typedef struct
{
uint8_t magicflag;
uint8_t debug_level;
// BLE, 33 bytes
uint8_t mac[6];
uint8_t ble_name[27];
// ADV PARAM, 33 bytes
uint8_t adver_type;
uint8_t adver_channel;
uint8_t adver_data_len;
uint8_t adver_data[26];
uint16_t adver_min;
uint16_t adver_max;
// CONN PARAM, 8 bytes
uint16_t conn_min;
uint16_t conn_max;
uint16_t conn_latency;
uint16_t supervisionTO;
// 8 bytes
uint8_t uuid_server[2];
uint8_t uuid_read[2];
uint8_t uuid_write[2];
uint8_t sleep_info; // enable & pin & lev
int8_t txpower;
// slave addr
uint8_t slave_mac[6];
uint8_t scan_mac[6];
uint8_t con_sta;
// UART
uint32_t baudrate;
uint8_t uart_send_delay;
uint8_t reserved[6];
uint8_t crc8;
} XC_CONFIG_DATA;
#pragma pack(pop)
#if CONFIG_SUPPORT_CONFIG_FILE
extern XC_CONFIG_DATA g_config_file;
#else
extern const XC_CONFIG_DATA g_config_file;
#endif
/**
* @brief Initialize configuration.
*
* @return XC_SUCCESS if successful.
*/
int xc_config_init(void);
/**
* @brief Erase or write configuration.
*
* @param flag - Erase or write flag.
*/
void xc_config_save(int flag);
/**
* @brief Clean configuration.
*/
void xc_config_clean(void);
/**
* @brief Save configuration.
*
* @return XC_SUCCESS if successful.
*/
int xc_config_direct_save(void);
#ifdef __cplusplus
}
#endif
#endif /* _XC_CONFIG_H_ */
@@ -0,0 +1,28 @@
#ifndef _XC_DEBUG_H_
#define _XC_DEBUG_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Print debug information through debug uart.
*/
#define xc_debug printf
/**
* @brief Print hexadecimal data through debug uart.
*
* @param data - hexadecimal data.
* @param len - the length of hexadecimal data.
*/
void xc_debug_hex(void *data, int len);
#ifdef __cplusplus
}
#endif
#endif/* _XC_DEBUG_H_ */
@@ -0,0 +1,76 @@
#ifndef _XC_FLASH_H_
#define _XC_FLASH_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Flash address definition.
*/
#define FLASH_ADDR_AUTH 0x1E000
#define FLASH_ADDR_CONFIG 0x1F000
/**
* @brief Initialize flash.
*
* @return XC_SUCCESS if successful.
*/
int xc_flash_init(void);
/**
* @brief Read data from flash.
*
* @param addr - the address of flash, start from 0.
* @param data - a pointer to data.
* @param len - the length of data.
*
* @return the length of read success.
*/
int xc_flash_read(uint32_t addr, void *data, int len);
/**
* @brief Write data to flash.
*
* @param addr - the address of flash, start from 0.
* @param data - a pointer to data.
* @param len - the length of data.
*
* @return the length of write success.
*/
int xc_flash_write(uint32_t addr, void *data, int len);
/**
* @brief Erase 4K flash.
*
* @param addr - the address of flash, start from 0.
*
* @return XC_SUCCESS if successful.
*/
int xc_flash_erase_page(uint32_t addr);
/**
* @brief Check if flash operation finished.
*
* @return TRUE if finished.
*/
int xc_flash_operation_is_finish(void);
/**
* @brief Get flash ruid.
*
* @param ruid - the ruid of flash.
*
* @return XC_SUCCESS if successful.
*/
int xc_flash_get_ruid(uint8_t *ruid);
#ifdef __cplusplus
}
#endif
#endif/* _XC_FLASH_H_ */
@@ -0,0 +1,51 @@
#ifndef _XC_HEAD_H_
#define _XC_HEAD_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef NULL
#define NULL ((void *)0)
#endif
#define XC_SUCCESS 0
#define WEAK __attribute__ ((weak))
#define FUNC_IN_RAM __attribute__((section("ram_code")))
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
#include "xc_debug.h"
#include "xc_sys.h"
#include "xc_task.h"
#include "xc_flash.h"
#include "xc_config.h"
#include "xc_uart.h"
#include "xc_atcmd.h"
#include "xc_ble.h"
#include "xc_timer.h"
#define SDK_VER "0.1.0"
#define SDK_LVER "(2025-12-29 13:00 2M)"
#ifdef __cplusplus
}
#endif
#endif/* _XC_HEAD_H_ */
@@ -0,0 +1,38 @@
#ifndef _XC_MAIN_H_
#define _XC_MAIN_H_
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief SDK feature definition.
*/
#define CONFIG_SUPPORT_FLASH 1
#define CONFIG_SUPPORT_CONFIG_FILE 1
#define CONFIG_SUPPORT_SECUKEY 1
#define CONFIG_SUPPORT_GPIO 1
#define CONFIG_SUPPORT_POWERSAVE 1
#define CONFIG_SUPPORT_DEEPSLEEP 1
/**
* @brief SDK Initialize.
*/
void xc_main_init(void);
/**
* @brief SDK entrance.
*/
void xc_main_start(void);
/**
* @brief SDK main task, need call continuously.
*/
void xc_main_run(void);
#ifdef __cplusplus
}
#endif
#endif /* _XC_MAIN_H_ */
@@ -0,0 +1,87 @@
#ifndef _XC_SYS_H_
#define _XC_SYS_H_
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief System deep-sleep GPIO wake-up level.
*/
#define SYS_DEEPSLEEP_GPIO_WAKE_LOW_LEVEL 0
#define SYS_DEEPSLEEP_GPIO_WAKE_HIGH_LEVEL 1
/**
* @brief System event types.
*/
enum SYS_EVENT_E
{
SYS_EVENT_REBOOT = 0
};
/**
* @brief System event handler definition.
*
* @param event_id - system event id.
* @param param - system event data.
*
* @return None.
*/
typedef int (*sys_event_callback_t)(uint32_t event_id, void *param);
/**
* @brief Initialize system.
*
* @return XC_SUCCESS if successful.
*/
int xc_sys_init(void);
/**
* @brief Register system callback.
*
* @param p_callback - callback function.
*
* @return XC_SUCCESS if successful.
*/
int xc_sys_register_event(sys_event_callback_t p_callback);
/**
* @brief Get SDK version.
*
* @return SDK version.
*/
const char *xc_sys_get_sdk_version(void);
/**
* @brief Get system time.
*
* @return the time from system startup, in milliseconds.
*/
uint32_t xc_sys_get_time(void);
/**
* @brief System reset.
*/
void xc_sys_reset(void);
/**
* @brief Block for a while.
*
* @param us - wait time, in microseconds.
*/
void xc_sys_wait_us(uint32_t us);
/**
* @brief Enter deep-sleep and configure wake-up GPIO.
*
* @param wake_gpio - wake-up gpio id.
* @param wake_level - wake-up level.
*/
void xc_sys_enter_deepsleep(int wake_gpio, int wake_level);
#ifdef __cplusplus
}
#endif
#endif /* _XC_SYS_H_ */
@@ -0,0 +1,45 @@
#ifndef _XC_TASK_H_
#define _XC_TASK_H_
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief Task handle.
*/
typedef void (*task_func_t)(void);
/**
* @brief Task data structure.
*/
typedef struct
{
void *next;
task_func_t func;
uint8_t run_flag;
} task_handle_t;
/**
* @brief Create a task.
*
* @param task - a variable pointing to the task handle.
* @param func - a pointer to the application-defined function to be executed by the task.
*
* @return the task handle.
*/
task_handle_t *xc_task_create(task_handle_t *task, task_func_t func);
/**
* @brief Stop task.
*
* @param task - the task handle.
*/
void xc_task_delete(task_handle_t *task);
#ifdef __cplusplus
}
#endif
#endif /* _XC_TASK_H_ */
@@ -0,0 +1,43 @@
#ifndef _XC_TIMER_H_
#define _XC_TIMER_H_
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief Timer definition.
*/
#define TIMER_ID_0 0
#define TIMER_ID_1 1
#define TIMER_ID_2 2
/**
* @brief Timer callback function definition.
*/
typedef void (*timer_callback_t)(void);
/**
* @brief Create a hardware timer.
*
* @param timer_id - timer is, such as: TIMER_ID_xx.
* @param period_us - the period of timer, in microseconds.
* @param p_callback - timer callback function pointer.
*
* @return XC_SUCCESS if successful.
*/
int xc_timer_create(uint32_t timer_id, uint32_t period_us, timer_callback_t p_callback);
/**
* @brief Delete timer.
*
* @param timer_id - timer is, such as: TIMER_ID_xx.
*/
void xc_timer_delete(uint32_t timer_id);
#ifdef __cplusplus
}
#endif
#endif /* _XC_TIMER_H_ */
@@ -0,0 +1,93 @@
#ifndef _XC_UART_H_
#define _XC_UART_H_
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief Uart handle.
*/
typedef void *uart_handle_t;
/**
* @brief Uart handle definition.
*/
#define XC_UART0 (uart_handle_t)(1)
#define XC_UART1 (uart_handle_t)(2)
/**
* @brief Uart event types.
*/
enum UART_EVENT_E
{
UART0_EVENT_DATA = 0
};
/**
* @brief Uart event handler definition.
*
* @param event - uart event id.
* @param data - uart event data.
* @param len - the length of uart event data.
*
* @return None.
*/
typedef int (*uart_event_callback_t)(uint32_t event, void *data, uint32_t len);
/**uart_task
* @brief Open uart.
*
* @param uart_id - uart id (0~1).
* @param baudrate - uart baudrate.
*
* @return the handle of uart, NULL is failure.
*/
uart_handle_t xc_uart_open(int uart_id, int baudrate);
/**
* @brief Recv data from uart.
*
* @param uart_handle - the handle of uart.
* @param data - buffer to store received data.
* @param bytes - the length of the data you want to receive.
*
* @return the length of data received.
*/
int xc_uart_recv(uart_handle_t uart_handle, void *data, uint32_t bytes);
/**
* @brief Send data through uart.
*
* @param uart_handle - the handle of uart.
* @param data - data to be sent.
* @param bytes - the length of data.
*
* @return the length of data sent.
*/
int xc_uart_send(uart_handle_t uart_handle, void *data, uint32_t bytes);
/**
* @brief Close uart.
*
* @param uart_handle - the handle of uart.
*
* @return XC_SUCCESS if successful.
*/
int xc_uart_close(uart_handle_t uart_handle);
/**
* @brief Register uart callback.
*
* @param p_callback - callback function.
*
* @return XC_SUCCESS if successful.
*/
int xc_uart_register_callback(uart_event_callback_t p_callback);
#ifdef __cplusplus
}
#endif
#endif /* _XC_UART_H_ */
@@ -0,0 +1,88 @@
/**
* \file
* Ring buffer library implementation
*/
#include <stdio.h>
#include "ringbuf.h"
/*---------------------------------------------------------------------------*/
void
ringbuf_init(struct ringbuf *r, uint8_t *dataptr, uint16_t size)
{
r->data = dataptr;
r->mask = size;
r->put_ptr = 0;
r->get_ptr = 0;
}
/*---------------------------------------------------------------------------*/
int
ringbuf_put(struct ringbuf *r, uint8_t c)
{
/* Check if buffer is full. If it is full, return 0 to indicate that
the element was not inserted into the buffer.
XXX: there is a potential risk for a race condition here, because
the ->get_ptr field may be written concurrently by the
ringbuf_get() function. To avoid this, access to ->get_ptr must
be atomic. We use an uint8_t type, which makes access atomic on
most platforms, but C does not guarantee this.
*/
if(((r->put_ptr+1)%r->mask)== r->get_ptr ) {
return 0;
}
r->data[r->put_ptr] = c;
r->put_ptr = (r->put_ptr + 1) % r->mask;
if(((r->put_ptr+1)%r->mask)== r->get_ptr )
return 2;
return 1;
}
/*---------------------------------------------------------------------------*/
int
ringbuf_get(struct ringbuf *r)
{
uint8_t c;
/* Check if there are bytes in the buffer. If so, we return the
first one and increase the pointer. If there are no bytes left, we
return -1.
XXX: there is a potential risk for a race condition here, because
the ->put_ptr field may be written concurrently by the
ringbuf_put() function. To avoid this, access to ->get_ptr must
be atomic. We use an uint8_t type, which makes access atomic on
most platforms, but C does not guarantee this.
*/
if(r->put_ptr != r->get_ptr) {
c = r->data[r->get_ptr];
//r->get_ptr = (r->get_ptr + 1)%r->mask;
r->get_ptr +=1;
if(r->get_ptr>=r->mask)
r->get_ptr = r->get_ptr-r->mask;
return c;
} else {
return -1;
}
}
/*---------------------------------------------------------------------------*/
int
ringbuf_size(struct ringbuf *r)
{
return r->mask;
}
/*---------------------------------------------------------------------------*/
int
ringbuf_elements(struct ringbuf *r)
{
if(r->put_ptr>=r->get_ptr)
return r->put_ptr-r->get_ptr;
else
return r->put_ptr+r->mask-r->get_ptr;
}
/*---------------------------------------------------------------------------*/
@@ -0,0 +1,94 @@
/**
* \file
* Header file for the ring buffer library
*/
#ifndef __RINGBUF_H__
#define __RINGBUF_H__
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Structure that holds the state of a ring buffer.
*
* This structure holds the state of a ring buffer. The
* actual buffer needs to be defined separately. This
* struct is an opaque structure with no user-visible
* elements.
*
*/
struct ringbuf {
uint8_t *data;
uint16_t mask;
/* XXX these must be 8-bit quantities to avoid race conditions. */
uint16_t put_ptr, get_ptr;
};
/**
* \brief Initialize a ring buffer
* \param r A pointer to a struct ringbuf to hold the state of the ring buffer
* \param a A pointer to an array to hold the data in the buffer
* \param size_power_of_two The size of the ring buffer, which must be a power of two
*
* This function initiates a ring buffer. The data in the
* buffer is stored in an external array, to which a
* pointer must be supplied. The size of the ring buffer
* must be a power of two and cannot be larger than 128
* bytes.
*
*/
void ringbuf_init(struct ringbuf *r, uint8_t *a,
uint16_t size_power_of_two);
/**
* \brief Insert a byte into the ring buffer
* \param r A pointer to a struct ringbuf to hold the state of the ring buffer
* \param c The byte to be written to the buffer
* \return Non-zero if there data could be written, or zero if the buffer was full.
*
* This function inserts a byte into the ring buffer. It
* is safe to call this function from an interrupt
* handler.
*
*/
int ringbuf_put(struct ringbuf *r, uint8_t c);
/**
* \brief Get a byte from the ring buffer
* \param r A pointer to a struct ringbuf to hold the state of the ring buffer
* \return The data from the buffer, or -1 if the buffer was empty
*
* This function removes a byte from the ring buffer. It
* is safe to call this function from an interrupt
* handler.
*
*/
int ringbuf_get(struct ringbuf *r);
/**
* \brief Get the size of a ring buffer
* \param r A pointer to a struct ringbuf to hold the state of the ring buffer
* \return The size of the buffer.
*/
int ringbuf_size(struct ringbuf *r);
/**
* \brief Get the number of elements currently in the ring buffer
* \param r A pointer to a struct ringbuf to hold the state of the ring buffer
* \return The number of elements in the buffer.
*/
int ringbuf_elements(struct ringbuf *r);
#ifdef __cplusplus
}
#endif
#endif /* __RINGBUF_H__ */
@@ -0,0 +1,596 @@
#include "xc_main.h"
#include "xc_head.h"
#include "xc_gap_api.h"
#include <ctype.h>
#define ATCMD_NAME_MAX_SIZE 32
/*typedef struct
{
const char * name;
int (*func)(char *, int, char *, int);
const char * doc;
} at_cmd_t;*/
static const at_cmd_t g_at_cmds_table[];
static at_rsp_func_t g_at_cmd_rsp_func = NULL;
static task_handle_t g_at_cmd_rst_task;
static uint32_t g_at_cmd_rst_time = 0;
extern const at_cmd_t user_define_at_cmds_table[];
static int at_cmd_help(char *data, int data_len, char *rsp, int rsp_buf_len)
{
at_cmd_t *p_table;
if (data_len == 0)
{
g_at_cmd_rsp_func("+ok\r\n", strlen("+ok\r\n"));
p_table = (at_cmd_t *)&user_define_at_cmds_table[0];
while (p_table->name != NULL && p_table->func != NULL)
{
if (p_table->doc && memcmp(p_table->doc, "\r\n", 2) != 0)
{
g_at_cmd_rsp_func((uint8_t *)p_table->doc, strlen(p_table->doc));
}
p_table++;
}
p_table = (at_cmd_t *)&g_at_cmds_table[0];
while (p_table->name != NULL && p_table->func != NULL)
{
if (p_table->doc && memcmp(p_table->doc, "\r\n", 2) != 0)
{
g_at_cmd_rsp_func((uint8_t *)p_table->doc, strlen(p_table->doc));
}
p_table++;
}
g_at_cmd_rsp_func("\r\n", strlen("\r\n"));
return AT_RESULT_NONE;
}
else
return AT_RESULT_WRONG;
}
static void at_rst_task(void)
{
if (xc_flash_operation_is_finish() && xc_sys_get_time() > g_at_cmd_rst_time)
{
xc_sys_reset();
}
}
static int at_cmd_rst(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
g_at_cmd_rst_time = xc_sys_get_time() + 200;
xc_task_create(&g_at_cmd_rst_task, at_rst_task);
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
}
static int at_cmd_baud(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
return AT_RESULT_OK;
}
else
{
#if CONFIG_SUPPORT_CONFIG_FILE
int baud = atoi(data);
if (baud == 4800 || baud == 9600 || baud == 19200 || baud == 38400 || baud == 57600 || baud == 115200 || baud == 230400 || baud == 921600)
{
g_config_file.baudrate = baud;
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
#else
return AT_RESULT_DENY;
#endif
}
}
static int at_cmd_name(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
sprintf(rsp, "=%s", (char *)g_config_file.ble_name);
return AT_RESULT_OK;
}
else
{
#if CONFIG_SUPPORT_CONFIG_FILE
if (data_len < sizeof(g_config_file.ble_name) && data_len + g_config_file.adver_data_len <= 26)
{
memset(g_config_file.ble_name, 0, sizeof(g_config_file.ble_name));
memcpy(g_config_file.ble_name, data, data_len);
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
#else
return AT_RESULT_DENY;
#endif
}
}
#if CONFIG_SUPPORT_CONFIG_FILE || CONFIG_SUPPORT_SECUKEY
static int get_number_from_string(char *string, int start_index, int end_index, int base)
{
int i, num, number = 0;
char c;
for (i = start_index; i <= end_index; i++)
{
c = string[i];
if (base == 10)
{
if (c >= '0' && c <= '9')
num = c - '0';
else
return -1;
}
else if (base == 16)
{
if (c >= '0' && c <= '9')
num = c - '0';
else if (c >= 'a' && c <= 'f')
num = c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
num = c - 'A' + 10;
else
return -1;
}
else
return -1;
number = number*base + num;
}
return number;
}
#endif
static int at_cmd_adp(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
sprintf(rsp, "=%04d%04d%d%d", g_config_file.adver_min, g_config_file.adver_max, g_config_file.adver_type, g_config_file.adver_channel);
return AT_RESULT_OK;
}
else
{
#if CONFIG_SUPPORT_CONFIG_FILE
if (data_len == 10)
{
uint16_t adver_min = (uint16_t)get_number_from_string(data, 0, 3, 10);
uint16_t adver_max = (uint16_t)get_number_from_string(data, 4, 7, 10);
uint8_t adver_type = (uint8_t)get_number_from_string(data, 8, 8, 10);
uint8_t adver_channel = (uint8_t)get_number_from_string(data, 9, 9, 10);
if (adver_min < 0x0020 || adver_min > adver_max)
return AT_RESULT_WRONG;
if (adver_max < adver_min || adver_max > 0x6400)
return AT_RESULT_WRONG;
if (adver_type != 0 && adver_type != 1)
return AT_RESULT_WRONG;
if (adver_channel <= 0 || adver_channel > 7)
return AT_RESULT_WRONG;
g_config_file.adver_min = adver_min;
g_config_file.adver_max = adver_max;
g_config_file.adver_type = adver_type;
g_config_file.adver_channel = adver_channel;
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
#else
return AT_RESULT_DENY;
#endif
}
}
static int at_cmd_adv(char *data, int data_len, char *rsp, int rsp_buf_len)
{
int i;
if (data_len == 0)
{
strcpy(rsp, "=");
for (i = 0; i < g_config_file.adver_data_len; i++)
sprintf(rsp+strlen(rsp), "%02X", g_config_file.adver_data[i]);
return AT_RESULT_OK;
}
else
{
#if CONFIG_SUPPORT_CONFIG_FILE
uint8_t adver_data[26];
int tmp;
if ((data_len%2 != 0) || (data_len > sizeof(adver_data)*2))
return AT_RESULT_WRONG;
for (i = 0; i < data_len/2; i++)
{
tmp = get_number_from_string(data, i*2, i*2+1, 16);
if (tmp < 0)
return AT_RESULT_WRONG;
adver_data[i] = (uint8_t)(tmp&0xFF);
}
if (i + strlen((char *)g_config_file.ble_name) <= 26)
{
memset(g_config_file.adver_data, 0, sizeof(g_config_file.adver_data));
memcpy(g_config_file.adver_data, adver_data, i);
g_config_file.adver_data_len = i;
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
#else
return AT_RESULT_DENY;
#endif
}
}
static int at_cmd_adval(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
sprintf(rsp, "=%d", 1);
return AT_RESULT_OK;
}
else
{
return AT_RESULT_WRONG;
}
}
static int at_cmd_disc(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
xc_disconnect();
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
}
static int at_cmd_power(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
sprintf(rsp, "=%d", g_config_file.txpower);
return AT_RESULT_OK;
}
else
{
#if CONFIG_SUPPORT_CONFIG_FILE
int power = atoi(data);
if (power >= -10 && power <= 13)
{
g_config_file.txpower = (int8_t)power;
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
#else
return AT_RESULT_DENY;
#endif
}
}
static int at_cmd_mac(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
uint8_t *mac = xc_ble_get_mac(NULL);
sprintf(rsp, "=%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return AT_RESULT_OK;
}
else
{
#if CONFIG_SUPPORT_CONFIG_FILE
uint8_t mac[6];
int i, tmp;
if (data_len == 12)
{
for (i = 0; i < 6; i++)
{
tmp = get_number_from_string(data, i*2, i*2+1, 16);
if (tmp < 0)
return AT_RESULT_WRONG;
mac[i] = (uint8_t)(tmp&0xFF);
}
memcpy(g_config_file.mac, mac, 6);
return AT_RESULT_OK;
}
else if (data_len == 5 && memcmp(data, "erase", 5) == 0)
{
memset(g_config_file.mac, 0, 6);
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
#else
return AT_RESULT_DENY;
#endif
}
}
static int at_cmd_ver(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
sprintf(rsp, "=V%s", xc_sys_get_sdk_version());
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
}
static int at_cmd_save(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
extern uint8_t g_uart_do_save;
extern uint8_t g_uart_after_save;
extern uint32_t g_uart_save_time;
if (g_uart_do_save != 0)
return AT_RESULT_WRONG;
else
{
xc_config_save(CONFIG_ERASE_FLAG);
g_uart_do_save = 1;
g_uart_after_save = 1;
g_uart_save_time = xc_sys_get_time();
return AT_RESULT_NONE;
}
}
else
return AT_RESULT_WRONG;
}
static int at_cmd_restore(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
extern uint8_t g_uart_do_save;
extern uint8_t g_uart_after_save;
extern uint32_t g_uart_save_time;
if (g_uart_do_save != 0)
return AT_RESULT_WRONG;
else
{
xc_config_clean();
xc_config_save(CONFIG_ERASE_FLAG);
g_uart_do_save = 1;
g_uart_after_save = 1;
g_uart_save_time = xc_sys_get_time();
return AT_RESULT_NONE;
}
}
else
return AT_RESULT_WRONG;
}
static int at_cmd_conn(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 0)
{
uint8_t *slave_mac = xc_ble_slave_mac(NULL);
sprintf(rsp, "=%02X%02X%02X%02X%02X%02X", slave_mac[0], slave_mac[1], slave_mac[2], slave_mac[3], slave_mac[4], slave_mac[5]);
return AT_RESULT_OK;
}
else
{
uint8_t slave_mac[6];
int i, tmp;
if (data_len == 12)
{
for (i = 0; i < 6; i++)
{
tmp = get_number_from_string(data, i*2, i*2+1, 16);
if (tmp < 0)
return AT_RESULT_WRONG;
slave_mac[i] = (uint8_t)(tmp&0xFF);
printf("%x ", slave_mac[i]);
}
if(memcmp(g_config_file.slave_mac,slave_mac,6) != 0)
{
xc_ble_disconnect(0x0, 0x16);
}
memcpy(g_config_file.slave_mac, slave_mac, 6);
g_config_file.con_sta = 1;
return AT_RESULT_OK;
}
else if (data_len == 5 && memcmp(data, "erase", 5) == 0)
{
memset(g_config_file.slave_mac, 0, 6);
return AT_RESULT_OK;
}
else
return AT_RESULT_WRONG;
}
}
static int at_cmd_scan(char *data, int data_len, char *rsp, int rsp_buf_len)
{
if (data_len == 12)
{
uint8_t scan_mac[6];
int i, tmp;
for (i = 0; i < 6; i++)
{
tmp = get_number_from_string(data, i*2, i*2+1, 16);
if (tmp < 0)
return AT_RESULT_WRONG;
scan_mac[i] = (uint8_t)(tmp&0xFF);
}
memcpy(g_config_file.scan_mac, scan_mac, 6);
extern uint8_t find_suc;
if(find_suc)
{
uint8_t *slave_scan_mac = xc_ble_scan_mac(NULL);
sprintf(rsp, "FInd idx success =%02X%02X%02X%02X%02X%02X", slave_scan_mac[0], slave_scan_mac[1], slave_scan_mac[2], slave_scan_mac[3], slave_scan_mac[4], slave_scan_mac[5]);
}
return AT_RESULT_OK;
}
else if(data_len == 0)
{
{
uint8_t *slave_scan_mac = xc_ble_scan_mac(NULL);
sprintf(rsp, "FInd idx success =%02X%02X%02X%02X%02X%02X", slave_scan_mac[0], slave_scan_mac[1], slave_scan_mac[2], slave_scan_mac[3], slave_scan_mac[4], slave_scan_mac[5]);
}
return AT_RESULT_OK;
}
else
{
return AT_RESULT_WRONG;
}
}
static const at_cmd_t g_at_cmds_table[] = {
{"HELP", at_cmd_help, "AT+HELP: Show all command.\r\n"},
{"SCAN", at_cmd_scan, "AT+SCAN: Scan and Query/Get the Corresponding BLE Device.\r\n"},
{"CON", at_cmd_conn, "AT+CONN: Retrieve / connect to the corresponding device\r\n"},
{"RST", at_cmd_rst, "AT+RST: Reset the module.\r\n"},
{"BAUD", at_cmd_baud, "AT+BAUD: Set/Get the uart baud rate.\r\n"},
{"NAME", at_cmd_name, "AT+NAME: Set/Get ble name.\r\n"},
{"ADP", at_cmd_adp, "AT+ADP: Set/Get ble advertise parameters.\r\n"},
{"ADV", at_cmd_adv, "AT+ADV: Set/Get ble advertise data.\r\n"},
{"ADVAL", at_cmd_adval, "AT+ADVAL: Start/Stop ble advertise.\r\n"},
//{"CIT", at_cmd_cit, "AT+CIT: Set/Get ble connection data.\r\n"},
{"DISC", at_cmd_disc, "AT+DISC: Disconnect ble.\r\n"},
{"POWER", at_cmd_power, "AT+POWER: Set/Get tx power.\r\n"},
{"MAC", at_cmd_mac, "AT+MAC: Set/Get mac address.\r\n"},
{"VER", at_cmd_ver, "AT+VER: Get the version.\r\n"},
//{"PID", at_cmd_pid, "AT+PID: Set/Ge PID.\r\n"},
#if (SLEEP_ENABLE)
#if CONFIG_SUPPORT_DEEPSLEEP
{"SLEEP", at_cmd_sleep, "AT+SLEEP: Enter deep-sleep mode.\r\n"},
#endif
#endif
{"SAVE", at_cmd_save, "AT+SAVE: Save setting.\r\n"},
{"RESTORE", at_cmd_restore, "AT+RESTORE: Reload the default setting and reboot.\r\n"},
//{"OTA", at_cmd_ota, "AT+OTA: Firmware update.\r\n"},
{NULL, NULL, NULL}
};
static at_cmd_t *at_find_cmd(char *cmd_name)
{
at_cmd_t *p_table = (at_cmd_t *)&user_define_at_cmds_table[0];
while (p_table->name != NULL && p_table->func != NULL)
{
if (strcmp(cmd_name, p_table->name) == 0)
{
return p_table;
}
p_table++;
}
p_table = (at_cmd_t *)&g_at_cmds_table[0];
while (p_table->name != NULL && p_table->func != NULL)
{
if (strcmp(cmd_name, p_table->name) == 0)
{
return p_table;
}
p_table++;
}
return NULL;
}
int xc_at_process_cmd(uint8_t *data, int len, char *rsp, int rsp_buf_len)
{
char cmd_name[ATCMD_NAME_MAX_SIZE];
uint8_t bpara = 0;
char *p_data = NULL;
int p_data_len = 0;
at_cmd_t *p_cmd = NULL;
int i, j = 0;
memset(cmd_name, 0, sizeof(cmd_name));
for (i = 3; i < len; i++)
{
if (data[i] == '=')
bpara = 1;
else if (data[i] == '\r' || data[i] == '\n')
break;
else
{
if (bpara == 0)
cmd_name[j++] = toupper(data[i]);
else
{
if (p_data == NULL)
p_data = (char *)(data+i);
p_data_len++;
}
}
}
if (j <= 0 || j >= ATCMD_NAME_MAX_SIZE)
{
xc_debug("[ATCMD] cmd_name parse failed\r\n");
return AT_RESULT_ERROR;
}
p_cmd = at_find_cmd(cmd_name);
if (p_cmd == NULL)
{
xc_debug("[ATCMD] not found cmd: %s (len=%d)\r\n", cmd_name, j);
return AT_RESULT_ERROR;
}
//xc_debug("[ATCMD] cmd: %s, data: %s, data_len: %d\r\n", cmd_name, p_data, p_data_len);
return p_cmd->func(p_data, p_data_len, rsp, rsp_buf_len);
}
int xc_at_data_handle(uint8_t *data, int len, at_rsp_func_t rsp_func)
{
char rsp[256];
int ret;
if (rsp_func == NULL)
return -1;
g_at_cmd_rsp_func = rsp_func;
memset(rsp, 0, sizeof(rsp));
ret = xc_at_process_cmd(data, len, rsp+3, sizeof(rsp)-3);
if (ret == AT_RESULT_OK)
memcpy(rsp, AT_RESPONSE_OK, 3);
else if (ret == AT_RESULT_ERROR)
strcpy(rsp, AT_RESPONSE_ERROR);
else if (ret == AT_RESULT_WRONG)
strcpy(rsp, AT_RESPONSE_WRONG);
else if (ret == AT_RESULT_DENY)
strcpy(rsp, AT_RESPONSE_DENY);
else if (ret == AT_RESULT_NONE)
strcpy(rsp, "");
if (strlen(rsp) > 0)
{
strcat(rsp, AT_RESPONSE_EOF);
g_at_cmd_rsp_func((uint8_t *)rsp, strlen(rsp));
}
return 0;
}
@@ -0,0 +1,233 @@
#include "xc_main.h"
#include "xc_head.h"
#include "ringbuf.h"
#include "xc_gap_api.h"
#define BLE_SEND_USE_LIST
static uint8_t g_ble_is_start = 0;
static uint8_t g_ble_is_connected = 0;
static uint8_t g_ble_ntf_is_enable = 0;
static ble_event_callback_t g_ble_event_callback = NULL;
#define MIN_NUM(a, b) ((a < b) ? (a) : (b))
#define BLE_SEND_RINGBUF_SIZE 512
#define BLE_SEND_BUF_SIZE 256
static struct ringbuf g_ble_send_ringbuf;
static uint8_t g_ble_send_ringbuf_buf[BLE_SEND_RINGBUF_SIZE];
static uint8_t g_ble_is_in_sending = 0;
static uint32_t g_ble_send_ringbuf_overflow = 0;
WEAK int ble_send_notify_data(uint8_t *buffer, int length)
{
(void)buffer;
(void)length;
return 0;
}
void ble_data_send_callback(void)
{
uint8_t buf[BLE_SEND_BUF_SIZE];
int len = 0;
int ch;
int bytes;
g_ble_is_in_sending = 0;
bytes = ringbuf_elements(&g_ble_send_ringbuf);
bytes = MIN_NUM(bytes, xc_ble_get_mtu_size() - 3);
bytes = MIN_NUM(bytes, BLE_SEND_BUF_SIZE);
if (bytes > 0)
{
while (len < bytes)
{
if ((ch = ringbuf_get(&g_ble_send_ringbuf)) == -1)
break;
buf[len++] = (uint8_t)(ch & 0xFF);
}
g_ble_is_in_sending = 1;
ble_send_notify_data(buf, len);
}
}
static int ble_data_send(uint8_t *data, int len)
{
int send_len = 0;
while (send_len < len)
{
if (ringbuf_put(&g_ble_send_ringbuf, data[send_len]) == 0)
{
g_ble_send_ringbuf_overflow += (len - send_len);
xc_debug("ble send overflow %d bytes\r\n", g_ble_send_ringbuf_overflow);
break;
}
send_len++;
}
if (g_ble_is_in_sending == 0)
{
ble_data_send_callback();
}
return send_len;
}
int xc_ble_status_callback(int status)
{
if (status == BLE_EVENT_INIT)
{
g_ble_is_start = 1;
}
else if (status == BLE_EVENT_ADV_START)
{
}
else if (status == BLE_EVENT_ADV_STOP)
{
}
else if (status == BLE_EVENT_CONNECTED)
{
g_ble_is_connected = 1;
#ifdef BLE_SEND_USE_LIST
ringbuf_init(&g_ble_send_ringbuf, (uint8_t *)g_ble_send_ringbuf_buf, BLE_SEND_RINGBUF_SIZE);
g_ble_is_in_sending = 0;
#endif
}
else if (status == BLE_EVENT_DISCONNECTED)
{
g_ble_is_connected = 0;
}
else if (status == BLE_EVENT_NTF_ENABLE)
{
g_ble_ntf_is_enable = 1;
}
else if (status == BLE_EVENT_NTF_DISABLE)
{
g_ble_ntf_is_enable = 0;
}
if (g_ble_event_callback)
g_ble_event_callback(status, NULL, 0);
return 0;
}
int xc_ble_data_recv_callback(void *data, uint32_t bytes)
{
if (g_ble_event_callback)
g_ble_event_callback(BLE_EVENT_NTF_DATA, data, bytes);
return 0;
}
/*int xc_ble_set_mtu_size_callback(uint16_t mtu)
{
g_ble_mtu_size = mtu;
return 0;
}*/
int xc_ble_is_start(void)
{
if (g_ble_is_start)
return 1;
else
return 0;
}
int xc_ble_is_connected(void)
{
if (g_ble_is_connected)
return 1;
else
return 0;
}
int xc_ble_data_send(void *data, uint32_t bytes)
{
printf("%s g_ble_is_connected = %d g_ble_ntf_is_enable = %d \n", __func__, g_ble_is_connected, g_ble_ntf_is_enable);
if (!g_ble_is_connected || !g_ble_ntf_is_enable)
return 0;
return ble_data_send(data, bytes);
}
WEAK uint16_t get_mtu_size(void)
{
return 23; // Default MTU size
}
int xc_ble_get_mtu_size(void)
{
extern uint16_t get_mtu_size();
return (int)get_mtu_size();
}
uint8_t *xc_ble_get_mac(uint8_t *mac)
{
uint8_t *ble_mac;
if (g_config_file.mac[0] != 0 || g_config_file.mac[1] != 0 || g_config_file.mac[2] != 0 || g_config_file.mac[3] != 0 || g_config_file.mac[4] != 0 || g_config_file.mac[5] != 0)
ble_mac = (uint8_t *)g_config_file.mac;
else
{
extern const uint8_t DEFAULT_BLE_MAC[6];
ble_mac = (uint8_t *)DEFAULT_BLE_MAC;
}
if (mac)
memcpy(mac, ble_mac, 6);
return ble_mac;
}
uint8_t *xc_ble_slave_mac(uint8_t *mac)
{
uint8_t *ble_slave_mac;
if (g_config_file.slave_mac[0] != 0 || g_config_file.slave_mac[1] != 0 || g_config_file.slave_mac[2] != 0 || g_config_file.slave_mac[3] != 0 || g_config_file.slave_mac[4] != 0 || g_config_file.slave_mac[5] != 0)
ble_slave_mac = (uint8_t *)g_config_file.slave_mac;
else
{
extern const uint8_t DEFAULT_SLAVE_MAC[6];
ble_slave_mac = (uint8_t *)DEFAULT_SLAVE_MAC;
}
if (mac)
memcpy(mac, ble_slave_mac, 6);
return ble_slave_mac;
}
uint8_t *xc_ble_scan_mac(uint8_t *mac)
{
uint8_t *ble_scan_mac;
if (g_config_file.scan_mac[0] != 0 || g_config_file.scan_mac[1] != 0 || g_config_file.scan_mac[2] != 0 || g_config_file.scan_mac[3] != 0 || g_config_file.scan_mac[4] != 0 || g_config_file.scan_mac[5] != 0)
ble_scan_mac = (uint8_t *)g_config_file.scan_mac;
else
{
extern const uint8_t DEFAULT_SLAVE_MAC[6];
ble_scan_mac = (uint8_t *)DEFAULT_SLAVE_MAC;
}
if (mac)
memcpy(mac, ble_scan_mac, 6);
return ble_scan_mac;
}
int xc_disconnect(void)
{
if (g_ble_is_connected)
{
xc_ble_disconnect(0x0, 0x16);
}
return 0;
}
int xc_ble_register_callback(ble_event_callback_t p_callback)
{
g_ble_event_callback = p_callback;
return 0;
}
@@ -0,0 +1,173 @@
#include "xc_main.h"
#include "xc_head.h"
#include "rf.h"
const uint8_t DEFAULT_BLE_MAC[6] = {0x90, 0xEB, 0x48, 0x00, 0x00, 0x01};
const uint8_t DEFAULT_SLAVE_MAC[6] = {0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
#if CONFIG_SUPPORT_CONFIG_FILE
XC_CONFIG_DATA g_config_file __attribute__ ((aligned(4)));
const XC_CONFIG_DATA g_config_file_default __attribute__ ((aligned(4))) = {
#else
const XC_CONFIG_DATA g_config_file __attribute__ ((aligned(4))) = {
#endif
.magicflag = CONFIG_MAGIC_FLAG,
.debug_level = 0,
.mac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
.ble_name = "XinChip_AT",
.adver_type = 0,
.adver_channel = 0x07,
.adver_data = {0x05, 0xFE, 0x01, 0x02, 0x03, 0x04},
.adver_data_len = 0,
.adver_min = 800,
.adver_max = 800,
.conn_min = 16,
.conn_max = 32,
.conn_latency = 0,
.supervisionTO = 200,
.uuid_server = {0xFF, 0xF0},
.uuid_read = {0xFF, 0xF1},
.uuid_write = {0xFF, 0xF2},
.sleep_info = 0,
.txpower = 7,
.baudrate = 115200,
.uart_send_delay = 0,
.reserved = {0, 0, 0, 0, 0, 0},
.slave_mac = {0,0,0,0,0,0},
.con_sta = 0,
.scan_mac = {0,0,0,0,0,0},
.crc8 = 0,
};
uint32_t xc_config_get_tx_power(void)
{
int8_t power = g_config_file.txpower;
if (power <= -10)
return TRANS_POWER_NEGTIVE_8_9_DBM;
else if (power <= -3)
return TRANS_POWER_NEGTIVE_2_7_DBM;
else if (power <= -1)
return TRANS_POWER_0_5DBM;
else if (power <= 0)
return TRANS_POWER_0_6DBM;
else if (power <= 1)
return TRANS_POWER_2_85DBM;
else if (power <= 2)
return TRANS_POWER_2_9DBM;
else if (power <= 4)
return TRANS_POWER_4_68DBM;
/*else if (power <= -1)
return TRANS_POWER_4_6DBM;*/
else if (power <= 6)
return TRANS_POWER_6_1DBM;
else if (power <= 7)
return TRANS_POWER_7_3DBM;
else if (power <= 8)
return TRANS_POWER_8_3DBM;
else if (power <= 9)
return TRANS_POWER_9_2DBM;
else if (power <= 12)
return TRANS_POWER_13_06DBM;
/*else if (power <= 12)
return TRANS_POWER_13_05DBM;*/
else
return TRANS_POWER_13_35DBM;
}
#if CONFIG_SUPPORT_CONFIG_FILE
static uint8_t crc8(uint8_t *ptr, int len)
{
uint8_t crc = 0;
uint8_t i, data;
while(len--)
{
data = (*ptr)&0xFF;
crc ^= data;
for(i = 0;i < 8;i++)
{
if(crc & 0x01)
{
crc = (crc >> 1) ^ 0x8C;
}
else
crc >>= 1;
}
ptr++;
}
return crc;
}
#endif
int xc_config_direct_save(void)
{
extern uint8_t g_uart_do_save;
extern uint8_t g_uart_after_save;
extern uint32_t g_uart_save_time;
if (g_uart_do_save != 0)
return -1;
else
{
xc_config_save(CONFIG_ERASE_FLAG);
g_uart_do_save = 1;
g_uart_after_save = 1;
g_uart_save_time = xc_sys_get_time();
return XC_SUCCESS;
}
}
void xc_config_save(int flag)
{
(void)flag;
#if CONFIG_SUPPORT_CONFIG_FILE
g_config_file.crc8 = crc8((uint8_t *)&g_config_file, sizeof(XC_CONFIG_DATA) - 1);
#if CONFIG_SUPPORT_FLASH
if (flag&CONFIG_ERASE_FLAG)
xc_flash_erase_page(FLASH_ADDR_CONFIG);
if (flag&CONFIG_WRITE_FLAG)
xc_flash_write(FLASH_ADDR_CONFIG, (void *)&g_config_file, sizeof(XC_CONFIG_DATA));
#endif
#endif
}
void xc_config_clean(void)
{
#if CONFIG_SUPPORT_CONFIG_FILE
uint8_t mac[6] = {0, 0, 0, 0, 0, 0};
uint8_t crc = 0;
crc = crc8((uint8_t *)&g_config_file, sizeof(XC_CONFIG_DATA) - 1);
if (g_config_file.magicflag == CONFIG_MAGIC_FLAG && crc == g_config_file.crc8)
memcpy(mac, g_config_file.mac, 6);
memcpy(&g_config_file, &g_config_file_default, sizeof(XC_CONFIG_DATA));
memcpy(g_config_file.mac, mac, 6);
#endif
}
int xc_config_init(void)
{
#if CONFIG_SUPPORT_CONFIG_FILE
uint8_t crc = 0;
#if CONFIG_SUPPORT_FLASH
xc_flash_read(FLASH_ADDR_CONFIG, (void *)&g_config_file, sizeof(XC_CONFIG_DATA));
#endif
crc = crc8((uint8_t *)&g_config_file, sizeof(XC_CONFIG_DATA) - 1);
if (g_config_file.magicflag != CONFIG_MAGIC_FLAG || crc != g_config_file.crc8)
{
#if CONFIG_SUPPORT_CONFIG_FILE
memcpy(&g_config_file, &g_config_file_default, sizeof(XC_CONFIG_DATA));
#endif
xc_debug("config is invalid!\r\n");
}
#endif
return XC_SUCCESS;
}
@@ -0,0 +1,146 @@
#include "xc_main.h"
#include "xc_head.h"
#include "xc6xxx.h"
#include "xc_drv_fmc_spi.h"
#define FLASH_AT_SECTOR_SIZE (4 * 1024)
#define FLASH_PROTECT_START (0 * 1024)
#define FLASH_PROTECT_SIZE (32 * 1024)
#define FLASH_OPER_UNIT (256)
typedef enum
{
FLASH_OP_IDLE = 0,
FLASH_OP_WAIT_WRITE,
FLASH_OP_WAIT_ERASE
} flash_op;
static flash_op g_flash_operation_state = FLASH_OP_IDLE;
static uint32_t g_flash_operation_addr = 0;
static uint8_t *g_flash_operation_buffer = NULL;
static int g_flash_operation_len = 0;
static int flash_check(uint32_t addr, int len)
{
if (addr < FLASH_PROTECT_START + FLASH_PROTECT_SIZE)
return 1;
if (addr + len > FLASH_PROTECT_START && addr + len < FLASH_PROTECT_START + FLASH_PROTECT_SIZE)
return 1;
return 0;
}
int xc_flash_read(uint32_t addr, void *data, int len)
{
#if CONFIG_SUPPORT_FLASH
xc_fmc_spi_flash_read(addr, data, len);
return len;
#else
return -1;
#endif
}
int xc_flash_write(uint32_t addr, void *data, int len)
{
#if CONFIG_SUPPORT_FLASH
if (flash_check(addr, FLASH_AT_SECTOR_SIZE))
return -1;
if (g_flash_operation_state != FLASH_OP_IDLE)
return -1;
if (xc_ble_is_start())
{
g_flash_operation_addr = addr;
g_flash_operation_buffer = data;
g_flash_operation_len = len;
g_flash_operation_state = FLASH_OP_WAIT_WRITE;
}
else
{
GLOBAL_INT_DISABLE();
// xc_fmc_spi_flash_write(addr, data, len);
FMC_SPI_FlashWrite(addr, data, len);
GLOBAL_INT_RESTORE();
}
return 0;
#else
return -1;
#endif
}
int xc_flash_erase_page(uint32_t addr)
{
#if CONFIG_SUPPORT_FLASH
if ((addr & 0xFFFFF000) != addr)
return -1;
if (flash_check(addr, FLASH_AT_SECTOR_SIZE))
return -1;
if (g_flash_operation_state != FLASH_OP_IDLE)
return -1;
if (xc_ble_is_start())
{
g_flash_operation_addr = addr;
g_flash_operation_state = FLASH_OP_WAIT_ERASE;
}
else
{
GLOBAL_INT_DISABLE();
xc_fmc_spi_flash_erase_sector(addr);
GLOBAL_INT_RESTORE();
}
return 0;
#else
return -1;
#endif
}
int xc_flash_operation_is_finish(void)
{
if (g_flash_operation_state == FLASH_OP_IDLE)
return 1;
else
return 0;
}
int xc_flash_handle(void)
{
if (g_flash_operation_state == FLASH_OP_WAIT_WRITE)
{
GLOBAL_INT_DISABLE();
// xc_fmc_spi_flash_write(g_flash_operation_addr, g_flash_operation_buffer, g_flash_operation_len);
FMC_SPI_FlashWrite(g_flash_operation_addr, g_flash_operation_buffer, g_flash_operation_len);
GLOBAL_INT_RESTORE();
g_flash_operation_state = FLASH_OP_IDLE;
}
else if (g_flash_operation_state == FLASH_OP_WAIT_ERASE)
{
GLOBAL_INT_DISABLE();
xc_fmc_spi_flash_erase_sector(g_flash_operation_addr);
GLOBAL_INT_RESTORE();
g_flash_operation_state = FLASH_OP_IDLE;
}
return 0;
}
int xc_flash_init(void)
{
return XC_SUCCESS;
}
int xc_flash_get_ruid(uint8_t *ruid)
{
if (ruid)
{
xc_fmc_spi_flash_ruid(ruid);
return XC_SUCCESS;
}
return -1;
}
@@ -0,0 +1,81 @@
#include "xc_main.h"
#include "xc_head.h"
//#include "xc_secukey.h"
#include "../uart_task.h"
#include "xc6xxx.h"
static void hardware_time_init(void)
{
RTC_InitCfg_t rtc_cfg = {0};
rtc_cfg.Date.Sec = 0;
rtc_cfg.Date.Min = 0;
rtc_cfg.Date.Hour = 0;
rtc_cfg.Date.Day = 0;
rtc_cfg.Date.Week = 0;
rtc_cfg.DateLimit.SecLimit = 60;
rtc_cfg.DateLimit.MinLimit = 60;
rtc_cfg.DateLimit.HourLimit = 24;
rtc_cfg.MatchTime.ch = RTC_MATCH_T1;
rtc_cfg.MatchTime.Sec = 0;
rtc_cfg.MatchTime.Min = 0;
rtc_cfg.MatchTime.Hour = 0;
rtc_cfg.MatchTime.Week = RTC_MATCH_SATURDAY;
rtc_cfg.MatchTimeEnable = false;
rtc_cfg.SecIT_Enable = false;
rtc_cfg.MinIT_Enable = false;
rtc_cfg.HourIT_Enable = false;
rtc_cfg.DayIT_Enable = false;
xc_rtc_init(&rtc_cfg);
xc_rtc_start();
}
__RAM_CODE uint32_t hardware_time_get(void)
{
return rtc_ccvr_get() * 1000 + (rtc_rvr_get() * 1000) / 32768;
}
void xc_main_init(void)
{
static uint8_t init_flag = 0;
if (init_flag == 0)
{
init_flag = 1;
xc_sys_init();
xc_flash_init();
xc_config_init();
}
}
void xc_main_start(void)
{
xc_debug("sdk version: %s, build time: %s %s\r\n", xc_sys_get_sdk_version(), __DATE__, __TIME__);
// 1. system init
xc_main_init();
// 2. start hardware time
hardware_time_init();
// 3. start application
uart_task_start();
// 5. start user_main
extern int user_main(void);
user_main();
}
void xc_main_run(void)
{
extern void xc_task_run(void);
xc_task_run();
extern int xc_flash_handle(void);
xc_flash_handle();
}
@@ -0,0 +1,79 @@
#include "xc_main.h"
#include "xc_head.h"
#include "xc6xxx.h"
static sys_event_callback_t g_sys_event_callback = NULL;
static void hardware_reset(void)
{
WDT_InitCfg_t wdt_cfg;
NVIC_EnableIRQ(WDT_IRQn);
wdt_cfg.WorkMode = WDT_WORK_MODE0;
wdt_cfg.ReloadValue = WDT_CLK_32M_RESET_MODE1_65536US;
wdt_cfg.PclkSel = WDT_WORK_32M;
xc_wdt_init(&wdt_cfg);
xc_wdt_start();
}
const char *xc_sys_get_sdk_version(void)
{
return SDK_VER;
}
uint32_t xc_sys_get_time(void)
{
extern uint32_t hardware_time_get(void);
return hardware_time_get();
}
void xc_sys_reset(void)
{
if (g_sys_event_callback)
g_sys_event_callback(SYS_EVENT_REBOOT, NULL);
hardware_reset();
while (1)
;
}
void xc_sys_wait_us(uint32_t us)
{
delay_us(us);
}
#if (SLEEP_ENABLE)
#if CONFIG_SUPPORT_DEEPSLEEP
void xc_sys_enter_deepsleep(int wake_gpio, int wake_level)
{
uint8_t wake_pin = ((wake_gpio & 0xFF) + GPIO_0);
system_sleep_init();
// PWRKEY Initialization is required after deep sleep wakeup
xc_pwr_pwrkey_init();
if (wake_gpio != NOPIN)
xc_pwr_pwrkey_deepsleep_wake_config(wake_pin, !wake_level);
system_deepsleep_cfg();
int xc_gpio_configure_sleep_check(void);
xc_gpio_configure_sleep_check();
while (1)
{
xc_deep_sleep();
}
}
#endif
#endif
int xc_sys_register_event(sys_event_callback_t p_callback)
{
g_sys_event_callback = p_callback;
return XC_SUCCESS;
}
int xc_sys_init(void)
{
return XC_SUCCESS;
}
@@ -0,0 +1,61 @@
#include "xc_main.h"
#include "xc_head.h"
static task_handle_t *g_task_head = NULL;
static task_handle_t *g_task_run = NULL;
task_handle_t *xc_task_create(task_handle_t *task, task_func_t func)
{
task_handle_t *tmp;
if (task == NULL)
{
return NULL;
}
if (task)
{
task->func = func;
task->run_flag = 1;
if (g_task_head == NULL)
{
g_task_head = task;
g_task_run = g_task_head;
}
else
{
tmp = g_task_head;
while (tmp->next)
tmp = tmp->next;
tmp->next = task;
}
func();
return task;
}
else
return NULL;
}
void xc_task_delete(task_handle_t *task)
{
if (task)
{
task->run_flag = 0;
}
}
void xc_task_run(void)
{
task_handle_t *tmp = g_task_run;
if (tmp && tmp->func)
{
tmp->func();
tmp = tmp->next;
if (tmp)
g_task_run = tmp;
else
g_task_run = g_task_head;
}
}
@@ -0,0 +1,179 @@
#include "xc_main.h"
#include "xc_head.h"
#include "ringbuf.h"
#include "xc6xxx.h"
#define UART0_IRQ_SIZE 256
static uint8_t g_uart_init[2] = {0, 0};
static struct ringbuf g_uart0_ringbuf;
static uint8_t g_uart0_ringbuf_buf[UART0_IRQ_SIZE];
uart_event_callback_t g_uart_event_callback = NULL;
static uint32_t g_uart0_ringbuf_buf_overflow = 0;
static FUNC_IN_RAM void UART0_handler_callback(uint8_t *buff, uint16_t len)
{
if (g_uart_init[0] == 0)
return;
int i;
for (i = 0; i < len; i++)
{
if (ringbuf_put(&g_uart0_ringbuf, buff[i]) == 0)
{
g_uart0_ringbuf_buf_overflow += (len - i);
xc_debug("uart0 irq overflow %d bytes\r\n", g_uart0_ringbuf_buf_overflow);
break;
}
}
}
static FUNC_IN_RAM void UART_handler_callback(uint8_t *buff, uint16_t len)
{
UART0_handler_callback(buff, len);
}
static uint32_t conv_baudrate(int baudrate)
{
if (baudrate == 4800)
return UART_BAUDRATE_4800;
else if (baudrate == 9600)
return UART_BAUDRATE_9600;
else if (baudrate == 19200)
return UART_BAUDRATE_19200;
else if (baudrate == 38400)
return UART_BAUDRATE_38400;
else if (baudrate == 57600)
return UART_BAUDRATE_57600;
else if (baudrate == 115200)
return UART_BAUDRATE_115200;
else if (baudrate == 230400)
return UART_BAUDRATE_230400;
else if (baudrate == 921600)
return UART_BAUDRATE_921600;
else if (baudrate == 1000000)
return UART_BAUDRATE_1M;
else
return UART_BAUDRATE_115200;
}
uart_handle_t xc_uart_open(int uart_id, int baudrate)
{
if (uart_id != 0 && uart_id != 1)
return NULL;
if (g_uart_init[uart_id] != 0)
return NULL;
if (uart_id == 0)
{
printf("%s\n", __func__);
ringbuf_init(&g_uart0_ringbuf, (uint8_t *)g_uart0_ringbuf_buf, UART0_IRQ_SIZE);
// because modeify retarget UART, need config UART pin
GPIO_InitCfg_t gpio_cfg = {0};
gpio_cfg.Mux = GPIO_Mux0;
gpio_cfg.Pull = GPIO_PULLUP;
gpio_cfg.Int = NOT_INT;
gpio_cfg.Pin = GPIO_18;
gpio_cfg.Dir = GPIO_DIR_OUTPUT;
gpio_cfg.FunSel = UART1_TX;
xc_gpio_init(&gpio_cfg);
gpio_cfg.Pin = GPIO_19;
gpio_cfg.Dir = GPIO_DIR_INPUT;
gpio_cfg.FunSel = UART1_RX;
xc_gpio_init(&gpio_cfg);
UART_InitCfg_t uart_cfg = {0};
uart_cfg.Parity = UART_PARITY_DISABLE;
uart_cfg.StopBits = UART_TCR_STOP_1BITS;
uart_cfg.WordLength = UART_DATA_8_BITS;
uart_cfg.BaudRate = conv_baudrate(baudrate);
uart_cfg.HardwareFlowControl = UART_HWFC_DISABLE;
xc_uart_init(UART1_IDX, &uart_cfg);
xc_uart_register_receive_cb(UART1_IDX, UART_handler_callback);
xc_uart_enable_rx_it(UART1_IDX);
NVIC_EnableIRQ(UART1_IRQn);
g_uart_init[0] = 1;
return (uart_handle_t)XC_UART0;
}
else if (uart_id == 1)
{
}
return NULL;
}
int xc_uart_recv(uart_handle_t uart_handle, void *data, uint32_t bytes)
{
int len = 0;
int ch;
int uart_id = (int)uart_handle - (int)XC_UART0;
uint8_t *p_data = (uint8_t *)data;
if (g_uart_init[uart_id] == 0)
return -1;
if (uart_id == 0)
{
while (len < bytes)
{
if ((ch = ringbuf_get(&g_uart0_ringbuf)) == -1)
break;
p_data[len++] = (uint8_t)(ch & 0xFF);
}
}
else if (uart_id == 1)
{
}
return len;
}
int xc_uart_send(uart_handle_t uart_handle, void *data, uint32_t bytes)
{
int uart_id = (int)uart_handle - (int)XC_UART0;
if (g_uart_init[uart_id] == 0)
return -1;
if (uart_id == 0)
{
xc_uart_send_data(UART1_IDX, data, bytes);
}
else if (uart_id == 1)
{
}
return bytes;
}
int xc_uart_close(uart_handle_t uart_handle)
{
int uart_id = (int)uart_handle - (int)XC_UART0;
if (g_uart_init[uart_id] == 0)
return -1;
if (uart_id == 0)
{
}
else if (uart_id == 1)
{
}
g_uart_init[uart_id] = 0;
return XC_SUCCESS;
}
int xc_uart_register_callback(uart_event_callback_t p_callback)
{
g_uart_event_callback = p_callback;
return XC_SUCCESS;
}
@@ -0,0 +1,140 @@
#include "xc_main.h"
#include "xc_head.h"
#include "uart_task.h"
#include <ctype.h>
#define UART_TASK_BUF_SIZE 256
#define UART_DATA_WAIT_TIME 50
static task_handle_t g_uart_task;
static uart_handle_t g_uart_handle = NULL;
static uint8_t g_uart_buf[UART_TASK_BUF_SIZE];
uint8_t g_uart_do_save = 0;
uint8_t g_uart_after_save = 0;
uint32_t g_uart_save_time = 0;
#define AT_CMD_HDR ("AT+")
static int uart_data_is_atcmd(uint8_t *data, int len)
{
char cmd_hdr[4];
int i;
if (len <= 3)
return 0;
cmd_hdr[0]=(char)toupper((int)data[0]);
cmd_hdr[1]=(char)toupper((int)data[1]);
cmd_hdr[2]=(char)toupper((int)data[2]);
cmd_hdr[3]='\0';
if (memcmp(cmd_hdr, AT_CMD_HDR, strlen(AT_CMD_HDR)) != 0)
return 0;
for (i = 0; i < len; i++)
{
if (data[i] == '\r' || data[i] == '\n')
return 1;
}
return 0;
}
int uart_data_send(uint8_t *data, int len)
{
return xc_uart_send(g_uart_handle, data, len);
}
static void uart_data_handle(uint8_t *data, int len)
{
//xc_debug("uart recv %d bytes\r\n", len);
//xc_debug_hex(data, len);
if (uart_data_is_atcmd(data, len))
{
xc_at_data_handle(data, len, uart_data_send);
}
else
{
extern uart_event_callback_t g_uart_event_callback;
if (g_uart_event_callback)
len = g_uart_event_callback(UART0_EVENT_DATA, data, len);
}
}
static void uart_do_save_check(void)
{
if (!(g_uart_do_save != 0 && xc_sys_get_time() - g_uart_save_time > 100))
return;
g_uart_save_time = xc_sys_get_time();
if (g_uart_do_save == 1 && xc_flash_operation_is_finish())
{
xc_config_save(CONFIG_WRITE_FLAG);
g_uart_do_save = 2;
}
if (g_uart_do_save == 2 && xc_flash_operation_is_finish())
{
if (g_uart_after_save == 1)
uart_data_send(AT_RESPONSE_OK AT_RESPONSE_EOF, strlen(AT_RESPONSE_OK AT_RESPONSE_EOF));
else if (g_uart_after_save == 2)
xc_sys_reset();
g_uart_do_save = 0;
g_uart_after_save =0;
}
}
static int uart_recv_timeout(int baudrate)
{
#if 0
if (baudrate == 4800)
return 200;
else if (baudrate == 9600)
return 100;
else if (baudrate == 19200)
return 100;
else if (baudrate == 38400)
return 100;
else if (baudrate == 57600)
return 100;
else //>=115200
return UART_DATA_WAIT_TIME;
#else
return UART_DATA_WAIT_TIME;
#endif
}
static void uart_task(void)
{
static int recv_num = 0;
static uint32_t recv_time = 0;
int len;
if (g_uart_handle == NULL)
g_uart_handle = xc_uart_open(0, g_config_file.baudrate);
len = xc_uart_recv(g_uart_handle, g_uart_buf + recv_num, UART_TASK_BUF_SIZE - recv_num);
if (len > 0)
{
recv_num += len;
recv_time = xc_sys_get_time();
}
if (recv_num >= UART_TASK_BUF_SIZE || (recv_num > 0 && xc_sys_get_time() - recv_time > uart_recv_timeout(115200)))
{
uart_data_handle(g_uart_buf, recv_num);
recv_num = 0;
recv_time = 0;
}
uart_do_save_check();
}
void uart_task_start(void)
{
xc_task_create(&g_uart_task, uart_task);
}
@@ -0,0 +1,15 @@
#ifndef _UART_TASK_H_
#define _UART_TASK_H_
void uart_task_start(void);
int uart_data_send(uint8_t *data, int len);
#ifdef __cplusplus
}
#endif
#endif/* _UART_TASK_H_ */
@@ -0,0 +1,92 @@
#include "xc_head.h"
const at_cmd_t user_define_at_cmds_table[] = {
{NULL, NULL, NULL}
};
static int sys_event_callback(uint32_t event_id, void * param)
{
switch (event_id)
{
case SYS_EVENT_REBOOT:
xc_debug("system reboot\r\n");
break;
default:
break;
}
return 0;
}
static int uart_recv_callback(uint32_t event_id, void *data, uint32_t len)
{
if (event_id == UART0_EVENT_DATA)
{
xc_debug("uart recv %d bytes data\r\n", len);
xc_ble_data_send(data, len);
}
return len;
}
static int ble_recv_callback(uint32_t event_id, void *data, uint32_t len)
{
switch (event_id)
{
case BLE_EVENT_INIT:
xc_debug("ble init\r\n");
break;
case BLE_EVENT_ADV_START:
xc_debug("ble adv start\r\n");
xc_uart_send(XC_UART0, "CONN=0\r\n", strlen("CONN=0\r\n"));
break;
case BLE_EVENT_ADV_STOP:
xc_debug("ble adv stop\r\n");
xc_uart_send(XC_UART0, "CONN=1\r\n", strlen("CONN=1\r\n"));
break;
case BLE_EVENT_CONNECTED:
xc_debug("ble connected\r\n");
xc_uart_send(XC_UART0, "CONN=2\r\n", strlen("CONN=2\r\n"));
break;
case BLE_EVENT_DISCONNECTED:
xc_debug("ble disconnected\r\n");
xc_uart_send(XC_UART0, "CONN=3\r\n", strlen("CONN=3\r\n"));
break;
case BLE_EVENT_NTF_ENABLE:
xc_debug("ble enable\r\n");
break;
case BLE_EVENT_NTF_DISABLE:
xc_debug("ble disable\r\n");
break;
case BLE_EVENT_NTF_DATA:
xc_debug("ble recv %d bytes data\r\n", len);
xc_uart_send(XC_UART0, data, len);
break;
default:
break;
}
return 0;
}
int user_main(void)
{
xc_debug("start user_main %s %s\r\n", __DATE__, __TIME__);
if (xc_sys_register_event((sys_event_callback_t)sys_event_callback) != XC_SUCCESS)
{
xc_debug("register uart callback fail!\r\n");
}
if (xc_uart_register_callback((uart_event_callback_t)uart_recv_callback) != XC_SUCCESS)
{
xc_debug("register uart callback fail!\r\n");
}
if (xc_ble_register_callback((ble_event_callback_t)ble_recv_callback) != XC_SUCCESS)
{
xc_debug("register ble callback fail!\r\n");
}
return XC_SUCCESS;
}
@@ -0,0 +1,189 @@
/**
****************************************************************************************
*
* @file app_batt.c
*
* @brief Battery Application Module entry point
*
* Copyright (C) RivieraWaves 2009-2015
*
*
****************************************************************************************
*/
/**
****************************************************************************************
* @addtogroup APP
* @{
****************************************************************************************
*/
#include "rwip_config.h" // SW configuration
#if (BLE_APP_BATT)
/*
* INCLUDE FILES
****************************************************************************************
*/
#include "app_batt.h" // Battery Application Module Definitions
#include "app_task.h" // application task definitions
#include "bass_msg.h" // health thermometer functions
#include "co_bt.h"
#include "co_utils.h"
#include "prf_types.h" // Profile common types definition
#include "arch.h" // Platform Definitions
#include "prf.h"
#include <string.h>
/*
* DEFINES
****************************************************************************************
*/
/*
* GLOBAL VARIABLE DEFINITIONS
****************************************************************************************
*/
/// Battery Application Module Environment Structure
struct app_batt_env_tag app_batt_env;
/*
* GLOBAL FUNCTION DEFINITIONS
****************************************************************************************
*/
void app_batt_init(void)
{
// Reset the environment
memset(&app_batt_env, 0, sizeof(struct app_batt_env_tag));
// Initial battery level: 100
app_batt_env.batt_lvl = 100;
}
void app_batt_add_bas(void)
{
struct bass_db_cfg* db_cfg;
// Allocate the BASS_CREATE_DB_REQ
struct gapm_profile_task_add_cmd *req = KE_MSG_ALLOC_DYN(GAPM_PROFILE_TASK_ADD_CMD,
TASK_GAPM, TASK_APP,
gapm_profile_task_add_cmd, sizeof(struct bass_db_cfg));
// Fill message
req->operation = GAPM_PROFILE_TASK_ADD;
req->sec_lvl = 0;//PERM(SVC_AUTH, AUTH);
req->prf_api_id = TASK_ID_BASS;
req->app_task = TASK_APP;
req->start_hdl = 0;
// Set parameters
db_cfg = (struct bass_db_cfg* ) req->param;
// Add a BAS instance
db_cfg->bas_nb = 1;
// Sending of notifications is supported
db_cfg->features[0] = BAS_BATT_LVL_NTF_SUP;
// Send the message
ke_msg_send(req);
}
void app_batt_enable_prf(uint8_t conidx)
{
app_batt_env.conidx = conidx;
// Allocate the message
struct bass_enable_req * req = KE_MSG_ALLOC(BASS_ENABLE_REQ,
prf_dst_task_get(TASK_ID_BASS),
TASK_APP,
bass_enable_req);
// Fill in the parameter structure
req->conidx = conidx;
// NTF initial status - Disabled
req->ntf_cfg = PRF_CLI_STOP_NTFIND;
req->old_batt_lvl[0] = 50;
// Send the message
ke_msg_send(req);
}
void app_batt_send_lvl(uint8_t batt_lvl)
{
ASSERT_ERR(batt_lvl <= BAS_BATTERY_LVL_MAX);
// Allocate the message
struct bass_batt_level_upd_req * req = KE_MSG_ALLOC(BASS_BATT_LEVEL_UPD_REQ,
prf_dst_task_get(TASK_ID_BASS),
TASK_APP,
bass_batt_level_upd_req);
// Fill in the parameter structure
req->bas_instance = 0;
req->batt_level = batt_lvl;
// Send the message
ke_msg_send(req);
}
static int bass_batt_level_ntf_cfg_ind_handler(ke_msg_id_t const msgid,
struct bass_batt_level_ntf_cfg_ind const *param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
return (KE_MSG_CONSUMED);
}
static int batt_level_upd_handler(ke_msg_id_t const msgid,
struct bass_batt_level_upd_rsp const *param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
return (KE_MSG_CONSUMED);
}
/**
****************************************************************************************
* @brief
*
* @param[in] msgid Id of the message received.
* @param[in] param Pointer to the parameters of the message.
* @param[in] dest_id ID of the receiving task instance (TASK_GAP).
* @param[in] src_id ID of the sending task instance.
*
* @return If the message was consumed or not.
****************************************************************************************
*/
static int app_batt_msg_dflt_handler(ke_msg_id_t const msgid,
void const *param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
// Drop the message
return (KE_MSG_CONSUMED);
}
/*
* LOCAL VARIABLE DEFINITIONS
****************************************************************************************
*/
/// Default State handlers definition
const struct ke_msg_handler app_batt_msg_handler_list[] =
{
// Note: first message is latest message checked by kernel so default is put on top.
{KE_MSG_DEFAULT_HANDLER, (ke_msg_func_t)app_batt_msg_dflt_handler},
{BASS_BATT_LEVEL_NTF_CFG_IND, (ke_msg_func_t)bass_batt_level_ntf_cfg_ind_handler},
{BASS_BATT_LEVEL_UPD_RSP, (ke_msg_func_t)batt_level_upd_handler},
};
const struct app_subtask_handlers app_batt_handlers = APP_HANDLERS(app_batt);
#endif //BLE_APP_BATT
/// @} APP
@@ -0,0 +1,110 @@
/**
****************************************************************************************
*
* @file app_batt.h
*
* @brief Battery Application Module entry point
*
* Copyright (C) RivieraWaves 2009-2015
*
*
****************************************************************************************
*/
#ifndef APP_BATT_H_
#define APP_BATT_H_
/**
****************************************************************************************
* @addtogroup APP
* @ingroup RICOW
*
* @brief Battery Application Module entry point
*
* @{
****************************************************************************************
*/
/*
* INCLUDE FILES
****************************************************************************************
*/
#include "rwip_config.h" // SW configuration
#if (BLE_APP_BATT)
#include <stdint.h> // Standard Integer Definition
#include "ke_task.h" // Kernel Task Definition
/*
* STRUCTURES DEFINITION
****************************************************************************************
*/
/// Battery Application Module Environment Structure
struct app_batt_env_tag
{
/// Connection handle
uint8_t conidx;
/// Current Battery Level
uint8_t batt_lvl;
};
/*
* GLOBAL VARIABLES DECLARATIONS
****************************************************************************************
*/
/// Battery Application environment
extern struct app_batt_env_tag app_batt_env;
/// Table of message handlers
extern const struct app_subtask_handlers app_batt_handlers;
/*
* FUNCTIONS DECLARATION
****************************************************************************************
*/
/**
****************************************************************************************
*
* Health Thermometer Application Functions
*
****************************************************************************************
*/
/**
****************************************************************************************
* @brief Initialize Battery Application Module
****************************************************************************************
*/
void app_batt_init(void);
/**
****************************************************************************************
* @brief Add a Battery Service instance in the DB
****************************************************************************************
*/
void app_batt_add_bas(void);
/**
****************************************************************************************
* @brief Enable the Battery Service
****************************************************************************************
*/
void app_batt_enable_prf(uint8_t conidx);
/**
****************************************************************************************
* @brief Send a Battery level value
****************************************************************************************
*/
void app_batt_send_lvl(uint8_t batt_lvl);
#endif //(BLE_APP_BATT)
/// @} APP
#endif // APP_BATT_H_
@@ -0,0 +1,56 @@
#if 0
/*@TRACE*/
enum basc_msg_id
{
/// Start the Battery Service Client Role - at connection
// BASC_ENABLE_REQ = MSG_ID(BASC, 0x00),
///Confirm that cfg connection has finished with discovery results, or that normal cnx started
BASC_ENABLE_RSP = MSG_ID(BASC, 0x01),
/// Read Characteristic Value Request
// BASC_READ_INFO_REQ = MSG_ID(BASC, 0x02),
/// Read Characteristic Value Request
BASC_READ_INFO_RSP = MSG_ID(BASC, 0x03),
/// Write Battery Level Notification Configuration Value request
// BASC_BATT_LEVEL_NTF_CFG_REQ = MSG_ID(BASC, 0x04),
/// Write Battery Level Notification Configuration Value response
BASC_BATT_LEVEL_NTF_CFG_RSP = MSG_ID(BASC, 0x05),
/// Indicate to APP that the Battery Level value has been received
BASC_BATT_LEVEL_IND = MSG_ID(BASC, 0x06),
};
#endif
void xc_basc_enbale_req()
{
//send msg
BASC_ENABLE_REQ
}
void xc_basc_read_info_req()
{
//send msg
BASC_READ_INFO_REQ
}
void xc_basc_batt_leval_ntf_cfg_req()
{
//send msg
BASC_BATT_LEVEL_NTF_CFG_REQ
}
/// Default State handlers definition
KE_MSG_HANDLER_TAB(basc)
{
// Note: all messages must be sorted in ID ascending order
{BASC_ENABLE_RSP, (ke_msg_func_t) xxx_handler },
{BASC_READ_INFO_RSP, (ke_msg_func_t) xxx_handler },
{BASC_BATT_LEVEL_NTF_CFG_RSP, (ke_msg_func_t) xxx_handler },
{BASC_BATT_LEVEL_IND, (ke_msg_func_t) xxx_handler },
};
@@ -0,0 +1,546 @@
/**
****************************************************************************************
*
* @file app_sec.c
*
* @brief Application Security Entry Point
*
* Copyright (C) RivieraWaves 2009-2015
*
*
****************************************************************************************
*/
/**
****************************************************************************************
* @addtogroup APP
* @{
****************************************************************************************
*/
/*
* INCLUDE FILES
****************************************************************************************
*/
#include "rwip_config.h"
#if (BLE_APP_PRESENT)
#if (BLE_HOST_SUPPORT_SMP)
#include "rwip_config.h"
#include <string.h>
#include "co_utils.h"
#include "co_math.h"
//#include "gapc_task.h" // GAP Controller Task API Definition
#include "gap.h" // GAP Definition
#include "gapc.h" // GAPC Definition
#include "gapc_int.h"
#include "prf_types.h"
#include "app_sec.h" // Application Security API Definition
#include "app_task.h" // Application Manager API Definition
#if (NVDS_SUPPORT)
#include "nvds.h" // NVDS API Definitions
#endif //(NVDS_SUPPORT)
#include "app_task.h"
uint8_t bond_flag = 0;
struct gapc_ltk g_ltk = {0};
/*
* GLOBAL VARIABLE DEFINITIONS
****************************************************************************************
*/
/// Application Security Environment Structure
struct app_sec_env_tag app_sec_env;
/*
* GLOBAL FUNCTION DEFINITIONS
****************************************************************************************
*/
void app_sec_init()
{
/*------------------------------------------------------
* RETRIEVE BOND STATUS
*------------------------------------------------------*/
#if (NVDS_SUPPORT)
uint8_t length = NVDS_LEN_PERIPH_BONDED;
// Get bond status from NVDS
if (nvds_get(NVDS_TAG_PERIPH_BONDED, &length, (uint8_t *)&app_sec_env.bonded) != NVDS_OK)
{
// If read value is invalid, set status to not bonded
app_sec_env.bonded = false;
}
if ((app_sec_env.bonded != true) && (app_sec_env.bonded != false))
{
app_sec_env.bonded = false;
}
LOGI("===bond_state:%d\r\n",app_sec_env.bonded);
#endif //(NVDS_SUPPORT)
}
bool app_sec_get_bond_status(void)
{
return app_sec_env.bonded;
}
#if (NVDS_SUPPORT)
void app_sec_remove_bond(void)
{
#if (BLE_APP_HID)
uint16_t ntf_cfg = PRF_CLI_STOP_NTFIND;
#endif //(BLE_APP_HID)
// Check if we are well bonded
if (app_sec_env.bonded == true)
{
// Update the environment variable
app_sec_env.bonded = false;
if (nvds_put(NVDS_TAG_PERIPH_BONDED, NVDS_LEN_PERIPH_BONDED,
(uint8_t *)&app_sec_env.bonded) != NVDS_OK)
{
ASSERT_ERR(0);
}
if (nvds_del(NVDS_TAG_LTK) != NVDS_OK)
{
ASSERT_ERR(0);
}
if (nvds_del(NVDS_TAG_PEER_BD_ADDRESS) != NVDS_OK)
{
ASSERT_ERR(0);
}
#if (BLE_APP_HID)
if (nvds_put(NVDS_TAG_MOUSE_NTF_CFG, NVDS_LEN_MOUSE_NTF_CFG,
(uint8_t *)&ntf_cfg) != NVDS_OK)
{
ASSERT_ERR(0);
}
#endif //(BLE_APP_HID)
}
}
#endif //(NVDS_SUPPORT)
/*
* MESSAGE HANDLERS
****************************************************************************************
*/
static int app_sec_msg_dflt_handler(ke_msg_id_t const msgid,
void *param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
// Drop the message
return (KE_MSG_CONSUMED);
}
static int gapc_bond_req_ind_handler(ke_msg_id_t const msgid,
void const * p_param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
struct gapc_bond_req_ind *param = (struct gapc_bond_req_ind *)p_param;
LOGI(" [debug] gapc_bond_req_ind_handler,request:0x%x \r\n",param->request);
// Prepare the GAPC_BOND_CFM message
struct gapc_bond_cfm *cfm = KE_MSG_ALLOC(GAPC_BOND_CFM,
src_id, TASK_APP,
gapc_bond_cfm);
switch (param->request)
{
case (GAPC_PAIRING_REQ):
{
cfm->request = GAPC_PAIRING_RSP;
{
cfm->accept = true;
#if (BLE_SEC_CON)
cfm->data.pairing_feat.auth = GAP_AUTH_REQ_SEC_CON_BOND;
#else // (BLE_SEC_CON)
cfm->data.pairing_feat.auth = GAP_AUTH_REQ_NO_MITM_BOND;
#endif // (BLE_SEC_CON)
app_env.sec_con_enabled = true;
cfm->data.pairing_feat.iocap = GAP_IO_CAP_NO_INPUT_NO_OUTPUT;//GAP_IO_CAP_KB_ONLY;//GAP_IO_CAP_DISPLAY_ONLY;//GAP_IO_CAP_NO_INPUT_NO_OUTPUT;
cfm->data.pairing_feat.key_size = 16;
cfm->data.pairing_feat.oob = GAP_OOB_AUTH_DATA_NOT_PRESENT;
cfm->data.pairing_feat.sec_req = GAP_SEC1_NOAUTH_PAIR_ENC;//GAP_SEC1_AUTH_PAIR_ENC;//GAP_NO_SEC;
cfm->data.pairing_feat.rkey_dist = GAP_KDIST_ENCKEY | GAP_KDIST_IDKEY;
cfm->data.pairing_feat.ikey_dist = GAP_KDIST_ENCKEY | GAP_KDIST_IDKEY;
}
} break;
case (GAPC_LTK_EXCH):
{
// Counter
uint8_t counter;
cfm->accept = true;
cfm->request = GAPC_LTK_EXCH;
// Generate all the values
cfm->data.ltk.ediv = (uint16_t)co_rand_word();
for (counter = 0; counter < RAND_NB_LEN; counter++)
{
cfm->data.ltk.ltk.key[counter] = (uint8_t)co_rand_word();
cfm->data.ltk.randnb.nb[counter] = (uint8_t)co_rand_word();
}
for (counter = RAND_NB_LEN; counter < KEY_LEN; counter++)
{
cfm->data.ltk.ltk.key[counter] = (uint8_t)co_rand_word();
}
#if (1)
LOGI( "nvds_put cfm->ediv=0x%x\r\nparam_randnb:",cfm->data.ltk.ediv);
for(uint8_t i=0;i<GAP_RAND_NB_LEN;i++)
LOGI( "%x",cfm->data.ltk.randnb.nb[i]);
LOGI("\r\nltk:");
for(uint8_t i=0;i<GAP_KEY_LEN;i++)
LOGI( "%x",cfm->data.ltk.ltk.key[i]);
LOGI("\r\n");
#endif
#if (NVDS_SUPPORT)
uint8_t err = nvds_del(NVDS_TAG_LTK);
LOGI("err2 =%d \n", err);
// Store the generated value in NVDS
if (nvds_put(NVDS_TAG_LTK, NVDS_LEN_LTK, (uint8_t *)&cfm->data.ltk) != NVDS_OK)
{
ASSERT_ERR(0);
}
// uint8_t buff5[10] = {1,2,3,4,5,6,9,8,9,11};
// // LOGI("nvds del:%d \r\n",nvds_del(16));
// if (nvds_put(18, 10, buff5) != NVDS_OK)
// {
// LOGI("77111\r\n");
// ASSERT_ERR(0);
// }
// LOGI("77222\r\n");
#endif // #if (NVDS_SUPPORT)
} break;
case (GAPC_IRK_EXCH):
{
#if (NVDS_SUPPORT)
uint8_t addr_len = BD_ADDR_LEN;
#endif //(NVDS_SUPPORT)
cfm->accept = true;
cfm->request = GAPC_IRK_EXCH;
// Load IRK
memcpy(cfm->data.irk.irk.key, app_env.loc_irk, KEY_LEN);
#if (NVDS_SUPPORT)
if (nvds_get(NVDS_TAG_BD_ADDRESS, &addr_len, cfm->data.irk.addr.addr) != NVDS_OK)
#endif //(NVDS_SUPPORT)
{
ASSERT_ERR(0);
}
// load device address
cfm->data.irk.addr.addr_type = (cfm->data.irk.addr.addr[5] & 0xC0) ? ADDR_RAND : ADDR_PUBLIC;
} break;
//#if (BLE_APP_HT)
case (GAPC_TK_EXCH):
{
// Generate a PIN Code- (Between 100000 and 999999)
uint32_t pin_code = (100000 + (co_rand_word()%900000));
LOGI("app_sec GAPC_TK_EXCH: tk_type=%d\r\n",param->data.tk_type);
cfm->accept = true;
cfm->request = GAPC_TK_EXCH;
// Set the TK value
memset(cfm->data.tk.key, 0, KEY_LEN);
cfm->data.tk.key[0] = (uint8_t)((pin_code & 0x000000FF) >> 0);
cfm->data.tk.key[1] = (uint8_t)((pin_code & 0x0000FF00) >> 8);
cfm->data.tk.key[2] = (uint8_t)((pin_code & 0x00FF0000) >> 16);
cfm->data.tk.key[3] = (uint8_t)((pin_code & 0xFF000000) >> 24);
LOGI("###GAPC_TK_EXCH pincode=%d\r\n", pin_code);
} break;
//#endif //(BLE_APP_HT)
default:
{
ASSERT_ERR(0);
} break;
}
// Send the message
ke_msg_send(cfm);
return (KE_MSG_CONSUMED);
}
static int gapc_bond_ind_handler(ke_msg_id_t const msgid,
void const *p_param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
struct gapc_bond_ind const *param = (struct gapc_bond_ind const *)p_param;
LOGI(" [debug] gapc_bond_ind_handler : info=%d\r\n", param->info);
switch (param->info)
{
case (GAPC_PAIRING_SUCCEED):
{
// Update the bonding status in the environment
app_sec_env.bonded = true;
bond_flag = 1;
LOGI("GAPC_PAIRING_SUCCEED auth=%d,ltk_present=%d\r\n",
param->data.pairing.level,param->data.pairing.ltk_present);
// Update the bonding status in the environment
#if (PLF_NVDS)
uint8_t err = nvds_del(NVDS_TAG_PERIPH_BONDED);
LOGI("err1 =%d \n", err);
if (nvds_put(NVDS_TAG_PERIPH_BONDED, NVDS_LEN_PERIPH_BONDED,
(uint8_t *)&app_sec_env.bonded) != NVDS_OK)
{
// An error has occurred during access to the NVDS
ASSERT_ERR(0);
LOGI("3\n");
}
LOGI("4\n");
// Set the BD Address of the peer device in NVDS
uint8_t err2 = nvds_del(NVDS_TAG_PEER_BD_ADDRESS);
LOGI("err2 =%d \n", err);
struct app_env_tag *app_env = get_app_env();
if (nvds_put(NVDS_TAG_PEER_BD_ADDRESS, NVDS_LEN_PEER_BD_ADDRESS,
(uint8_t *)gapc_get_bdaddr(app_env->slave_conidx, GAPC_SMP_INFO_PEER)) != NVDS_OK)
{
// An error has occurred during access to the NVDS
ASSERT_ERR(0);
LOGI("5\n");
}
LOGI("6\n");
#endif //(PLF_NVDS)
} break;
case (GAPC_REPEATED_ATTEMPT):
{
// app_disconnect();
} break;
case (GAPC_IRK_EXCH):
{
#if (NVDS_SUPPORT)
// Store peer identity in NVDS
LOGI("GAPC_IRK_EXCH\r\n");
uint8_t err = nvds_del(NVDS_TAG_PEER_IRK);
LOGI("err2 =%d \n", err);
if (nvds_put(NVDS_TAG_PEER_IRK, NVDS_LEN_PEER_IRK, (uint8_t *)&param->data.irk.irk.key[0]) != NVDS_OK)
{
LOGI("1\r\n");
ASSERT_ERR(0);
}
LOGI("2\r\n");
#endif // (NVDS_SUPPORT)
} break;
case (GAPC_PAIRING_FAILED):
{
// app_sec_send_security_req(0);
} break;
// In Secure Connections we get BOND_IND with SMPC calculated LTK
case (GAPC_LTK_EXCH) :
{
LOGI( "GAPC_LTK_EXCH sec_con_enabled=%d\r\n",app_env.sec_con_enabled);
LOGI( " param->ediv=0x%x\r\nparam_randnb:",param->data.ltk.ediv);
for(uint8_t i=0;i<GAP_RAND_NB_LEN;i++)
LOGI( "%x",param->data.ltk.randnb.nb[i]);
LOGI("\r\nltk:");
for(uint8_t i=0;i<GAP_KEY_LEN;i++)
LOGI( "%x",param->data.ltk.ltk.key[i]);
LOGI("\r\n");
#if (0)
if (app_env.sec_con_enabled == true)
{
#if (NVDS_SUPPORT)
// Store LTK in NVDS
if (nvds_put(NVDS_TAG_LTK, NVDS_LEN_LTK,(uint8_t *)&param->data.ltk.ltk.key[0]) != NVDS_OK)
{
ASSERT_ERR(0);
}
#endif // (NVDS_SUPPORT)
}
#endif // (BLE_APP_SEC_CON)
}
break;
default:
{
ASSERT_ERR(0);
} break;
}
return (KE_MSG_CONSUMED);
}
static int gapc_encrypt_req_ind_handler(ke_msg_id_t const msgid,
void const *p_param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
#if (NVDS_SUPPORT)
struct gapc_encrypt_req_ind const *param = (struct gapc_encrypt_req_ind const *)p_param;
#endif // (NVDS_SUPPORT)
LOGI(" [debug] gapc_encrypt_req_ind_handler \r\n");
#if (NVDS_SUPPORT)
// LTK value
struct gapc_ltk ltk;
// Length
uint8_t length = NVDS_LEN_LTK;
#endif // #if (NVDS_SUPPORT)
// Prepare the GAPC_ENCRYPT_CFM message
struct gapc_encrypt_cfm *cfm = KE_MSG_ALLOC(GAPC_ENCRYPT_CFM,
src_id, TASK_APP,
gapc_encrypt_cfm);
cfm->found = false;
LOGI("app_sec gapc_encrypt_req_ind_handler: bonded=%d\r\n", app_sec_env.bonded);
// if (app_sec_env.bonded)
{
#if (NVDS_SUPPORT)
// Retrieve the required informations from NVDS
if (nvds_get(NVDS_TAG_LTK, &length, (uint8_t *)&ltk) == NVDS_OK)
{
LOGI( "nvds_get param->ediv=0x%x,ltk.ediv=0x%x\r\nparam_randnb:",param->ediv,ltk.ediv);
for(uint8_t i=0;i<GAP_RAND_NB_LEN;i++)
LOGI( "%x",param->rand_nb.nb[i]);
LOGI("\r\nltk.randnb.nb:");
for(uint8_t i=0;i<GAP_RAND_NB_LEN;i++)
LOGI( "%x",ltk.randnb.nb[i]);
LOGI("\r\n");
// Check if the provided EDIV and Rand Nb values match with the stored values
if ((param->ediv == ltk.ediv) &&
!memcmp(&param->rand_nb.nb[0], &ltk.randnb.nb[0], sizeof(struct rand_nb)))
{
LOGI("EDIV and randnb are same!!!\r\n");
cfm->found = true;
cfm->key_size = 16;
memcpy(&cfm->ltk, &ltk.ltk, sizeof(struct gap_sec_key));
bond_flag = 1;
}
else
{
LOGI("EDIV and randnb not same!!!\r\n");
}
/*
* else we are bonded with another device, disconnect the link
*/
}
else
{
ASSERT_ERR(0);
}
#endif // (NVDS_SUPPORT)
}
/*
* else the peer device is not known, an error should trigger a new pairing procedure.
*/
// Send the message
ke_msg_send(cfm);
return (KE_MSG_CONSUMED);
}
static int gapc_encrypt_ind_handler(ke_msg_id_t const msgid,
void const *p_param,
ke_task_id_t const dest_id,
ke_task_id_t const src_id)
{
struct gapc_encrypt_ind const *param = (struct gapc_encrypt_ind const *)p_param;
LOGI(" [debug] gapc_encrypt_ind_handler \r\n");
// encryption/ re-encryption succeeded
LOGI("app_sec gapc_encrypt_ind_handler: auth=%d\r\n", param->pairing_lvl);
// struct gapc_set_le_pkt_size_cmd *req = KE_MSG_ALLOC(GAPC_SET_LE_PKT_SIZE_CMD,
// KE_BUILD_ID(TASK_GAPC, KE_IDX_GET(src_id)), TASK_APP,
// gapc_set_le_pkt_size_cmd);
// req->operation = GAPC_SET_LE_PKT_SIZE;
// req->tx_octets = 0xFB;
// req->tx_time = 2120;
// // Send the message
// ke_msg_send(req);
return (KE_MSG_CONSUMED);
}
/*
* LOCAL VARIABLE DEFINITIONS
****************************************************************************************
*/
/// Default State handlers definition
const struct ke_msg_handler app_sec_msg_handler_list[] =
{
// Note: first message is latest message checked by kernel so default is put on top.
{KE_MSG_DEFAULT_HANDLER, (ke_msg_func_t)app_sec_msg_dflt_handler},
{GAPC_BOND_REQ_IND, (ke_msg_func_t)gapc_bond_req_ind_handler},
{GAPC_BOND_IND, (ke_msg_func_t)gapc_bond_ind_handler},
{GAPC_ENCRYPT_REQ_IND, (ke_msg_func_t)gapc_encrypt_req_ind_handler},
{GAPC_ENCRYPT_IND, (ke_msg_func_t)gapc_encrypt_ind_handler},
};
const struct app_subtask_handlers app_sec_handlers = {&app_sec_msg_handler_list[0], ARRAY_LEN(app_sec_msg_handler_list)};
#endif
#endif // (BLE_APP_PRESENT)
/// @} APP
@@ -0,0 +1,93 @@
/**
****************************************************************************************
*
* @file app_sec.h
*
* @brief Application Security Entry Point
*
* Copyright (C) RivieraWaves 2009-2015
*
*
****************************************************************************************
*/
/**
****************************************************************************************
* @addtogroup APP_SEC
* @{
****************************************************************************************
*/
#ifndef APP_SEC_H_
#define APP_SEC_H_
/*
* INCLUDE FILES
****************************************************************************************
*/
#include "rwip_config.h"
#include <stdbool.h>
#include <stdint.h> // Standard Integer Definition
/*
* DEFINES
****************************************************************************************
*/
/*
* STRUCTURES DEFINITIONS
****************************************************************************************
*/
struct app_sec_env_tag
{
// Bond status
bool bonded;
};
/*
* GLOBAL VARIABLE DECLARATIONS
****************************************************************************************
*/
/// Application Security Environment
extern struct app_sec_env_tag app_sec_env;
/// Table of message handlers
extern const struct app_subtask_handlers app_sec_handlers;
/*
* GLOBAL FUNCTIONS DECLARATIONS
****************************************************************************************
*/
/**
****************************************************************************************
* @brief Initialize the Application Security Module
****************************************************************************************
*/
void app_sec_init(void);
#if (NVDS_SUPPORT)
/**
****************************************************************************************
* @brief Remove all bond data stored in NVDS
****************************************************************************************
*/
void app_sec_remove_bond(void);
#endif //(NVDS_SUPPORT)
/**
****************************************************************************************
* @brief Send a security request to the peer device. This function is used to
*require the central to start the encryption with a LTK that would have shared
*during a previous bond procedure.
*
* @param[in] - conidx: Connection Index
****************************************************************************************
*/
void app_sec_send_security_req(uint8_t conidx);
#endif // APP_SEC_H_
/// @} APP_SEC
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,519 @@
/**
****************************************************************************************
*
* @file arch_main.c
*
* @brief Main loop of the application.
*
* Copyright (C) RivieraWaves 2009-2015
*
*
****************************************************************************************
*/
/*
* INCLUDES
****************************************************************************************
*/
#include "rwip_config.h" // RW SW configuration
#include "xc_drv_pwr.h"
#if (USE_ROM_FLASH)
#include "xc6xxx_fmc_spi.h"
#endif // (USE_ROM_FLASH)
#include "app_task.h"
#include "rom_port.h"
#include "xc_drv_bor.h"
#if (BLE_TEST_MODE_SUPPORT)
#include "uart.h" // UART initialization
#endif // (BLE_TEST_MODE_SUPPORT)
#if (BLE_EMB_PRESENT || BT_EMB_PRESENT)
#include "rf.h" // RF initialization
#endif // BLE_EMB_PRESENT || BT_EMB_PRESENT
#if (PLF_NVDS)
#include "nvds.h" // NVDS definitions
#endif // PLF_NVDS
#include "xc6xxx.h"
#include "xc_drv_fmc_spi.h"
#include "xc_main.h"
#include "xc_head.h"
/**
****************************************************************************************
* @addtogroup DRIVERS
* @{
*
*
* ****************************************************************************************
*/
/*
* DEFINES
****************************************************************************************
*/
/// NVDS location in FLASH : 0x000E0000 (896KB (1Mo - 128KB))
#define NVDS_FLASH_ADDRESS (0x0003E000)
/// NVDS size in RAM : 0x00010000 (128KB)
#define NVDS_FLASH_SIZE (0x00000200)
/*
* GLOBAL VARIABLE DEFINITIONS
****************************************************************************************
*/
/*
* MAIN FUNCTION
****************************************************************************************
*/
/**
****************************************************************************************
* @brief RW main function.
*
* This function is called right after the booting process has completed.
*
* @return status exit status
****************************************************************************************
*/
void flash_init()
{
// uint32_t mid = 0;
// uint32_t flash_size;
// uint16_t flash_type;
// xc_fmc_spi_init_oprt();
// xc_fmc_spi_flash_wake_up();
// xc_fmc_spi_flash_rdid((uint8_t *)&mid);
// LOGI("Flash RDID: 0x%08x\n", mid);
#if (PLF_NVDS)
if (false == flash_size_and_type_get(&flash_size, &flash_type)) {
LOGI("Flash Memory size Get ERROR ! ");
while (1)
;
}
nvds_space_init(flash_size);
#endif
// if chip unique get failed,then use flash RUID
if (false == xc_unique_identification_read(co_default_bdaddr.addr)) {
uint8_t ruid[16];
xc_fmc_spi_flash_ruid(ruid);
LOGI("Flash RUID11: ");
for (int i = 0; i < 16; i++) {
LOGI("%02x ", ruid[i]);
}
LOGI("\n");
LOGI("The chip does not have unique , then use flash RUID\n");
memset(co_default_bdaddr.addr, 0, 6);
for (int i = 0; i < 16; i++) {
co_default_bdaddr.addr[i % 6] += ruid[i];
}
}
xc_main_init();
uint8_t ble_addr[6];
xc_ble_get_mac(ble_addr);
co_default_bdaddr.addr[0] = ble_addr[5];
co_default_bdaddr.addr[1] = ble_addr[4];
co_default_bdaddr.addr[2] = ble_addr[3];
co_default_bdaddr.addr[3] = ble_addr[2];
co_default_bdaddr.addr[4] = ble_addr[1];
co_default_bdaddr.addr[5] = ble_addr[0];
}
#define clrbit(x, y) ((x) &= ~(1 << (y)))
#define AHB_CTL clrbit(*(uint32_t volatile *)(0x40000000 + 0x130), 0)
#define _TOSTRING(s) #s
#define TOSTRING(s) _TOSTRING(s)
extern void clock_init(void);
void app_uart_init(void)
{
GPIO_InitCfg_t gpio_cfg = {0};
gpio_cfg.Mux = GPIO_Mux1;
gpio_cfg.Pull = GPIO_PULLUP;
gpio_cfg.Int = NOT_INT;
gpio_cfg.FunSel = UART0_TX;
gpio_cfg.Pin = GPIO_12;
gpio_cfg.Dir = GPIO_DIR_OUTPUT;
xc_gpio_init(&gpio_cfg);
gpio_cfg.FunSel = UART0_RX;
gpio_cfg.Pin = GPIO_13;
gpio_cfg.Dir = GPIO_DIR_INPUT;
xc_gpio_init(&gpio_cfg);
UART_InitCfg_t uart_cfg = {0};
uart_cfg.Parity = UART_PARITY_DISABLE;
uart_cfg.StopBits = UART_STOP_1_BITS;
uart_cfg.WordLength = UART_DATA_8_BITS;
uart_cfg.BaudRate = UART_BAUDRATE_115200;
uart_cfg.HardwareFlowControl = UART_HWFC_DISABLE;
xc_uart_init(UART0_IDX, &uart_cfg);
gpio_cfg.FunSel = GPIO_Dx;
gpio_cfg.Pin = GPIO_18;
gpio_cfg.Dir = GPIO_DIR_INPUT;
xc_gpio_init(&gpio_cfg);
gpio_cfg.FunSel = GPIO_Dx;
gpio_cfg.Pin = GPIO_19;
gpio_cfg.Dir = GPIO_DIR_INPUT;
xc_gpio_init(&gpio_cfg);
}
void wdt_init(void)
{
WDT_InitCfg_t wdt_cfg ;
wdt_cfg.WorkMode = WDT_WORK_MODE0;
wdt_cfg.ReloadValue = WDT_CLK_32K_RESET_MODE0_2048MS;
wdt_cfg.PclkSel = WDT_WORK_32K;
xc_wdt_init(&wdt_cfg);
xc_wdt_start();
}
void system_lightsleep_cfg()
{
#if (USE_XIP != 1)
cprao_aon_puctrl1_set(0x4); /* puctrl1= 0x4 , SSI0RX must pulldown*/
#endif
cprao_aon_sys_time_set((RST_READY_TIME << 12) | (OSC32_STABLE_TIME));
xc_pwr_pd_lightsleep_set();
xc_pwr_sleepsrc_mask_set(0x1e001e);
xc_pwr_osc_off();
}
struct ADV_INFO adv_info;
void set_single_addr_name(uint8_t conidx, uint8_t reason)
{
uint32_t flash_type=0;
uint32_t flash_size=0;
uint8_t spi_idx=0;
int32_t mid = 0;
xc_fmc_spi_flash_rdid((uint8_t *)&mid);
flash_type = (mid & 0xffff);
flash_size = (mid >> 16) & 0xff;
flash_type = (mid & 0xffff);
uint32_t write_addr=0;
switch(flash_size)
{
case FLASH_128K_FLAG:
write_addr = (1024 * 128)-256;
if(flash_type==PURAN_128K_FLASH)
{
write_addr = (1024 * 124)-256;
}
break;
case FLASH_256K_FLAG:
write_addr = (1024 * 256)-256;
break;
case FLASH_512K_FLAG:
write_addr = (1024 * 512)-256;
break;
case FLASH_1M_FLAG:
write_addr = (1024 * 1024)-256;
break;
case FLASH_2M_FLAG:
write_addr = (1024 * 2048)-256;
break;
}
uint8_t para_buf[256];
memset(&para_buf,0xFF,256);
memcpy(&adv_info.addr,&co_default_bdaddr.addr,6);
memcpy(&para_buf,&adv_info,28);
xc_fmc_spi_flash_erase_page(write_addr);
xc_fmc_spi_flash_write_page(write_addr, para_buf,FLASH_PAGE_SIZE);
}
/* Zero the host global variable. */
void rom_env_host_init()
{
uint32_t *ptr = (uint32_t *)(0x10000800);
memset(ptr, 0, 0x10001300 - 0x10000800);
rom_env.prf_cleanup = set_single_addr_name;
rom_env.stack_printf = printf;
}
void board_init()
{
clock_init();
app_uart_init();
LOGI("sdk version: %s build time: %s %s\n", TOSTRING(SDK_VERSION), __DATE__,
__TIME__);
// xc_fmc_spi_init_oprt();
#if (SLEEP_ENABLE)
// xc_rc32k_calib_by_hw();
// xc_rc32k_calib_by_soft();
#endif // (SLEEP_ENABLE)
rom_env_host_init();
rom_env_init();
AHB_CTL;
// Initialize random process
// srand(1);
}
__RAM_CODE __STATIC int8_t rf_rssi_convert(uint8_t rssi_reg)
{
int8_t rssi_dbm;
// uint16_t power_modem;
if (rssi_reg < 128) {
rssi_dbm = rssi_reg - 50;
} else {
rssi_dbm = rssi_reg - 256 - 50;
}
#if (CONN_RSSI_DEBUG)
if(evt_start){
printf("con rssi %d\n", rssi_dbm);
}
#endif
return (rssi_dbm);
}
void bluetooth_init()
{
uint32_t error = RESET_NO_ERROR;
flash_init();
#if (PLF_NVDS)
// Initialize NVDS module
nvds_init(NVDS_FLASH_SIZE);
#endif // PLF_NVDS
/*
************************************************************************************
* RW SW stack initialization
************************************************************************************
*/
NVIC_SetPriority((IRQn_Type)BLE_IRQn, 0);
NVIC_EnableIRQ((IRQn_Type)BLE_IRQn);
#if defined(CFG_RSSI_ENABLE)
// Initialize modem
modem_init(1);
#else
modem_init(0);
#endif // defined(CFG_RSSI_ENABLE)
// Measure the single carrier and configure the correct frequency offset.
// rf_xtal_cal_set(uint8_t set_value);
rf_tx_power_set(TRANS_POWER_0_5DBM);
// Initialize RF
#if (BT_EMB_PRESENT || BLE_EMB_PRESENT)
rf_init(&rwip_rf);
rwip_rf.rssi_convert = rf_rssi_convert;
#endif // BT_EMB_PRESENT || BLE_EMB_PRESENT
// Initialize RW SW stack
rwip_init(error);
uint32_t seed;
rwip_time_t current_time = rwip_time_get();
seed = current_time.hs;
seed += current_time.hus;
//Init the random seed
co_random_init(seed);
#if (BLE_TEST_MODE_SUPPORT)
enter_test_mode();
#else // (BLE_TEST_MODE_SUPPORT)
// Initialize APP
app_init();
#endif // (BLE_TEST_MODE_SUPPORT)
// finally start interrupt handling
GLOBAL_INT_START();
}
#if ((ADV_EVENT_NOT_RUN_XIP ==1) || (CONN_EVENT_NOT_RUN_XIP == 0) || (CONN_EVENT_NOT_RUN_XIP == 1))
extern uint8_t adv_evt_start ; // adv event
extern uint8_t evt_start ; // conn event
extern volatile uint8_t sv_lock;
extern volatile uint8_t sv_txlen;
__RAM_CODE void PendSV_Handler(void)
{
if(adv_evt_start){ // adv event
#if (ADV_EVENT_NOT_RUN_XIP ==1)
while (!sv_lock)
;
#endif // (ADV_EVENT_NOT_RUN_XIP ==1)
}else if(evt_start){ // conn event
#if (CONN_EVENT_NOT_RUN_XIP == 0)
uint32_t nus = sv_txlen * 8 + 148;
uint32_t unit = 32;
uint32_t temp;
SysTick->CTRL = 0x00;
SysTick->LOAD = unit * nus - unit + 1;
SysTick->VAL = 0;
SysTick->CTRL = 0x05;
do {
temp = SysTick->CTRL;
if (sv_lock) {
break;
}
} while ((temp & 0x01) && (!(temp & (1 << 16))));
#endif // (CONN_EVENT_NOT_RUN_XIP == 0)
#if (CONN_EVENT_NOT_RUN_XIP == 1)
while (!sv_lock)
;
#endif // (CONN_EVENT_NOT_RUN_XIP == 1)
}
}
#endif // ((ADV_EVENT_NOT_RUN_XIP ==1) || (CONN_EVENT_NOT_RUN_XIP == 0) || (CONN_EVENT_NOT_RUN_XIP == 1))
#if (FLASH_TEST_IN_INTERRUPT)
void flash_test_in_interrupt(void)
{
uint8_t wr_data[10] = {0x63,0x89,0x63,0x89,0x63,0x89};
uint8_t rd_data[10] ={0};
// Timer 1 can be used for flash, interrupt priority is lower than bluetooth, then higher than other interrupts.
// Operate flash in timer 1 interrupt context, no need to lock interrupt, won't affect bluetooth send/receive packets.
// xc_fmc_spi_flash_write(0x32000 , wr_data, sizeof(wr_data));
xc_fmc_spi_flash_write_page(0x32000, wr_data,
sizeof(wr_data));
xc_fmc_spi_flash_read(0x32000 , rd_data, sizeof(rd_data));
for(uint8_t i = 0;i<sizeof(rd_data);i++)
{
printf(" %02x ",rd_data[i]);
}
printf("\r\n");
}
void timer_init(uint8_t timer_idx,uint32_t us)
{
Timer_InitCfg_t timer_cfg;
timer_cfg.timer_src_clk = TIMER_CLK_SRC_32K;
timer_cfg.timer_div_clk = TIMER_DIV_CLK_16MHzOr16K;
timer_cfg.timer_mode = TIMER_MODE_CYCLE;
xc_timer_init(timer_idx, &timer_cfg);
xc_timer_set_value(timer_idx, us);
xc_timer_start(timer_idx);
NVIC_SetPriority((IRQn_Type)TIMER0_IRQn + timer_idx, 1);
}
void timer1_callback(void *context) {
flash_test_in_interrupt();
}
#endif // (FLASH_TEST_IN_INTERRUPT)
#if (FLASH_TEST_IN_TASK)
void flash_test_in_task(void)
{
uint8_t wr_data[10] = {0x63,0x89,0x63,0x89,0x63,0x89};
static uint8_t wr_cnt= 0;
uint8_t rd_data[10] ={0};
wr_cnt++;
if(wr_cnt >= 252)
{
wr_cnt = 0;
}
wr_data[9] = wr_cnt;
GLOBAL_INT_DISABLE();
xc_fmc_spi_flash_write_page(0x32000, wr_data,
sizeof(wr_data));
xc_fmc_spi_flash_read(0x32000 , rd_data, sizeof(rd_data));
GLOBAL_INT_RESTORE();
for(uint8_t i = 0;i<sizeof(rd_data);i++)
{
printf(" %02x ",rd_data[i]);
}
printf("\r\n");
}
#endif // (FLASH_TEST_IN_TASK)
#if (FLASH_TEST_IN_BLUETOOTH_GAP)
#include "rwip_int.h"
extern struct rwip_env_tag rwip_env;
void flash_test_in_bluetooth_gap(void)
{
uint8_t wr_data[10] = {0x63,0x89,0x63,0x89,0x63,0x89};
static uint8_t wr_cnt= 0;
uint8_t rd_data[10] ={0};
wr_cnt++;
if(wr_cnt >= 252)
{
wr_cnt = 0;
}
wr_data[9] = wr_cnt;
if (rwip_env.prevent_sleep != 0)
return;
rwip_time_t current_time;
current_time = rwip_time_get();
// Get the most recent Bluetooth event interval.
int32_t duration = CLK_DIFF(current_time.hs, rwip_env.timer_arb_target); //312.5us
if(duration < 64){ // 20ms = 64*312.5
return;
}
GLOBAL_INT_DISABLE();
xc_fmc_spi_flash_write_page(0x32000, wr_data,
sizeof(wr_data));
xc_fmc_spi_flash_read(0x32000 , rd_data, sizeof(rd_data));
GLOBAL_INT_RESTORE();
for(uint8_t i = 0;i<sizeof(rd_data);i++)
{
printf(" %02x ",rd_data[i]);
}
printf("\r\n");
}
#endif // (FLASH_TEST_IN_BLUETOOTH_GAP)
int main(void)
{
wdt_init();
board_init();
bluetooth_init();
//lvr bor_intr
Bor_InitCfg_t bor_cfg = {
.mode = BOR_MODE_INTRST,
.rst_volt = BOR_RST_VOLT_1_76V,
};
xc_bor_init(&bor_cfg);
#if ((ADV_EVENT_NOT_RUN_XIP ==1) || (CONN_EVENT_NOT_RUN_XIP == 0) || (CONN_EVENT_NOT_RUN_XIP == 1))
NVIC_SetPriority(PendSV_IRQn, 0xff);
NVIC_EnableIRQ(PendSV_IRQn);
#endif // ((ADV_EVENT_NOT_RUN_XIP ==1) || (CONN_EVENT_NOT_RUN_XIP == 0) || (CONN_EVENT_NOT_RUN_XIP == 1))
#if (FLASH_TEST_IN_INTERRUPT)
timer_init(TIMER1_IDX,1000*1000);
#endif //(FLASH_TEST_IN_INTERRUPT)
xc_system_param_check();
// rf_test_pin_init();
xc_main_start();
extern int xc_ble_status_callback(int status);
xc_ble_status_callback(BLE_EVENT_INIT);
#if (BLE_APP_PRESENT)
while (1) {
// schedule all pending events
rwip_schedule();
xc_main_run();
#if (SLEEP_ENABLE)
sleep_schedule();
#endif // (SLEEP_ENABLE)
xc_wdt_reload();
}
#endif // (BLE_APP_PRESENT)
}
/// @} DRIVERS
@@ -0,0 +1,305 @@
#<SYMDEFS># ARM Linker, 5060750: Last Updated: Tue Sep 05 15:30:26 2023
0x10000808 D co_default_bdaddr
0x00004169 T ke_msg_alloc
0x000041ed T ke_msg_send
0x00004225 T ke_msg_send_basic
0x000042e9 T ke_state_set
0x00004359 T ke_task_create
0x000042b9 T ke_state_get
0x000041af T ke_msg_discard
0x000041b3 T ke_msg_forward
0x000041dd T ke_msg_in_queue
0x00004233 T ke_msg_src_id_get
0x00003e05 T ke_free
0x000041d5 T ke_msg_free
0x00003c21 T ke_check_malloc
0x0000dbf5 T rwip_init
0x0000de79 T rwip_schedule
0x10000938 D rwip_rf
0x00000df9 T BLE_Handler
0x0000238d T co_buf_alloc
0x000024fd T co_buf_copy_data_from_mem
0x00002721 T co_buf_release
0x000028c9 T co_djob_prepare
0x000028d5 T co_djob_reg
0x0000291d T co_djob_unreg
0x00002969 T co_list_extract
0x000029ad T co_list_extract_after
0x00002ac5 T co_list_pop_front
0x00002ae9 T co_list_push_back
0x00002b39 T co_list_push_front
0x00002b55 T co_time_get
0x00002ce5 T co_time_timer_init
0x00002dcd T co_time_timer_set
0x00002df9 T co_time_timer_stop
0x00000e95 T aes_c1
0x00001465 T aes_encrypt
0x000014cd T aes_f4
0x00001521 T aes_f5
0x00001641 T aes_f6
0x000016bd T aes_g2
0x00001c35 T aes_rand
0x000012a1 T aes_cmac
0x000025b1 T co_buf_head_release
0x000025dd T co_buf_head_reserve
0x00002ec5 T co_util_pack
0x000030d5 T co_util_unpack
0x0000ddd9 T rwip_reset
0x00001da5 T aes_rpa_resolve
0x00002799 T co_buf_reuse
0x000027dd T co_buf_size
0x00002489 T co_buf_copy
0x00002569 T co_buf_duplicate
0x000027ed T co_buf_tail_release
0x00002a0d T co_list_init
0x00002285 T ble_util_buf_rx_free
0x00001f69 T ble_util_buf_acl_tx_alloc
0x00002439 T co_buf_cb_free_set
0x00003fad T ke_malloc
0x00002a25 T co_list_insert_after
0x0000459d T ke_timer_active
0x000045ad T ke_timer_clear
0x00004641 T ke_timer_set
0x00002369 T co_buf_acquire
0x00002819 T co_buf_tail_reserve
0x00002531 T co_buf_copy_data_to_mem
0x00002a55 T co_list_insert_before
0x10000e90 D rom_env
0x1000096c D rwip_param
0x0000fe8d D one_bits
0x000039bd T hci_rd_rem_ver_info_cmd_handler
0x00003445 T hci_le_con_upd_cmd_handler
0x00003705 T hci_le_rd_chnl_map_cmd_handler
0x00003761 T hci_le_rd_rem_feats_cmd_handler
0x0000354d T hci_le_en_enc_cmd_handler
0x0000369d T hci_le_ltk_req_reply_cmd_handler
0x0000360d T hci_le_ltk_req_neg_reply_cmd_handler
0x00003851 T hci_le_rem_con_param_req_reply_cmd_handler
0x000037f9 T hci_le_rem_con_param_req_neg_reply_cmd_handler
0x000038d9 T hci_le_set_data_len_cmd_handler
0x00003be5 T hci_vs_set_pref_slave_latency_cmd_handler
0x00003b9d T hci_vs_set_pref_slave_evt_dur_cmd_handler
0x00003ab9 T hci_vs_set_max_rx_size_and_time_cmd_handler
0x00003a39 T hci_rd_rssi_cmd_handler
0x0000d749 T llm_ch_map_update_ind_handler
0x0000650d T llc_loc_llcp_rsp_to_handler
0x00007161 T llc_rem_llcp_rsp_to_handler
0x00005255 T llc_encrypt_ind_handler
0x00006739 T llc_op_ver_exch_ind_handler
0x000066d5 T llc_op_feats_exch_ind_handler
0x00006675 T llc_op_encrypt_ind_handler
0x00006609 T llc_op_dl_upd_ind_handler
0x0000657d T llc_op_con_upd_ind_handler
0x00006525 T llc_op_ch_map_upd_ind_handler
0x0000bda9 T lld_llcp_rx_ind_handler
0x0000bf1d T lld_llcp_tx_cfm_handler
0x00007551 T lld_acl_rx_ind_handler
0x000075dd T lld_acl_tx_cfm_handler
0x00009509 T lld_con_param_upd_cfm_handler
0x00008921 T lld_ch_map_upd_cfm_handler
0x000094cd T lld_con_offset_upd_ind_handler
0x00003435 T hci_command_llc_handler
0x00003385 T hci_acl_data_handler
0x00003cc1 T ke_event_callback_set
0x00003cd9 T ke_event_clear
0x00003db1 T ke_event_set
0x000022e5 T ble_util_nb_good_channels
0x0000230d T ble_util_pkt_dur_in_us
0x0000234d T co_bdaddr_compare
0x000088bd T lld_ch_assess_data_get
0x000088c5 T lld_ch_map_set
0x0000c16d T lld_read_clock
0x0000c30d T lld_res_list_peer_update
0x0000d60d T lld_white_list_add
0x0000dd99 T rwip_prevent_sleep_clear
0x0000ddb9 T rwip_prevent_sleep_set
0x0000f071 T sch_plan_rem
0x00001ce5 T aes_rpa_gen
0x00002029 T ble_util_buf_adv_tx_alloc
0x00002061 T ble_util_buf_adv_tx_free
0x0000feae D co_null_bdaddr
0x0000feb4 D co_null_key
0x000050c9 T llc_con_move_cbk
0x000071d9 T llc_start
0x00007669 T lld_adv_adv_data_update
0x00007ff5 T lld_adv_rand_addr_update
0x00008071 T lld_adv_restart
0x0000817d T lld_adv_scan_rsp_data_update
0x000081c5 T lld_adv_start
0x00008831 T lld_adv_stop
0x0000d6c1 T lld_white_list_rem
0x0000b401 T lld_init_rand_addr_update
0x0000c179 T lld_res_list_add
0x0000c251 T lld_res_list_clear
0x0000c27d T lld_res_list_local_rpa_get
0x0000c2c5 T lld_res_list_peer_rpa_get
0x0000c341 T lld_res_list_priv_mode_update
0x0000c37d T lld_res_list_rem
0x0000cedd T lld_scan_rand_addr_update
0x0000b699 T lld_init_start
0x0000bc9d T lld_init_stop
0x0000f081 T sch_plan_req
0x0000f0d5 T sch_plan_set
0x0000fec4 D co_rate_to_phy
0x0000cb81 T lld_scan_params_update
0x0000d115 T lld_scan_start
0x0000d5c5 T lld_scan_stop
0x0000c3ad T lld_rpa_renew
0x0000408d T ke_mem_init
0x00002609 T co_buf_init
0x0000de9d T rwip_sleep
0x10000810 D em_ble_base_address_table_0
0x10000812 D em_ble_base_address_table_1
0x10000814 D em_ble_base_address_table_2
0x10000816 D em_ble_base_address_table_3
0x10000818 D em_ble_base_address_table_4
0x1000081a D em_ble_base_address_table_5
0x10000822 D em_ble_base_address_table_6
0x1000081c D em_ble_base_address_table_7
0x10000824 D em_ble_base_address_table_8
0x1000081e D em_ble_base_address_table_9
0x10000820 D em_ble_base_address_table_10
0x000021d9 T ble_util_buf_init_env
0x10000978 D PATCH_FUN
0x1000108c D lld_adv_env
0x0000ebe5 T sch_arb_remove
0x0000f739 T sch_slice_fg_remove
0x10000f44 D llc_env
0x0000693d T llc_proc_err_ind
0x000073c1 T llc_stop
0x00004695 T ll_channel_map_ind_handler
0x0000471d T ll_connection_param_req_handler
0x00004809 T ll_connection_param_rsp_handler
0x0000489d T ll_connection_update_ind_handler
0x000049c1 T ll_enc_req_handler
0x00004a85 T ll_enc_rsp_handler
0x00004af9 T ll_feature_req_handler
0x00004b4d T ll_feature_rsp_handler
0x00004ba1 T ll_length_req_handler
0x00004bf9 T ll_length_rsp_handler
0x00004c75 T ll_min_used_channels_ind_handler
0x00004cf1 T ll_pause_enc_req_handler
0x00004d5d T ll_pause_enc_rsp_handler
0x00004db5 T ll_reject_ext_ind_handler
0x00004dd5 T ll_reject_ind_handler
0x00004df5 T ll_slave_feature_req_handler
0x00004e49 T ll_start_enc_req_handler
0x00004e99 T ll_start_enc_rsp_handler
0x00004ee9 T ll_unknown_rsp_handler
0x00004ef9 T ll_version_ind_handler
0x00001fd9 T ble_util_buf_acl_tx_free
0x0000c5c1 T lld_rxdesc_check
0x0000c609 T lld_rxdesc_free
0x0000fee4 D rwip_priority
0x0000e8b1 T sch_arb_insert
0x0000f355 T sch_prog_push
0x0000fde5 T FMC_SPI_Flash_RDID
0x0000fd8d T FMC_SPI_Flash_RUID
0x0000fa71 T FMC_SPI_Flash_WakeUp
0x0000f9f1 T FMC_SPI_Init_Oprt
0x0000fa49 T FMC_SPI_Flash_PowerDown
0x0000fceb T FMC_SPI_FlashRead
0x0000fc1f T FMC_SPI_FlashWrite
0x0000fb09 T FMC_SPI_Flash_Erase_Sector
0x00004fc9 T llc_cleanup
0x00005091 T llc_cmd_stat_send
0x00005a39 T llc_llcp_send
0x00005ac9 T llc_llcp_state_set
0x00006981 T llc_proc_get
0x00006999 T llc_proc_id_get
0x000069b5 T llc_proc_init
0x000069c1 T llc_proc_reg
0x00006a05 T llc_proc_state_get
0x00006a09 T llc_proc_state_set
0x00006a0d T llc_proc_timer_pause_set
0x00006a7d T llc_proc_timer_set
0x00006ae5 T llc_proc_unreg
0x0000a1c1 T lld_con_stop
0x00007869 T lld_adv_evt_start_cbk
0x10000e68 D rwip_env
0x1000080e D rwip_prog_delay
0x0000e041 T rwip_time_get
0x0000e2cd T rwip_wakeup_end
0x1000112c D sch_arb_env
0x00007905 T lld_adv_frm_cbk
0x0000e0b1 T rwip_timer_alarm_handler
0x0000e11d T rwip_timer_arb_handler
0x0000e189 T rwip_timer_co_handler
0x10000f94 D lld_env
0x10000828 D aa_gen
0x00007c25 T lld_adv_init
0x00009301 T lld_con_init
0x0000a7f1 T lld_core_init
0x1000082c D lld_rpa_renew_env
0x00008959 T lld_channel_assess
0x100010dc D lld_con_env
0x0000a4ad T lld_con_tx_len_update
0x10000830 D lld_exp_sync_pos_tab
0x0000bce5 T lld_instant_proc_end
0x110134fd T prf_dst_task_get
0x11013abd T rom_env_init
0x11005201 T gapc_get_bdaddr
0x1100c77d T gatt_db_svc16_add
0x1100c901 T gatt_db_svc_add
0x1100df41 T gatt_srv_event_send
0x1100e349 T gatt_user_srv_register
0x11014afc D llc_msg_handler_tab
0x1000217c D rom_llc_state
0x00008e4d T lld_con_evt_start_cbk
0x00008ddd T lld_con_evt_canceled_cbk
0x0000fe9e D co_sca2ppm
0x00009051 T lld_con_evt_time_update
0x00009415 T lld_con_max_lat_calc
0x00009a69 T lld_con_sched
0x0000f7e1 T sch_slice_per_add
0x0000d801 T rwble_isr
0x0000dc75 T rwip_isr
0x00009189 T lld_con_frm_isr
0x000044f9 T ke_task_schedule
0x00007949 T lld_adv_frm_isr
0x1000219d D sv_lock
0x1000219e D sv_txlen
0x100017e5 T rom_lld_con_rx
0x10001a55 T rom_lld_con_evt_start_cbk
0x10001aad T rom_lld_con_frm_isr
0x1100b661 T gatt_cli_mtu_exch
0x1000219c D evt_start
0x1100a791 T gatt_cli_discover_svc
0x1100e3e9 T gatt_uuid16_comp
0x11009eb9 T gatt_cli_att_event_cfm
0x1100a1cd T gatt_cli_discover_cancel
0x1100a221 T gatt_cli_discover_char
0x1100a287 T gatt_cli_discover_desc
0x1100ac5d T gatt_cli_event_register
0x1100b741 T gatt_cli_read
0x1100b775 T gatt_cli_read_by_uuid
0x1100be0d T gatt_cli_write
0x1100e251 T gatt_user_cli_register
0x110041e9 T co_rand_word
0x110041f1 T co_random_init
0x10002194 D adv_evt_start
0x1000213c D gatt_srv_read_api_tbl
0x10002150 D gatt_srv_write_api_tbl
0x110132a9 T modem_init
0x1101381d T rf_init
0x11014095 T xc_ble_set_dev_info_cfm
0x11013fe5 T xc_ble_get_dev_info_cfm
0x11013f0d T xc_ble_gatt_cli_mtu_exch
0x110140bd T xc_ble_update_param
0x11013fdd T xc_ble_gatt_user_srv_register
0x11013fcd T xc_ble_gatt_srv_write_cfm
0x11013f75 T xc_ble_gatt_srv_read_cfm
0x11013f2b T xc_ble_gatt_srv_notify
0x11013f15 T xc_ble_gatt_service16_add
0x11013ffd T xc_ble_param_update_cfm
0x11014069 T xc_ble_set_dev_config
0x11013ef1 T xc_ble_gapm_reset
0x11013ec5 T xc_ble_conn_cfm
0x11013e99 T xc_ble_advertise_start
0x11014031 T xc_ble_set_adv_data
0x11013e71 T xc_ble_advertise_create
0x10001f83 T rom_xc_fmc_spi_flash_erase_page
0x1000203b T rom_xc_fmc_spi_flash_read_page
0x10001fd3 T rom_xc_fmc_spi_flash_write_page
0x11013a85 T rf_xtal_cal_set
0x11013a71 T rf_tx_power_set
@@ -0,0 +1,219 @@
/**
****************************************************************************************
*
* @file arch_main.c
*
* @brief Main loop of the application.
*
* Copyright (C) RivieraWaves 2009-2015
*
*
****************************************************************************************
*/
/*
* INCLUDES
****************************************************************************************
*/
#include "rwip_config.h" // RW SW configuration
#include "arch.h" // architectural platform definitions
#include "boot.h" // boot definition
#include "rwip.h" // RW SW initialization
#include "xc_drv_pwr.h"
#include <stdbool.h> // boolean definition
#include <stddef.h> // standard definitions
#include <stdint.h> // standard integer definition
#include <stdlib.h> // standard lib functions
#if (BLE_TEST_MODE_SUPPORT)
#include "uart.h" // UART initialization
#endif // (BLE_TEST_MODE_SUPPORT)
#if (BLE_EMB_PRESENT || BT_EMB_PRESENT)
#include "rf.h" // RF initialization
#endif // BLE_EMB_PRESENT || BT_EMB_PRESENT
#if (BLE_APP_PRESENT)
// #include "app.h" // application functions
#endif // BLE_APP_PRESENT
#if PLF_DMA
#include "dma.h" // DMA initialization
#endif // PLF_DMA
#if (PLF_NVDS)
#include "nvds.h" // NVDS definitions
#endif // PLF_NVDS
#include "reg_assert_mgr.h"
#if (PLF_PROFILING || PLF_MEM_PROTECTION)
#include "reg_sw_profiling.h"
#endif // (PLF_PROFILING || PLF_MEM_PROTECTION)
#include "platform.h"
#include "xc6xxx.h"
// CPU early wake-up time (unit:us)
#define SLEEP_TIME_EARLY (3000)
#define HS_TO_US(frame) (((frame) * SLOT_SIZE) >> 1)
/**
* @brief clock_init
* @details
* @param void
* @retval void
*/
void clock_init(void)
{
CLOCK_InitCfg_t clock_cfg;
clock_cfg.hfclk_src = CLOCK_HFCLK_SRC_XTAL;
clock_cfg.hfclk_in = CLOCK_HFCLK_IN_32M;
#if (RC_32K)
clock_cfg.lfclk_src = CLOCK_LFCLK_SRC_RC;
#endif //(RC_32K)
#if (XTAL_32K)
clock_cfg.lfclk_src = CLOCK_LFCLK_SRC_XTAL;
#endif // (XTAL_32K)
#if (XTAL_32768K)
clock_cfg.lfclk_src = CLOCK_LFCLK_SRC_XTAL;
#endif // (XTAL_32768K)
if (clock_cfg.lfclk_src == CLOCK_LFCLK_SRC_XTAL) {
clock_cfg.lfclk_in = CLOCK_LFCLK_IN_32768;
} else if (clock_cfg.lfclk_src == CLOCK_LFCLK_SRC_RC) {
clock_cfg.lfclk_in = CLOCK_LFCLK_IN_32K;
}
xc_clock_init_cfg(&clock_cfg);
SysTick_Config(xc_clock_hfclk_in_get() / 100);
SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;
}
#if (SLEEP_ENABLE)
void wakeup_timer_init(void)
{
TIMER_BaseInitTypeDef Timer_Init;
Timer_Init.src_clk = TIMER_CLK_SRC_32K;
Timer_Init.mode = TIMER_MODE_SINGLE_COUNT;
Timer_Init.div_clk = TIMER_DIV_CLK_32000Hz;
// Timer0 Config & Start
TIMER_Base_Init(XC_TIMER0, &Timer_Init);
PWR_InitTypeDef PWR_InitStruct = {0};
PWR_InitStruct.PWR_WakeITSrc = GPIO_IRQn_WAKE | TIMER0_IRQn_WAKE;
PWR_InitStruct.PWR_SleepMode = LIGHT_SLEEP_MODE;
PWR_SleepInit(&PWR_InitStruct);
PWR_GPIO_SleepConfig(PWR_InitStruct.PWR_SleepMode);
PWR_GPIO_LightSleepWakeConfig(GPIO_2, RIS_EDGE_INT);
PWR_GPIO_LightSleepWakeConfig(GPIO_3, RIS_EDGE_INT);
}
void sleep_wkup()
{
PWR_InitTypeDef PWR_InitStruct = {0};
#if (USE_XIP != 1)
SPI_InitCfg_t spi_cfg = {0};
spi_cfg.Mode = SPI_MODE_MASTER;
spi_cfg.DataSize = SSI_CTRL0_DFS_LEN_8BIT;
spi_cfg.Direction = SSI_CTRL0_TMOD_WR;
spi_cfg.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
spi_cfg.CLKPolarity = SSI_CTRL0_SCPOL_LOW;
spi_cfg.CLKPhase = SPI_CPHA_LEAD;
spi_cfg.FirstBit = SPI_FirstBit_MSB;
xc_spi_init(XC_SPI0, &spi_cfg);
SPI_Flash_PowerDown(XC_SPI0);
#endif //(USE_XIP!=1)
// PWR_InitStruct.PWR_WakeITSrc = GPIO_IRQn_WAKE | TIMER0_IRQn_WAKE ;
// PWR_InitStruct.PWR_SleepMode = LIGHT_SLEEP_MODE;
// PWR_SleepInit(&PWR_InitStruct);
// PWR_GPIO_SleepConfig(PWR_InitStruct.PWR_SleepMode);
sleep_init();
PWR_BLE_SleepEnter();
}
void Turn_Off_PeripheralClk()
{
XC_CPR->SSI0_MCLK_CTL = (((0UL << CPR_SSI_MCLK_CTL_SSI_MCLK_DIV_Pos) |
CPR_SSI_MCLK_CTL_SSI_MCLK_DIV_WE) |
((CPR_SSI_MCLK_CTL_SSI_MCLK_EN_DISABLE) |
CPR_SSI_MCLK_CTL_SSI_MCLK_EN_WE));
XC_CPR->CTLAPBCLKEN_GRCTL = ((CPR_CTLAPBCLKEN_GRCTL_SSI0_PCLK_EN_DISABLE) |
(CPR_CTLAPBCLKEN_GRCTL_SSI0_PCLK_EN_Msk
<< CPR_CTLAPBCLKEN_GRCTL_MASK_OFFSET))
<< 0;
XC_CPR->CTLAPBCLKEN_GRCTL = ((CPR_CTLAPBCLKEN_GRCTL_UART0_PCLK_EN_DISABLE) |
(CPR_CTLAPBCLKEN_GRCTL_UART0_PCLK_EN_Msk
<< CPR_CTLAPBCLKEN_GRCTL_MASK_OFFSET));
XC_CPR->UART0_CLK_GRCTL = (((8UL << CPR_UART_CLK_GRCTL_UART0_CLK_GR_Pos) |
CPR_UART_CLK_GRCTL_UART0_CLK_GR_WE) |
((CPR_UART_CLK_GRCTL_UART0_CLK_GR_UPD_DISABLE) |
(CPR_UART_CLK_GRCTL_UART1_CLK_GR_UPD_WE)));
XC_CPR->CTLAPBCLKEN_GRCTL = ((CPR_CTLAPBCLKEN_GRCTL_UART0_PCLK_EN_DISABLE) |
(CPR_CTLAPBCLKEN_GRCTL_UART0_PCLK_EN_Msk
<< CPR_CTLAPBCLKEN_GRCTL_MASK_OFFSET))
<< 1;
//
// XC_CPR->UART1_CLK_GRCTL = (((8UL <<
// CPR_UART_CLK_GRCTL_UART1_CLK_GR_Pos) |
// CPR_UART_CLK_GRCTL_UART1_CLK_GR_WE) |
// ((CPR_UART_CLK_GRCTL_UART1_CLK_GR_UPD_DISABLE)
// |
// (CPR_UART_CLK_GRCTL_UART1_CLK_GR_UPD_WE)));
// XC_CPR->AHBCLKEN_GRCTL =0x1e001e;
}
void sleep_schedule()
{
// Checks for sleep have to be done with interrupt disabled
GLOBAL_INT_DISABLE();
// Check if the processor clock can be gated
uint32_t duration = 0;
uint32_t duration_timer = 0;
// switch(rwip_sleep(&duration, 2, \
// 0x7D00, RWIP_MINIMUM_SLEEP_TIME)){
switch (rwip_sleep(&duration, 1, 0x7D00, 20)) {
case RWIP_DEEP_SLEEP: {
duration_timer = (HS_TO_US(duration) - SLEEP_TIME_EARLY);
TIMER_SetUs(XC_TIMER0, duration_timer);
TIMER_Start_IT(XC_TIMER0);
sleep_wkup();
__TIMER_Disable(XC_TIMER0);
}
// no break
case RWIP_CPU_SLEEP: {
// Wait for interrupt
// Turn_Off_PeripheralClk();
// __PWR_SleepSrcMask_Set(0x1e000e);
// __NOP();__NOP();__NOP();__NOP();__NOP();__NOP();
// __WFI();
// __NOP();__NOP();__NOP();__NOP();__NOP();__NOP();
// __PWR_SleepSrcMask_Set(0x1e001e);
} break;
case RWIP_ACTIVE:
default: {
// nothing to do.
} break;
}
// Checks for sleep have to be done with interrupt disabled
GLOBAL_INT_RESTORE();
}
#endif // (SLEEP_ENABLE)
@@ -0,0 +1,245 @@
;/*****************************************************************************
; * @file: startup_xinc.s
; * @purpose: CMSIS Cortex-M0 Core Device Startup File for the
; * Device xinc.
; *****************************************************************************/
Stack_Size EQU 0x000006f0
AREA STACK, NOINIT, READWRITE, ALIGN=3
Stack_Mem SPACE Stack_Size
__initial_sp
Heap_Size EQU 0x00000000
AREA HEAP, NOINIT, READWRITE, ALIGN=3
__heap_base
Heap_Mem SPACE Heap_Size
__heap_limit
PRESERVE8
THUMB
; Vector Table Mapped to Address 0 at Reset
AREA RESET, DATA, READONLY
EXPORT __Vectors
EXPORT __Vectors_End
EXPORT __Vectors_Size
__Vectors DCD __initial_sp ; Top of Stack
DCD Reset_Handler ; Reset Handler
DCD NMI_Handler ; NMI Handler
DCD HardFault_Handler ; Hard Fault Handler
DCD MemManage_Handler ; MPU Fault Handler
DCD BusFault_Handler ; Bus Fault Handler
DCD UsageFault_Handler ; Usage Fault Handler
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD SVC_Handler ; SVCall Handler
DCD DebugMon_Handler ; Debug Monitor Handler
DCD 0 ; Reserved
DCD PendSV_Handler ; PendSV Handler
DCD SysTick_Handler ; SysTick Handler
; External Interrupts
; ToDo: Add here the vectors for the device specific external interrupts handler
DCD BLE_Handler ; 0
DCD DMA_Handler ; 1
DCD CPR_Handler ; 2
DCD GPIO_Handler ; 3
DCD RTC_Handler ; 4
DCD TIMER0_Handler ; 5
DCD TIMER1_Handler ; 6
DCD TIMER2_Handler ; 7
DCD TIMER3_Handler ; 8
DCD WDT_Handler ; 9
DCD I2C_Handler ; 10
DCD UART0_Handler ; 11
DCD UART1_Handler ; 12
DCD SPI0_Handler ; 13
DCD SPI1_Handler ; 14
DCD 0 ; 15
DCD 0 ; 16
DCD GADC_Handler ; 17
DCD PWM_Handler ; 18
DCD AES_Handler ; 19
DCD USB_Handler ; 20
DCD AUDIO_Handler ; 21
DCD RF24G_Handler ; 22
DCD SPI2_Handler ; 23
DCD MPU_Handler ; 24
DCD UART2_Handler ; 25
DCD I2S_Handler ; 26
DCD AOTIMER0_Handler ; 27
DCD AOTIMER1_Handler ; 28
DCD CMP_Handler ; 29
DCD FMC_Handler ; 30
DCD CAN_Handler ; 31
__Vectors_End
__Vectors_Size EQU __Vectors_End - __Vectors
AREA |.text|, CODE, READONLY
; Reset Handler
Reset_Handler PROC
EXPORT Reset_Handler [WEAK]
IMPORT SystemInit
IMPORT __main
LDR r0, =0x4000013C ; remap
LDR r1, =0x10000001
STR r1, [r0]
LDR R0, =SystemInit
BLX R0
LDR R0, =__main
BX R0
ENDP
; Dummy Exception Handlers (infinite loops which can be modified)
NMI_Handler PROC
EXPORT NMI_Handler [WEAK]
B .
ENDP
HardFault_Handler\
PROC
EXPORT HardFault_Handler [WEAK]
B .
ENDP
MemManage_Handler\
PROC
EXPORT MemManage_Handler [WEAK]
B .
ENDP
BusFault_Handler\
PROC
EXPORT BusFault_Handler [WEAK]
B .
ENDP
UsageFault_Handler\
PROC
EXPORT UsageFault_Handler [WEAK]
B .
ENDP
SVC_Handler PROC
EXPORT SVC_Handler [WEAK]
B .
ENDP
DebugMon_Handler\
PROC
EXPORT DebugMon_Handler [WEAK]
B .
ENDP
Default_Handler PROC
EXPORT BLE_Handler [WEAK]
EXPORT DMA_Handler [WEAK]
EXPORT CPR_Handler [WEAK]
EXPORT GPIO_Handler [WEAK]
EXPORT RTC_Handler [WEAK]
EXPORT TIMER0_Handler [WEAK]
EXPORT TIMER1_Handler [WEAK]
EXPORT TIMER2_Handler [WEAK]
EXPORT TIMER3_Handler [WEAK]
EXPORT WDT_Handler [WEAK]
EXPORT I2C_Handler [WEAK]
EXPORT UART0_Handler [WEAK]
EXPORT UART1_Handler [WEAK]
EXPORT SPI0_Handler [WEAK]
EXPORT SPI1_Handler [WEAK]
;EXPORT KBS_Handler [WEAK]
;EXPORT QDEC_Handler [WEAK]
EXPORT GADC_Handler [WEAK]
EXPORT PWM_Handler [WEAK]
EXPORT AES_Handler [WEAK]
EXPORT PendSV_Handler [WEAK]
EXPORT SysTick_Handler [WEAK]
EXPORT USB_Handler [WEAK];20
EXPORT AUDIO_Handler [WEAK];21
EXPORT RF24G_Handler [WEAK];22
EXPORT SPI2_Handler [WEAK];23
EXPORT MPU_Handler [WEAK];24
EXPORT UART2_Handler [WEAK];25
EXPORT I2S_Handler [WEAK];26
EXPORT AOTIMER0_Handler [WEAK];27
EXPORT AOTIMER1_Handler [WEAK];28
EXPORT CMP_Handler [WEAK];29
EXPORT FMC_Handler [WEAK];30
EXPORT CAN_Handler [WEAK];31
PendSV_Handler
SysTick_Handler
BLE_Handler
RF24G_Handler
DMA_Handler
CPR_Handler
GPIO_Handler
RTC_Handler
TIMER0_Handler
TIMER1_Handler
TIMER2_Handler
TIMER3_Handler
WDT_Handler
I2C_Handler
I2S_Handler
UART0_Handler
UART1_Handler
UART2_Handler
SPI0_Handler
SPI1_Handler
SPI2_Handler
MPU_Handler
;KBS_Handler
;QDEC_Handler
GADC_Handler
PWM_Handler
AUDIO_Handler
;SIM_Handler
AES_Handler
AOTIMER0_Handler
AOTIMER1_Handler
CMP_Handler
FMC_Handler
CAN_Handler
USB_Handler
B .
ENDP
ALIGN
; User Initial Stack & Heap
IMPORT __use_two_region_memory
EXPORT __user_initial_stackheap
__user_initial_stackheap
LDR R0, = Heap_Mem
LDR R1, = (Stack_Mem + Stack_Size)
LDR R2, = (Heap_Mem + Heap_Size)
LDR R3, = Stack_Mem
BX LR
ALIGN
END
@@ -0,0 +1,117 @@
/**
* Initialize the system
*
* @param none
* @return none
*
* @brief Setup the microcontroller system
*
*/
/*-----------------------------------------------------------------------------------
INCLUDE HEADE FILES
------------------------------------------------------------------------------------*/
#include <stdio.h>
#include "rwip.h"
#include "xc6xxx.h"
/*------------------------------------------------------------------------------------
Macros
-------------------------------------------------------------------------------------*/
#define __DEBUG_OUT_PORT 0
/*------------------------------------------------------------------------------------
Functions
-------------------------------------------------------------------------------------*/
#define VECTOR_NUM 48
void set_vector(void)
{
#if (USE_XIP == 1)
GLOBAL_INT_DISABLE();
for (uint32_t i = 0, *Pvector = (uint32_t *)(0x11016000 + 0),
*_vector_table = (uint32_t *)(0x10000000);
i < VECTOR_NUM; i++) // copy vertor table
{
_vector_table[i] = *Pvector++;
}
*((volatile unsigned int *)(0x4000013C)) =
0x10000001; // inter vertor table remap
GLOBAL_INT_RESTORE();
#endif
}
static void WDT_ResetInit(void)
{
cpr_ctlapbclken_grctl__wdt_pclk_en__setf(ENABLE);
cpr_rstctl_ctlapb_sw__wdt_rstn__setf(RSTCTL_ENABLE);
cpr_rstctl_ctlapb_sw__wdt_rstn__setf(RSTCTL_DISABLE);
cpr_rstctl_wdtrst_mask_set(
(WDT_SYS_RSTN_MASK_DISABLE | WDT_M0_RSTN_MASK_ENABLE));
cpr_lp_ctl__wdt_tclk_en__setf(DISABLE);
wdt_cr__wdt_en__setf(DISABLE);
}
void SystemInit(void)
{
WDT_ResetInit();
#if (USE_XIP == 1)
set_vector();
#endif
// enable BT CLK
writel(0x40000040, readl(0x40000040) | (0x01 << 4) | 0xFFFF0000);
}
__RAM_CODE int sendchar(int c)
{
unsigned int status;
#if (__DEBUG_OUT_PORT == 1)
for (;;) {
status = (*((volatile unsigned *)(0x40011000 + 0x14)));
status &= 0x20;
if (status == 0x20)
break;
}
(*((volatile unsigned *)(0x40011000 + 0x00))) = c;
return (1);
#else
for (;;) {
status = (*((volatile unsigned *)(0x40010000 + 0x14)));
status &= 0x20;
if (status == 0x20)
break;
}
(*((volatile unsigned *)(0x40010000 + 0x00))) = c;
return (1);
#endif
}
struct __FILE
{
int handle; /* Add whatever you need here */
};
FILE __stdout;
__RAM_CODE int fputc(int ch, FILE *f) { return (sendchar(ch)); }
int ferror(FILE *f)
{
/* Your implementation of ferror */
return EOF;
}
void _ttywrch(int ch) { sendchar(ch); }
void _sys_exit(int return_code)
{
label:
goto label; /* endless loop */
}
@@ -0,0 +1,192 @@
#include "usr_client.h"
uint8_t cli_user_lid = GATT_INVALID_USER_LID;
/* Handle for sending data from the centre to the slave. */
uint16_t cli_tx_hdl = GATT_INVALID_HDL;
uint16_t cli_chg_ccc_hdl = GATT_INVALID_HDL;
#define CUSTOM_SVC_UUID_CLI 0xFFF0
#define CUSTOM_SVC_RX_CHAR_UUID_CLI 0xFFF3
#define CUSTOM_SVC_TX_CHAR_UUID_CLI 0xFFF4
uint8_t get_cli_user_ild(void) { return cli_user_lid; }
void cli_discover_cmp_cb(uint8_t conidx, uint8_t user_lid, uint16_t dummy,
uint16_t status)
{
LOGI(
"[%s] conidx = 0x%x, user_lid = 0x%x, dummy = 0x%x, status = 0x%x \r\n",
__func__, conidx, user_lid, dummy, status);
uint16_t cli_cfg = GATT_CCC_START_NTF;
status = xc_ble_gatt_cli_write(conidx, get_cli_user_ild(), 0, GATT_WRITE,
cli_chg_ccc_hdl, 2, (uint8_t *)&cli_cfg);
if (status != GATT_NO_ERROR) {
LOGI_ERR("xc_ble_gatt_cli_write error 0x%x", status);
}
// send_data(conidx);
}
void cli_read_cmp_cb(uint8_t conidx, uint8_t user_lid, uint16_t dummy,
uint16_t status)
{
LOGI(
"[%s] conidx = 0x%x, user_lid = 0x%x, dummy = 0x%x, status = 0x%x \r\n",
__func__, conidx, user_lid, dummy, status);
}
void cli_write_cmp_cb(uint8_t conidx, uint8_t user_lid, uint16_t dummy,
uint16_t status)
{
LOGI("[%s] conidx = 0x%x, user_lid = 0x%x, dummy = 0x%x, status = 0x%x\r\n",
__func__, conidx, user_lid, dummy, status);
}
void cli_svc_cb(uint8_t conidx, uint8_t user_lid, uint16_t dummy, uint16_t hdl,
uint8_t disc_info, uint8_t nb_att, const gatt_svc_att_t *p_atts)
{
LOGI("[%s] conidx = 0x%x, user_lid = 0x%x, dummy = 0x%x, hdl = 0x%x \r\n",
__func__, conidx, user_lid, dummy, hdl);
uint8_t cursor;
uint16_t att_handle = GATT_INVALID_HDL;
// check all attributes
for (cursor = 0; cursor < nb_att; cursor++) {
const gatt_svc_att_t *p_att = &(p_atts[cursor]);
switch (p_att->att_type) {
case GATT_ATT_PRIMARY_SVC: {
} break;
case GATT_ATT_CHAR: {
att_handle = p_att->info.charac.val_hdl;
} break;
case GATT_ATT_VAL: {
if (gatt_uuid16_comp(p_att->uuid, p_att->uuid_type,
CUSTOM_SVC_RX_CHAR_UUID_CLI)) {
cli_tx_hdl = att_handle;
LOGI("cli_tx_hdl=0x%x\n", cli_tx_hdl);
}
} break;
case GATT_ATT_DESC: {
// Client Char Configuration of service changed value
if (gatt_uuid16_comp(p_att->uuid, p_att->uuid_type,
GATT_DESC_CLIENT_CHAR_CFG)) {
cli_chg_ccc_hdl = hdl + cursor;
LOGI("cli_chg_ccc_hdl=0x%x\n", cli_chg_ccc_hdl);
}
} break;
default: { /* Nothing to do */
} break;
}
}
}
void cli_svc_info_cb(uint8_t conidx, uint8_t user_lid, uint16_t dummy,
uint16_t start_hdl, uint16_t end_hdl, uint8_t uuid_type,
const uint8_t *p_uuid)
{
LOGI("[%s] conidx = 0x%x, user_lid = 0x%x, start_hdl = 0x%x, end_hdl = "
"0x%x, uuid[0] = 0x%x, uuid[1] = 0x%x \r\n",
__func__, conidx, user_lid, start_hdl, end_hdl, p_uuid[0], p_uuid[1]);
}
void cli_read_val_cb(uint8_t conidx, uint8_t user_lid, uint16_t dummy,
uint16_t hdl, uint16_t offset, co_buf_t *p_data)
{
uint16_t length = co_buf_data_len(p_data);
LOGI("[%s] conidx = 0x%x, user_lid = 0x%x, handler = 0x%x, length = "
"0x%x data: \r\n",
__func__, conidx, user_lid, hdl, length);
// DUMP_DATA_PRINTF(&(co_buf_data(p_data)[0]), length);
}
void cli_val_evt_cb(uint8_t conidx, uint8_t user_lid, uint16_t token,
uint8_t evt_type, bool complete, uint16_t hdl,
co_buf_t *p_data)
{
uint16_t status;
uint16_t length = co_buf_data_len(p_data);
LOGI("[%s] conidx = 0x%x, user_lid = 0x%x, token = 0x%x evt_type = \
0x%x complete = 0x%x handler = 0x%x, length = %d data: \r\n",
__func__, conidx, user_lid, token, evt_type, complete, hdl, length);
status = xc_ble_gatt_cli_indicate_cfm(conidx, user_lid, token);
if (status != GATT_NO_ERROR) {
LOGI_ERR("gatt_cli_indicate_cfm error 0x%x", status);
}
for(uint8_t i = 0;i<length;i++)
{
LOGI(" %02x ",co_buf_data(p_data)[i]);
}
LOGI("\r\n");
//(&(co_buf_data(p_data)[0]), length);
}
void cli_svc_changed_cb(uint8_t conidx, uint8_t user_lid, bool out_of_sync,
uint16_t start_hdl, uint16_t end_hdl)
{
LOGI("[%s] conidx = 0x%x, user_lid = 0x%x, out_of_sync = 0x%x ,start_hdl = "
"0x%x, end_hdl = "
"0x%x \r\n",
__func__, conidx, user_lid, out_of_sync, start_hdl, end_hdl);
}
static const gatt_cli_cb_t cli_cb = {
.cb_discover_cmp = cli_discover_cmp_cb,
.cb_read_cmp = cli_read_cmp_cb,
.cb_write_cmp = cli_write_cmp_cb,
.cb_svc = cli_svc_cb,
.cb_svc_info = cli_svc_info_cb,
.cb_att_val = cli_read_val_cb,
.cb_att_val_evt = cli_val_evt_cb,
.cb_svc_changed = cli_svc_changed_cb,
};
uint8_t app_cli_register(void)
{
uint16_t status = 0;
status = xc_ble_gatt_user_cli_register(GAP_LE_MTU_MAX, 0, &cli_cb,
&cli_user_lid);
if (status != GATT_NO_ERROR) {
LOGI_ERR("gatt_user_cli_register error 0x%x", status);
}
return status;
}
__RAM_EM uint8_t data_test[THROUGHTPUT_SEND_DATA_LEN] = {0x00, 0x01, 0x02,
0x03};
void send_data(uint8_t conidx)
{
uint16_t status;
status = xc_ble_gatt_cli_write(conidx, get_cli_user_ild(), 0, GATT_WRITE,
cli_tx_hdl, sizeof(data_test), data_test);
if (status != GATT_NO_ERROR) {
LOGI_ERR("write error 0x%x", status);
}
}
void usr_cli_feat_enable(uint8_t conidx)
{
uint16_t svc_uuid = CUSTOM_SVC_UUID_CLI;
uint8_t status = gatt_cli_discover_svc(
conidx, get_cli_user_ild(), 0, GATT_DISCOVER_SVC_PRIMARY_BY_UUID, true,
GATT_MIN_HDL, GATT_MAX_HDL, GATT_UUID_16, (uint8_t *)&svc_uuid);
if (status == GATT_NO_ERROR) {
status = xc_ble_gatt_cli_event_register(conidx, get_cli_user_ild(),
GATT_MIN_HDL, GATT_MAX_HDL);
if (status != GATT_NO_ERROR) {
LOGI_ERR("xc_ble_gatt_cli_event_register error 0x%x", status);
}
} else {
LOGI_ERR("gatt_cli_discover_svc error 0x%x", status);
}
// uint16_t xc_ble_gatt_cli_mtu_exch( conidx, get_cli_user_ild());
}
@@ -0,0 +1,28 @@
/**
****************************************************************************************
*
* @file usr_client.h
*
* @brief Custom client
*
* Copyright (c) 2022 - 2025, XinChip
* All rights reserved.
*
****************************************************************************************
*/
#ifndef _USR_CLIENT_H_
#define _USE_CLIENT_H_
#include "app_task.h"
#include "dbg.h"
#include "gatt_msg.h"
#include "usr_server.h"
#include "xc_gatt_client_api.h"
#define THROUGHTPUT_SEND_DATA_LEN 20
uint8_t get_cli_user_ild(void);
uint8_t app_cli_register(void);
void usr_cli_feat_enable(uint8_t conidx);
#endif // _USE_CLIENT_H_
@@ -0,0 +1,190 @@
/**
****************************************************************************************
*
* @file usr_server.c
*
* @brief Custom Server profile database definitions.
*
* Copyright (c) 2022 - 2025, XinChip
* All rights reserved.p
*
****************************************************************************************
*/
#include "usr_server.h"
#include "xc6xxx.h"
#include "xc_head.h"
#include <string.h>
uint8_t srv_user_lid = GATT_INVALID_USER_LID;
uint16_t custom_svc_start_hdl = GATT_INVALID_HDL;
uint8_t custom_svc_tx_char_notify = DISABLE;
static const gatt_att_desc_t custom_server_atts[] = {
[CUSTOM_SVC_DECL] =
{
.uuid = 0x00,
0x28,
.info = GATT_ATT_RD_BIT | ATT_UUID(16),
.ext_info = 0,
},
[CUSTOM_SVC_RX_CHAR_DECL_CHAR] =
{
.uuid = 0x03,
0x28,
.info = GATT_ATT_RD_BIT | ATT_UUID(16),
.ext_info = 0,
},
[CUSTOM_SVC_RX_CHAR_VAL] =
{
.uuid = CUSTOM_SVC_RX_CHAR_UUID,
.info = GATT_ATT_WC_BIT | GATT_ATT_RD_BIT | ATT_UUID(128),
.ext_info =
GATT_ATT_NO_OFFSET_BIT | CUSTOM_SVC_RX_CHAR_VAL_MAX_LENGTH,
},
[CUSTOM_SVC_TX_CHAR_DECL_CHAR] =
{
.uuid = 0x03,
0x28,
.info = GATT_ATT_RD_BIT | ATT_UUID(16),
.ext_info = 0,
},
[CUSTOM_SVC_TX_CHAR_VAL] =
{
.uuid = CUSTOM_SVC_TX_CHAR_UUID,
.info = GATT_ATT_N_BIT | ATT_UUID(128),
.ext_info =
GATT_ATT_NO_OFFSET_BIT | CUSTOM_SVC_TX_CHAR_VAL_MAX_LENGTH,
},
[CUSTOM_SVC_TX_CHAR_CFG] =
{
.uuid = 0x02,
0x29,
.info = GATT_ATT_RD_BIT | GATT_ATT_WR_BIT | ATT_UUID(16),
.ext_info = 0,
},
};
uint8_t slave_send_data(uint8_t *data, uint8_t len, uint8_t att_idx);
uint16_t srv_get_hdl_from_att_idx(uint8_t idx)
{
return custom_svc_start_hdl + idx;
}
// This function is called when GATT server user has initiated event send to
// peer device or if an error occurs.
__STATIC void custom_svc_cb_event_sent(uint8_t conidx, uint8_t user_lid,
uint16_t dummy, uint16_t status)
{
LOGI("[%s] conidx:%d, usr_lid:%d, dummy:%d, status:%d \r\n", __func__,
conidx, user_lid, dummy, status);
extern void ble_data_send_callback(void);
ble_data_send_callback();
}
// This function is called when peer want to read local attribute database
// value.
__STATIC void custom_svc_cb_att_read_get(uint8_t conidx, uint8_t user_lid,
uint16_t token, uint16_t hdl,
uint16_t offset, uint16_t max_length)
{
uint16_t status;
uint8_t data[] = {0x12, 0x15, 0x46, 0x62};
LOGI("[%s] conidx:%d, usr_lid:%d, token:%d, hdl:%d, offset:%d, "
"max_length:%d \r\n",
__func__, conidx, user_lid, token, hdl, offset, max_length);
// Send result to peer device
status = xc_ble_gatt_srv_read_cfm(conidx, user_lid, token, GAP_ERR_NO_ERROR,
sizeof(data), sizeof(data), data);
if (status != GATT_NO_ERROR) {
LOGI_ERR("gatt_srv_read_cfm error 0x%x", status);
}
}
// This function is called during a write procedure to modify attribute handle.
__STATIC void custom_svc_cb_att_val_set(uint8_t conidx, uint8_t user_lid,
uint16_t token, uint16_t hdl,
uint16_t offset, co_buf_t *p_data)
{
uint16_t length = co_buf_data_len(p_data);
uint16_t status;
LOGI("[%s] conidx:%d, usr_lid:%d, token:%d, hdl:%d, offset:%d \r\n",
__func__, conidx, user_lid, token, hdl, offset);
status =
xc_ble_gatt_srv_write_cfm(conidx, user_lid, token, GAP_ERR_NO_ERROR);
if (status != GATT_NO_ERROR) {
LOGI_ERR("gatt_srv_write_cfm error 0x%x", status);
}
LOGI("length:%d data:\r\n", length);
// DUMP_DATA_PRINTF(co_buf_data(p_data), length);
// xc_fota_server_write_ind(co_buf_data(p_data), length);
// LOGI("hdl=%x %x\r\n", hdl,
// srv_get_hdl_from_att_idx(CUSTOM_SVC_TX_CHAR_CFG));
if (hdl == srv_get_hdl_from_att_idx(CUSTOM_SVC_TX_CHAR_CFG)) {
if ((co_buf_data(p_data)[1] == 0) && (co_buf_data(p_data)[0] == 0)) {
custom_svc_tx_char_notify = DISABLE;
extern int xc_ble_status_callback(int status);
xc_ble_status_callback(BLE_EVENT_NTF_DISABLE);
} else {
custom_svc_tx_char_notify = ENABLE;
LOGI("notify test\r\n");
extern int xc_ble_status_callback(int status);
xc_ble_status_callback(BLE_EVENT_NTF_ENABLE);
}
}
if (hdl == srv_get_hdl_from_att_idx(CUSTOM_SVC_RX_CHAR_VAL))
{
extern int xc_ble_data_recv_callback(void *data, uint32_t bytes);
xc_ble_data_recv_callback(co_buf_data(p_data), length);
}
}
int ble_send_notify_data(uint8_t *buffer, int length)
{
slave_send_data(buffer, length, CUSTOM_SVC_TX_CHAR_VAL);
return 0;
}
static const gatt_srv_cb_t custom_src_cb = {
.cb_event_sent = custom_svc_cb_event_sent,
.cb_att_read_get = custom_svc_cb_att_read_get,
.cb_att_val_set = custom_svc_cb_att_val_set,
};
uint8_t custom_svc_add(void)
{
int nb_att = sizeof(custom_server_atts) / sizeof(custom_server_atts[0]);
uint16_t status;
uint8_t custom_svc_uuid[GATT_UUID_128_LEN] = CUSTOM_SVC_UUID;
status = xc_ble_gatt_user_srv_register(GAP_LE_MTU_MAX, 0, &custom_src_cb,
&srv_user_lid);
if (status != GATT_NO_ERROR) {
LOGI_ERR("gatt_user_srv_register error 0x%x", status);
}
status = xc_ble_gatt_service_add(
srv_user_lid, GATT_UUID_128 << GATT_SVC_UUID_TYPE_LSB, custom_svc_uuid,
nb_att, NULL, &(custom_server_atts[0]), nb_att, &custom_svc_start_hdl);
if (status != GATT_NO_ERROR) {
LOGI_ERR("xc_ble_gatt_service_add error 0x%x", status);
}
return status;
}
uint8_t slave_send_data(uint8_t *data, uint8_t len, uint8_t att_idx)
{
uint16_t status = INVALID_DATA;
struct app_env_tag *app_env = get_app_env();
if (app_env->slave_connected && custom_svc_tx_char_notify) {
status = xc_ble_gatt_srv_notify(app_env->slave_conidx, srv_user_lid, 0,
srv_get_hdl_from_att_idx(att_idx), len,
data);
if (status != GATT_NO_ERROR) {
LOGI_ERR("gatt_srv_notify error 0x%x", status);
}
}
return status;
}
@@ -0,0 +1,64 @@
/**
****************************************************************************************
*
* @file usr_server.h
*
* @brief Custom Server profile database definitions.
*
* Copyright (c) 2022 - 2025, XinChip
* All rights reserved.
*
****************************************************************************************
*/
#ifndef _USR_SERVER_H_
#define _USR_SERVER_H_
#include "app_task.h"
#include "dbg.h"
#include "gatt.h"
#include "gatt_msg.h"
#include "rwble_hl_config.h"
#include "xc_gatt_server_api.h"
// #define CUSTOM_SVC_UUID
// {0x00,0x00,0xFF,0x10,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0x80,0x5F,0x9B,0x34,0xFA}
// #define CUSTOM_SVC_RX_CHAR_UUID
// 0x00,0x00,0xFF,0x11,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0x80,0x5F,0x9B,0x34,0xFB
// #define CUSTOM_SVC_TX_CHAR_UUID
// 0x00,0x00,0xFF,0x12,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0x80,0x5F,0x9B,0x34,0xFB
#define CUSTOM_SVC_UUID \
{ \
0xFA, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, \
0x00, 0x10, 0xFF, 0x00, 0x00 \
}
#define CUSTOM_SVC_TX_CHAR_UUID \
0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, \
0x11, 0xFF, 0x00, 0x00
#define CUSTOM_SVC_RX_CHAR_UUID \
0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, \
0x12, 0xFF, 0x00, 0x00
#define CUSTOM_SVC_RX_CHAR_VAL_MAX_LENGTH (512)
#define CUSTOM_SVC_TX_CHAR_VAL_MAX_LENGTH (512)
#ifndef DISABLE
#define DISABLE 0
#endif // DISABLE
#ifndef ENABLE
#define ENABLE 1
#endif // ENABLE
enum cust_svc
{
CUSTOM_SVC_DECL = 0,
CUSTOM_SVC_RX_CHAR_DECL_CHAR,
CUSTOM_SVC_RX_CHAR_VAL,
CUSTOM_SVC_TX_CHAR_DECL_CHAR,
CUSTOM_SVC_TX_CHAR_VAL,
CUSTOM_SVC_TX_CHAR_CFG,
};
uint8_t custom_svc_add(void);
uint8_t slave_send_data(uint8_t *data, uint8_t len, uint8_t att_idx);
#endif // _USR_SERVER_H_