diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs index 52b711d..cb3d62f 100644 --- a/.settings/org.eclipse.core.resources.prefs +++ b/.settings/org.eclipse.core.resources.prefs @@ -9,5 +9,8 @@ encoding//StdPeriphDriver/CH58x_gpio.c=GBK encoding//StdPeriphDriver/CH58x_sys.c=GBK encoding//StdPeriphDriver/CH58x_uart3.c=GBK encoding//StdPeriphDriver/inc/CH585SFR.h=GBK +encoding//StdPeriphDriver/inc/CH58x_common.h=GBK encoding//StdPeriphDriver/inc/CH58x_gpio.h=GBK -encoding//bsp/src/bsp_flash.c=GBK +encoding//StdPeriphDriver/inc/CH58x_sys.h=GBK +encoding//StdPeriphDriver/inc/ISP585.h=GBK +encoding//bsp/inc/bsp_uart.h=UTF-8 diff --git a/.vscode/settings.json b/.vscode/settings.json index 351511d..e34c388 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -18,6 +18,8 @@ } ], "files.associations": { - "config.h": "c" + "*.dbclient-js": "javascript", + "config.h": "c", + "ch58xble_lib.h": "c" } } \ No newline at end of file diff --git a/APP/include/multiCentral.h b/APP/include/multiCentral.h index adcfc21..c0e3647 100644 --- a/APP/include/multiCentral.h +++ b/APP/include/multiCentral.h @@ -23,6 +23,8 @@ #ifndef MULTICENTRAL_H #define MULTICENTRAL_H +#include "CONFIG.h" + #ifdef __cplusplus extern "C" { #endif @@ -55,6 +57,11 @@ extern "C" { // 定义启动写入CCCD(客户端特性配置描述符)事件的常量 #define START_WRITE_CCCD_EVT 0x0100 +// 定义启动读或写操作事件的常量 +#define CH2_READ_EVT 0x0200 +#define CH3_WRITE_EVT 0x0400 +#define CH4_NOTI_EVT 0x0800 + #define CONNECT0_ITEM 0 #define CONNECT1_ITEM 1 // #define CONNECT2_ITEM 2 @@ -65,6 +72,8 @@ extern "C" { // #define CONNECT7_ITEM 7 + + /********************************************************************* * MACROS */ @@ -79,6 +88,9 @@ typedef struct uint16_t svcStartHdl; // Discovered service start handle uint16_t svcEndHdl; // Discovered service end handle uint16_t charHdl; // Discovered characteristic handle + uint16_t charHd2; // Discovered characteristic handle + uint16_t charHd3; // Discovered characteristic handle + uint16_t charHd4; // Discovered characteristic handle uint16_t cccHdl; // client characteristic configuration discovery handle } centralConnItem_t; @@ -100,7 +112,7 @@ extern void Central_Init(void); * Task Event Processor for the BLE Application */ extern uint16_t Central_ProcessEvent(uint8_t task_id, uint16_t events); - +extern centralConnItem_t centralConnList[CENTRAL_MAX_CONNECTION]; /********************************************************************* *********************************************************************/ diff --git a/APP/multiCentral.c b/APP/multiCentral.c index a167609..ce378f8 100644 --- a/APP/multiCentral.c +++ b/APP/multiCentral.c @@ -7,94 +7,96 @@ #include "bsp_uart.h" #include "log.h" +#include "bsp_valve.h" + #undef LOG_ENABLE #define LOG_ENABLE 1 - /********************************************************************* * MACROS */ // Length of bd addr as a string -#define B_ADDR_STR_LEN 15 +#define B_ADDR_STR_LEN 15 /********************************************************************* * CONSTANTS */ // Maximum number of scan responses -#define DEFAULT_MAX_SCAN_RES 10 +#define DEFAULT_MAX_SCAN_RES 10 -// Scan duration in 0.625ms 扫描窗口要小于等于扫描间隔 -#define DEFAULT_SCAN_DURATION 2400 +// Scan duration in 0.625ms +#define DEFAULT_SCAN_DURATION 2400 // 2400*0.625 = 1500ms // Connection min interval in 1.25ms -#define DEFAULT_MIN_CONNECTION_INTERVAL 20 //25ms连接一次 范围为7.5ms~4s之间 +#define DEFAULT_MIN_CONNECTION_INTERVAL 80 // Connection max interval in 1.25ms -#define DEFAULT_MAX_CONNECTION_INTERVAL 100 //125ms连接一次 +#define DEFAULT_MAX_CONNECTION_INTERVAL 80 * 5 // Connection supervision timeout in 10ms -#define DEFAULT_CONNECTION_TIMEOUT 100 //10(100ms)~3200(32s) +/*修改为最大值*/ +#define DEFAULT_CONNECTION_TIMEOUT 100 // 32s // Discovey mode (limited, general, all) -#define DEFAULT_DISCOVERY_MODE DEVDISC_MODE_ALL +#define DEFAULT_DISCOVERY_MODE DEVDISC_MODE_ALL // TRUE to use active scan -#define DEFAULT_DISCOVERY_ACTIVE_SCAN TRUE +#define DEFAULT_DISCOVERY_ACTIVE_SCAN TRUE // TRUE to use white list during discovery -// #define DEFAULT_DISCOVERY_WHITE_LIST FALSE -#define DEFAULT_DISCOVERY_WHITE_LIST FALSE +#define DEFAULT_DISCOVERY_WHITE_LIST FALSE // TRUE to use high scan duty cycle when creating link -#define DEFAULT_LINK_HIGH_DUTY_CYCLE FALSE +#define DEFAULT_LINK_HIGH_DUTY_CYCLE FALSE // TRUE to use white list when creating link -#define DEFAULT_LINK_WHITE_LIST FALSE +#define DEFAULT_LINK_WHITE_LIST FALSE // Default read RSSI period in 0.625ms -#define DEFAULT_RSSI_PERIOD 2400 +#define DEFAULT_RSSI_PERIOD 2400 // Minimum connection interval (units of 1.25ms) -#define DEFAULT_UPDATE_MIN_CONN_INTERVAL 100 +#define DEFAULT_UPDATE_MIN_CONN_INTERVAL 20 // Maximum connection interval (units of 1.25ms) -#define DEFAULT_UPDATE_MAX_CONN_INTERVAL 400 +#define DEFAULT_UPDATE_MAX_CONN_INTERVAL 100 + // Slave latency to use parameter update -#define DEFAULT_UPDATE_SLAVE_LATENCY 5 +#define DEFAULT_UPDATE_SLAVE_LATENCY 5 // Supervision timeout value (units of 10ms) -#define DEFAULT_UPDATE_CONN_TIMEOUT 200 +#define DEFAULT_UPDATE_CONN_TIMEOUT 600 // Default passcode -#define DEFAULT_PASSCODE 0 +#define DEFAULT_PASSCODE 0 // Default GAP pairing mode -#define DEFAULT_PAIRING_MODE GAPBOND_PAIRING_MODE_WAIT_FOR_REQ +#define DEFAULT_PAIRING_MODE GAPBOND_PAIRING_MODE_WAIT_FOR_REQ // Default MITM mode (TRUE to require passcode or OOB when pairing) -#define DEFAULT_MITM_MODE TRUE +#define DEFAULT_MITM_MODE TRUE // Default bonding mode, TRUE to bond, max bonding 6 devices -#define DEFAULT_BONDING_MODE TRUE +#define DEFAULT_BONDING_MODE TRUE // Default GAP bonding I/O capabilities -#define DEFAULT_IO_CAPABILITIES GAPBOND_IO_CAP_NO_INPUT_NO_OUTPUT +#define DEFAULT_IO_CAPABILITIES GAPBOND_IO_CAP_NO_INPUT_NO_OUTPUT // Default service discovery timer delay in 0.625ms -#define DEFAULT_SVC_DISCOVERY_DELAY 1600 +#define DEFAULT_SVC_DISCOVERY_DELAY 1600 // Default parameter update delay in 0.625ms -#define DEFAULT_PARAM_UPDATE_DELAY 3200 +#define DEFAULT_PARAM_UPDATE_DELAY 3200 // Default read or write timer delay in 0.625ms -#define DEFAULT_READ_OR_WRITE_DELAY 100 +#define DEFAULT_READ_OR_WRITE_DELAY 1600 // Default write CCCD delay in 0.625ms -#define DEFAULT_WRITE_CCCD_DELAY 1600 +#define DEFAULT_WRITE_CCCD_DELAY 1600 // Establish link timeout in 0.625ms -#define ESTABLISH_LINK_TIMEOUT 3200 +#define ESTABLISH_LINK_TIMEOUT 3200 // Application states enum @@ -110,9 +112,10 @@ enum { BLE_DISC_STATE_IDLE, // Idle BLE_DISC_STATE_SVC, // Service discovery - BLE_DISC_STATE_CHAR, // Characteristic discovery - BLE_DISC_STATE_CCCD, // client characteristic configuration discovery + BLE_DISC_STATE_CHAR, // Characteristic discovery + BLE_DISC_STATE_CCCD, // client characteristic configuration discovery }; + /********************************************************************* * TYPEDEFS */ @@ -145,12 +148,13 @@ static gapDevRec_t centralDevList[DEFAULT_MAX_SCAN_RES]; // Peer device address static peerAddrDefItem_t PeerAddrDef[CENTRAL_MAX_CONNECTION] = { // {0xcf, 0xb4, 0x8f, 0x10, 0x53, 0x5c}, - {0xe1, 0X51, 0x89, 0x88, 0x19, 0x70}, + // {0xe1, 0X51, 0x89, 0x88, 0x19, 0x70}, + {0xb6, 0xb4, 0x8f, 0x10, 0x53, 0x5c}, // {0x03, 0x02, 0x03, 0xE4, 0xC2, 0x84}, }; // Connection item list -static centralConnItem_t centralConnList[CENTRAL_MAX_CONNECTION]; +centralConnItem_t centralConnList[CENTRAL_MAX_CONNECTION]; // Value to write static uint8_t centralCharVal = 0x01; @@ -161,23 +165,21 @@ static uint8_t centralDoWrite = TRUE; /********************************************************************* * LOCAL FUNCTIONS */ -static void centralProcessGATTMsg(gattMsgEvent_t *pMsg); -static void centralRssiCB(uint16_t connHandle, int8_t rssi); -static void centralEventCB(gapRoleEvent_t *pEvent); -static void centralHciMTUChangeCB(uint16_t connHandle, uint16_t maxTxOctets, uint16_t maxRxOctets); -static void centralPasscodeCB(uint8_t *deviceAddr, uint16_t connectionHandle, - uint8_t uiInputs, uint8_t uiOutputs); -static void centralPairStateCB(uint16_t connHandle, uint8_t state, uint8_t status); +static void centralProcessGATTMsg(gattMsgEvent_t *pMsg); +static void centralRssiCB(uint16_t connHandle, int8_t rssi); +static void centralEventCB(gapRoleEvent_t *pEvent); +static void centralHciMTUChangeCB(uint16_t connHandle, uint16_t maxTxOctets, uint16_t maxRxOctets); +static void centralPasscodeCB(uint8_t *deviceAddr, uint16_t connectionHandle, + uint8_t uiInputs, uint8_t uiOutputs); +static void centralPairStateCB(uint16_t connHandle, uint8_t state, uint8_t status); static uint16_t connect0_ProcessEvent(uint8_t task_id, uint16_t events); -static void central_ProcessTMOSMsg(tmos_event_hdr_t *pMsg); -static void centralGATTDiscoveryEvent(uint8_t connItem, gattMsgEvent_t *pMsg); -static void centralConnIistStartDiscovery_0(void); -static void centralAddDeviceInfo(uint8_t *pAddr, uint8_t addrType); -static void centralInitConnItem(uint8_t task_id, centralConnItem_t *centralConnList); -static uint8_t centralAddrCmp(peerAddrDefItem_t *PeerAddrDef, uint8_t *addr); +static void central_ProcessTMOSMsg(tmos_event_hdr_t *pMsg); +static void centralGATTDiscoveryEvent(uint8_t connItem, gattMsgEvent_t *pMsg); +static void centralConnIistStartDiscovery_0(void); +static void centralAddDeviceInfo(uint8_t *pAddr, uint8_t addrType); +static void centralInitConnItem(uint8_t task_id, centralConnItem_t *centralConnList); +static uint8_t centralAddrCmp(peerAddrDefItem_t *PeerAddrDef, uint8_t *addr); -static void centralConnIistStartDiscovery_1(void); -static uint16_t connect1_ProcessEvent(uint8_t task_id, uint16_t events); /********************************************************************* * PROFILE CALLBACKS */ @@ -191,9 +193,8 @@ static gapCentralRoleCB_t centralRoleCB = { // Bond Manager Callbacks static gapBondCBs_t centralBondCB = { - centralPasscodeCB,// 连接时需要使用有密码的函数。 - centralPairStateCB//配对时的回调函数 -}; + centralPasscodeCB, + centralPairStateCB}; /********************************************************************* * PUBLIC FUNCTIONS @@ -215,23 +216,21 @@ static gapBondCBs_t centralBondCB = { */ void Central_Init() { - centralTaskId = TMOS_ProcessEventRegister(Central_ProcessEvent);//注册事件处理函数,将返回的任务赋值给变量 + centralTaskId = TMOS_ProcessEventRegister(Central_ProcessEvent); // Setup GAP - GAP_SetParamValue(TGAP_DISC_SCAN_WIND, DEFAULT_SCAN_DURATION);//扫描窗口 - GAP_SetParamValue(TGAP_DISC_SCAN, DEFAULT_SCAN_DURATION);//扫描连续时间,单位0.625ms 4800*0.625ms = 3000ms - GAP_SetParamValue(TGAP_DISC_SCAN_INT, DEFAULT_SCAN_DURATION);////扫描间隔,需要>=扫描窗口 - GAP_SetParamValue(TGAP_CONN_EST_INT_MIN, DEFAULT_MIN_CONNECTION_INTERVAL);////设置链路层连接间隔,这里是最小连接间隔 - GAP_SetParamValue(TGAP_CONN_EST_INT_MAX, DEFAULT_MAX_CONNECTION_INTERVAL);//最大连续间隔 - GAP_SetParamValue(TGAP_CONN_EST_SUPERV_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);//连接超时时间 - + GAP_SetParamValue(TGAP_DISC_SCAN, DEFAULT_SCAN_DURATION); + GAP_SetParamValue(TGAP_CONN_EST_INT_MIN, DEFAULT_MIN_CONNECTION_INTERVAL); + GAP_SetParamValue(TGAP_CONN_EST_INT_MAX, DEFAULT_MAX_CONNECTION_INTERVAL); + GAP_SetParamValue(TGAP_CONN_EST_SUPERV_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); + // Setup the GAP Bond Manager { - uint32_t passkey = DEFAULT_PASSCODE;//PASSKEY 是在配对过程中用于验证设备身份的一种方式 - uint8_t pairMode = DEFAULT_PAIRING_MODE;//(配对模式)配对模式定义了设备进行配对过程中的行为和要求 - uint8_t mitm = DEFAULT_MITM_MODE;//MIMT模式定义了是否需要保护免受中间人攻击的配对过程 - uint8_t ioCap = DEFAULT_IO_CAPABILITIES;//IO能力定义了设备对配对过程的输入输出能力 - uint8_t bonding = DEFAULT_BONDING_MODE;//(绑定模式)绑定模式定义了设备在配对后是否应该建立安全的绑定关系 + uint32_t passkey = DEFAULT_PASSCODE; + uint8_t pairMode = DEFAULT_PAIRING_MODE; + uint8_t mitm = DEFAULT_MITM_MODE; + uint8_t ioCap = DEFAULT_IO_CAPABILITIES; + uint8_t bonding = DEFAULT_BONDING_MODE; GAPBondMgr_SetParameter(GAPBOND_CENT_DEFAULT_PASSCODE, sizeof(uint32_t), &passkey); GAPBondMgr_SetParameter(GAPBOND_CENT_PAIRING_MODE, sizeof(uint8_t), &pairMode); @@ -243,7 +242,7 @@ void Central_Init() // Init Connection Item centralInitConnItem(centralTaskId, centralConnList); // Initialize GATT Client - GATT_InitClient();//初始化通用规范属性客户端 + GATT_InitClient(); // Register to receive incoming ATT Indications/Notifications GATT_RegisterForInd(centralTaskId); // Setup a delayed profile startup @@ -263,17 +262,18 @@ void Central_Init() static void centralInitConnItem(uint8_t task_id, centralConnItem_t *centralConnList) { uint8_t connItem; - for(connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) + for (connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) { - centralConnList[connItem].taskID = TMOS_ProcessEventRegister(Central_ProcessEvent); - centralConnList[connItem].connHandle = GAP_CONNHANDLE_INIT; - centralConnList[connItem].state = BLE_STATE_IDLE; - centralConnList[connItem].discState = BLE_DISC_STATE_IDLE; + // 每个连接的任务通过taskID区分 + centralConnList[connItem].taskID = TMOS_ProcessEventRegister(Central_ProcessEvent); + centralConnList[connItem].connHandle = GAP_CONNHANDLE_INIT; + centralConnList[connItem].state = BLE_STATE_IDLE; + centralConnList[connItem].discState = BLE_DISC_STATE_IDLE; centralConnList[connItem].procedureInProgress = FALSE; - centralConnList[connItem].charHdl = 0; - centralConnList[connItem].svcStartHdl = 0; - centralConnList[connItem].svcEndHdl = 0; - centralConnList[connItem].cccHdl = 0; + centralConnList[connItem].charHdl = 0; + centralConnList[connItem].svcStartHdl = 0; + centralConnList[connItem].svcEndHdl = 0; + centralConnList[connItem].cccHdl = 0; } } @@ -283,7 +283,7 @@ static void centralInitConnItem(uint8_t task_id, centralConnItem_t *centralConnL * @brief Central Application Task event processor. This function * is called to process all events for the task. Events * include timers, messages and any other user defined events. - *中央应用程序任务事件处理器。调用此函数来处理任务的所有事件。事件包括定时器、消息和任何其他用户定义的事件。 + * * @param task_id - The TMOS assigned task ID. * @param events - events to process. This is a bit map and can * contain more than one event. @@ -292,11 +292,11 @@ static void centralInitConnItem(uint8_t task_id, centralConnItem_t *centralConnL */ uint16_t Central_ProcessEvent(uint8_t task_id, uint16_t events) { - if(events & SYS_EVENT_MSG) + if (events & SYS_EVENT_MSG) { uint8_t *pMsg; - if((pMsg = tmos_msg_receive(centralTaskId)) != NULL) + if ((pMsg = tmos_msg_receive(centralTaskId)) != NULL) { central_ProcessTMOSMsg((tmos_event_hdr_t *)pMsg); // Release the TMOS message @@ -306,31 +306,32 @@ uint16_t Central_ProcessEvent(uint8_t task_id, uint16_t events) return (events ^ SYS_EVENT_MSG); } - if(events & START_DEVICE_EVT) + if (events & START_DEVICE_EVT) { - // Start the Device 启动设备 + // Start the Device GAPRole_CentralStartDevice(centralTaskId, ¢ralBondCB, ¢ralRoleCB); return (events ^ START_DEVICE_EVT); } - //终止现有连接 - if(events & ESTABLISH_LINK_TIMEOUT_EVT) + + if (events & ESTABLISH_LINK_TIMEOUT_EVT) { GAPRole_TerminateLink(INVALID_CONNHANDLE); return (events ^ ESTABLISH_LINK_TIMEOUT_EVT); } - if(task_id == centralConnList[CONNECT0_ITEM].taskID) + // 连接0的任务处理 + if (task_id == centralConnList[CONNECT0_ITEM].taskID) { return connect0_ProcessEvent(task_id, events); } - else if(task_id == centralConnList[CONNECT1_ITEM].taskID) + // 连接1的任务处理 + else if (task_id == centralConnList[CONNECT1_ITEM].taskID) { - return connect1_ProcessEvent(task_id, events); } - // else if(task_id == centralConnList[CONNECT2_ITEM].taskID) - // { - // return connect2_ProcessEvent(task_id, events); - // } + // 连接2的任务处理 + // else if(task_id == centralConnList[CONNECT2_ITEM].taskID) + // { + // } // Discard unknown events return 0; } @@ -346,35 +347,35 @@ uint16_t Central_ProcessEvent(uint8_t task_id, uint16_t events) */ static uint16_t connect0_ProcessEvent(uint8_t task_id, uint16_t events) { - if(events & START_SVC_DISCOVERY_EVT) + if (events & START_SVC_DISCOVERY_EVT) { // start service discovery centralConnIistStartDiscovery_0(); return (events ^ START_SVC_DISCOVERY_EVT); } - if(events & START_READ_OR_WRITE_EVT) + if (events & START_READ_OR_WRITE_EVT) { - if(centralConnList[CONNECT0_ITEM].procedureInProgress == FALSE) + if (centralConnList[CONNECT0_ITEM].procedureInProgress == FALSE) { - if(centralDoWrite) + if (centralDoWrite) { // Do a write attWriteReq_t req; - req.cmd = FALSE; - req.sig = FALSE; + req.cmd = FALSE; + req.sig = FALSE; req.handle = centralConnList[CONNECT0_ITEM].charHdl; - req.len = 1; + req.len = 1; req.pValue = GATT_bm_alloc(centralConnList[CONNECT0_ITEM].connHandle, ATT_WRITE_REQ, req.len, NULL, 0); - if(req.pValue != NULL) + if (req.pValue != NULL) { *req.pValue = centralCharVal; - if(GATT_WriteCharValue(centralConnList[CONNECT0_ITEM].connHandle, &req, centralTaskId) == SUCCESS) + if (GATT_WriteCharValue(centralConnList[CONNECT0_ITEM].connHandle, &req, centralTaskId) == SUCCESS) { centralConnList[CONNECT0_ITEM].procedureInProgress = TRUE; - centralDoWrite = !centralDoWrite; + centralDoWrite = !centralDoWrite; tmos_start_task(centralConnList[CONNECT0_ITEM].taskID, START_READ_OR_WRITE_EVT, DEFAULT_READ_OR_WRITE_DELAY); } else @@ -389,17 +390,54 @@ static uint16_t connect0_ProcessEvent(uint8_t task_id, uint16_t events) attReadReq_t req; req.handle = centralConnList[CONNECT0_ITEM].charHdl; - if(GATT_ReadCharValue(centralConnList[CONNECT0_ITEM].connHandle, &req, centralTaskId) == SUCCESS) + if (GATT_ReadCharValue(centralConnList[CONNECT0_ITEM].connHandle, &req, centralTaskId) == SUCCESS) { centralConnList[CONNECT0_ITEM].procedureInProgress = TRUE; - centralDoWrite = !centralDoWrite; + centralDoWrite = !centralDoWrite; } } } return (events ^ START_READ_OR_WRITE_EVT); } - if(events & START_PARAM_UPDATE_EVT) + if (events & CH3_WRITE_EVT) + { + PRINT("CH3_WRITE_EVT\r\n"); + if (centralConnList[CONNECT0_ITEM].procedureInProgress == FALSE) + { + PRINT("centralConnList CH3_WRITE_EVT\n"); + static uint8_t sendcnt = 0; + attWriteReq_t req; + + req.cmd = FALSE; + req.sig = FALSE; + req.handle = centralConnList[CONNECT0_ITEM].charHd3; + PRINT("handle:%x\r\n", req.handle); + req.len = 3; + req.pValue = GATT_bm_alloc(centralConnList[CONNECT0_ITEM].connHandle, ATT_WRITE_REQ, req.len, NULL, 0); + if (req.pValue != NULL) + { + PRINT("req.pValue != NULL\r\n"); + req.pValue[0] = 0x11; + req.pValue[1] = 0x22; + req.pValue[2] = sendcnt++; + + if (GATT_WriteCharValue(centralConnList[CONNECT0_ITEM].connHandle, &req, centralTaskId) == SUCCESS) + { + centralConnList[CONNECT0_ITEM].procedureInProgress = TRUE; + tmos_start_task(centralConnList[CONNECT0_ITEM].taskID, CH3_WRITE_EVT, DEFAULT_READ_OR_WRITE_DELAY); + PRINT("GATT_WriteCharValue\r\n"); + } + else + { + GATT_bm_free((gattMsg_t *)&req, ATT_WRITE_REQ); + } + } + } + return (events ^ CH3_WRITE_EVT); + } + + if (events & START_PARAM_UPDATE_EVT) { // start connect parameter update GAPRole_UpdateLink(centralConnList[CONNECT0_ITEM].connHandle, @@ -411,24 +449,24 @@ static uint16_t connect0_ProcessEvent(uint8_t task_id, uint16_t events) return (events ^ START_PARAM_UPDATE_EVT); } - if(events & START_WRITE_CCCD_EVT) + if (events & START_WRITE_CCCD_EVT) { - if(centralConnList[CONNECT0_ITEM].procedureInProgress == FALSE) + if (centralConnList[CONNECT0_ITEM].procedureInProgress == FALSE) { // Do a write attWriteReq_t req; - req.cmd = FALSE; - req.sig = FALSE; + req.cmd = FALSE; + req.sig = FALSE; req.handle = centralConnList[CONNECT0_ITEM].cccHdl; - req.len = 2; + req.len = 2; req.pValue = GATT_bm_alloc(centralConnList[CONNECT0_ITEM].connHandle, ATT_WRITE_REQ, req.len, NULL, 0); - if(req.pValue != NULL) + if (req.pValue != NULL) { req.pValue[0] = 1; req.pValue[1] = 0; - if(GATT_WriteCharValue(centralConnList[CONNECT0_ITEM].connHandle, &req, centralTaskId) == SUCCESS) + if (GATT_WriteCharValue(centralConnList[CONNECT0_ITEM].connHandle, &req, centralTaskId) == SUCCESS) { centralConnList[CONNECT0_ITEM].procedureInProgress = TRUE; } @@ -441,7 +479,7 @@ static uint16_t connect0_ProcessEvent(uint8_t task_id, uint16_t events) return (events ^ START_WRITE_CCCD_EVT); } - if(events & START_READ_RSSI_EVT) + if (events & START_READ_RSSI_EVT) { GAPRole_ReadRssiCmd(centralConnList[CONNECT0_ITEM].connHandle); tmos_start_task(centralConnList[CONNECT0_ITEM].taskID, START_READ_RSSI_EVT, DEFAULT_RSSI_PERIOD); @@ -450,122 +488,6 @@ static uint16_t connect0_ProcessEvent(uint8_t task_id, uint16_t events) // Discard unknown events return 0; } - -/********************************************************************* - * @fn connect1_ProcessEvent - * - * @brief Process an incoming task message. - * - * @param pMsg - message to process - * - * @return none - */ -static uint16_t connect1_ProcessEvent(uint8_t task_id, uint16_t events) -{ - if(events & START_SVC_DISCOVERY_EVT) - { - // start service discovery - centralConnIistStartDiscovery_1(); - return (events ^ START_SVC_DISCOVERY_EVT); - } - - if(events & START_READ_OR_WRITE_EVT) - { - if(centralConnList[CONNECT0_ITEM].procedureInProgress == FALSE) - { - if(centralDoWrite) - { - // Do a write - attWriteReq_t req; - - req.cmd = FALSE; - req.sig = FALSE; - req.handle = centralConnList[CONNECT1_ITEM].charHdl; - req.len = 1;//发送的长度 - req.pValue = GATT_bm_alloc(centralConnList[CONNECT1_ITEM].connHandle, ATT_WRITE_REQ, req.len, NULL, 0); - if(req.pValue != NULL) - { - *req.pValue = centralCharVal;//发送的数据 - - if(GATT_WriteCharValue(centralConnList[CONNECT1_ITEM].connHandle, &req, centralTaskId) == SUCCESS)//发送函数 - { - centralConnList[CONNECT1_ITEM].procedureInProgress = TRUE; - centralDoWrite = !centralDoWrite; - tmos_start_task(centralConnList[CONNECT1_ITEM].taskID, START_READ_OR_WRITE_EVT, DEFAULT_READ_OR_WRITE_DELAY); - } - else - { - GATT_bm_free((gattMsg_t *)&req, ATT_WRITE_REQ); - } - } - } - else - { - // Do a read - attReadReq_t req; - - req.handle = centralConnList[CONNECT1_ITEM].charHdl; - if(GATT_ReadCharValue(centralConnList[CONNECT1_ITEM].connHandle, &req, centralTaskId) == SUCCESS)//读取函数 - { - centralConnList[CONNECT1_ITEM].procedureInProgress = TRUE; - centralDoWrite = !centralDoWrite; - } - } - } - return (events ^ START_READ_OR_WRITE_EVT); - } - - if(events & START_PARAM_UPDATE_EVT) - { - // start connect parameter update - GAPRole_UpdateLink(centralConnList[CONNECT1_ITEM].connHandle, - DEFAULT_UPDATE_MIN_CONN_INTERVAL, - DEFAULT_UPDATE_MAX_CONN_INTERVAL, - DEFAULT_UPDATE_SLAVE_LATENCY, - DEFAULT_UPDATE_CONN_TIMEOUT); - - return (events ^ START_PARAM_UPDATE_EVT); - } - if(events & START_WRITE_CCCD_EVT) - { - if(centralConnList[CONNECT1_ITEM].procedureInProgress == FALSE) - { - // Do a write - attWriteReq_t req; - - req.cmd = FALSE; - req.sig = FALSE; - req.handle = centralConnList[CONNECT1_ITEM].cccHdl; - req.len = 2; - req.pValue = GATT_bm_alloc(centralConnList[CONNECT1_ITEM].connHandle, ATT_WRITE_REQ, req.len, NULL, 0); - if(req.pValue != NULL) - { - req.pValue[0] = 1; - req.pValue[1] = 0; - - if(GATT_WriteCharValue(centralConnList[CONNECT1_ITEM].connHandle, &req, centralTaskId) == SUCCESS) - { - centralConnList[CONNECT1_ITEM].procedureInProgress = TRUE; - } - else - { - GATT_bm_free((gattMsg_t *)&req, ATT_WRITE_REQ); - } - } - } - return (events ^ START_WRITE_CCCD_EVT); - } - - if(events & START_READ_RSSI_EVT) - { - GAPRole_ReadRssiCmd(centralConnList[CONNECT1_ITEM].connHandle); - tmos_start_task(centralConnList[CONNECT1_ITEM].taskID, START_READ_RSSI_EVT, DEFAULT_RSSI_PERIOD); - return (events ^ START_READ_RSSI_EVT); - } - // Discard unknown events - return 0; -} - /********************************************************************* * @fn central_ProcessTMOSMsg * @@ -577,7 +499,7 @@ static uint16_t connect1_ProcessEvent(uint8_t task_id, uint16_t events) */ static void central_ProcessTMOSMsg(tmos_event_hdr_t *pMsg) { - switch(pMsg->event) + switch (pMsg->event) { case GATT_MSG_EVENT: centralProcessGATTMsg((gattMsgEvent_t *)pMsg); @@ -595,18 +517,18 @@ static void central_ProcessTMOSMsg(tmos_event_hdr_t *pMsg) static void centralProcessGATTMsg(gattMsgEvent_t *pMsg) { uint8_t connItem; - for(connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) + for (connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) { - if(centralConnList[connItem].connHandle == pMsg->connHandle) + if (centralConnList[connItem].connHandle == pMsg->connHandle) break; } - if(connItem == CENTRAL_MAX_CONNECTION) + if (connItem == CENTRAL_MAX_CONNECTION) { return; // Should not go there } - if(centralConnList[connItem].state != BLE_STATE_CONNECTED) + if (centralConnList[connItem].state != BLE_STATE_CONNECTED) { // In case a GATT message came after a connection has dropped, // ignore the message @@ -614,10 +536,11 @@ static void centralProcessGATTMsg(gattMsgEvent_t *pMsg) return; } - if((pMsg->method == ATT_EXCHANGE_MTU_RSP) || ((pMsg->method == ATT_ERROR_RSP) && - (pMsg->msg.errorRsp.reqOpcode == ATT_EXCHANGE_MTU_REQ))) + if ((pMsg->method == ATT_EXCHANGE_MTU_RSP) || + ((pMsg->method == ATT_ERROR_RSP) && + (pMsg->msg.errorRsp.reqOpcode == ATT_EXCHANGE_MTU_REQ))) { - if(pMsg->method == ATT_ERROR_RSP) + if (pMsg->method == ATT_ERROR_RSP) { uint8_t status = pMsg->msg.errorRsp.errCode; @@ -626,16 +549,16 @@ static void centralProcessGATTMsg(gattMsgEvent_t *pMsg) centralConnList[connItem].procedureInProgress = FALSE; } - if(pMsg->method == ATT_MTU_UPDATED_EVENT) + if (pMsg->method == ATT_MTU_UPDATED_EVENT) { PRINT("MTU: %x\r\n", pMsg->msg.mtuEvt.MTU); } - if((pMsg->method == ATT_READ_RSP) || - ((pMsg->method == ATT_ERROR_RSP) && - (pMsg->msg.errorRsp.reqOpcode == ATT_READ_REQ))) + if ((pMsg->method == ATT_READ_RSP) || + ((pMsg->method == ATT_ERROR_RSP) && + (pMsg->msg.errorRsp.reqOpcode == ATT_READ_REQ))) { - if(pMsg->method == ATT_ERROR_RSP) + if (pMsg->method == ATT_ERROR_RSP) { uint8_t status = pMsg->msg.errorRsp.errCode; @@ -648,11 +571,11 @@ static void centralProcessGATTMsg(gattMsgEvent_t *pMsg) } centralConnList[connItem].procedureInProgress = FALSE; } - else if((pMsg->method == ATT_WRITE_RSP) || - ((pMsg->method == ATT_ERROR_RSP) && - (pMsg->msg.errorRsp.reqOpcode == ATT_WRITE_REQ))) + else if ((pMsg->method == ATT_WRITE_RSP) || + ((pMsg->method == ATT_ERROR_RSP) && + (pMsg->msg.errorRsp.reqOpcode == ATT_WRITE_REQ))) { - if(pMsg->method == ATT_ERROR_RSP == ATT_ERROR_RSP) + if (pMsg->method == ATT_ERROR_RSP == ATT_ERROR_RSP) { uint8_t status = pMsg->msg.errorRsp.errCode; @@ -662,16 +585,16 @@ static void centralProcessGATTMsg(gattMsgEvent_t *pMsg) { // After a succesful write, display the value that was written and increment value PRINT("Write sent: %x\r\n", centralCharVal); - } centralConnList[connItem].procedureInProgress = FALSE; } - else if(pMsg->method == ATT_HANDLE_VALUE_NOTI) + else if (pMsg->method == ATT_HANDLE_VALUE_NOTI) { - PRINT("Receive noti: %x\r\n", *pMsg->msg.handleValueNoti.pValue); + // PRINT("Receive noti: %x\r\n", *pMsg->msg.handleValueNoti.pValue); + logHexDumpAll(pMsg->msg.handleValueNoti.pValue, pMsg->msg.handleValueNoti.len); } - else if(centralConnList[connItem].discState != BLE_DISC_STATE_IDLE) + else if (centralConnList[connItem].discState != BLE_DISC_STATE_IDLE) { centralGATTDiscoveryEvent(connItem, pMsg); } @@ -718,15 +641,14 @@ static void centralHciMTUChangeCB(uint16_t connHandle, uint16_t maxTxOctets, uin */ static void centralEventCB(gapRoleEvent_t *pEvent) { - uint8_t advdata[32] = {0}; - switch(pEvent->gap.opcode) + switch (pEvent->gap.opcode) { case GAP_DEVICE_INIT_DONE_EVENT: { PRINT("Discovering...\r\n"); GAPRole_CentralStartDiscovery(DEFAULT_DISCOVERY_MODE, DEFAULT_DISCOVERY_ACTIVE_SCAN, - DEFAULT_DISCOVERY_WHITE_LIST);//开始扫描设备 + DEFAULT_DISCOVERY_WHITE_LIST); } break; @@ -736,29 +658,31 @@ static void centralEventCB(gapRoleEvent_t *pEvent) centralAddDeviceInfo(pEvent->deviceInfo.addr, pEvent->deviceInfo.addrType); } break; + case GAP_DEVICE_DISCOVERY_EVENT: { uint8_t i; - // See if peer device has been discovered - for(i = 0; i < centralScanRes; i++) + // See if peer device has been discovered + for (i = 0; i < centralScanRes; i++) { - if(centralAddrCmp(PeerAddrDef, centralDevList[i].addr)) + if (centralAddrCmp(PeerAddrDef, centralDevList[i].addr)) break; } - /*Peer device not found*/ - if(i == centralScanRes) + // Peer device not found + if (i == centralScanRes) { PRINT("Device not found...\r\n"); - centralScanRes = 0; GAPRole_CentralStartDiscovery(DEFAULT_DISCOVERY_MODE, DEFAULT_DISCOVERY_ACTIVE_SCAN, DEFAULT_DISCOVERY_WHITE_LIST); PRINT("Discovering...\r\n"); - } - else// Peer device found + } + + // Peer device found + else { PRINT("Device found...\r\n"); GAPRole_CentralEstablishLink(DEFAULT_LINK_HIGH_DUTY_CYCLE, @@ -775,58 +699,62 @@ static void centralEventCB(gapRoleEvent_t *pEvent) case GAP_LINK_ESTABLISHED_EVENT: { - tmos_stop_task(centralTaskId, ESTABLISH_LINK_TIMEOUT_EVT);//关闭连接超时任务 - if(pEvent->gap.hdr.status == SUCCESS) + tmos_stop_task(centralTaskId, ESTABLISH_LINK_TIMEOUT_EVT); + if (pEvent->gap.hdr.status == SUCCESS) { uint8_t connItem; - for(connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) + // 查询是否有空余连接条目 + for (connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) { - if(centralConnList[connItem].connHandle == GAP_CONNHANDLE_INIT) + if (centralConnList[connItem].connHandle == GAP_CONNHANDLE_INIT) break; } - if(connItem == CENTRAL_MAX_CONNECTION) + if (connItem == CENTRAL_MAX_CONNECTION) { GAPRole_TerminateLink(pEvent->linkCmpl.connectionHandle); PRINT("Connection max...\r\n"); } else { - centralConnList[connItem].state = BLE_STATE_CONNECTED; + centralConnList[connItem].state = BLE_STATE_CONNECTED; centralConnList[connItem].connHandle = pEvent->linkCmpl.connectionHandle; PRINT("Conn %x - Int %x \r\n", pEvent->linkCmpl.connectionHandle, pEvent->linkCmpl.connInterval); - if(connItem == CONNECT0_ITEM) + // 连接0 + if (connItem == CONNECT0_ITEM) { centralConnList[connItem].procedureInProgress = TRUE; - // Initiate service discovery 开启枚举服务任务 + // Initiate service discovery tmos_start_task(centralConnList[connItem].taskID, START_SVC_DISCOVERY_EVT, DEFAULT_SVC_DISCOVERY_DELAY); - // Initiate connect parameter update 开始连接参数更新任务 + // Initiate connect parameter update tmos_start_task(centralConnList[connItem].taskID, START_PARAM_UPDATE_EVT, DEFAULT_PARAM_UPDATE_DELAY); - // Start RSSI polling + // Start RSSI polling tmos_start_task(centralConnList[connItem].taskID, START_READ_RSSI_EVT, DEFAULT_RSSI_PERIOD); } - // else if(connItem == CONNECT1_ITEM) - // { - // } + // 连接1 + else if (connItem == CONNECT1_ITEM) + { + } - // else if(connItem == CONNECT2_ITEM) - // { - // } + // 连接2 + // else if(connItem == CONNECT2_ITEM) + // { + // } PRINT("Connected...\r\n"); // See if need discover again - for(connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) + for (connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) { - if(centralConnList[connItem].connHandle == GAP_CONNHANDLE_INIT) + if (centralConnList[connItem].connHandle == GAP_CONNHANDLE_INIT) break; } - if(connItem < CENTRAL_MAX_CONNECTION) + if (connItem < CENTRAL_MAX_CONNECTION) { PRINT("Discovering...\r\n"); centralScanRes = 0; @@ -843,30 +771,30 @@ static void centralEventCB(gapRoleEvent_t *pEvent) centralScanRes = 0; GAPRole_CentralStartDiscovery(DEFAULT_DISCOVERY_MODE, DEFAULT_DISCOVERY_ACTIVE_SCAN, - DEFAULT_DISCOVERY_WHITE_LIST);//重新开始扫描 + DEFAULT_DISCOVERY_WHITE_LIST); } } break; - case GAP_LINK_TERMINATED_EVENT: //断开连接事件,打印断开连接原因,并重新开始扫描 + case GAP_LINK_TERMINATED_EVENT: { uint8_t connItem; - for(connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) + for (connItem = 0; connItem < CENTRAL_MAX_CONNECTION; connItem++) { - if(centralConnList[connItem].connHandle == pEvent->linkTerminate.connectionHandle) + if (centralConnList[connItem].connHandle == pEvent->linkTerminate.connectionHandle) break; } - if(connItem == CENTRAL_MAX_CONNECTION) + if (connItem == CENTRAL_MAX_CONNECTION) { // Should not go there } PRINT(" %x Disconnected...Reason:%x\r\n", centralConnList[connItem].connHandle, pEvent->linkTerminate.reason); - centralConnList[connItem].state = BLE_STATE_IDLE; - centralConnList[connItem].connHandle = GAP_CONNHANDLE_INIT; - centralConnList[connItem].discState = BLE_DISC_STATE_IDLE; - centralConnList[connItem].charHdl = 0; + centralConnList[connItem].state = BLE_STATE_IDLE; + centralConnList[connItem].connHandle = GAP_CONNHANDLE_INIT; + centralConnList[connItem].discState = BLE_DISC_STATE_IDLE; + centralConnList[connItem].charHdl = 0; centralConnList[connItem].procedureInProgress = FALSE; - centralScanRes = 0; + centralScanRes = 0; tmos_stop_task(centralConnList[connItem].taskID, START_READ_RSSI_EVT); @@ -897,13 +825,13 @@ static void centralEventCB(gapRoleEvent_t *pEvent) */ static void centralPairStateCB(uint16_t connHandle, uint8_t state, uint8_t status) { - if(state == GAPBOND_PAIRING_STATE_STARTED) + if (state == GAPBOND_PAIRING_STATE_STARTED) { PRINT("Connection %04x - Pairing started:%d\r\n", connHandle, status); } - else if(state == GAPBOND_PAIRING_STATE_COMPLETE) + else if (state == GAPBOND_PAIRING_STATE_COMPLETE) { - if(status == SUCCESS) + if (status == SUCCESS) { PRINT("Connection %04x - Pairing success\r\n", connHandle); } @@ -912,16 +840,16 @@ static void centralPairStateCB(uint16_t connHandle, uint8_t state, uint8_t statu PRINT("Connection %04x - Pairing fail\r\n", connHandle); } } - else if(state == GAPBOND_PAIRING_STATE_BONDED) + else if (state == GAPBOND_PAIRING_STATE_BONDED) { - if(status == SUCCESS) + if (status == SUCCESS) { PRINT("Connection %04x - Bonding success\r\n", connHandle); } } - else if(state == GAPBOND_PAIRING_STATE_BOND_SAVED) + else if (state == GAPBOND_PAIRING_STATE_BOND_SAVED) { - if(status == SUCCESS) + if (status == SUCCESS) { PRINT("Connection %04x - Bond save success\r\n", connHandle); } @@ -948,7 +876,7 @@ static void centralPasscodeCB(uint8_t *deviceAddr, uint16_t connectionHandle, passcode = tmos_rand(); passcode %= 1000000; // Display passcode to user - if(uiOutputs != 0) + if (uiOutputs != 0) { PRINT("Passcode:%06d\r\n", (int)passcode); } @@ -979,29 +907,7 @@ static void centralConnIistStartDiscovery_0(void) ATT_BT_UUID_SIZE, centralTaskId); } -/********************************************************************* - * @fn centralConnIistStartDiscovery_1 - * - * @brief Start connection 1 service discovery. - * - * @return none - */ -static void centralConnIistStartDiscovery_1(void) -{ - uint8_t uuid[ATT_BT_UUID_SIZE] = {LO_UINT16(SIMPLEPROFILE_SERV_UUID), - HI_UINT16(SIMPLEPROFILE_SERV_UUID)}; - // Initialize cached handles - centralConnList[CONNECT1_ITEM].svcStartHdl = centralConnList[CONNECT1_ITEM].svcEndHdl = centralConnList[CONNECT1_ITEM].charHdl = 0; - - centralConnList[CONNECT1_ITEM].discState = BLE_DISC_STATE_SVC; - - // Discovery simple BLE service - GATT_DiscPrimaryServiceByUUID(centralConnList[CONNECT1_ITEM].connHandle, - uuid, - ATT_BT_UUID_SIZE, - centralTaskId); -} /********************************************************************* * @fn centralGATTDiscoveryEvent * @@ -1012,23 +918,48 @@ static void centralConnIistStartDiscovery_1(void) static void centralGATTDiscoveryEvent(uint8_t connItem, gattMsgEvent_t *pMsg) { attReadByTypeReq_t req; - if(connItem == CONNECT0_ITEM) + // 连接0的枚举 + if (connItem == CONNECT0_ITEM) { - if(centralConnList[connItem].discState == BLE_DISC_STATE_SVC) + if (centralConnList[connItem].discState == BLE_DISC_STATE_SVC) { // Service found, store handles - if(pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP && - pMsg->msg.findByTypeValueRsp.numInfo > 0) + if (pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP && + pMsg->msg.findByTypeValueRsp.numInfo > 0) { centralConnList[connItem].svcStartHdl = ATT_ATTR_HANDLE(pMsg->msg.findByTypeValueRsp.pHandlesInfo, 0); - centralConnList[connItem].svcEndHdl = ATT_GRP_END_HANDLE(pMsg->msg.findByTypeValueRsp.pHandlesInfo, 0); + centralConnList[connItem].svcEndHdl = ATT_GRP_END_HANDLE(pMsg->msg.findByTypeValueRsp.pHandlesInfo, 0); // Display Profile Service handle range PRINT("Found Profile Service handle : %x ~ %x \r\n", centralConnList[connItem].svcStartHdl, centralConnList[connItem].svcEndHdl); +#if 1 + for (uint16_t i = 0; i < pMsg->msg.readByGrpTypeRsp.numGrps; i++) + { + // uuid + printf("uuid = %x", BUILD_UINT16( + pMsg->msg.readByGrpTypeRsp.pDataList[pMsg->msg.readByGrpTypeRsp.len * i + 4], + pMsg->msg.readByGrpTypeRsp.pDataList[pMsg->msg.readByGrpTypeRsp.len * i + 5])); + + // Primary Service UUID Length + printf("%02d bit x", pMsg->msg.readByGrpTypeRsp.len - 4); + + // printf("att len = %d\n", pMsg->msg.readByGrpTypeRsp.len); + printf("start handle:%04x", BUILD_UINT16( + pMsg->msg.readByGrpTypeRsp.pDataList[pMsg->msg.readByGrpTypeRsp.len * i], + pMsg->msg.readByGrpTypeRsp.pDataList[pMsg->msg.readByGrpTypeRsp.len * i + 1])); + // Attribute End Group Handle + printf("end handle:%04x\r\n", BUILD_UINT16( + pMsg->msg.readByGrpTypeRsp.pDataList[pMsg->msg.readByGrpTypeRsp.len * i + 2], + pMsg->msg.readByGrpTypeRsp.pDataList[pMsg->msg.readByGrpTypeRsp.len * i + 3])); + } +#endif } // If procedure complete - if((pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP && pMsg->hdr.status == bleProcedureComplete) || (pMsg->method == ATT_ERROR_RSP)) + if ((pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP && + pMsg->hdr.status == bleProcedureComplete) || + (pMsg->method == ATT_ERROR_RSP)) { +#if 0 if(centralConnList[connItem].svcStartHdl != 0) { // Discover characteristic @@ -1041,93 +972,16 @@ static void centralGATTDiscoveryEvent(uint8_t connItem, gattMsgEvent_t *pMsg) GATT_ReadUsingCharUUID(centralConnList[connItem].connHandle, &req, centralTaskId); } - } - } - else if(centralConnList[connItem].discState == BLE_DISC_STATE_CHAR) - { - // Characteristic found, store handle - if(pMsg->method == ATT_READ_BY_TYPE_RSP && pMsg->msg.readByTypeRsp.numPairs > 0) - { - centralConnList[connItem].charHdl = BUILD_UINT16(pMsg->msg.readByTypeRsp.pDataList[0], - pMsg->msg.readByTypeRsp.pDataList[1]); - centralConnList[connItem].procedureInProgress = FALSE; - - // Start do read or write - tmos_start_task(centralConnList[connItem].taskID, START_READ_OR_WRITE_EVT, DEFAULT_READ_OR_WRITE_DELAY);//开启一个读写测试任务 - - // Display Characteristic 1 handle - PRINT("Found Characteristic 1 handle : %x \r\n", centralConnList[0].charHdl); - } - - if((pMsg->method == ATT_READ_BY_TYPE_RSP && pMsg->hdr.status == bleProcedureComplete) || (pMsg->method == ATT_ERROR_RSP)) - { +#endif // Discover characteristic - centralConnList[connItem].discState = BLE_DISC_STATE_CCCD; - req.startHandle = centralConnList[connItem].svcStartHdl; - req.endHandle = centralConnList[connItem].svcEndHdl; - req.type.len = ATT_BT_UUID_SIZE; - req.type.uuid[0] = LO_UINT16(GATT_CLIENT_CHAR_CFG_UUID); - req.type.uuid[1] = HI_UINT16(GATT_CLIENT_CHAR_CFG_UUID); - - GATT_ReadUsingCharUUID(centralConnList[connItem].connHandle, &req, centralTaskId);//根据UUID寻找其句柄 - } - - } - else if(centralConnList[connItem].discState == BLE_DISC_STATE_CCCD) - { - // Characteristic found, store handle - if(pMsg->method == ATT_READ_BY_TYPE_RSP && pMsg->msg.readByTypeRsp.numPairs > 0) - { - centralConnList[connItem].cccHdl = BUILD_UINT16(pMsg->msg.readByTypeRsp.pDataList[0], - pMsg->msg.readByTypeRsp.pDataList[1]); - - centralConnList[connItem].procedureInProgress = FALSE; - - // Start do write CCCD - tmos_start_task(centralConnList[connItem].taskID, START_WRITE_CCCD_EVT, DEFAULT_WRITE_CCCD_DELAY);//开启一个使能从机notify的定时器任务 - - // Display Characteristic 1 handle - PRINT("Found client characteristic configuration handle : %x \r\n", centralConnList[connItem].cccHdl);//输出的句柄值 - } - centralConnList[connItem].discState = BLE_DISC_STATE_IDLE; - } - } - - else if(connItem == CONNECT1_ITEM) - { - if(centralConnList[connItem].discState == BLE_DISC_STATE_SVC) - { - // Service found, store handles - if(pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP && - pMsg->msg.findByTypeValueRsp.numInfo > 0) - { - centralConnList[connItem].svcStartHdl = ATT_ATTR_HANDLE(pMsg->msg.findByTypeValueRsp.pHandlesInfo, 0); - centralConnList[connItem].svcEndHdl = ATT_GRP_END_HANDLE(pMsg->msg.findByTypeValueRsp.pHandlesInfo, 0); - - // Display Profile Service handle range - PRINT("Found Profile Service handle : %x ~ %x \r\n", centralConnList[connItem].svcStartHdl, centralConnList[connItem].svcEndHdl); - } - // If procedure complete - if((pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP && - pMsg->hdr.status == bleProcedureComplete) || - (pMsg->method == ATT_ERROR_RSP)) - { - if(centralConnList[connItem].svcStartHdl != 0) - { - // Discover characteristic - centralConnList[connItem].discState = BLE_DISC_STATE_CHAR; - req.startHandle = centralConnList[connItem].svcStartHdl; - req.endHandle = centralConnList[connItem].svcEndHdl; - req.type.len = ATT_BT_UUID_SIZE; - req.type.uuid[0] = LO_UINT16(SIMPLEPROFILE_CHAR1_UUID); - req.type.uuid[1] = HI_UINT16(SIMPLEPROFILE_CHAR1_UUID); - - GATT_ReadUsingCharUUID(centralConnList[connItem].connHandle, &req, centralTaskId); - } + centralConnList[connItem].discState = BLE_DISC_STATE_CHAR; + uint8_t ret = GATT_DiscAllChars(centralConnList[connItem].connHandle, 0x01,0xFFFF, centralTaskId); + PRINT("GATT_DiscAllChars:%02x\r\n", ret); } } - else if(centralConnList[connItem].discState == BLE_DISC_STATE_CHAR) + else if (centralConnList[connItem].discState == BLE_DISC_STATE_CHAR) { +#if 0 // Characteristic found, store handle if(pMsg->method == ATT_READ_BY_TYPE_RSP && pMsg->msg.readByTypeRsp.numPairs > 0) @@ -1157,16 +1011,85 @@ static void centralGATTDiscoveryEvent(uint8_t connItem, gattMsgEvent_t *pMsg) GATT_ReadUsingCharUUID(centralConnList[connItem].connHandle, &req, centralTaskId); } - - } - else if(centralConnList[connItem].discState == BLE_DISC_STATE_CCCD) - { +#endif // Characteristic found, store handle if(pMsg->method == ATT_READ_BY_TYPE_RSP && pMsg->msg.readByTypeRsp.numPairs > 0) + { + for (unsigned char i = 0; i < pMsg->msg.readByTypeRsp.numPairs; i++) + { + // characteristic properties + uint8_t char_properties = pMsg->msg.readByTypeRsp.pDataList[pMsg->msg.readByTypeRsp.len * i + 2]; + uint16_t char_value_handle = BUILD_UINT16(pMsg->msg.readByTypeRsp.pDataList[pMsg->msg.readByTypeRsp.len * i + 3], + pMsg->msg.readByTypeRsp.pDataList[pMsg->msg.readByTypeRsp.len * i + 4]); + // characteristic uuid length + uint8_t char_uuid_length = pMsg->msg.readByGrpTypeRsp.len - 5; + // uuid + uint8_t *char_uuid = &(pMsg->msg.readByGrpTypeRsp.pDataList[pMsg->msg.readByGrpTypeRsp.len * i + 5]); + PRINT("______________________________\n"); + PRINT("char_uuid :"); + for (uint8_t i = 0; i < char_uuid_length; i++) + { + printf("%02x ", char_uuid[i]); + } + printf("\n"); + // PRINT("char_properties :%02x,%s\r\n",char_properties,(char_properties&(GATT_PROP_WRITE|GATT_PROP_WRITE_NO_RSP))?"wite handle":""); + PRINT("char_value_handle:%04x\r\n", char_value_handle); + PRINT("char_uuid_length :%02d bit\r\n", char_uuid_length); + uint16_t char1uuid = SIMPLEPROFILE_CHAR1_UUID; + uint16_t char2uuid = SIMPLEPROFILE_CHAR2_UUID; + uint16_t char3uuid = SIMPLEPROFILE_CHAR3_UUID; + // req.type.uuid[0] = LO_UINT16(GATT_CLIENT_CHAR_CFG_UUID); + // req.type.uuid[1] = HI_UINT16(GATT_CLIENT_CHAR_CFG_UUID); + if (tmos_memcmp(char_uuid, &char3uuid, 2)) + { + if (char_properties & (GATT_PROP_WRITE | GATT_PROP_WRITE_NO_RSP)) + { + centralConnList[connItem].charHd3 = char_value_handle; + PRINT("char3 Write handle:%04x\r\n", char_value_handle); + centralConnList[connItem].procedureInProgress = FALSE; + tmos_start_task(centralConnList[CONNECT0_ITEM].taskID, CH3_WRITE_EVT, 1600); + } + } + else if (tmos_memcmp(char_uuid, &char2uuid, 2)) + { + if (char_properties & (GATT_PROP_READ)) + { + centralConnList[connItem].charHd2 = char_value_handle; + centralConnList[connItem].procedureInProgress = FALSE; + PRINT("char2 Write handle:%04x\r\n", char_value_handle); + // tmos_start_task(centralConnList[CONNECT0_ITEM].taskID, CH2_READ_EVT, 1600); + } + } + // if (char_properties & (GATT_PROP_WRITE | GATT_PROP_WRITE_NO_RSP)) + // { + // centralConnList[connItem].charHdl = char_value_handle; + // PRINT("Write handle:%04x\r\n", char_value_handle); + // tmos_start_task(centralTaskId, START_READ_OR_WRITE_EVT, 1600); + // } + if (char_properties & GATT_PROP_NOTIFY) + { + centralConnList[connItem].cccHdl = char_value_handle + 1; // 通过GATT_DiscAllChars或者handle,noti/indi的handle值需要+1 + PRINT("Notify handle:%04x\r\n", char_value_handle); + tmos_start_task(centralConnList[CONNECT0_ITEM].taskID, START_WRITE_CCCD_EVT, 1600); + } + if (char_properties & GATT_PROP_INDICATE) + { + centralConnList[connItem].cccHdl = char_value_handle + 1; // 通过GATT_DiscAllChars或者handle,noti/indi的handle值需要+1 + PRINT("Indicate handle:%04x\r\n", char_value_handle); + tmos_start_task(centralConnList[CONNECT0_ITEM].taskID, START_WRITE_CCCD_EVT, 800); + } + } + } + } + else if (centralConnList[connItem].discState == BLE_DISC_STATE_CCCD) + { + // Characteristic found, store handle + if (pMsg->method == ATT_READ_BY_TYPE_RSP && + pMsg->msg.readByTypeRsp.numPairs > 0) { centralConnList[connItem].cccHdl = BUILD_UINT16(pMsg->msg.readByTypeRsp.pDataList[0], - pMsg->msg.readByTypeRsp.pDataList[1]); + pMsg->msg.readByTypeRsp.pDataList[1]); centralConnList[connItem].procedureInProgress = FALSE; @@ -1179,10 +1102,14 @@ static void centralGATTDiscoveryEvent(uint8_t connItem, gattMsgEvent_t *pMsg) centralConnList[connItem].discState = BLE_DISC_STATE_IDLE; } } - -// else if(connItem == CONNECT2_ITEM) -// { -// } + // 连接1的枚举 + else if (connItem == CONNECT1_ITEM) + { + } + // 连接2的枚举 + // else if(connItem == CONNECT2_ITEM) + // { + // } } /********************************************************************* @@ -1197,12 +1124,12 @@ static void centralAddDeviceInfo(uint8_t *pAddr, uint8_t addrType) uint8_t i; // If result count not at max - if(centralScanRes < DEFAULT_MAX_SCAN_RES) + if (centralScanRes < DEFAULT_MAX_SCAN_RES) { // Check if device is already in scan results - for(i = 0; i < centralScanRes; i++) + for (i = 0; i < centralScanRes; i++) { - if(tmos_memcmp(pAddr, centralDevList[i].addr, B_ADDR_LEN)) + if (tmos_memcmp(pAddr, centralDevList[i].addr, B_ADDR_LEN)) { return; } @@ -1233,12 +1160,12 @@ static void centralAddDeviceInfo(uint8_t *pAddr, uint8_t addrType) static uint8_t centralAddrCmp(peerAddrDefItem_t *PeerAddrDef, uint8_t *addr) { uint8_t i; - for(i = 0; i < CENTRAL_MAX_CONNECTION; i++) + for (i = 0; i < CENTRAL_MAX_CONNECTION; i++) { - if(tmos_memcmp(PeerAddrDef[i].peerAddr, addr, B_ADDR_LEN)) + if (tmos_memcmp(PeerAddrDef[i].peerAddr, addr, B_ADDR_LEN)) break; } - if(i == CENTRAL_MAX_CONNECTION) + if (i == CENTRAL_MAX_CONNECTION) { return FALSE; } diff --git a/APP/multiCentral_main.c b/APP/multiCentral_main.c index 2eaf639..63ab90a 100644 --- a/APP/multiCentral_main.c +++ b/APP/multiCentral_main.c @@ -2,7 +2,7 @@ * @Author: mbw * @Date: 2024-12-03 11:13:13 * @LastEditors: mbw && 1600520629@qq.com - * @LastEditTime: 2024-12-07 16:17:02 + * @LastEditTime: 2024-12-09 13:34:51 * @FilePath: \ble_-tyq_-bjq_-ch584-m\APP\multiCentral_main.c * @Description: * @@ -26,6 +26,8 @@ #include "multiCentral.h" #include "bsp_uart.h" #include "log.h" +#include "bsp_flash.h" + #undef LOG_ENABLE @@ -97,6 +99,7 @@ int main(void) #endif BSP_UART1_Init();//BT UART logDebug("test log debug\n"); + BSP_FLASH_Init(); Main_Circulation(); } diff --git a/HAL/include/CONFIG.h b/HAL/include/CONFIG.h index 941bc5e..3e1363a 100644 --- a/HAL/include/CONFIG.h +++ b/HAL/include/CONFIG.h @@ -80,7 +80,7 @@ #define BLE_MEMHEAP_SIZE (1024*12) #endif #ifndef BLE_BUFF_MAX_LEN -#define BLE_BUFF_MAX_LEN 27 +#define BLE_BUFF_MAX_LEN 251 #endif #ifndef BLE_BUFF_NUM #define BLE_BUFF_NUM 5 @@ -89,7 +89,7 @@ #define BLE_TX_NUM_EVENT 1 #endif #ifndef BLE_TX_POWER -#define BLE_TX_POWER LL_TX_POWEER_0_DBM +#define BLE_TX_POWER LL_TX_POWEER_4_DBM #endif #ifndef PERIPHERAL_MAX_CONNECTION #define PERIPHERAL_MAX_CONNECTION 1 diff --git a/LIB/CH58xBLE_LIB.h b/LIB/CH58xBLE_LIB.h index 4760ba3..36a7685 100644 --- a/LIB/CH58xBLE_LIB.h +++ b/LIB/CH58xBLE_LIB.h @@ -123,7 +123,7 @@ typedef struct tag_ble_clock_config // RF-8K config uint32_t Clock1Frequency; // RF-8K timing clock frequency(Hz) - pfnGetSysClock getClock1Value; // RF 8k ͨŹʱ Ҫߣ + pfnGetSysClock getClock1Value; // RF 8k ͨ�Ź���ʱ�� ������Ҫ����ߣ� pfnSetSysClockIRQ SetClock1PendingIRQ; pfnSetSysClockTign SetTign; }bleClockConfig_t; @@ -195,7 +195,7 @@ extern const uint8_t VER_LIB[]; // LIB version #define ABS(n) (((n) < 0) ? -(n) : (n)) #endif -/* TxPower define(Accuracy:2dBm) */ +/* TxPower define(Accuracy:��2dBm) */ #define LL_TX_POWEER_MINUS_20_DBM 0x01 #define LL_TX_POWEER_MINUS_15_DBM 0x03 #define LL_TX_POWEER_MINUS_10_DBM 0x05 @@ -812,7 +812,7 @@ extern const uint8_t VER_LIB[]; // LIB version #define TGAP_AUTH_TASK_ID 24 //!< Task ID override for Task Authentication control (for stack internal use only) // v5.x -#define TGAP_ADV_TX_POWER 25 //!< Indicates the maximum power level Range: -127 N +126 Units: dBm.Default 127(Host has no preference). +#define TGAP_ADV_TX_POWER 25 //!< Indicates the maximum power level Range: -127 �� N �� +126 Units: dBm.Default 127(Host has no preference). #define TGAP_ADV_PRIMARY_PHY 26 //!< resv. #define TGAP_ADV_SECONDARY_PHY 27 //!< LE 1M/LE 2M. Default GAP_PHY_VAL_LE_1M. #define TGAP_ADV_SECONDARY_MAX_SKIP 28 //!< Maximum advertising events the Controller can skip before sending the AUX_ADV_IND packets on the secondary advertising channel. Default 0. @@ -1153,7 +1153,7 @@ extern const uint8_t VER_LIB[]; // LIB version #define SMP_PAIRING_FAILED_UNSPECIFIED 0x08 //!< Pairing failed due to an unspecified reason #define SMP_PAIRING_FAILED_REPEATED_ATTEMPTS 0x09 //!< Pairing or authentication procedure is disallowed because too little time has elapsed since the last pairing request or security request. #define SMP_PAIRING_FAILED_INVALID_PARAMERERS 0x0A //!< The Invalid Parameters error code indicates that the command length is invalid or that a parameter is outside of the specified range. -#define SMP_PAIRING_FAILED_DHKEY_CHECK_FAILED 0x0B //!< Indicates to the remote device that the DHKey Check value received doesnt match the one calculated by the local device. +#define SMP_PAIRING_FAILED_DHKEY_CHECK_FAILED 0x0B //!< Indicates to the remote device that the DHKey Check value received doesn��t match the one calculated by the local device. #define SMP_PAIRING_FAILED_NUMERIC_COMPARISON 0x0C //!< Indicates that the confirm values in the numeric comparison protocol do not match. #define SMP_PAIRING_FAILED_KEY_REJECTED 0x0F //!< Indicates that the device chose not to accept a distributed key. @@ -2067,13 +2067,13 @@ typedef struct uint8_t enable; //!< bit0 Enable periodic advertising //!< bit1 Include the ADI field in AUX_SYNC_IND PDUs uint8_t advHandle; //!< Used to identify a periodic advertising train - uint16_t advIntervalMin; //!< Minimum advertising interval for periodic advertising.Time = N 1.25ms.Time Range: 7.5ms to 81.91875s - uint16_t advIntervalMax; //!< Maximum advertising interval for periodic advertising.Time = N 1.25ms.Time Range: 7.5ms to 81.91875s + uint16_t advIntervalMin; //!< Minimum advertising interval for periodic advertising.Time = N �� 1.25ms.Time Range: 7.5ms to 81.91875s + uint16_t advIntervalMax; //!< Maximum advertising interval for periodic advertising.Time = N �� 1.25ms.Time Range: 7.5ms to 81.91875s uint16_t advProperties; //!< bit6 Include TxPower in the advertising PDU uint8_t numSubevents; //!< Number of subevents. - uint8_t subInterval; //!< Interval between subevents.Time = N 1.25ms.Time Range: 7.5 ms to 318.75 ms - uint8_t rspSlotDelay; //!< Time between the advertising packet in a subevent and the first response slot.Time = N 1.25 ms.Time Range: 1.25ms to 317.5ms - uint8_t rspSlotSpacing; //!< Time between response slots.Time = N 0.125ms.Time Range: 0.25ms to 31.875ms + uint8_t subInterval; //!< Interval between subevents.Time = N �� 1.25ms.Time Range: 7.5 ms to 318.75 ms + uint8_t rspSlotDelay; //!< Time between the advertising packet in a subevent and the first response slot.Time = N �� 1.25 ms.Time Range: 1.25ms to 317.5ms + uint8_t rspSlotSpacing; //!< Time between response slots.Time = N �� 0.125ms.Time Range: 0.25ms to 31.875ms uint8_t numRspSlots; //!< Number of subevent response slots.Range: 0x01 to 0xFF }gapPawrSetParam_t; @@ -3068,7 +3068,7 @@ extern void LLE_IRQLibHandler( void ); * @return access address * the Access Address meets the following requirements: * It shall have no more than six consecutive zeros or ones. - * It shall not be t he advertising channel packets Access Address. + * It shall not be t he advertising channel packets�� Access Address. * It shall not be a sequence that differ s from the advertising channel packets' Access Address by only one bit. * It shall not have all four octets equal. * It shall have no more than 24 transitions. diff --git a/StdPeriphDriver/CH58x_sys.c b/StdPeriphDriver/CH58x_sys.c index cce7a1c..cddf51f 100644 --- a/StdPeriphDriver/CH58x_sys.c +++ b/StdPeriphDriver/CH58x_sys.c @@ -456,6 +456,17 @@ __HIGH_CODE __attribute__((weak)) void HardFault_Handler(void) { + uint32_t v_mepc,v_mcause,v_mtval; + + v_mepc=__get_MEPC(); + v_mcause=__get_MCAUSE(); + v_mtval=__get_MTVAL(); + printf("hardfault\n"); + printf("mepc:%08x\n",v_mepc); + printf("mcause:%08x\n",v_mcause); + printf("mtval:%08x\n",v_mtval); + + FLASH_ROM_SW_RESET(); sys_safe_access_enable(); R16_INT32K_TUNE = 0xFFFF; @@ -463,6 +474,9 @@ void HardFault_Handler(void) sys_safe_access_enable(); R8_RST_WDOG_CTRL |= RB_SOFTWARE_RESET; sys_safe_access_disable(); + + + while(1); } diff --git a/bsp/inc/bsp_master.h b/bsp/inc/bsp_master.h new file mode 100644 index 0000000..ec7f3f9 --- /dev/null +++ b/bsp/inc/bsp_master.h @@ -0,0 +1,84 @@ +//#ifndef __BSP_MASTER_H__ +//#define __BSP_MASTER_H__ +// +// +//#include "CH58x_common.h" +//#include "CH58xBLE_LIB.h" +// +// +// +//typedef enum +//{ +// BLE_STATE_IDLE, +// BLE_STATE_ADV, +// BLE_STATE_CONNECT, +// BLE_STATE_DISCONNECT, +//} BleState; +// +//typedef enum +//{ +// kValveClose, +// kValveOpen, +//}BtValveState; +// +//typedef struct +//{ +// uint8_t buf[]; +//}BleValveData; +// +//struct __attribute__((packed)) valve_data +//{ +// uint8_t header; +// uint8_t valve_type; // 阀门类型 +// uint8_t valve_bat; // 1B 电池电压 30=3V,18=1.8V +// uint8_t valve_status; // 1B 阀门工作状态 超欠压、过流 +// uint8_t valve_connct_status; // 1B 阀门连接状态 (电磁阀BLE控制盒) 0=未连接 1=已连接 +// uint8_t valve_switch_status; // 1B 阀门开关状态 0=未知 1=关闭 2=关闭过,未按按键恢复 3=关闭过,按下了恢复键 4=打开 +// int8_t valve_temp; // 1B 阀门温度 有符号整数 25 ℃ +// uint32_t valve_in_pressure; // 4B 阀门入口压力 Pa +// uint32_t valve_out_pressure; // 4B 阀门出口压力 Pa +// uint32_t valve_atm_pressure; // 4B 阀门大气压力 Pa +// uint8_t check; +// uint8_t tail; +//}; +// +// +// +//void BSP_Master_Send(centralConnItem_t *centralConnList, uint8_t id, uint8_t *Data, uint8_t Len); +//int BSP_Master_Receive_Data(uint8_t *data, uint16_t len); +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +//#endif // ! __BSP_MASTER_H__ diff --git a/bsp/inc/bsp_uart.h b/bsp/inc/bsp_uart.h index 0e6b849..0bf4938 100644 --- a/bsp/inc/bsp_uart.h +++ b/bsp/inc/bsp_uart.h @@ -2,7 +2,7 @@ * @Author: mbw * @Date: 2024-12-06 16:52:29 * @LastEditors: mbw && 1600520629@qq.com - * @LastEditTime: 2024-12-07 15:10:15 + * @LastEditTime: 2024-12-09 11:15:13 * @FilePath: \ble_-tyq_-bjq_-ch584-m\bsp\inc\bsp_uart.h * @Description: * @ @@ -13,44 +13,30 @@ #include "CH58x_common.h" -#define MAX_VALVE_NUM 8 +#define BT_START_EVT (0X01 << 0) +#define BT_REC_EVT (0X01 << 1) +#define BT_INFO_UPDATA_EVT (0X01 << 2) +#define BT_SEND_EVT (0X01 << 3)// -#define UART3_RX_PIN GPIO_Pin_20 //PB20 日志打印 +#define UART3_RX_PIN GPIO_Pin_20 //PB20 #define UART3_TX_PIN GPIO_Pin_21 // PB21 #define BT_UART_TX_PIN GPIO_Pin_9 //PA9 #define BT_UART_RX_PIN GPIO_Pin_8 //PA8 -typedef struct valve_data valve_data_t; -/* -无线调压阀编号 -无线调压阀 MAC 地址 -无线调压阀连接状态 -无线调压阀开关状态 -无线调压阀温度 -无线调压阀进口压力 -无线调压阀出口压力 -无线调压阀大气压 -*/ -struct __attribute__((packed)) valve_data +typedef struct __attribute__((packed)) { - uint8_t valve_id; - uint8_t valve_mac[6]; - uint8_t valve_connct_status; - uint8_t valve_switch_status; - uint8_t valve_temp; - uint32_t valve_in_pressure; - uint32_t valve_out_pressure; - uint32_t valve_atm_pressure; -}; + uint8_t cmd; + uint8_t buf[]; +} BtData_t; -typedef struct valve_data_list +typedef struct __attribute__((packed)) { - uint8_t valve_num; - valve_data_t valve_data[MAX_VALVE_NUM]; -} valve_data_list_t ; + uint8_t len; + uint8_t buf[256]; +} BTFrameData; void BSP_UART1_Init(void); @@ -61,7 +47,8 @@ unsigned int BSP_Uart1_Send_Data(const void *buf, unsigned int len); void BSP_UART3_Init(void); unsigned int BSP_Uart3_Receive_Data(void *buf, unsigned int len); unsigned int BSP_Uart3_Send_Data(const void *buf, unsigned int len); -void BSP_Shell_Loop(void); +uint8_t XOR_CheckSum(const uint8_t *data, size_t len); +extern uint8_t BtRxTaskId; #endif // !__BSP_UART_H__ diff --git a/bsp/inc/bsp_valve.h b/bsp/inc/bsp_valve.h new file mode 100644 index 0000000..2a90d01 --- /dev/null +++ b/bsp/inc/bsp_valve.h @@ -0,0 +1,85 @@ +#ifndef __BSP_VALVE_H__ +#define __BSP_VALVE_H__ + +#include "CH58x_common.h" + +#define MAX_VALVE_NUM 8 + + +typedef enum { + kValveCmdCtr = 0X01, + kValveCmdReg, + kValveCmdRem, + kValveCmdRep, + kValveCmdMax +} ValveCmdType; + +typedef enum +{ + WirelessValveClose, + WirelessValveOpen, +} WireLessState; + + +typedef struct valve_data valve_data_t; + +/* +无线调压阀编号 +无线调压阀 MAC 地址 +无线调压阀连接状态 +无线调压阀开关状态 +无线调压阀温度 +无线调压阀进口压力 +无线调压阀出口压力 +无线调压阀大气压 +*/ +struct __attribute__((packed)) valve_data +{ + uint8_t valve_id; + uint8_t valve_mac[6]; + uint8_t valve_connct_status; + uint8_t valve_switch_status; + uint8_t valve_temp; + uint32_t valve_in_pressure; + uint32_t valve_out_pressure; + uint32_t valve_atm_pressure; +}; + +typedef struct valve_data_list +{ + uint8_t valve_num; + valve_data_t valve_data[MAX_VALVE_NUM]; +} valve_data_list_t ; + + + +extern valve_data_list_t valve_list; + +int BSP_Bt_Valve_Ctr(uint8_t *data, uint8_t len); +int BSP_Bt_Register_Valve(uint8_t *data, uint8_t len); +int BSP_Bt_Remove_Valve(uint8_t *data, uint8_t len); +int BSP_Bt_Replace_Valve(uint8_t *data, uint8_t len); +void BSP_Bt_Valve_Updata(void); + + + + + + + + + + + + + + + + + + + + + + +#endif // ! __BSP_VALVE_H__ diff --git a/bsp/src/bsp_flash.c b/bsp/src/bsp_flash.c index a515f5a..133a22b 100644 --- a/bsp/src/bsp_flash.c +++ b/bsp/src/bsp_flash.c @@ -2,15 +2,17 @@ * @Author: mbw * @Date: 2024-12-06 14:49:21 * @LastEditors: mbw && 1600520629@qq.com - * @LastEditTime: 2024-12-07 12:58:09 + * @LastEditTime: 2024-12-10 15:28:37 * @FilePath: \ble_-tyq_-bjq_-ch584-m\bsp\src\bsp_flash.c * @Description: 主要用于对一些MAC地址等关键信息进行保存和读取操作 - * - * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. + * + * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. */ #include "bsp_flash.h" #include "CONFIG.h" #include "string.h" +#include "bsp_valve.h" + void Flash_ErasePage_ReadConfigInfo(uint8_t *page_buf) { @@ -29,10 +31,10 @@ int Flash_Write_ConfigInfo(uint8_t *page_buf) int Flash_Set_Mac_Addr(uint8_t *mac_addr, uint8_t number) { uint8_t page_buf[DATA_FLASH_PAGE_SIZE] = {0}; - uint8_t in_page_offset = ((FLASH_MAC_1_ADDR + number * FLASH_MAC_INFO_LEN) - FLASH_MAC_INFO_START_ADDR); - if (mac_addr == NULL) + uint8_t in_page_offset = ((FLASH_MAC_1_ADDR + number * FLASH_MAC_INFO_LEN) - FLASH_MAC_INFO_START_ADDR); + if ((mac_addr == NULL)||( number > MAX_VALVE_NUM)) { - return -1; + return -1; } Flash_ErasePage_ReadConfigInfo(page_buf); for (int i = 0; i < FLASH_MAC_INFO_LEN; i++) @@ -46,9 +48,9 @@ int Flash_Set_Mac_Addr(uint8_t *mac_addr, uint8_t number) int Flash_Get_Mac_Addr(uint8_t *mac_addr, uint8_t number) { __attribute__((aligned(4))) - uint8_t data[FLASH_MAC_INFO_LEN + 2]; //读写buf需要4字节对齐 - char mac[16] = {20}; - tmos_memcpy(data, (uint8_t *)(FLASH_MAC_1_ADDR + number * FLASH_MAC_INFO_LEN), FLASH_MAC_INFO_LEN); + uint8_t data[FLASH_MAC_INFO_LEN + 2]; // 读写buf需要4字节对齐 + // char mac[16] = {0}; + EEPROM_READ((FLASH_MAC_INFO_START_ADDR + number * FLASH_MAC_INFO_LEN), data, FLASH_MAC_INFO_LEN); if (data == NULL) { // PRINTF("Flash_Get_Mac_Addr failed"); @@ -66,7 +68,7 @@ int Flash_Get_Mac_Addr(uint8_t *mac_addr, uint8_t number) int Flash_Set_Valve_Num(uint8_t valve_num) { uint8_t page_buf[DATA_FLASH_PAGE_SIZE] = {0}; - uint8_t in_page_offset = (FLASH_INFO_ADDR - FLASH_MAC_INFO_START_ADDR); + uint8_t in_page_offset = (FLASH_INFO_ADDR - FLASH_MAC_INFO_START_ADDR); Flash_ErasePage_ReadConfigInfo(page_buf); page_buf[in_page_offset] = valve_num; return Flash_Write_ConfigInfo(page_buf); @@ -81,15 +83,14 @@ uint8_t Flash_Get_Valve_Num(void) } void BSP_FLASH_Init(void) -{ +{ uint32_t flash_write_flag = 0; - EEPROM_READ(FLASH_INFO_WRITE_FLAG_ADDR, &flash_write_flag, FLASH_INFO_WRITE_FLAG_LEN); - if (flash_write_flag != FLASH_INFO_WRITE_FLAG_VAL)//用以防止刷掉写入的数据 + if (flash_write_flag != FLASH_INFO_WRITE_FLAG_VAL) // 用以防止刷掉写入的数据 { flash_write_flag = FLASH_INFO_WRITE_FLAG_VAL; - //擦除数据 - EEPROM_ERASE(FLASH_INFO_ADDR, DATA_FLASH_PAGE_SIZE);//擦除待写区 - EEPROM_WRITE(FLASH_INFO_ADDR, &flash_write_flag, FLASH_INFO_WRITE_FLAG_LEN); + // 擦除数据 + EEPROM_ERASE(FLASH_INFO_ADDR, DATA_FLASH_PAGE_SIZE); // 擦除待写区 + EEPROM_WRITE(FLASH_INFO_WRITE_FLAG_ADDR, &flash_write_flag, FLASH_INFO_WRITE_FLAG_LEN); } } diff --git a/bsp/src/bsp_master.c b/bsp/src/bsp_master.c new file mode 100644 index 0000000..5ad0b5b --- /dev/null +++ b/bsp/src/bsp_master.c @@ -0,0 +1,119 @@ +// #include "bsp_master.h" +// #include "bsp_uart.h" +// #include "log.h" +// #include "multiCentral.h" +// #include "bsp_valve.h" + +// #undef LOG_ENABLE +// #define LOG_ENABLE 1 + +// void BSP_Bt_Init(void) +// { +// } + +// void BSP_Master_Send(centralConnItem_t *centralConnList, uint8_t id, uint8_t *Data, uint8_t Len) +// { +// attWriteReq_t req; +// uint8_t res; + +// if (centralConnList[id].state == BLE_STATE_CONNECTED) // 检查连接状态是否为连接状态 +// { +// if (centralConnList[id].procedureInProgress == TRUE) +// { +// logWarning("\n Write buy"); +// } +// else +// { +// req.cmd = FALSE; +// req.sig = FALSE; +// req.handle = centralConnList[id].connHandle; +// req.len = Len; +// req.pValue = GATT_bm_alloc(centralConnList[id].connHandle, ATT_WRITE_REQ, req.len, NULL, 0); +// if (req.pValue != NULL) +// { +// tmos_memcpy(req.pValue, Data, Len); +// res = GATT_WriteCharValue(centralConnList[id].connHandle, &req, centralTaskId); +// if (res == SUCCESS) +// { +// centralConnList[id].procedureInProgress = TRUE; // 翻转读写状态 +// logDebug("\n Master Write ok"); +// } +// else +// { +// logDebug("\n Master Write faild= %x", res); +// GATT_bm_free((gattMsg_t *)&req, ATT_WRITE_REQ); +// } +// } +// else +// { +// logDebug("\n alloc Faild"); +// } +// } +// } +// else +// { +// } +// } + +// int BSP_Master_Receive_Data(uint8_t *data, uint16_t len) +// { +// int ret = 0; +// uint16_t index = 0; +// uint8_t data_buf[64] = {0}; +// // 解析接收到的数据帧,先寻找AA开头,然后再找AA下一个字节,其代表了数据长度,然后找到代表长度的值的长度的下一位,其为校验码,校验码后为结束码0x55, +// // 如果数据正确,则提取数据,不正确,则不处理 +// if (len < 4) +// { // 至少需要 4 个字节:起始码、长度、校验码、结束码 +// logError("BT 数据帧长度不足"); +// logHexDumpAll(data, len); +// return 1; +// } + +// while (index < len && data[index] != 0xAA) // 寻找起始码 0xAA +// { +// index++; +// } +// if (index >= len - 3) // 不够空间容纳长度、校验码和结束码 +// { +// logError("BT 数据帧起始码错误"); +// logHexDumpAll(data, len); +// return 2; +// } + +// uint16_t datalength = data[index + 1]; // 读取数据长度 +// if (index + 2 + datalength + 1 >= len) // 检查数据长度是否合理 数据长度 + 校验码 + 结束码 +// { + +// logError("BT 数据帧长度错误"); +// logHexDumpAll(data, len); +// return 3; // +// } + +// uint8_t rx_sum = data[index + 2 + datalength]; // 读取校验码 +// uint8_t calculated_sum = XOR_CheckSum(&data[0], datalength + 2); // 计算校验码 +// if (rx_sum != calculated_sum) +// { + +// logError("BT 数据帧校验码错误 rx_sum = %02X, calculated_sum = %02X", rx_sum, calculated_sum); +// logHexDumpAll(data, len); +// return 4; +// } + +// if (data[index + 2 + datalength + 1] != 0x55) // 检查结束码 +// { +// logError("BT 数据帧结束码错误"); +// logHexDumpAll(data, len); +// return 5; +// } +// // 到这一步说明数据没问题,将接收到的数据通过中心任务发送出去 +// uint8_t *p_data; +// p_data = tmos_msg_allocate(length); +// if (p_data) +// { +// tmos_memcpy(p_data, data, length); +// tmos_msg_send(task_id, p_data); +// } + +// tmos_msg_send(task_id, data); +// return ret; +// } \ No newline at end of file diff --git a/bsp/src/bsp_uart.c b/bsp/src/bsp_uart.c index 4911828..e92c972 100644 --- a/bsp/src/bsp_uart.c +++ b/bsp/src/bsp_uart.c @@ -1,22 +1,32 @@ +/* + * @Author: mbw + * @Date: 2024-12-06 16:52:30 + * @LastEditors: mbw && 1600520629@qq.com + * @LastEditTime: 2024-12-11 16:35:52 + * @FilePath: \ble_-tyq_-bjq_-ch584-m\bsp\src\bsp_uart.c + * @Description: + * + * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. + */ #include "bsp_uart.h" #include "lwrb.h" #include "CH58x_uart.h" #include "shell_port.h" #include "CH58xBLE_LIB.h" - +#include "bsp_flash.h" +#include "bsp_valve.h" +#include "shell.h" #undef LOG_ENABLE #define LOG_ENABLE 1 #include "log.h" +#define UART1_RX_BUFFER_LENGTH 512U +#define UART1_TX_BUFFER_LENGTH 512U -#define UART1_RX_BUFFER_LENGTH 512U -#define UART1_TX_BUFFER_LENGTH 512U - -#define UART3_RX_BUFFER_LENGTH 1024U -#define UART3_TX_BUFFER_LENGTH 1024U - +#define UART3_RX_BUFFER_LENGTH 1024U +#define UART3_TX_BUFFER_LENGTH 1024U lwrb_t uart1_rx_t; lwrb_t uart1_tx_t; @@ -28,20 +38,34 @@ lwrb_t uart3_tx_t; uint8_t uart3_tx_buf[UART3_TX_BUFFER_LENGTH] = {0}; uint8_t uart3_rx_buf[UART3_RX_BUFFER_LENGTH] = {0}; +uint8_t BtRxTaskId; -static uint8_t BtRxTaskId; +BTFrameData bt_frame = {0}; -#define BT_START_EVT (0X01 << 0) -#define BT_REC_EVT (0X01 << 1) +/** + * @description: 从帧起始符开始到校验码之前所有字节的和的模256,即各字节不计超过255的溢出值的二进制算术和。 + * @param {uint8_t} *data + * @param {uint16_t} len + * @return {*} + */ +uint8_t XOR_CheckSum(const uint8_t *data, size_t len) +{ + uint8_t sum = 0; + for (size_t i = 0; i < len; i++) + { + sum += data[i]; + } + return sum; +} -//串口接收 +// 串口接收 unsigned int BSP_Uart1_Receive_Data(void *buf, unsigned int len) { return lwrb_read(&uart1_rx_t, buf, len); } -//串口发送数据 +// 串口发送数据 unsigned int BSP_Uart1_Send_Data(const void *buf, unsigned int len) { unsigned int ret; @@ -51,13 +75,18 @@ unsigned int BSP_Uart1_Send_Data(const void *buf, unsigned int len) return ret; } -//串口接收 +unsigned int BSP_Uart1_Send_String(const void *buf) +{ + return BSP_Uart1_Send_Data(buf, strlen((const char *)buf)); +} + +// 串口接收 unsigned int BSP_Uart3_Receive_Data(void *buf, unsigned int len) { return lwrb_write(&uart3_rx_t, buf, len); } -//串口发送数据 +// 串口发送数据 unsigned int BSP_Uart3_Send_Data(const void *buf, unsigned int len) { unsigned int ret; @@ -71,7 +100,6 @@ void UART1_FifoInit(void) { lwrb_init(&uart1_tx_t, uart1_tx_buf, sizeof(uart1_tx_buf)); lwrb_init(&uart1_rx_t, uart1_rx_buf, sizeof(uart1_rx_buf)); - } void UART3_FifoInit(void) @@ -80,32 +108,178 @@ void UART3_FifoInit(void) lwrb_init(&uart3_rx_t, uart3_rx_buf, sizeof(uart3_rx_buf)); } -__HIGH_CODE -__attribute__((noinline)) -uint16_t BT_Rx_ProcessEvent(uint8_t task_id, uint16_t events) +/*bt接收数据处理*/ +int BSP_Bt_Process(uint8_t *data, uint16_t len) { - if(events & BT_START_EVT) + int ret = 0; + uint16_t index = 0; + uint8_t data_buf[64] = {0}; + // 解析接收到的数据帧,先寻找AA开头,然后再找AA下一个字节,其代表了数据长度,然后找到代表长度的值的长度的下一位,其为校验码,校验码后为结束码0x55, + // 如果数据正确,则提取数据,不正确,则不处理 + if (len < 4) + { // 至少需要 4 个字节:起始码、长度、校验码、结束码 + logError("BT 数据帧长度不足"); + logHexDumpAll(data, len); + return 1; + } + + while (index < len && data[index] != 0xAA) // 寻找起始码 0xAA + { + index++; + } + if (index >= len - 3) // 不够空间容纳长度、校验码和结束码 + { + logError("BT 数据帧起始码错误"); + logHexDumpAll(data, len); + return 2; + } + + uint16_t datalength = data[index + 1]; // 读取数据长度 + if (index + 2 + datalength + 1 >= len) // 检查数据长度是否合理 数据长度 + 校验码 + 结束码 + { + logError("BT 数据帧长度错误"); + logHexDumpAll(data, len); + return 3; // + } + + uint8_t rx_sum = data[index + 2 + datalength]; // 读取校验码 + uint8_t calculated_sum = XOR_CheckSum(&data[0], datalength + 2); // 计算校验码 + if (rx_sum != calculated_sum) + { + + logError("BT 数据帧校验码错误 rx_sum = %02X, calculated_sum = %02X", rx_sum, calculated_sum); + logHexDumpAll(data, len); + return 4; + } + + if (data[index + 2 + datalength + 1] != 0x55) // 检查结束码 + { + logError("BT 数据帧结束码错误"); + logHexDumpAll(data, len); + return 5; + } + // 当程序走到这里时,就说明接收到了正确的数据帧,开始解析命令 + tmos_memcpy(data_buf, &data[index + 3], datalength); + switch (data[index + 2]) + { + case kValveCmdCtr: + ret = BSP_Bt_Valve_Ctr(&data_buf[0], datalength); + logDebug("recv cmd: 0x01, 执行的动作是关闭阀门"); + break; + case kValveCmdReg: + ret = BSP_Bt_Register_Valve(&data_buf[0], datalength); + logDebug("recv cmd: 0x02, 执行的动作是注册阀门"); + break; + case kValveCmdRem: + ret = BSP_Bt_Remove_Valve(&data_buf[0], datalength); + logDebug("recv cmd: 0x03, 执行的动作是移除阀门"); + break; + case kValveCmdRep: + ret = BSP_Bt_Replace_Valve(&data_buf[0], datalength); + logDebug("recv cmd: 0x04, 执行的动作是更换阀门"); + break; + default: + logError("unknow cmd: %02X", data[index + 2]); + break; + } + + return ret; +} + +/*发送数据帧处理*/ +uint8_t BT_GenerateRawFrame(BTFrameData *pRawData, const uint8_t *p_src, uint8_t src_len) +{ + pRawData->len = src_len + 4; + + tmos_memset(pRawData->buf, 0, sizeof(pRawData->buf)); + + pRawData->buf[0] = 0XAA; + pRawData->buf[1] = src_len; + + tmos_memcpy(&pRawData->buf[2], p_src, src_len); + + // 从帧起始符开始到校验码之前所有字节的和的模256 + // ,即各字节不计超过255的溢出值的二进制算术和。 + pRawData->buf[pRawData->len - 2] = XOR_CheckSum(&pRawData->buf[0], pRawData->len - 2); + pRawData->buf[pRawData->len - 1] = 0X55; + + logHexDumpAll(&pRawData->buf[0], pRawData->len); + + return 0; +} + +/** + * @brief 向报警器发送数据 + * @param {uint8_t} task_id + * @param {uint16_t} events + * @return {*} + */ +uint16_t BSP_Send_Process(uint8_t *pdata, uint16_t len) +{ + int8_t ret = 0; + __attribute__((aligned(4))) uint8_t buf[128] = {0}; + ret = BSP_Bt_Process(buf, len); + if (ret != 0) + { + logError("BT 操作失败[%d]", ret); + } +} + +uint16_t BT_ProcessEvent(uint8_t task_id, uint16_t events) +{ + int8_t ret = 0; + if (events & SYS_EVENT_MSG) + { + uint8_t *pMsg; + if ((pMsg = tmos_msg_receive(BtRxTaskId)) != NULL) + { + PRINT("revice data:"); + for (uint8_t i = 0; i < 8; i++) + { + PRINT("%02x ", pMsg[i]); + } + PRINT("\r\n"); + // Release the TMOS message + tmos_msg_deallocate(pMsg); + } + } + else if (events & BT_START_EVT) { lwrb_reset(&uart1_rx_t); tmos_start_task(task_id, BT_REC_EVT, 20); + tmos_start_task(task_id, BT_INFO_UPDATA_EVT, 1000); return (events ^ BT_START_EVT); } - else if(events & BT_REC_EVT) + else if (events & BT_REC_EVT) { int len = lwrb_get_full(&uart1_rx_t); if (len > 0) { - uint8_t buf[128] = {0}; - char *ptr = (char *)malloc(len + 1); - lwrb_read(&uart1_rx_t, ptr, len); - logHexDumpAll(ptr, len); - free(ptr); + __attribute__((aligned(4))) uint8_t buf[256] = {0}; + lwrb_read(&uart1_rx_t, buf, len); + ret = BSP_Bt_Process(buf, len); + if (ret != 0) + { + logError("BT 操作失败[%d]", ret); + } } tmos_start_task(task_id, BT_REC_EVT, 20); return (events ^ BT_REC_EVT); } + else if (events & BT_SEND_EVT) + { + BSP_Uart1_Send_String("\r\n");//报警器端接收是以回车换行结尾,所以这里也加上换行 + tmos_start_task(task_id, BT_SEND_EVT, 1000); + return (events ^ BT_SEND_EVT); + } + else if (events & BT_INFO_UPDATA_EVT) // 更新蓝牙连接信息 + { + BSP_Bt_Valve_Updata(); + return (events ^ BT_INFO_UPDATA_EVT); + } return 0; } + /*BT与报警器主机接口*/ void BSP_UART1_Init(void) { @@ -121,12 +295,10 @@ void BSP_UART1_Init(void) UART1_INTCfg(ENABLE, RB_IER_LINE_STAT | RB_IER_RECV_RDY | RB_IER_THR_EMPTY); PFIC_EnableIRQ(UART1_IRQn); UART1_FifoInit(); - BtRxTaskId = TMOS_ProcessEventRegister(BT_Rx_ProcessEvent); + BtRxTaskId = TMOS_ProcessEventRegister(BT_ProcessEvent); tmos_set_event(BtRxTaskId, BT_START_EVT); } - - /*调试接口*/ void BSP_UART3_Init(void) { @@ -144,7 +316,6 @@ void BSP_UART3_Init(void) UART3_FifoInit(); userShellInit(); - } /********************************************************************* @@ -159,16 +330,16 @@ __HIGH_CODE void UART1_IRQHandler(void) { uint8_t data; - switch(UART1_GetITFlag()) + switch (UART1_GetITFlag()) { case UART_II_LINE_STAT: // 线路状态错误 { -// UART1_GetLinSTA(); + // UART1_GetLinSTA(); break; } case UART_II_RECV_RDY: case UART_II_RECV_TOUT: // 接收数据 - while(R8_UART1_RFC) + while (R8_UART1_RFC) { data = R8_UART1_RBR; lwrb_write(&uart1_rx_t, &data, 1); @@ -176,7 +347,7 @@ void UART1_IRQHandler(void) break; case UART_II_THR_EMPTY: // 发送缓存区空,可继续发送 - if(lwrb_read(&uart1_tx_t, &data, 1)) + if (lwrb_read(&uart1_tx_t, &data, 1)) { UART1_SendByte(data); } @@ -207,22 +378,22 @@ __HIGH_CODE void UART3_IRQHandler(void) { uint8_t data; - switch(UART3_GetITFlag()) + switch (UART3_GetITFlag()) { case UART_II_LINE_STAT: // 线路状态错误 { -// UART1_GetLinSTA(); + // UART1_GetLinSTA(); break; } case UART_II_RECV_RDY: - case UART_II_RECV_TOUT: //接收超时 - while(R8_UART3_RFC) + case UART_II_RECV_TOUT: // 接收超时 + while (R8_UART3_RFC) { shellHandler(&shell, R8_UART3_RBR); } break; case UART_II_THR_EMPTY: // 发送缓存区空,可继续发送 - if(lwrb_get_full(&uart3_tx_t)) + if (lwrb_get_full(&uart3_tx_t)) { lwrb_read(&uart3_tx_t, &data, 1); UART3_SendByte(data); @@ -241,3 +412,10 @@ void UART3_IRQHandler(void) break; } } + +int reboot(void) +{ + PFIC_SystemReset(); +} +SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC), + reboot, reboot, "reboot"); diff --git a/bsp/src/bsp_valve.c b/bsp/src/bsp_valve.c new file mode 100644 index 0000000..6bf822a --- /dev/null +++ b/bsp/src/bsp_valve.c @@ -0,0 +1,243 @@ +/* + * @Author: mbw + * @Date: 2024-12-09 11:40:10 + * @LastEditors: mbw && 1600520629@qq.com + * @LastEditTime: 2024-12-11 15:43:47 + * @FilePath: \ble_-tyq_-bjq_-ch584-m\bsp\src\bsp_valve.c + * @Description: + * + * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. + */ +#include "bsp_valve.h" +#include "bsp_flash.h" +#include "CH58xBLE_LIB.h" +#include "bsp_uart.h" +#include "bsp_master.h" +#include "multiCentral.h" + +/* +接收数据帧格式: 帧头 + 数据长度 + 命令 + id + mac + (状态)(只针对控制指令,其他指令不含) + 校验码 + 帧尾 +发送数据帧格式: 帧头 + 数据长度 + 命令 + id + mac + 响应码 + 校验码 + 帧尾 +*/ + +#undef LOG_ENABLE +#define LOG_ENABLE 1 + +#include "log.h" + +valve_data_list_t valve_list = {0}; + +int BSP_Valve_Close(uint8_t valve_id) +{ + uint8_t num = Flash_Get_Valve_Num(); + + if ((valve_id > 8) && (num == 0)) + { + logError("BSP_Valve_Close: valve id error"); + + return -1; + } + logDebug("BSP_Valve_Close: valve id: %d", valve_id); + // TODO:检查是否连接, 如果连接,则发送数据,将关闭阀门指令发送过去,然后等待数据接收响应,如果接收到响应是关闭状态0x01,则返回成功,否则失败 + +// BSP_Master_Send(centralConnList, CONNECT0_ITEM, 0x01, 1); + + return 0; +} + +/*用于控制阀门的状态 + * id: 1-8 + * mac_addr: 6字节 + * status: 0-关闭 1-打开 + */ +int BSP_Bt_Valve_Ctr(uint8_t *data, uint8_t len) +{ + uint8_t mac_addr[FLASH_MAC_INFO_LEN] = {0}; + if ((data[0] >= 1) && (data[0] <= 8)) + { + Flash_Get_Mac_Addr(mac_addr, data[0] - 1); + } + else + { + logError("BSP_Bt_Valve_Ctr: id error"); + return -1; + } + if (tmos_memcmp(&data[1], mac_addr, FLASH_MAC_INFO_LEN) != TRUE) + { + logError("mac addr error read mac addr : %02X %02X %02X %02X %02X %02X != bt_rx mac addr: %02X %02X %02X %02X %02X %02X", + mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5], data[1], data[2], data[3], data[4], data[5], data[6]); + + return -2; + } + /*如果到这里了,说明ID和MAC地址对应没问题,则关闭对应阀门*/ + return BSP_Valve_Close(data[0]); +} + +/*注册阀门信息*/ +int BSP_Bt_Register_Valve(uint8_t *data, uint8_t len) +{ + size_t i = 0; + uint8_t mac_addr[FLASH_MAC_INFO_LEN] = {0}; + if ((data[0] >= 1) && (data[0] <= 8)) + { + Flash_Get_Mac_Addr(mac_addr, data[0] - 1); + } + else + { + logError("valve id error"); + + return 1; + } + for (; i < FLASH_MAC_INFO_LEN; i++) + { + if (mac_addr[i] != 0xFF) + break; + } + if (i == FLASH_MAC_INFO_LEN) // 说明此处未写入数据,那就在此处写入注册MAC地址 + { + if (Flash_Set_Mac_Addr(&data[1], data[0] - 1) != 0) + { + logError("register valve error"); + return 2; + } + tmos_start_task(BtRxTaskId, BT_INFO_UPDATA_EVT, 10); + } + else + { + logError("valve info has been registered"); // 这个ID号已经注册了 + return 3; + } + + return 0; +} + +/*移除阀门信息*/ +int BSP_Bt_Remove_Valve(uint8_t *data, uint8_t len) +{ + size_t i = 0; + uint8_t mac_addr[FLASH_MAC_INFO_LEN] = {0}; + if ((data[0] >= 1) && (data[0] <= 8)) + { + Flash_Get_Mac_Addr(mac_addr, data[0] - 1); + } + else + { + logError("valve id error"); + return -1; + } + for (; i < FLASH_MAC_INFO_LEN; i++) + { + if (mac_addr[i] != data[i + 1]) + break; + } + if (i == FLASH_MAC_INFO_LEN) // 说明MAC地址没问题,那么就将其擦除 + { + tmos_memset(mac_addr, 0xFF, FLASH_MAC_INFO_LEN); + if (Flash_Set_Mac_Addr(mac_addr, data[0] - 1) != 0) + { + logError("移除阀门信息失败"); + return -2; + } + tmos_start_task(BtRxTaskId, BT_INFO_UPDATA_EVT, 10); + } + else + { + logError("valve mac addr error"); // 这个ID号已经注册了, + return -3; + } + return 0; +} + +/*更换阀门信息*/ +int BSP_Bt_Replace_Valve(uint8_t *data, uint8_t len) +{ + size_t i = 0; + uint8_t mac_addr[FLASH_MAC_INFO_LEN] = {0}; + if ((len == 0) || (len < 12)) + { + return -1; + } + if ((data[0] >= 1) && (data[0] <= 8)) + { + Flash_Get_Mac_Addr(mac_addr, data[0] - 1); + } + else + { + logError("valve id error"); + return -2; + } + for (; i < FLASH_MAC_INFO_LEN; i++) + { + if (mac_addr[i] != data[i + 1]) + break; + } + if (i == FLASH_MAC_INFO_LEN) // 说明MAC地址没问题 + { + tmos_memset(mac_addr, 0xFF, FLASH_MAC_INFO_LEN); + if (Flash_Set_Mac_Addr(mac_addr, data[0] - 1) != 0) + { + logError("擦除阀门信息失败"); + return -3; + } + if (Flash_Set_Mac_Addr(&data[7], data[0] - 1) != 0) + { + logError("更换阀门信息失败"); + return -4; + } + tmos_start_task(BtRxTaskId, BT_INFO_UPDATA_EVT, 10); + } + return 0; +} + +/*更新阀门信息*/ +void BSP_Bt_Valve_Updata(void) +{ + uint8_t cnt = 0; + uint8_t mac[6] = {0}; + uint8_t num = Flash_Get_Valve_Num(); + logInfo("BSP_Bt_Valve_Updata"); + tmos_memset(&valve_list, 0, sizeof(valve_data_list_t)); + for (int i = 0; i < MAX_VALVE_NUM; i++)//这个循环是为了将数据拷贝到valve_list中, 并且保证id号和flash对应起来 + { + if(Flash_Get_Mac_Addr(mac, i) == 0) + { + if (tmos_isbufset(mac, 0xFF, 6) == FALSE)//不是默认值 + { + tmos_memcpy(valve_list.valve_data[cnt].valve_mac, mac, 6);//这样做的目的就是读取方便,只需要根据flash中读取到的数量进行读取前N个值 + valve_list.valve_data[cnt].valve_id = i + 1; + cnt++; + logDebug(" updata valve_id: %d, valve_mac: %02X %02X %02X %02X %02X %02X", i + 1, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + } + else + { + tmos_memset(&valve_list.valve_data[i], 0, sizeof(valve_data_t)); + } + } + else + { + logError("BSP_Bt_Valve_Updata: flash read error"); + } + } +} + +/*接收从机的状态上报数据,并对所有数据进行整理*/ +void BSP_Bt_Valve_Rx_Data(uint8_t *data, uint8_t len) +{ + uint8_t i = 0; +} +void BSP_Valve_Init(void) +{ + uint8_t num = Flash_Get_Valve_Num(); + logInfo("num: %d", num); + + logInfo("BSP_Valve_Init"); + valve_list.valve_num = num; + for (int i = 0; i < num; i++) + { + valve_list.valve_data[i].valve_id = i + 1; + Flash_Get_Mac_Addr(valve_list.valve_data[i].valve_mac, i); + } + + logInfo("BSP_Valve_Init end"); + +}