/********************************************************************* * @fn simpleProfileChangeCB * * @brief Callback from SimpleBLEProfile indicating a value change * * @param paramID - parameter ID of the value that was changed. * * @return none */ static void simpleProfileChangeCB( uint8 paramID ) { uint8 newValue; switch( paramID ) { case SIMPLEPROFILE_CHAR1: SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, &newValue ); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 1:", (uint16)(newValue), 10, HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) break; case SIMPLEPROFILE_CHAR3: SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, &newValue ); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 3:", (uint16)(newValue), 10, HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) break; default: // should not reach here! break; } }
/** * ¸Ä±äµÆ¹âµÄº¯Êý£¬phoneStatus ÊÖ»ú״̬£¬isChange ÊÇ·ñ²¥·ÅÇл»Ð§¹û¡£ * phoneStatus = -2 ±íʾ¶ÁÈ¡µ½ÁËcharacteristic1 µÄÊý×éÖµ¡£ * phoneStatus = -1 ±íʾ¶ÁÈ¡µ½ÁËcharacteristic2 µÄÊý×éÖµ¡£ */ static void dataChange(int8 phoneStatus,uint8 isChange){ HalLcdWriteStringValue( "phoneStatus +£º", phoneStatus, 10, HAL_LCD_LINE_7 ); uint8 newValueBuf[20]={0}; SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, newValueBuf ); //Ö»¶ÁÈ¡µ½Êý×é1µÄÊý¾Ý£¬ÏȲ»¸Ä±äµÆ¹âÖ»¼Ç¼ÏÂÀ´£¬µÈÊý×é2µÄÊý¾Ý±»¶Áµ½ºó²Å½øÐеƹâ¸Ä±äµÄ²Ù×÷¡£ if(phoneStatus == -2){ //HalLcdWriteStringValue( "Char 1:", newValueBuf[0], 10, HAL_LCD_LINE_3 ); init_QI_Switch(newValueBuf[1]); return; } uint8 newValueBuf2[20]={0}; SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR2, newValueBuf2 ); //newValueBuf[0] = 1; if(phoneStatus >=0){ newValueBuf[0] = phoneStatus; //HalLcdWriteStringValue( "change:", newValueBuf[13], 10, HAL_LCD_LINE_4 ); //HalLcdWriteStringValue( "change:", newValueBuf[16], 10, HAL_LCD_LINE_5 ); } HalLcdWriteStringValue( "status:", newValueBuf[0], 10, HAL_LCD_LINE_6 ); if(newValueBuf[0] != 16){ //дÈëµ½flashÖÐ osal_snv_write(0x80,20,newValueBuf); osal_snv_write(0x95,20,newValueBuf2); } //¸Ä±äµÈÑÕÉ« setValus(newValueBuf,newValueBuf2,isChange); LedChange(); }
/********************************************************************* * @fn simpleProfileChangeCB * * @brief Callback from SimpleBLEProfile indicating a value change * * @param paramID - parameter ID of the value that was changed. * * @return none */ static void simpleProfileChangeCB( uint8 paramID ) { uint8 newValue; switch( paramID ) { case SIMPLEPROFILE_CHAR1: SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, &newValue ); //存储mp,校准是需要重新写入measured power osal_snv_write(0xfe,1,&newValue); //通知重启 osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD ); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 1:", (uint16)(newValue), 10, HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) break; case SIMPLEPROFILE_CHAR3: SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, &newValue ); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 3:", (uint16)(newValue), 10, HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) break; default: // should not reach here! break; } }
/********************************************************************* * @fn zllSampleBridge_ProcessTL * * @brief Process notification data of target being touch-linked: * - Add target to linked targets list * - Provide user notification * - initiate post-TL procedures (send EP Info to end-device) * * @param pRec - Target's enpoint information record * * @return status */ static ZStatus_t zllSampleBridge_ProcessTL( epInfoRec_t *pRec ) { zllSampleBridge_DstAddr.endPoint = pRec->endpoint; zllSampleBridge_DstAddr.addrMode = afAddr16Bit; zllSampleBridge_DstAddr.addr.shortAddr = pRec->nwkAddr; #if defined( INTER_PAN ) zllSampleBridge_DstAddr.panId = _NIB.nwkPanId; #endif zllSampleBridge_UpdateLinkedTarget( pRec ); #if ( HAL_LED == TRUE ) // Light LED HalLedSet( HAL_LED_2, HAL_LED_MODE_ON ); HalLedSet( HAL_LED_1, HAL_LED_MODE_OFF ); #endif //check if this is a light. if( pRec->deviceID < ZLL_DEVICEID_COLOR_CONTORLLER ) { HalLcdWriteStringValue( "TL Light:", pRec->nwkAddr, 16, HAL_LCD_LINE_3 ); } else { HalLcdWriteStringValue( "TL Ctrlr:", pRec->nwkAddr, 16, HAL_LCD_LINE_3 ); #ifdef ZLL_UTILITY_SEND_EPINFO_ENABLED zllInitiator_SendEPInfo( SAMPLEBRIDGE_ENDPOINT, &zllSampleBridge_DstAddr, sampleBridgeSeqNum++ ); #endif //ZLL_UTILITY_SEND_EPINFO_ENABLED } return ( ZSuccess ); }
/** * @brief Maneja los eventos de teclas, generados cuando ocurre un pulsación * en el joystick de la placa. * @param shift true si shift/alt está presionado. * @param keys Mascara de bits para los eventos de teclado. Válidos: * EVAL_SW4, EVAL_SW3, EVAL_SW2, EVAL_SW1. */ void zb_HandleKeys(uint8 shift, uint8 keys) { static uint8 allowJoin = TRUE; uint8 logicalType; if (keys & HAL_KEY_CENTER) { if (appState == APP_INIT) { // configura el dispositivo como coordinador logicalType = ZG_DEVICETYPE_COORDINATOR; zb_WriteConfiguration(ZCD_NV_LOGICAL_TYPE, sizeof(uint8), &logicalType); zb_SystemReset(); } } if (keys & HAL_KEY_UP) { // configura condición de máxima carga (I RMS) en pasos de 0.1 A, hasta 2 A if (alarm_max_irms > 2) alarm_max_irms = 0.1; else alarm_max_irms += 0.1; HalLcdWriteString("MAX I RMS (mA)", HAL_LCD_LINE_1); HalLcdWriteStringValue("", (int)(alarm_max_irms*1000), 10, 2); } if (keys & HAL_KEY_DOWN) // joystick abajo { // configura condicion de máximo consumo (E) en pasos de 50 Ws, hasta 400 Ws if (alarm_max_energy > 400) alarm_max_energy = 50; else alarm_max_energy += 50; HalLcdWriteString("MAX ENERGIA (Ws)", HAL_LCD_LINE_1); HalLcdWriteStringValue("", alarm_max_energy, 10, 2); } if (keys & HAL_KEY_RIGHT) // joystick derecha { // inicia evento para pruebas msgReport.sequence = 0; osal_start_timerEx(sapi_TaskID, MY_TEST_EVT, 5000); } if (keys & HAL_KEY_LEFT) // joystick izquierda { // controla si el dispositivo acepta join requests // refleja este estado en el LED 3 allowJoin ^= 1; if (allowJoin) { NLME_PermitJoiningRequest(0xFF); HalLedSet(HAL_LED_3, HAL_LED_MODE_ON); } else { NLME_PermitJoiningRequest(0); HalLedSet(HAL_LED_3, HAL_LED_MODE_OFF); } } }
/********************************************************************* * @fn simpleProfileChangeCB * * @brief Callback from SimpleBLEProfile indicating a value change * * @param paramID - parameter ID of the value that was changed. * * @return none */ static void simpleProfileChangeCB( uint8 paramID ) { uint8 newValue, intval[3]; switch( paramID ) { case SIMPLEPROFILE_CHAR1: SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, &newValue ); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 1:", (uint16)(newValue), 10, HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) //发射功率有四个级别,-23dbm,-6dbm,0dbm, 4dbm, newValue为0~3,当连接的时候,只能设置-6, 0 if(newValue == LL_EXT_TX_POWER_MINUS_6_DBM || newValue == LL_EXT_TX_POWER_0_DBM) { HCI_EXT_SetTxPowerCmd(newValue); ProxReporter_SetParameter( PP_TX_POWER_LEVEL, sizeof ( int8 ), &newValue ); } break; case SIMPLEPROFILE_CHAR2: SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR2, &newValue ); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 2:", (uint16)(newValue), 10, HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) if( newValue == 1 && gOpenDoorStep == 0 ){ gOpenDoorStep++; osal_set_event( simpleBLEPeripheral_TaskID, SBP_OPENDOOR_DEVICE_EVT ); } break; case SIMPLEPROFILE_CHAR3: SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, intval ); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 3:", (uint16)(newValue), 10, HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) advert_internal = (intval[0] - 0x30) *100 + (intval[1] - 0x30) * 10 + (intval[2] - 0x30); break; default: // should not reach here! break; } }
/********************************************************************* * @fn SimpleProfile_AddService * * @brief Initializes the Simple Profile service by registering * GATT attributes with the GATT server. * * @param services - services to add. This is a bit map and can * contain more than one service. * * @return Success or Failure */ bStatus_t ExampleService_AddService( void ) { static uint8 excute_time =0; uint8 status = SUCCESS; if(excute_time > 0) //make sure it is only excuted once, because everytime it excuted, it add the attr to the list ,no matter wheather it exists in it. return(status); else excute_time++; HalLcdWriteStringValue("excute_time",excute_time,10,HAL_LCD_LINE_6); // Initialize Client Characteristic Configuration attributes GATTServApp_InitCharCfg( INVALID_CONNHANDLE, simpleProfileChar2Config ); // Register with Link DB to receive link status change callback VOID linkDB_Register( simpleProfile_HandleConnStatusCB ); // Register GATT attribute list and CBs with GATT Server App status = GATTServApp_RegisterService( simpleProfileAttrTbl, GATT_NUM_ATTRS( simpleProfileAttrTbl ), &simpleProfileCBs ); return ( status ); }
/********************************************************************* * @fn pairStateCB * @brief Pairing state callback. * @return none */ static void simpleBLEPeripheralPairStateCB(uint16 connHandle, uint8 state, uint8 status) { if (state == GAPBOND_PAIRING_STATE_STARTED) { HalLcdWriteString("Pairing started", HAL_LCD_LINE_7); } else if (state == GAPBOND_PAIRING_STATE_COMPLETE) { if (status == SUCCESS) { HalLcdWriteString("Pairing success", HAL_LCD_LINE_7); } else { HalLcdWriteStringValue("Pairing fail", status, 10, HAL_LCD_LINE_7); uint8 a = GAPRole_TerminateConnection(); HalLcdWriteStringValue("Pairing fail--a", a, 10, HAL_LCD_LINE_7); } } else if (state == GAPBOND_PAIRING_STATE_BONDED) { if (status == SUCCESS) { HalLcdWriteString("Bonding success", HAL_LCD_LINE_1); } } //osal_start_timerEx(simpleBLEPeripheral_TaskID, SBP_ZEKEZANG_EVT, 5000); }
/** * @brief Este callback es llamado asincrónicamente por el stack de ZigBee * para notificar a la aplicación que se recibieron datos, enviados * por otro nodo de la red. * @param source Short Address (NWK) del nodo que envío los datos. * @param command ID del comando asociado con los datos. * @param len Cantidad de bytes del parámetro pData. * @param pData Puntero al inicio de los datos envíados por el nodo. */ void zb_ReceiveDataIndication(uint16 source, uint16 command, uint16 len, uint8 *pData) { // imprime la dirección fuente en el display HalLcdWriteStringValue("RCB", source, 16, 1); // flashea el LED 2 para indicar que se recibió un mensaje HalLedSet(HAL_LED_2, HAL_LED_MODE_FLASH); // deserealiza mensaje recibido msgReport = deserializeMessage(pData); if (msgReport.msgType == MSG_TYPE_REPORT) { HalLcdWriteStringValue("#", msgReport.sequence, 10, 2); // verifica condiciones de alarmas alarmFlags = checkAlarms(&msgReport); // imprime alarma en LCD //HalLcdWriteStringValue("ALARM", alarmFlags, 16, 2); if (alarmFlags != 0) { // crea paquete de respuesta con igual MAC y nº de secuencia struct message_t msgAlarm; msgAlarm.sequence = msgReport.sequence; memcpy(&(msgAlarm.mac), &(msgReport.mac), sizeof(msgReport.mac)); msgAlarm.msgType = MSG_TYPE_ALARM; msgAlarm.lenData = MSG_LEN_DATA_ALARM; // flags en little-endian msgAlarm.data[0] = LO_UINT16(alarmFlags); msgAlarm.data[1] = HI_UINT16(alarmFlags); // serializa mensaje y lo envía serializeMessage(&(msgAlarm), msgBuf); zb_SendDataRequest(source, MESSAGE_CLUSTER, getSizeOfMessage(&(msgAlarm)), msgBuf, 0, AF_TX_OPTIONS_NONE, 0); } // crea evento para enviar el reporte por UART a la PC, añandiendo // los flags osal_start_timerEx(sapi_TaskID, SEND_UART_MSG, 0); } }
/** * @brief Esta función es llamada por el SO cuando se debe atender un * evento de la tarea. * @param event Mascara de bits conteniendo los eventos a atender */ void zb_HandleOsalEvent(uint16 event) { uint8 logicalType; if (event & SYS_EVENT_MSG) { } if (event & ZB_ENTRY_EVENT) { // inicializa UART initUart(uartRxCB); // blick LED 1 para indicar que se está uniendo a la red HalLedBlink(HAL_LED_1, 0, 50, 500 ); HalLedSet(HAL_LED_2, HAL_LED_MODE_OFF); // lee tipo de logical device desde la memoria NV zb_ReadConfiguration(ZCD_NV_LOGICAL_TYPE, sizeof(uint8), &logicalType); // inicia la red zb_StartRequest(); } if (event & MY_START_EVT) { // inicia la red zb_StartRequest(); } if (event & SEND_UART_MSG) { // envia mensaje por UART a la PC //HalLcdWriteString("UART_EVT", HAL_LCD_LINE_1); sendUartMessage(&msgReport, &alarmFlags); } if (event & MY_TEST_EVT) { // crea mensaje de prueba msgReport.msgType = MSG_TYPE_REPORT; msgReport.sequence++; msgReport.lenData = MSG_LEN_DATA_REPORT; for (uint8 i = 0; i < 8; i++) msgReport.mac[i] = i; // datos de prueba static double d[10] = {220.5, 0.354, 85.12, 88.33, 85.06, 0.98, 1.23, 3.25, 0.97, 4.55}; for (int i = 0; i < 10; i++) memcpy(&(msgReport.data[i*4]), &(d[i]), sizeof(double)); // flags de prueba uint16 flags = 0; // imprime info en LCD HalLcdWriteString("TEST_EVT", HAL_LCD_LINE_1); HalLcdWriteStringValue("#", msgReport.sequence, 10, HAL_LCD_LINE_2); // envia mensaje por UART sendUartMessage(&msgReport, &flags); // crea evento nuevamente osal_start_timerEx(sapi_TaskID, MY_TEST_EVT, 5000); } }
void SbpHalUARTReadCallback(uint8 port, uint8 event) { UART_PORT_HAVE_READ = 0; //UART_HAL_DELAY(15000); numBytes = Hal_UART_RxBufLen(port); HalLcdWriteStringValue("numBytes", numBytes, 10, HAL_LCD_LINE_2); if (numBytes > 0 && (u_state == IR_DATA_STUDY_CMD_START_BEGIN_STATE)) { SbpHalUARTRead(port, pktBuffer, numBytes); //HalLcdWriteStringValue("pktBuffer", pktBuffer[0], 16, HAL_LCD_LINE_3); if (pktBuffer[0] == SBP_UART_STUDY_CMD) { osal_memset(UartBuffer, 0, SBP_UART_RX_BUF_SIZE); point = 0; irdatalen = 0; u_state = IR_DATA_STUDY_CMD_START_END_STATE; } } else if (numBytes > 0 && (u_state == IR_DATA_STUDY_CMD_START_END_STATE)) { SbpHalUARTRead(port, pktBuffer, numBytes); if (irdatalen == 0) { irdatalen = pktBuffer[0]; } osal_memcpy(UartBuffer + point, pktBuffer, numBytes); point += numBytes; if (irdatalen == point) { u_state = IR_DATA_STUDY_CMD_RECV_END_STATE; studyCompletedAndBroadcastData(); } } else if (numBytes > 0 && (u_state == IR_DATA_SEND_BEGIN_STATE)) { SbpHalUARTRead(port, pktBuffer, numBytes); HalLcdWriteStringValue("send resp:", pktBuffer[0], 16, HAL_LCD_LINE_6); u_state = IR_DATA_SEND_END_RESP_STATE; } if (numBytes > 0 && UART_PORT_HAVE_READ == 0) { SbpHalUARTRead(port, pktBuffer, numBytes); HalLcdWriteStringValue("HAVE_READ", pktBuffer[0], 16, HAL_LCD_LINE_6); } }
static void simpleBLEPeripheral_HandleKeys(uint8 shift, uint8 keys) { if (keys & HAL_KEY_UP) { u_state = IR_DATA_STUDY_CMD_START_BEGIN_STATE; SbpHalUARTWrite(&SBP_UART_STUDY_CMD, SBP_UART_STUDY_CMD_LEN); } if (keys & HAL_KEY_LEFT) { } if (keys & HAL_KEY_DOWN) { HalLcdWriteString("send after 3s...", HAL_LCD_LINE_4); osal_start_timerEx(simpleBLEPeripheral_TaskID, SBP_SEND_IRDATA_EVT, 3000); } if (keys & HAL_KEY_RIGHT) { HalLcdWriteStringValue("data_len:", data_len, 10, HAL_LCD_LINE_2); } }
/************************************************************************************************** * @fn HalKeyPoll * * @brief Called by hal_driver to poll the keys * * @param None * * @return None **************************************************************************************************/ void HalKeyPoll (void) { uint8 keys = 0; if ((HAL_KEY_JOY_MOVE_PORT & HAL_KEY_JOY_MOVE_BIT)) /* Key is active HIGH */ { keys = halGetJoyKeyInput(); } /* If interrupts are not enabled, previous key status and current key status * are compared to find out if a key has changed status. */ if (!Hal_KeyIntEnable) { if (keys == halKeySavedKeys) { /* Exit - since no keys have changed */ return; } /* Store the current keys for comparation next time */ halKeySavedKeys = keys; } else { #if defined ( POWER_SAVING ) osal_pwrmgr_device( PWRMGR_BATTERY ); #endif Pulses++; HalLcdWriteStringValue( (char*)titulo, Pulses, 10, 2 ); } if (HAL_PUSH_BUTTON1()) { keys |= HAL_KEY_SW_6; } /* Invoke Callback if new keys were depressed */ if (keys && (pHalKeyProcessFunction)) { (pHalKeyProcessFunction) (keys, HAL_KEY_STATE_NORMAL); } }
/** * @brief Envía un mensaje por UART según el protocolo implementado. Este se * crea a partir de un mensaje y otros datos (genéricos) pasados como * argumento. Para el mensaje de tipo REPORT, los otros datos * corresponden a los flags de alarmas, y son añadidos al mensaje antes * de los parámetros eléctricos. * Los mensajes tienen el siguiente formato: * HEADER DATA * SOF | DATA LENGTH | COMMAND | SENSOR MAC | DATA[DATA LENGTH] * Donde SOF=0xFE es el delimitador del inicio del frame; DATA LENGTH * es la cantidad de bytes de datos envíados luego del HEADER; COMMAND * es el comando enviado a la PC (REPORT, etc.); SENSOR MAC es la * dirección MAC de 64 bytes del nodo al cual se refiere la información; * y DATA corresponde a los datos enviados en formato Little Endian. * * @param msg Mensaje que se desea retransmitir por UART. * @param other Otros datos para añadir al mensaje. */ static void sendUartMessage(struct message_t *msg, void *other) { uint8 pFrame[UART_FRAME_MAX_LENGTH]; // start of frame pFrame[UART_FRAME_SOF_OFFSET] = CPT_SOP; // tipo de mensaje pFrame[UART_FRAME_CMD_OFFSET] = msg->msgType; // MAC memcpy(&(pFrame[UART_FRAME_MAC_OFFSET]), &(msg->mac), sizeof(msg->mac)); if (msg->msgType == MSG_TYPE_REPORT) { // length pFrame[UART_FRAME_LENGTH_OFFSET] = UART_FRAME_REPORT_LENGTH; // secuencia pFrame[UART_FRAME_DATA_OFFSET] = LO_UINT16(msg->sequence); pFrame[UART_FRAME_DATA_OFFSET+1] = HI_UINT16(msg->sequence); // flags alarmas uint16 flags = *((uint16*)other); pFrame[UART_FRAME_DATA_OFFSET+2] = LO_UINT16(flags); pFrame[UART_FRAME_DATA_OFFSET+3] = HI_UINT16(flags); // parámetros eléctricos memcpy(&(pFrame[UART_FRAME_DATA_OFFSET+4]), &(msg->data), msg->lenData); } else { // otros tipos de mensaje pFrame[UART_FRAME_LENGTH_OFFSET] = 0; } // escribe mensaje en UART uint16 b = HalUARTWrite(HAL_UART_PORT_0, pFrame, UART_FRAME_HEADER_LENGTH+pFrame[UART_FRAME_LENGTH_OFFSET]); if (b > 0) HalLcdWriteStringValue("UART", b, 10, 3); else HalLcdWriteString("", HAL_LCD_LINE_3); }
/********************************************************************* * @fn hwLight_UpdateColor * * @brief Update light output according to color attributes * * @param none * * @return none */ static void hwLight_UpdateColor(void) { if(zclColor_ColorMode == COLOR_MODE_CURRENT_X_Y) { #ifdef ZLL_HW_LED_LAMP hwLight_UpdateLampColor(zclColor_CurrentX, zclColor_CurrentY, zclLevel_CurrentLevel); #else //ZLL_HW_LED_LAMP #else #if defined ZCL_LEVEL_CTRL HalLcdWriteStringValue( "Level:", zclLevel_CurrentLevel, 10, HAL_LCD_LINE_1 ); #endif //ZCL_LEVEL_CTRL HalLcdWriteStringValue( "x: 0x", zclColor_CurrentX, 16, HAL_LCD_LINE_2 ); HalLcdWriteStringValue( "y: 0x", zclColor_CurrentY, 16, HAL_LCD_LINE_3 ); #endif //ZLL_HW_LED_LAMP } else { if(zclColor_EnhancedColorMode == ENHANCED_COLOR_MODE_ENHANCED_CURRENT_HUE_SATURATION) { //add enhancement here for color Zoom. zclColor_CurrentHue = (zclColor_EnhancedCurrentHue&0xFF00)>>8; if ( zclColor_CurrentHue > COLOR_HUE_MAX ) { zclColor_CurrentHue = COLOR_HUE_MAX; } #ifdef ZLL_HW_LED_LAMP hwLight_UpdateLampColorHueSat( zclColor_CurrentHue, zclColor_CurrentSaturation, zclLevel_CurrentLevel); #else //ZLL_HW_LED_LAMP #else #if defined ZCL_LEVEL_CTRL HalLcdWriteStringValue( "Level:", zclLevel_CurrentLevel, 10, HAL_LCD_LINE_1 ); #endif //ZCL_LEVEL_CTRL HalLcdWriteStringValue( "EnhHue: 0x", zclColor_EnhancedCurrentHue, 16, HAL_LCD_LINE_2 ); HalLcdWriteStringValue( "Sat:", zclColor_CurrentSaturation, 10, HAL_LCD_LINE_3 ); #endif //ZLL_HW_LED_LAMP } else {
/************************************************************************************************** * @fn pulseBPM * * @brief This function is called by pulseDataCalc(). This function contains the main algorithm for * pulse calculation that was originally develop for the arduino by Joel Murphy and Yury Gitman from * www.pulsesensor.com. The code has been migrated to work in the MSP430 with minor adjustments to * deal with problems caused by high frequency noise. * * * input parameters * * Pointer to the MHMSdata array that will be sent over the air. * * output parameters * * None. * * @return None. **************************************************************************************************/ static void pulseBPM(uint8 *pulsedata) { static int BPM; // used to hold the pulse rate static int Signal; // holds the incoming raw data static int IBI = 600; // holds the time between beats, the Inter-Beat Interval static bool Pulse = FALSE; // TRUE when pulse wave is high, FALSE when it's low static int rate[10]; // used to hold last ten IBI values static uint32 sampleCounter = 0; // used to determine pulse timing static uint32 lastBeatTime = 0; // used to find the inter beat interval static int P = 512; // used to find peak in pulse wave static int T = 512; // used to find trough in pulse wave static int thresh = 512; // used to find instant moment of heart beat static int amp = 100; // used to hold amplitude of pulse waveform static bool firstBeat = TRUE; // used to seed rate array so we startup with reasonable BPM static bool secondBeat = TRUE; // used to seed rate array so we startup with reasonable BPM BPM = pulsedata[MHMS_BPM]; // used to hold the pulse rate IBI = pulsedata[MHMS_IBI]; // holds the time between beats, the Inter-Beat Interval //MHMS using HAL layer API to set channel to read and 10 Bit resolution Signal = HalAdcRead(HAL_ADC_CHANNEL_7, HAL_ADC_RESOLUTION_10); sampleCounter +=2; // keep track of the time in mS with this variable int Number = (sampleCounter - lastBeatTime); // monitor the time since the last beat to avoid noise // find the peak and trough of the pulse wave if(Signal < thresh && Number > (IBI/5)*3){ // avoid dichrotic noise by waiting 3/5 of last IBI if (Signal < T){ // T is the trough T = Signal; // keep track of lowest point in pulse wave } } if(Signal > thresh && Signal > P){ // thresh condition helps avoid noise P = Signal; // P is the peak } // keep track of highest point in pulse wave // NOW IT'S TIME TO LOOK FOR THE HEART BEAT // signal surges up in value every time there is a pulse if (Number > 500){ // avoid high frequency noise //MHMS increased from 250 to 500 to reduce high freq noise if ((Signal > thresh) && (Pulse == FALSE) && (Number > (int)(IBI/5)*3) ){ Pulse = TRUE; // set the Pulse flag when we think there is a pulse //MHMS could define some external LED or just write to LCD screen "Pulse found" HalLedSet (HAL_LED_2, HAL_LED_MODE_OFF); //MHMS beat found HalLedSet (HAL_LED_1, HAL_LED_MODE_ON); //MHMS LED on during upbeat IBI = sampleCounter - lastBeatTime; // measure time between beats in mS lastBeatTime = sampleCounter; // keep track of time for next pulse if(firstBeat){ // if it's the first time we found a beat, if firstBeat == TRUE firstBeat = FALSE; // clear firstBeat flag return; // IBI value is unreliable so discard it } if(secondBeat){ // if this is the second beat, if secondBeat == TRUE secondBeat = FALSE; // clear secondBeat flag for(int i=0; i<=9; i++){ // seed the running total to get a realisitic BPM at startup rate[i] = IBI; } } // keep a running total of the last 10 IBI values int16 runningTotal = 0; // clear the runningTotal variable for(int i=0; i<=8; i++){ // shift data in the rate array rate[i] = rate[i+1]; // and drop the oldest IBI value runningTotal += rate[i]; // add up the 9 oldest IBI values } rate[9] = IBI; // add the latest IBI to the rate array runningTotal += rate[9]; // add the latest IBI to runningTotal runningTotal /= 10; // average the last 10 IBI values BPM = 60000/runningTotal; // how many beats can fit into a minute? that's BPM! QS = TRUE; // set Quantified Self flag //MHMS we will use this to flag other event to transmit data over network HalLcdWriteStringValue("BPM:",BPM, 10, HAL_LCD_LINE_5); //MHMS display BPM on LCD screen } } if (Signal < thresh && Pulse == TRUE){ // when the values are going down, the beat is over HalLedSet (HAL_LED_1, HAL_LED_MODE_OFF); //MHMS turn LED light off for the off beat Pulse = FALSE; // reset the Pulse flag so we can do it again amp = P - T; // get amplitude of the pulse wave thresh = amp/2 + T + 100; // set thresh at 50% of the amplitude //MHMS offset up by 100 to ignore small flucuations due to noise P = thresh; // reset these for next time T = thresh; } if (Number > 2500){ // if 2.5 seconds go by without a beat HalLedSet (HAL_LED_2, HAL_LED_MODE_ON);// MHMS Indicate that no beat found thresh = 512 + 100; // set thresh default //MHMS offset by 100 to ignore small flucuations due to noise P = 512; // set P default T = 512; // set T default lastBeatTime = sampleCounter; // bring the lastBeatTime up to date firstBeat = TRUE; // set these to avoid noise secondBeat = TRUE; // when we get the heartbeat back QS = FALSE; // Clears Pulse measurement quantifier flag so no data is sent over the air } //MHMS Loading 16 bit results into 8 bit blocks for pulsedata array for pulsedata[MHMS_BPM] = (uint8)((BPM & 0x00FF)); pulsedata[MHMS_RAW_MSB] = (uint8)((Signal >> 8)); pulsedata[MHMS_RAW_LSB] = (uint8)((Signal & 0x00FF)); pulsedata[MHMS_IBI] = (uint8)((IBI & 0x00FF)); pulsedata[MHMS_BPM_CHAR] = 'B'; pulsedata[MHMS_RAW_CHAR] = 'S'; pulsedata[MHMS_IBI_CHAR] = 'Q'; }
/********************************************************************* * @fn zllSampleLight_IdentifyCB * * @brief Callback from the ZCL General Cluster Library when * it received an Identity Command for this application. * * @param srcAddr - source address and endpoint of the response message * @param identifyTime - the number of seconds to identify yourself * * @return none */ static void zllSampleLight_IdentifyEffectCB( zclIdentifyTriggerEffect_t *pCmd ) { HalLcdWriteStringValue( "IdentifyEffId", pCmd->effectId, 16, HAL_LCD_LINE_1 ); zllEffects_InitiateEffect( ZCL_CLUSTER_ID_GEN_IDENTIFY, COMMAND_IDENTIFY_TRIGGER_EFFECT, pCmd->effectId, pCmd->effectVariant ); }
/********************************************************************* * @fn simpleProfileChangeCB * @brief Callback from SimpleBLEProfile indicating a value change * @param paramID - parameter ID of the value that was changed. * * @return none */ static void simpleProfileChangeCB(uint8 paramID) { osal_memset(newValueBuf, 0, 20); switch (paramID) { case SIMPLEPROFILE_CHAR1: SimpleProfile_GetParameter(SIMPLEPROFILE_CHAR1, newValueBuf); if ((newValueBuf[0] == TRANSFER_DATA_SIGN) && (newValueBuf[1] == TRANSFER_DATA_SIGN_RE)) { TRANSFER_DATA_STATE_IN = FALSE; } if ((newValueBuf[2] != 0) && (!TRANSFER_DATA_STATE_IN)) { data_len = newValueBuf[UART_DATA_START_INDEX]; TRANSFER_DATA_STATE_IN = TRUE; data_len_index = 0; osal_memset(recv_value, 0, data_len); } cur_data_len = osal_strlen(newValueBuf); if (TRANSFER_DATA_STATE_IN) { osal_memcpy((recv_value + data_len_index), newValueBuf, cur_data_len); data_len_index += cur_data_len; if ((data_len_index - send_times * one_time_data_len - UART_DATA_START_INDEX) >= one_time_data_len) { if (send_times == 0) { recv_value[UART_DATA_START_INDEX] = 0xE3; if (u_state != IR_DATA_SEND_BEGIN_STATE) { u_state = IR_DATA_SEND_BEGIN_STATE; SbpHalUARTWrite(recv_value + UART_DATA_START_INDEX, one_time_data_len); } } else { SbpHalUARTWrite(recv_value + UART_DATA_START_INDEX + send_times * one_time_data_len, one_time_data_len); } send_times++; } else if ((send_times > 0) && ((data_len_index - send_times * one_time_data_len) < one_time_data_len) && (data_len_index == data_len)) { SbpHalUARTWrite(recv_value + UART_DATA_START_INDEX + send_times * one_time_data_len, data_len - send_times * one_time_data_len - UART_DATA_START_INDEX); send_times++; } else if ((send_times == 0) && (data_len < one_time_data_len) && (data_len_index == data_len)) { recv_value[UART_DATA_START_INDEX] = 0xE3; if (u_state != IR_DATA_SEND_BEGIN_STATE) { u_state = IR_DATA_SEND_BEGIN_STATE; SbpHalUARTWrite(recv_value + UART_DATA_START_INDEX, data_len - UART_DATA_START_INDEX); } } else { } } HalLcdWriteStringValue("data_len_index:", data_len_index, 10, HAL_LCD_LINE_7); if (data_len_index == data_len) { TRANSFER_DATA_STATE_IN = FALSE; HalLcdWriteStringValue("data_len:", osal_strlen((char *)recv_value), 10, HAL_LCD_LINE_6); send_times = 0; data_len = 0; cur_data_len = 0; data_len_index = 0; osal_memset(recv_value, 0, data_len); } break; case SIMPLEPROFILE_CHAR3: //SimpleProfile_GetParameter(SIMPLEPROFILE_CHAR3, &newValue); break; default: // should not reach here! break; } }
/********************************************************************* * @fn zllSampleBridge_HandleKeys * * @brief Handles all key events for this device. * * @param shift - true if in shift/alt. * @param keys - bit field for key events. * * @return none */ static void zllSampleBridge_HandleKeys( byte shift, byte keys ) { if(shift) { keys |= HAL_KEY_SW_6; } if ( keys == ON_KEY ) { zclGeneral_SendOnOff_CmdOn( SAMPLEBRIDGE_ENDPOINT, &zllSampleBridge_DstAddr, FALSE, sampleBridgeSeqNum++ ); } if ( keys == FACTORY_RESET_KEY ) { zllInitiator_ResetToFactoryNew(); } if ( keys == OFF_KEY ) { zclGeneral_SendOnOff_CmdOff( SAMPLEBRIDGE_ENDPOINT, &zllSampleBridge_DstAddr, FALSE, sampleBridgeSeqNum++ ); } if ( keys == TOUCH_LINK_KEY ) { zllInitiator_StartDevDisc(); } if ( keys == DEV_SEL_UP_KEY ) { if ( linkedAddrNum > 0 ) { if( (linkedAddrSelIdx+1) >= linkedAddrNum ) { linkedAddrSelIdx = 0; } else { linkedAddrSelIdx++; } zllSampleBridge_DstAddr.addrMode = afAddr16Bit; zllSampleBridge_DstAddr.addr.shortAddr = linkedTargets.arr[linkedAddrSelIdx].Addr; zllSampleBridge_DstAddr.endPoint = linkedTargets.arr[linkedAddrSelIdx].EP; zclGeneral_SendIdentify( SAMPLEBRIDGE_ENDPOINT, &zllSampleBridge_DstAddr, SAMPLEBRIDGE_CMD_IDENTIFY_TIME, FALSE, sampleBridgeSeqNum++ ); HalLcdWriteStringValue( "Dev Sel:", zllSampleBridge_DstAddr.addr.shortAddr, 16, HAL_LCD_LINE_3 ); } else { HalLcdWriteString( "Dev Sel: no trgt", HAL_LCD_LINE_3 ); } } if ( keys == DEV_SEL_DN_KEY ) { if ( linkedAddrNum > 0 ) { if(linkedAddrSelIdx < 1) { linkedAddrSelIdx = (linkedAddrNum-1); } else { linkedAddrSelIdx--; } zllSampleBridge_DstAddr.addrMode = afAddr16Bit; zllSampleBridge_DstAddr.addr.shortAddr = linkedTargets.arr[linkedAddrSelIdx].Addr; zllSampleBridge_DstAddr.endPoint = linkedTargets.arr[linkedAddrSelIdx].EP; zclGeneral_SendIdentify( SAMPLEBRIDGE_ENDPOINT, &zllSampleBridge_DstAddr, SAMPLEBRIDGE_CMD_IDENTIFY_TIME, FALSE, sampleBridgeSeqNum++ ); HalLcdWriteStringValue( "Dev Sel:", zllSampleBridge_DstAddr.addr.shortAddr, 16, HAL_LCD_LINE_3 ); } else { HalLcdWriteString( "Dev Sel: no trgt", HAL_LCD_LINE_3 ); } } if ( keys == PERMIT_JOIN_KEY ) { if ( zllInitiator_BridgeStartNetwork() != ZSuccess ) { zllInitiator_PermitJoin( PERMIT_JOIN_DURATION ); HalLcdWriteString( "PermitJoin", HAL_LCD_LINE_3 ); } } if ( keys == CLASSIC_COMMISS_KEY ) { zllInitiator_ClassicalCommissioningStart(); } }
/********************************************************************* * @fn SimpleBLEPeripheral_Init * * @brief Initialization function for the Simple BLE Peripheral App Task. * This is called during initialization and should contain * any application specific initialization (ie. hardware * initialization/setup, table initialization, power up * notificaiton ... ). * * @param task_id - the ID assigned by OSAL. This ID should be * used to send messages and set timers. * * @return none */ void SimpleBLEPeripheral_Init( uint8 task_id ) { simpleBLEPeripheral_TaskID = task_id; // Setup the GAP VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL ); // Setup the GAP Peripheral Role Profile { #if defined( CC2540_MINIDK ) // For the CC2540DK-MINI keyfob, device doesn't start advertising until button is pressed uint8 initial_advertising_enable = FALSE; #else // For other hardware platforms, device starts advertising upon initialization uint8 initial_advertising_enable = TRUE; #endif // By setting this to zero, the device will go into the waiting state after // being discoverable for 30.72 second, and will not being advertising again // until the enabler is set back to TRUE uint16 gapRole_AdvertOffTime = 0; uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST; uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL; uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL; uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY; uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT; // Set the GAP Role Parameters GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime ); GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request ); GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval ); GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval ); GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency ); GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout ); //ÉèÖÃRSSI »ñÈ¡ËÙÂÊ uint16 rssi_rate = RSSI_RATE; GAPRole_SetParameter(GAPROLE_RSSI_READ_RATE,sizeof(uint16),&rssi_rate); } // Set the GAP Characteristics GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); // Set advertising interval { uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt ); GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt ); GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt ); GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt ); } // Setup the GAP Bond Manager { uint32 passkey = 0; // passkey "000000" uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; uint8 mitm = TRUE; uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; uint8 bonding = TRUE; GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); } // Initialize GATT attributes Ìí¼ÓÁË4¸öService ·þÎñ GGS_AddService( GATT_ALL_SERVICES ); // GAP GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes DevInfo_AddService(); // Device Information Service SimpleProfile_AddService( GATT_ALL_SERVICES ); // Simple GATT Profile ankiÐèÒªÐ޸ĵķþÎñ #if defined FEATURE_OAD VOID OADTarget_AddService(); // OAD Profile #endif // Setup the SimpleProfile Characteristic Values { //³õʼ»¯±àÒë½øÈ¥µÄµÆ¹âÑÕÉ« uint8 charValue1[20] = {0, 1,255,100,100,255,255,255, 20,1,1,255,1,200, 20,100,100,20,100,10}; uint8 charValue2[20] = {20,1,1,20,1,1,20,1,250,20,1,250,20,1,250,20,1,250,1}; uint8 charValue3 = 3; uint8 charValue4 = 4; uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 }; #if (defined HAL_LCD) && (HAL_LCD == TRUE) //´ÓÎļþÖжÁÈ¡ uint8 wirteTag = osal_snv_read(0x80,20,charValue1); osal_snv_read(0x95,20,charValue2); if( wirteTag == SUCCESS){ HalLcdWriteStringValue("read Ok",(uint16)wirteTag,10, HAL_LCD_LINE_6 ); }else{ HalLcdWriteStringValue("read failed",(uint16)wirteTag,10, HAL_LCD_LINE_6 ); //½øÐгõʼ»¯ wirteTag = osal_snv_write(0x80,20,charValue1); osal_snv_write(0x95,20,charValue1); if(wirteTag == SUCCESS){ HalLcdWriteStringValue( "init", (uint16)wirteTag, 10, HAL_LCD_LINE_7 ); }else{ HalLcdWriteStringValue("init failed", (uint16)wirteTag,10, HAL_LCD_LINE_7 ); } } #else if( osal_snv_read(0x80,20,charValue1) != SUCCESS){ //½øÐгõʼ»¯ //osal_snv_write(0x80,20,charValue1); //HalLcdWriteStringValue( "rece:", osal_snv_write(0x80,20,charValue1), 10, HAL_LCD_LINE_8 ); osal_snv_write(0x95,20,charValue2); } #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, 20, &charValue1 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, 20, &charValue2 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 ); //Ç°Ãæ3¾äÖ»ÊǶԶÔÏóÖµµÄÉèÖã¬Õâ¾ä´úÂë ½øÐÐÁË£¬ServiceµÄcharacteristicÉèÖã¬Process Client Characteristis Configuration Change SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, sizeof ( uint8 ), &charValue4 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); } #if defined( CC2540_MINIDK ) SK_AddService( GATT_ALL_SERVICES ); // Simple Keys Profile // Register for all key events - This app will handle all key events¡£ ×¢²á°´Å¥Ê¼þ£¬OSAL´¦Àí°´Å¥Ê¼þ RegisterForKeys( simpleBLEPeripheral_TaskID ); // makes sure LEDs are off HalLedSet( (HAL_LED_1 | HAL_LED_2), HAL_LED_MODE_OFF ); #endif // #if defined( CC2540_MINIDK ) #if (defined HAL_LCD) && (HAL_LCD == TRUE) #if defined FEATURE_OAD #if defined (HAL_IMAGE_A) HalLcdWriteStringValue( "BLE Peri-A", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 ); #else HalLcdWriteStringValue( "BLE Peri-B", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 ); #endif // HAL_IMAGE_A #else HalLcdWriteString( "BLE Peripheral", HAL_LCD_LINE_1 ); #endif // FEATURE_OAD #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) // Register callback with SimpleGATTprofile // ¸Ã»Øµ÷±» simpleProfile_WriteAttrCB ·½·¨´¥·¢£¬simpleProfileCBs °üº¬´Ë·½·¨£¬ÔÚSimpleProfile_AddService µÄʱºò×¢²áµ½GATTÐÒéÕ»·þÎñÖÐ //Öµ¸Ä±äÖ®ºó£¬Í¨Öª PROFILES--->SimpleProfileCBs.simpleProfile_WriteAttrCB È»ºóÔÙ֪ͨAPP--->simpleBLEPeripheral_SimpleProfileCBs VOID SimpleProfile_RegisterAppCBs( &simpleBLEPeripheral_SimpleProfileCBs ); // Enable clock divide on halt // This reduces active current while radio is active and CC254x MCU // is halted //²»É¾³ý PWM²»Îȶ¨ //HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_ENABLE_CLK_DIVIDE_ON_HALT ); #if defined ( DC_DC_P0_7 ) // Enable stack to toggle bypass control on TPS62730 (DC/DC converter) HCI_EXT_MapPmIoPortCmd( HCI_EXT_PM_IO_PORT_P0, HCI_EXT_PM_IO_PORT_PIN7 ); #endif // defined ( DC_DC_P0_7 ) // Setup a delayed profile startup ·¢ÆðBLEÁ¬½Ó³õʼ»¯Ïà¹Ø·þÎñ¡£ÏÂÃæ·½·¨¶Ô SBP_START_DEVICE_EVT ʼþ½øÐд¦Àí osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT ); }
/********************************************************************* * @fn SimpleBLEPeripheral_Init * * @brief Initialization function for the Simple BLE Peripheral App Task. * This is called during initialization and should contain * any application specific initialization (ie. hardware * initialization/setup, table initialization, power up * notificaiton ... ). * * @param task_id - the ID assigned by OSAL. This ID should be * used to send messages and set timers. * * @return none */ void SimpleBLEPeripheral_Init( uint8 task_id ) { HCI_EXT_SetTxPowerCmd(LL_EXT_TX_POWER_MINUS_6_DBM); simpleBLEPeripheral_TaskID = task_id; if(osal_snv_read(0xfe,1,&gMP)!=NV_OPER_FAILED){ advertData[29]=gMP; } // Setup the GAP VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL );//连接间隙 // Setup the GAP Peripheral Role Profile { #if defined( CC2540_MINIDK ) // For the CC2540DK-MINI keyfob, device doesn't start advertising until button is pressed uint8 initial_advertising_enable = FALSE; #else // For other hardware platforms, device starts advertising upon initialization uint8 initial_advertising_enable = TRUE; #endif // By setting this to zero, the device will go into the waiting state after // being discoverable for 30.72 second, and will not being advertising again // until the enabler is set back to TRUE uint16 gapRole_AdvertOffTime = 0; uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST; uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL; uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL; uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY; uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT; uint16 desired_rssi_rate=DEFAULT_DESIRED_REEI_RATE; // Set the GAP Role Parameters GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); //GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime ); GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); GAPRole_SetParameter(GAPROLE_RSSI_READ_RATE,sizeof(uint16),&desired_rssi_rate);//设定RSSI的参数值 GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request ); GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval ); GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval ); GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency ); GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout ); } // Set the GAP Characteristics GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); // Set advertising interval { uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt ); GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt ); GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt ); GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt ); } // Setup the GAP Bond Manager { uint32 passkey = 0; // passkey "000000" uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; uint8 mitm = TRUE; uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; uint8 bonding = TRUE; GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); } // Initialize GATT attributes GGS_AddService( GATT_ALL_SERVICES ); // GAP GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes DevInfo_AddService(); // Device Information Service SimpleProfile_AddService( GATT_ALL_SERVICES ); // Simple GATT Profile #if defined FEATURE_OAD VOID OADTarget_AddService(); // OAD Profile #endif // Setup the SimpleProfile Characteristic Values { uint8 charValue1 = 1; uint8 charValue2 = 0; uint8 charValue3 = 3; uint8 charValue4 = 4; uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 }; SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, sizeof ( uint8 ), &gMP ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, sizeof ( uint8 ), &charValue2 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, sizeof ( uint8 ), &charValue4 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); } #if defined( CC2540_MINIDK ) SK_AddService( GATT_ALL_SERVICES ); // Simple Keys Profile // Register for all key events - This app will handle all key events RegisterForKeys( simpleBLEPeripheral_TaskID ); // makes sure LEDs are off HalLedSet( (HAL_LED_1 | HAL_LED_2), HAL_LED_MODE_OFF ); // For keyfob board set GPIO pins into a power-optimized state // Note that there is still some leakage current from the buzzer, // accelerometer, LEDs, and buttons on the PCB. P0SEL = 0; // Configure Port 0 as GPIO P1SEL = 0; // Configure Port 1 as GPIO P2SEL = 0; // Configure Port 2 as GPIO P0DIR = 0xFC; // Port 0 pins P0.0 and P0.1 as input (buttons), // all others (P0.2-P0.7) as output P1DIR = 0xFF; // All port 1 pins (P1.0-P1.7) as output P2DIR = 0x1F; // All port 1 pins (P2.0-P2.4) as output P0 = 0x03; // All pins on port 0 to low except for P0.0 and P0.1 (buttons) P1 = 0; // All pins on port 1 to low P2 = 0; // All pins on port 2 to low #endif // #if defined( CC2540_MINIDK ) #if (defined HAL_LCD) && (HAL_LCD == TRUE) #if defined FEATURE_OAD #if defined (HAL_IMAGE_A) HalLcdWriteStringValue( "BLE Peri-A", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 ); #else HalLcdWriteStringValue( "BLE Peri-B", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 ); #endif // HAL_IMAGE_A #else HalLcdWriteString( "iBeacon", HAL_LCD_LINE_1 ); #endif // FEATURE_OAD #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) // Register callback with SimpleGATTprofile VOID SimpleProfile_RegisterAppCBs( &simpleBLEPeripheral_SimpleProfileCBs ); // Enable clock divide on halt // This reduces active current while radio is active and CC254x MCU // is halted HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_ENABLE_CLK_DIVIDE_ON_HALT ); #if defined ( DC_DC_P0_7 ) // Enable stack to toggle bypass control on TPS62730 (DC/DC converter) HCI_EXT_MapPmIoPortCmd( HCI_EXT_PM_IO_PORT_P0, HCI_EXT_PM_IO_PORT_PIN7 ); #endif // defined ( DC_DC_P0_7 ) // Setup a delayed profile startup osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT ); }
/********************************************************************* * @fn SimpleBLEPeripheral_Init * * @brief Initialization function for the Simple BLE Peripheral App Task. * This is called during initialization and should contain * any application specific initialization (ie. hardware * initialization/setup, table initialization, power up * notificaiton ... ). * * @param task_id - the ID assigned by OSAL. This ID should be * used to send messages and set timers. * * @return none */ void SimpleBLEPeripheral_Init( uint8 task_id ) { simpleBLEPeripheral_TaskID = task_id; // Setup the GAP VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL ); // Setup the GAP Peripheral Role Profile { //first turn off advertisement uint8 initial_advertising_enable = TRUE; // By setting this to zero, the device will go into the waiting state after // being discoverable for 30.72 second, and will not being advertising again // until the enabler is set back to TRUE uint16 gapRole_AdvertOffTime = 0; uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST; uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL; uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL; uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY; uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT; // Set the GAP Role Parameters GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable ); GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime ); GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData ); GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData ); GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request ); GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval ); GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval ); GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency ); GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout ); } // Set the GAP Characteristics GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName ); // Set advertising interval { uint16 advInt = DEFAULT_ADVERTISING_INTERVAL; GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt ); GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt ); GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt ); GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt ); } // Setup the GAP Bond Manager { uint32 passkey = 0; // passkey "000000" uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ; uint8 mitm = TRUE; uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY; uint8 bonding = TRUE; GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey ); GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof ( uint8 ), &pairMode ); GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm ); GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap ); GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); } // Initialize GATT attributes GGS_AddService( GATT_ALL_SERVICES ); // GAP GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes DevInfo_AddService(); // Device Information Service SimpleProfile_AddService( GATT_ALL_SERVICES ); // Simple GATT Profile #if defined FEATURE_OAD VOID OADTarget_AddService(); // OAD Profile #endif // Setup the SimpleProfile Characteristic Values { uint8 charValue1[SIMPLEPROFILE_CHAR1_LEN] = dB_DevID(0x0001) ; uint8 charValue2[SIMPLEPROFILE_CHAR2_LEN] ={0}; //uint8 charValue3 = 3; uint8 charValue4 = 4; uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = {0}; SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, SIMPLEPROFILE_CHAR1_LEN, charValue1 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, SIMPLEPROFILE_CHAR2_LEN, charValue2 ); //SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, sizeof ( uint8 ), &charValue4 ); SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 ); } #if defined (SERIAL_INTERFACE) UART_SEND_STRING( "BLE Peripheral\r\n", 16 ); #endif #if (defined HAL_LCD) && (HAL_LCD == TRUE) #if defined FEATURE_OAD #if defined (HAL_IMAGE_A) HalLcdWriteStringValue( "BLE Peri-A", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 ); #else HalLcdWriteStringValue( "BLE Peri-B", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 ); #endif // HAL_IMAGE_A #else HalLcdWriteString( "BLE Peripheral", HAL_LCD_LINE_1 ); #endif // FEATURE_OAD #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) // Register callback with SimpleGATTprofile VOID SimpleProfile_RegisterAppCBs( &simpleBLEPeripheral_SimpleProfileCBs ); // Enable clock divide on halt // This reduces active current while radio is active and CC254x MCU // is halted HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_ENABLE_CLK_DIVIDE_ON_HALT ); // Setup a delayed profile startup osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT ); //call in order to allow more CPU time for driver HCI_EXT_HaltDuringRfCmd(HCI_EXT_HALT_DURING_RF_DISABLE); // << Wayne >> << Clock >> ++ // Start clock update timer osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_CLOCK_UPDATE_EVT, DEFAULT_CLOCK_UPDATE_PERIOD ); // << Wayne >> << Clock >> -- // }
/********************************************************************* * @fn peripheralStateNotificationCB * * @brief Notification from the profile of a state change. * * @param newState - new state * * @return none */ static void peripheralStateNotificationCB(gaprole_States_t newState) { HalLcdWriteStringValue("newState", newState, 10, HAL_LCD_LINE_4); switch (newState) { case GAPROLE_STARTED: { uint8 ownAddress[B_ADDR_LEN]; uint8 systemId[DEVINFO_SYSTEM_ID_LEN]; GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress); // use 6 bytes of device address for 8 bytes of system ID value systemId[0] = ownAddress[0]; systemId[1] = ownAddress[1]; systemId[2] = ownAddress[2]; // set middle bytes to zero systemId[4] = 0x00; systemId[3] = 0x00; // shift three bytes up systemId[7] = ownAddress[5]; systemId[6] = ownAddress[4]; systemId[5] = ownAddress[3]; DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId); // Display device address HalLcdWriteString(bdAddr2Str(ownAddress), HAL_LCD_LINE_3); HalLcdWriteString("Initialized", HAL_LCD_LINE_3); } break; case GAPROLE_ADVERTISING: { HalLcdWriteString("Advertising", HAL_LCD_LINE_3); } break; case GAPROLE_CONNECTED: { HalLcdWriteString("Connected", HAL_LCD_LINE_3); //simpleProfile_StateNotify( uint16 connHandle, attHandleValueNoti_t *pNoti ) GAPRole_GetParameter(GAPROLE_CONNHANDLE, &gapConnHandle); } break; case GAPROLE_WAITING: { HalLcdWriteString("Disconnected", HAL_LCD_LINE_3); } break; case GAPROLE_WAITING_AFTER_TIMEOUT: { HalLcdWriteString("Timed Out", HAL_LCD_LINE_3); } break; case GAPROLE_ERROR: { HalLcdWriteString("Error", HAL_LCD_LINE_3); } break; default: { HalLcdWriteString("", HAL_LCD_LINE_3); } break; } gapProfileState = newState; #if !defined( CC2540_MINIDK ) VOID gapProfileState; // added to prevent compiler warning with // "CC2540 Slave" configurations #endif }
/********************************************************************* * @fn nwk_Status() * * @brief * * Status report. * * @param statusCode * @param statusValue * * @return none */ void nwk_Status( uint16 statusCode, uint16 statusValue ) { #if defined ( LCD_SUPPORTED ) switch ( statusCode ) { case NWK_STATUS_COORD_ADDR: if ( ZSTACK_ROUTER_BUILD ) { HalLcdWriteString( (char*)ZigbeeCoordStr, HAL_LCD_LINE_1 ); HalLcdWriteStringValue( (char*)NetworkIDStr, statusValue, 16, HAL_LCD_LINE_2 ); BuzzerControl( BUZZER_BLIP ); } break; case NWK_STATUS_ROUTER_ADDR: if ( ZSTACK_ROUTER_BUILD ) { HalLcdWriteStringValue( (char*)RouterStr, statusValue, 16, HAL_LCD_LINE_1 ); } break; case NWK_STATUS_ORPHAN_RSP: if ( ZSTACK_ROUTER_BUILD ) { if ( statusValue == ZSuccess ) HalLcdWriteScreen( (char*)OrphanRspStr, (char*)SentStr ); else HalLcdWriteScreen( (char*)OrphanRspStr, (char*)FailedStr ); } break; case NWK_ERROR_ASSOC_RSP: if ( ZSTACK_ROUTER_BUILD ) { HalLcdWriteString( (char*)AssocRspFailStr, HAL_LCD_LINE_1 ); HalLcdWriteValue( (uint32)(statusValue), 16, HAL_LCD_LINE_2 ); } break; case NWK_STATUS_ED_ADDR: if ( ZSTACK_END_DEVICE_BUILD ) { HalLcdWriteStringValue( (char*)EndDeviceStr, statusValue, 16, HAL_LCD_LINE_1 ); } break; case NWK_STATUS_PARENT_ADDR: HalLcdWriteStringValue( (char*)ParentStr, statusValue, 16, HAL_LCD_LINE_2 ); break; case NWK_STATUS_ASSOC_CNF: HalLcdWriteScreen( (char*)AssocCnfStr, (char*)SuccessStr ); break; case NWK_ERROR_ASSOC_CNF_DENIED: inNetwork = false; HalLcdWriteString((char*)AssocCnfFailStr, HAL_LCD_LINE_1 ); HalLcdWriteValue( (uint32)(statusValue), 16, HAL_LCD_LINE_2 ); break; case NWK_ERROR_ENERGY_SCAN_FAILED: HalLcdWriteScreen( (char*)EnergyLevelStr, (char*)ScanFailedStr ); break; } #endif }
/********************************************************************* * @fn simpleProfileChangeCB * * @brief Callback from SimpleBLEProfile indicating a value change * * @param paramID - parameter ID of the value that was changed. * * @return none */ static void simpleProfileChangeCB( uint8 paramID ) { uint8 newValue[20]; uint8 returnBytes; switch( paramID ) { case SIMPLEPROFILE_CHAR1: // 收到 CHAR1 的数据 SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, &newValue, &returnBytes); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 1:", (uint16)(newValue[0]), 10, HAL_LCD_LINE_5 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) HalLedBlink (HAL_LED_1, 1, 50, 100);//这个的意思是, 100ms内,以50%的占空比闪烁1次, 实际就是点亮50ms break; case SIMPLEPROFILE_CHAR5: // 收到 CHAR5 的数据 SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR5, &newValue, &returnBytes); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char 5[0]:", (uint16)(newValue[0]), 16, HAL_LCD_LINE_5 ); HalLcdWriteStringValue( "Char 5[1]:", (uint16)(newValue[1]), 16, HAL_LCD_LINE_6 ); HalLcdWriteStringValue( "Char 5[2]:", (uint16)(newValue[2]), 16, HAL_LCD_LINE_7 ); HalLcdWriteStringValue( "Char 5[3]:", (uint16)(newValue[3]), 16, HAL_LCD_LINE_8 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) // 设定温度更新时间, 注意高位在前 if(returnBytes == 4) { sys_config.update_time_ms = (uint32)newValue[0]<<24 | (uint32)newValue[1]<<16| (uint32)newValue[2]<<8| (uint32)newValue[3]; osal_snv_write(0x80, sizeof(SYS_CONFIG), &sys_config); // 写所有参数 if(sys_config.update_time_ms > 0) { osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_READ_SENSOR_EVT, sys_config.update_time_ms); } else { osal_stop_timerEx( simpleBLEPeripheral_TaskID, SBP_READ_SENSOR_EVT); } } HalLedBlink (HAL_LED_2, 1, 50, 100);//这个的意思是, 100ms内,以50%的占空比闪烁1次, 实际就是点亮50ms break; case SIMPLEPROFILE_CHAR6: // 这个是我们添加char6, 用于做串口透传 与从机 notify 数据到主机 很合适 SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR6, &newValue, &returnBytes); { char str[21]={0}; char str2[32]={0}; osal_memcpy(str, newValue, returnBytes); sprintf(str2,"Char 6: %s", str); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString(str2, HAL_LCD_LINE_6 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) // 通过串口透传出去,达到透传目的,amo家的透传就是使用 CHAR6 NPI_WriteTransport(newValue, returnBytes); HalLedBlink (HAL_LED_3, 1, 50, 100);//这个的意思是, 100ms内,以50%的占空比闪烁1次, 实际就是点亮50ms } break; case SIMPLEPROFILE_CHAR7: // 收到 CHAR7 的数据 SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR7, &newValue, &returnBytes); osal_memset(sys_config.name, 0, sizeof(sys_config.name)); osal_memcpy(sys_config.name, newValue, returnBytes); osal_snv_write(0x80, sizeof(SYS_CONFIG), &sys_config); // 写所有参数 HalLcdWriteString( "Char 7 Set", HAL_LCD_LINE_4 ); HalLcdWriteString( (char*)sys_config.name, HAL_LCD_LINE_5 ); // 需要重启后设备名生效 break; case SIMPLEPROFILE_CHAR8: // 收到 CHAR8 的数据 SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR8, &newValue, &returnBytes); // 最高温度报警 sys_config.tempeature_hight = newValue[0]<<8; sys_config.tempeature_hight |= newValue[1]; // 最低温度报警 sys_config.tempeature_low = newValue[2]<<8; sys_config.tempeature_low |= newValue[3]; break; case SIMPLEPROFILE_CHAR9: // adc 只读 break; case SIMPLEPROFILE_CHARA: // // pwm SimpleProfile_GetParameter( SIMPLEPROFILE_CHARA, &newValue, &returnBytes); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteStringValue( "Char A[0]:", (uint16)(newValue[0]), 16, HAL_LCD_LINE_5 ); HalLcdWriteStringValue( "Char A[1]:", (uint16)(newValue[1]), 16, HAL_LCD_LINE_6 ); HalLcdWriteStringValue( "Char A[2]:", (uint16)(newValue[2]), 16, HAL_LCD_LINE_7 ); HalLcdWriteStringValue( "Char A[3]:", (uint16)(newValue[3]), 16, HAL_LCD_LINE_8 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) // 设定pwm if(returnBytes == 4) { sys_config.pwm[3] = newValue[0]; // 白色 sys_config.pwm[2] = newValue[1]; // 红色 sys_config.pwm[1] = newValue[2]; // 绿色 sys_config.pwm[0] = newValue[3]; // 蓝色 osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_SET_PWM_EVT, 50); } break; default: // should not reach here! break; } }