/************************************************************************************************** z-stack代码,未修改 **************************************************************************************************/ void HalLcdDisplayPercentBar( char *title, uint8 value ) { #if (HAL_LCD == TRUE) uint8 percent; uint8 leftOver; uint8 buf[17]; uint32 err; uint8 x; /* Write the title: */ HalLcdWriteString( title, HAL_LCD_LINE_1 ); if ( value > 100 ) value = 100; /* convert to blocks */ percent = (uint8)(value / 10); leftOver = (uint8)(value % 10); /* Make window */ osal_memcpy( buf, "[ ] ", 15 ); for ( x = 0; x < percent; x ++ ) { buf[1+x] = '>'; } if ( leftOver >= 5 ) buf[1+x] = '+'; err = (uint32)value; _ltoa( err, (uint8*)&buf[13], 10 ); HalLcdWriteString( (char*)buf, HAL_LCD_LINE_2 ); #endif }
/********************************************************************* * @fn peripheralStateNotificationCB * * @brief Notification from the profile of a state change. * * @param newState - new state * * @return none */ static void peripheralStateNotificationCB( gaprole_States_t newState ) { switch ( newState ) { case GAPROLE_STARTED: { uint8 ownAddress[B_ADDR_LEN]; GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress); #if (defined HAL_LCD) && (HAL_LCD == TRUE) // Display device address HalLcdWriteString( bdAddr2Str( ownAddress ), HAL_LCD_LINE_2 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_ADVERTISING: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_WAITING: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_ERROR: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; default: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; } }
/************************************************************************************************** * @fn pulseAfMsgRx * * @brief This function is called by pulseSysEvtMsg() to process an incoming AF message. * * input parameters * * @param msg - A pointer to the afIncomingMSGPacket_t packet. * * output parameters * * None. * * @return None. ************************************************************************************************** */ static void pulseAfMsgRx(afIncomingMSGPacket_t *msg) { uint8 *buf = msg->cmd.Data; if(PanEstablishedwithRouter == FALSE & devState == DEV_ZB_COORD){ if(zap_set_logicalType(ZG_DEVICETYPE_ROUTER)){ HalLcdWriteString("Should be Router",HAL_LCD_LINE_7); } PanEstablishedwithRouter = TRUE; if (ZSuccess != osal_start_timerEx(pulseTaskId, PULSE_EVT_ANN, PULSE_DLY_ANN)) { (void)osal_set_event(pulseTaskId, PULSE_EVT_ANN); } } else{ switch (buf[PULSE_CMD_IDX]) { case PULSE_CMD_DAT: //Nodes will send this by default pulseDataRx(msg); break; case PULSE_CMD_BEG: if (INVALID_NODE_ADDR == pulseAddr) { NLME_SetPollRate(0); if(PulseEvtDat_sync == FALSE){ (void)osal_set_event(pulseTaskId, PULSE_EVT_DAT); //Sync Pulsedat event operation } } pulseAddr = msg->srcAddr.addr.shortAddr; // BUILD_UINT16(buf[PULSE_ADR_LSB], buf[PULSE_ADR_MSB]); break; case PULSE_CMD_END: NLME_SetPollRate(POLL_RATE); pulseAddr = INVALID_NODE_ADDR; break; case PULSE_CMD_DAT_TEST: //This is used for testing different payload sizes. Not used in normal operation pulseTestingDataRx(msg); break; default: break; } } //end else }
/********************************************************************* * @fn zclSampleSw_Init * * @brief Initialization function for the zclGeneral layer. * * @param none * * @return none */ void zclSampleSw_Init( byte task_id ) { zclSampleSw_TaskID = task_id; #ifdef ZCL_ON_OFF // Set destination address to indirect zclSampleSw_DstAddr.addrMode = (afAddrMode_t)AddrNotPresent; zclSampleSw_DstAddr.endPoint = 0; zclSampleSw_DstAddr.addr.shortAddr = 0; #endif // This app is part of the Home Automation Profile zclHA_Init( &zclSampleSw_SimpleDesc ); // Register the ZCL General Cluster Library callback functions zclGeneral_RegisterCmdCallbacks( SAMPLESW_ENDPOINT, &zclSampleSw_CmdCallbacks ); // Register the application's attribute list zcl_registerAttrList( SAMPLESW_ENDPOINT, SAMPLESW_MAX_ATTRIBUTES, zclSampleSw_Attrs ); // Register the Application to receive the unprocessed Foundation command/response messages zcl_registerForMsg( zclSampleSw_TaskID ); #ifdef ZCL_EZMODE // Register EZ-Mode zcl_RegisterEZMode( &zclSampleSw_RegisterEZModeData ); // Register with the ZDO to receive Match Descriptor Responses ZDO_RegisterForZDOMsg(task_id, Match_Desc_rsp); #endif // Register for all key events - This app will handle all key events RegisterForKeys( zclSampleSw_TaskID ); // Register for a test endpoint afRegister( &sampleSw_TestEp ); ZDO_RegisterForZDOMsg( zclSampleSw_TaskID, End_Device_Bind_rsp ); ZDO_RegisterForZDOMsg( zclSampleSw_TaskID, Match_Desc_rsp ); #ifdef LCD_SUPPORTED HalLcdWriteString ( (char *)sDeviceName, HAL_LCD_LINE_3 ); #endif #if defined (OTA_CLIENT) && (OTA_CLIENT == TRUE) // Register for callback events from the ZCL OTA zclOTA_Register(zclSampleSw_TaskID); #endif }
// << Wayne >> << dBCmd Service >> ++ void dBCommand_Service(uint8 *pCmd) { if(osal_memcmp( pCmd, DBCMD_COMFIRM_TICKET, DBCMD_COMFIRM_TICKET_LEN)) { repeatCmdSendData("s,et,01,cfm,0005,e",18); // << Wayne >> << Exchanging Take >> ++ dbExchangeCounter++; // << Wayne >> << Exchanging Take >> -- UART_SEND_STRING(pCmd,19); #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Confirm", HAL_LCD_LINE_6 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } else if(osal_memcmp( pCmd, DBCMD_READ_EXCHANGE_NUMBER, DBCMD_READ_EXCHANGE_NUMBER_LEN)) { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "ReadCounter", HAL_LCD_LINE_6 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) num2Str_Max4L( &pCmd[12], dbExchangeCounter, 4); UART_SEND_DEBUG_MSG( pCmd, 18 ); repeatCmdSendData(pCmd,18); } }
/************************************************************************************************** * @fn HalLcdWriteStringValue * * @brief Write a string followed by a value to the LCD * * @param title - Title that will be displayed before the value * value - value * format - redix * line - line number * * @return None **************************************************************************************************/ void HalLcdWriteStringValue( char *title, uint16 value, uint8 format, uint8 line ) { #if (HAL_LCD == TRUE) uint8 tmpLen; uint8 buf[LCD_MAX_BUF]; uint32 err; tmpLen = (uint8)osal_strlen( (char*)title ); osal_memcpy( buf, title, tmpLen ); buf[tmpLen] = ' '; err = (uint32)(value); _ltoa( err, &buf[tmpLen+1], format ); HalLcdWriteString( (char*)buf, line ); #endif }
/****************************************************************************** * @fn zb_StartConfirm * * @brief The zb_StartConfirm callback is called by the ZigBee stack * after a start request operation completes * * @param status - The status of the start operation. Status of * ZB_SUCCESS indicates the start operation completed * successfully. Else the status is an error code. * * @return none */ void zb_StartConfirm( uint8 status ) { // If the device sucessfully started, change state to running if ( status == ZB_SUCCESS ) { // Change application state appState = APP_START; // Set LED 1 to indicate that node is operational on the network HalLedSet( HAL_LED_1, HAL_LED_MODE_ON ); // Update the display #if defined ( LCD_SUPPORTED ) HalLcdWriteString( "SensorDemo", HAL_LCD_LINE_1 ); HalLcdWriteString( "Sensor", HAL_LCD_LINE_2 ); #endif // Store parent short address zb_GetDeviceInfo(ZB_INFO_PARENT_SHORT_ADDR, &parentShortAddr); // Set event to bind to a collector osal_set_event( sapi_TaskID, MY_FIND_COLLECTOR_EVT ); } }
/********************************************************************* * @fn ipd_PublishPriceCB * * @brief Callback from the ZCL SE Profile Pricing Cluster Library when * it received a Publish Price for this application. * * @param pCmd - pointer to structure for Publish Price command * @param srcAddr - source address * @param seqNum - sequence number for this command * * @return none */ static void ipd_PublishPriceCB( zclCCPublishPrice_t *pCmd, afAddrType_t *srcAddr, uint8 seqNum ) { if ( pCmd ) { // display Provider ID field HalLcdWriteString("Provider ID", HAL_LCD_LINE_1); HalLcdWriteValue( pCmd->providerId, 10, HAL_LCD_LINE_2 ); } #if defined ( INTER_PAN ) ZMacSetReq( ZMacRxOnIdle, &rxOnIdle ); // set receiver on when idle flag to false // after getting publish price command via INTER-PAN #endif }
/********************************************************************* * @fn zclSampleSw_LcdDisplayMainMode * * @brief Called to display the main screen on the LCD. * * @param none * * @return none */ void zclSampleSw_LcdDisplayMainMode(void) { if ( zclSampleSw_NwkState == DEV_ZB_COORD ) { zclHA_LcdStatusLine1(0); } else if ( zclSampleSw_NwkState == DEV_ROUTER ) { zclHA_LcdStatusLine1(1); } else if ( zclSampleSw_NwkState == DEV_END_DEVICE ) { zclHA_LcdStatusLine1(2); } #ifdef LCD_SUPPORTED if ( ( zclSampleSw_NwkState == DEV_ZB_COORD ) || ( zclSampleSw_NwkState == DEV_ROUTER ) ) { // display help key with permit join status if ( gPermitDuration ) { HalLcdWriteString("SW5: Help *", HAL_LCD_LINE_3); } else { HalLcdWriteString("SW5: Help ", HAL_LCD_LINE_3); } } else { // display help key HalLcdWriteString((char *)sSwHelp, HAL_LCD_LINE_3); } #endif }
/********************************************************************* * @fn SerialApp_Init * * @brief This is called during OSAL tasks' initialization. * * @param task_id - the Task ID assigned by OSAL. * * @return none */ void SerialApp_Init( uint8 task_id ) { halUARTCfg_t uartConfig; SerialApp_MsgID = 0x00; SerialApp_SeqRx = 0xC3; SerialApp_TaskID = task_id; SerialApp_DstAddr.endPoint = 0; SerialApp_DstAddr.addr.shortAddr = 0; SerialApp_DstAddr.addrMode = (afAddrMode_t)AddrNotPresent; SerialApp_RspDstAddr.endPoint = 0; SerialApp_RspDstAddr.addr.shortAddr = 0; SerialApp_RspDstAddr.addrMode = (afAddrMode_t)AddrNotPresent; afRegister( (endPointDesc_t *)&SerialApp_epDesc ); RegisterForKeys( task_id ); uartConfig.configured = TRUE; // 2430 don't care. uartConfig.baudRate = SERIAL_APP_BAUD; uartConfig.flowControl = TRUE; uartConfig.flowControlThreshold = SERIAL_APP_THRESH; uartConfig.rx.maxBufSize = SERIAL_APP_RX_MAX; uartConfig.tx.maxBufSize = SERIAL_APP_TX_MAX; uartConfig.idleTimeout = SERIAL_APP_IDLE; // 2430 don't care. uartConfig.intEnable = TRUE; // 2430 don't care. #if SERIAL_APP_LOOPBACK uartConfig.callBackFunc = rxCB_Loopback; #else uartConfig.callBackFunc = rxCB; #endif HalUARTOpen (SERIAL_APP_PORT, &uartConfig); #if defined ( LCD_SUPPORTED ) HalLcdWriteString( "SerialApp2", HAL_LCD_LINE_2 ); #endif HalLedSet(HAL_LED_1,HAL_LED_MODE_OFF); HalLedSet(HAL_LED_2,HAL_LED_MODE_OFF); HalLedSet(HAL_LED_3,HAL_LED_MODE_OFF); ZDO_RegisterForZDOMsg( SerialApp_TaskID, End_Device_Bind_rsp ); ZDO_RegisterForZDOMsg( SerialApp_TaskID, Match_Desc_rsp ); osal_start_timerEx(SerialApp_TaskID,SERIALAPP_MSG_AUTOMATCH,2000); }
/********************************************************************* * @fn GenericApp_Init * * @brief Initialization function for the Generic 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 GenericApp_Init( byte task_id ) { GenericApp_TaskID = task_id; GenericApp_NwkState = DEV_INIT; GenericApp_TransID = 0; // Device hardware initialization can be added here or in main() (Zmain.c). // If the hardware is application specific - add it here. // If the hardware is other parts of the device add it in main(). GenericApp_DstAddr.addrMode = (afAddrMode_t)AddrNotPresent; GenericApp_DstAddr.endPoint = 0; GenericApp_DstAddr.addr.shortAddr = 0; // Fill out the endpoint description. GenericApp_epDesc.endPoint = GENERICAPP_ENDPOINT; GenericApp_epDesc.task_id = &GenericApp_TaskID; GenericApp_epDesc.simpleDesc = (SimpleDescriptionFormat_t *)&GenericApp_SimpleDesc; GenericApp_epDesc.latencyReq = noLatencyReqs; // Register the endpoint description with the AF afRegister( &GenericApp_epDesc ); // Register for all key events - This app will handle all key events RegisterForKeys( GenericApp_TaskID ); // Update the display #if defined ( LCD_SUPPORTED ) HalLcdWriteString( "GenericApp", HAL_LCD_LINE_1 ); #endif ZDO_RegisterForZDOMsg( GenericApp_TaskID, End_Device_Bind_rsp ); ZDO_RegisterForZDOMsg( GenericApp_TaskID, Match_Desc_rsp ); ZDO_RegisterForZDOMsg( GenericApp_TaskID, SPI_INCOMING_ZAPP_DATA ); /*****for SHP *************begin******************/{ //extern void shp_example_init_called_by_system(void); //shp_example_init_called_by_system(); /*****for SHP *************end********************/} //QBing MT_UartRegisterTaskID(GenericApp_TaskID); MT_UartZAppBufferLengthRegister(100); osal_start_timerEx(GenericApp_TaskID,GENERICAPP_TIMER_EVT,1000); }
/********************************************************************* * @fn ipd_DisplayMessageCB * * @brief Callback from the ZCL SE Profile Message Cluster Library when * it received a Display Message Command for * this application. * * @param pCmd - pointer to structure for Display Message command * @param srcAddr - source address * @param seqNum - sequence number for this command * * @return none */ static void ipd_DisplayMessageCB( zclCCDisplayMessage_t *pCmd, afAddrType_t *srcAddr, uint8 seqNum ) { // Upon receipt of the Display Message Command, the device shall // display the message. If the Message Confirmation bit indicates // the message originator require a confirmation of receipt from // a Utility Customer, the device should display the message or // alert the user until it is either confirmed via a button or by // selecting a confirmation option on the device. Confirmation is // typically used when the Utility is sending down information // such as a disconnection notice, or prepaid billing information. // Message duration is ignored when confirmation is requested and // the message is displayed until confirmed. #if defined ( LCD_SUPPORTED ) HalLcdWriteString( (char*)pCmd->msgString.pStr, HAL_LCD_LINE_3 ); #endif // LCD_SUPPORTED }
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); } }
/** * @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 zclSampleTemperatureSensor_Init * * @brief Initialization function for the zclGeneral layer. * * @param none * * @return none */ void zclSampleTemperatureSensor_Init( byte task_id ) { zclSampleTemperatureSensor_TaskID = task_id; // Set destination address to indirect zclSampleTemperatureSensor_DstAddr.addrMode = (afAddrMode_t)AddrNotPresent; zclSampleTemperatureSensor_DstAddr.endPoint = 0; zclSampleTemperatureSensor_DstAddr.addr.shortAddr = 0; // This app is part of the Home Automation Profile zclHA_Init( &zclSampleTemperatureSensor_SimpleDesc ); // Register the ZCL General Cluster Library callback functions zclGeneral_RegisterCmdCallbacks( SAMPLETEMPERATURESENSOR_ENDPOINT, &zclSampleTemperatureSensor_CmdCallbacks ); // Register the application's attribute list zcl_registerAttrList( SAMPLETEMPERATURESENSOR_ENDPOINT, SAMPLETEMPERATURESENSOR_MAX_ATTRIBUTES, zclSampleTemperatureSensor_Attrs ); // Register the Application to receive the unprocessed Foundation command/response messages zcl_registerForMsg( zclSampleTemperatureSensor_TaskID ); #ifdef ZCL_EZMODE // Register EZ-Mode zcl_RegisterEZMode( &zclSampleTemperatureSensor_RegisterEZModeData ); // Register with the ZDO to receive Match Descriptor Responses ZDO_RegisterForZDOMsg(task_id, Match_Desc_rsp); #endif // Register for all key events - This app will handle all key events RegisterForKeys( zclSampleTemperatureSensor_TaskID ); // Register for a test endpoint afRegister( &sampleTemperatureSensor_TestEp ); #ifdef LCD_SUPPORTED // display the device name HalLcdWriteString( (char *)sDeviceName, HAL_LCD_LINE_3 ); #endif }
/********************************************************************* * @fn GenericApp_Init * * @brief Initialization function for the Generic 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 GenericApp_Init( uint8 task_id ) { GenericApp_TaskID = task_id; GenericApp_NwkState = DEV_INIT; GenericApp_TransID = 0; // Device hardware initialization can be added here or in main() (Zmain.c). // If the hardware is application specific - add it here. // If the hardware is other parts of the device add it in main(). GenericApp_DstAddr.addrMode = (afAddrMode_t)Addr16Bit; GenericApp_DstAddr.endPoint = 2; GenericApp_DstAddr.addr.shortAddr = 0x0000; // Fill out the endpoint description. GenericApp_epDesc.endPoint = GENERICAPP_ENDPOINT; GenericApp_epDesc.task_id = &GenericApp_TaskID; GenericApp_epDesc.simpleDesc = (SimpleDescriptionFormat_t *)&GenericApp_SimpleDesc; GenericApp_epDesc.latencyReq = noLatencyReqs; // Register the endpoint description with the AF afRegister( &GenericApp_epDesc ); // Register for all key events - This app will handle all key events RegisterForKeys( GenericApp_TaskID ); // Update the display #if defined ( LCD_SUPPORTED ) HalLcdWriteString( "GenericApp", HAL_LCD_LINE_1 ); #endif ZDO_RegisterForZDOMsg( GenericApp_TaskID, End_Device_Bind_rsp ); ZDO_RegisterForZDOMsg( GenericApp_TaskID, Match_Desc_rsp ); #if defined( IAR_ARMCM3_LM ) // Register this task with RTOS task initiator RTOS_RegisterApp( task_id, GENERICAPP_RTOS_MSG_EVT ); #endif }
//Initialization function for the Park Way task. This is called during initialization and should contain any application specific initialization (ie. hardware initialization/setup, table initialization, power up notificaiton ... ) void ParkWay_Init( uint8 task_id ) { ParkWay_TaskID = task_id; ParkWay_NwkState = DEV_INIT; ParkWay_TransID = 0; // Device hardware initialization can be added here or in main() (Zmain.c). // If the hardware is application specific - add it here. // If the hardware is other parts of the device add it in main(). ParkWay_DstAddr.addrMode = (afAddrMode_t)AddrNotPresent; ParkWay_DstAddr.endPoint = 0; ParkWay_DstAddr.addr.shortAddr = 0; // Fill out the endpoint description. ParkWay_epDesc.endPoint = ParkWay_ENDPOINT; ParkWay_epDesc.task_id = &ParkWay_TaskID; ParkWay_epDesc.simpleDesc = (SimpleDescriptionFormat_t *)&ParkWay_SimpleDesc; ParkWay_epDesc.latencyReq = noLatencyReqs; // Register the endpoint description with the AF afRegister( &ParkWay_epDesc ); // Register for all key events - This app will handle all key events RegisterForKeys( ParkWay_TaskID ); // Update the display #if defined ( LCD_SUPPORTED ) HalLcdWriteString( "ParkWay-Coord", HAL_LCD_LINE_1 ); #endif ZDO_RegisterForZDOMsg( ParkWay_TaskID, End_Device_Bind_rsp ); ZDO_RegisterForZDOMsg( ParkWay_TaskID, Match_Desc_rsp ); osal_start_timerEx( ParkWay_TaskID, POLL_PARWAY_EVT, TIME_PARKWAY_POLL); }
/********************************************************************* * @fn zclHA_LcdStatusLine1 * * @brief Display LCD line 1 with network status * only call after on network * ZC: PPPP CH ADDR * ZR: PPPP CH ADDR * ZE: PPPP CH ADDR * * @param kind (0=ZC, 1=ZR, 2=ZED) * * @return none */ void zclHA_LcdStatusLine1( uint8 kind ) { #if defined ( LCD_SUPPORTED ) char szLine[20]; // copy in what node type it is if ( kind > ZCL_HA_DEVICE_END_DEVICE ) { return; } // ZE: PANx CH ADDR osal_memcpy( szLine, NwkInfoStrs[kind], 4 ); zclHA_uint16toa( _NIB.nwkPanId, &szLine[4] ); szLine[8] = ' '; _ltoa( _NIB.nwkLogicalChannel, (void *)(&szLine[9]), 10 ); szLine[11] = ' '; zclHA_uint16toa( _NIB.nwkDevAddress, &szLine[12] ); HalLcdWriteString( (char*)szLine, HAL_LCD_LINE_1 ); #endif }
/********************************************************************* * @fn SampleApp_Init * * @brief Initialization function for the Generic 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 SampleApp_Init( uint8 task_id ) { SampleApp_TaskID = task_id; SampleApp_NwkState = DEV_INIT; SampleApp_TransID = 0; MT_UartInit();//串口初始化 MT_UartRegisterTaskID(task_id);//登记任务号 #ifdef MODE_ED //终端节点下才配置 /**************超声波***************/ #define trig P0_1 #define echo P0_0 P0DIR |= 0x02; //P01输出trig P0DIR &= ~0x01; //P00输入echo trig=0; /*定时器配置*/ HalTimerInit(); HalTimerConfig(HAL_TIMER_0, HAL_TIMER_MODE_CTC, HAL_TIMER_CHANNEL_SINGLE, HAL_TIMER_CH_MODE_OUTPUT_COMPARE, TRUE, timer_callback); /***********步进电机**************/ #define in1 P0_4 #define in2 P0_5 #define in3 P0_6 #define in4 P0_7 P0SEL &=~0xf0; P0DIR |= 0xf0; P0INP &=~0Xf0; //打开上拉 in1=0; in2=0; in3=0; in4=0; /*测试*/ int i=0; for(i=0;i<128;i++) { MotorCW(); } for(i=0;i<128;i++) { MotorCCW(); } HalLedBlink( HAL_LED_2, 2,50, 500); #endif // Device hardware initialization can be added here or in main() (Zmain.c). // If the hardware is application specific - add it here. // If the hardware is other parts of the device add it in main(). #if defined ( BUILD_ALL_DEVICES ) // The "Demo" target is setup to have BUILD_ALL_DEVICES and HOLD_AUTO_START // We are looking at a jumper (defined in SampleAppHw.c) to be jumpered // together - if they are - we will start up a coordinator. Otherwise, // the device will start as a router. if ( readCoordinatorJumper() ) zgDeviceLogicalType = ZG_DEVICETYPE_COORDINATOR; else zgDeviceLogicalType = ZG_DEVICETYPE_ROUTER; #endif // BUILD_ALL_DEVICES #if defined ( HOLD_AUTO_START ) // HOLD_AUTO_START is a compile option that will surpress ZDApp // from starting the device and wait for the application to // start the device. ZDOInitDevice(0); #endif // Setup for the periodic message's destination address // Broadcast to everyone SampleApp_Periodic_DstAddr.addrMode = (afAddrMode_t)AddrBroadcast; SampleApp_Periodic_DstAddr.endPoint = SAMPLEAPP_ENDPOINT; SampleApp_Periodic_DstAddr.addr.shortAddr = 0xFFFF; // Setup for the flash command's destination address - Group 1 SampleApp_Flash_DstAddr.addrMode = (afAddrMode_t)afAddrGroup; SampleApp_Flash_DstAddr.endPoint = SAMPLEAPP_ENDPOINT; SampleApp_Flash_DstAddr.addr.shortAddr = SAMPLEAPP_FLASH_GROUP; // 网蜂点对点通讯定义 Point_To_Point_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;//点播 Point_To_Point_DstAddr.endPoint = SAMPLEAPP_ENDPOINT; Point_To_Point_DstAddr.addr.shortAddr = 0x0000; //发给协调器 // Fill out the endpoint description. SampleApp_epDesc.endPoint = SAMPLEAPP_ENDPOINT; SampleApp_epDesc.task_id = &SampleApp_TaskID; SampleApp_epDesc.simpleDesc = (SimpleDescriptionFormat_t *)&SampleApp_SimpleDesc; SampleApp_epDesc.latencyReq = noLatencyReqs; // Register the endpoint description with the AF afRegister( &SampleApp_epDesc ); // Register for all key events - This app will handle all key events RegisterForKeys( SampleApp_TaskID ); // By default, all devices start out in Group 1 SampleApp_Group.ID = 0x0001; osal_memcpy( SampleApp_Group.name, "Group 1", 7 ); aps_AddGroup( SAMPLEAPP_ENDPOINT, &SampleApp_Group ); #if defined ( LCD_SUPPORTED ) HalLcdWriteString( "SmartPark", HAL_LCD_LINE_1 ); #endif }
/************************************************************************************************** z-stack代码,未修改 **************************************************************************************************/ void HalLcdWriteString ( char *str, uint8 option) { #ifdef LCD_TO_UART NPI_WriteTransport ( (uint8*)str,osal_strlen(str)); NPI_WriteTransport ("\r\n",2); #endif #if (HAL_LCD == TRUE) uint8 strLen = 0; uint8 totalLen = 0; uint8 *buf; uint8 tmpLen; if ( Lcd_Line1 == NULL ) { Lcd_Line1 = osal_mem_alloc( HAL_LCD_MAX_CHARS+1 ); HalLcdWriteString( "TexasInstruments", 1 ); } strLen = (uint8)osal_strlen( (char*)str ); /* Check boundries */ if ( strLen > HAL_LCD_MAX_CHARS ) strLen = HAL_LCD_MAX_CHARS; if ( option == HAL_LCD_LINE_1 ) { /* Line 1 gets saved for later */ osal_memcpy( Lcd_Line1, str, strLen ); Lcd_Line1[strLen] = '\0'; } else { /* Line 2 triggers action */ tmpLen = (uint8)osal_strlen( (char*)Lcd_Line1 ); totalLen = tmpLen + 1 + strLen + 1; buf = osal_mem_alloc( totalLen ); if ( buf != NULL ) { /* Concatenate strings */ osal_memcpy( buf, Lcd_Line1, tmpLen ); buf[tmpLen++] = ' '; osal_memcpy( &buf[tmpLen], str, strLen ); buf[tmpLen+strLen] = '\0'; /* Send it out */ #if defined (ZTOOL_P1) || defined (ZTOOL_P2) #if defined(SERIAL_DEBUG_SUPPORTED) debug_str( (uint8*)buf ); #endif //LCD_SUPPORTED #endif //ZTOOL_P1 /* Free mem */ osal_mem_free( buf ); } } /* Display the string */ HalLcd_HW_WriteLine (option, str); #endif //HAL_LCD }
/********************************************************************* * @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 peripheralStateNotificationCB * * @brief Notification from the profile of a state change. * * @param newState - new state * * @return none */ static void peripheralStateNotificationCB( gaprole_States_t newState ) { 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); #if (defined HAL_LCD) && (HAL_LCD == TRUE) // Display device address HalLcdWriteString( bdAddr2Str( ownAddress ), HAL_LCD_LINE_2 ); HalLcdWriteString( "Initialized", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_ADVERTISING: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Advertising", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) HalLedSet( HAL_LED_2, HAL_LED_MODE_ON ); } break; case GAPROLE_CONNECTED: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Connected", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) HalLedSet( HAL_LED_2, HAL_LED_MODE_OFF ); } break; case GAPROLE_WAITING: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Disconnected", HAL_LCD_LINE_3 ); P0_7=0; #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_WAITING_AFTER_TIMEOUT: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Timed Out", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_ERROR: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Error", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; default: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; } gapProfileState = newState; #if !defined( CC2540_MINIDK ) VOID gapProfileState; // added to prevent compiler warning with // "CC2540 Slave" configurations #endif }
/********************************************************************* * @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 TransmitApp_DisplayResults * * @brief Display the results and clear the accumulators * * @param none * * @return none */ void TransmitApp_DisplayResults( void ) { #ifdef LCD_SUPPORTED #define LCD_W 16 uint32 rxShdw, txShdw, tmp; byte lcd_buf[LCD_W+1]; byte idx; #endif // The OSAL timers are not real-time, so calculate the actual time expired. uint32 msecs = osal_GetSystemClock() - clkShdw; clkShdw = osal_GetSystemClock(); rxTotal += rxAccum; txTotal += txAccum; #if defined ( LCD_SUPPORTED ) rxShdw = (rxAccum * 1000 + msecs/2) / msecs; txShdw = (txAccum * 1000 + msecs/2) / msecs; osal_memset( lcd_buf, ' ', LCD_W ); lcd_buf[LCD_W] = NULL; idx = 4; tmp = (rxShdw >= 100000) ? 99999 : rxShdw; do { lcd_buf[idx--] = (uint8) ('0' + (tmp % 10)); tmp /= 10; } while ( tmp ); idx = LCD_W-1; tmp = rxTotal; do { lcd_buf[idx--] = (uint8) ('0' + (tmp % 10)); tmp /= 10; } while ( tmp ); HalLcdWriteString( (char*)lcd_buf, HAL_LCD_LINE_1 ); osal_memset( lcd_buf, ' ', LCD_W ); idx = 4; tmp = (txShdw >= 100000) ? 99999 : txShdw; do { lcd_buf[idx--] = (uint8) ('0' + (tmp % 10)); tmp /= 10; } while ( tmp ); idx = LCD_W-1; tmp = txTotal; do { lcd_buf[idx--] = (uint8) ('0' + (tmp % 10)); tmp /= 10; } while ( tmp ); HalLcdWriteString( (char*)lcd_buf, HAL_LCD_LINE_2 ); #else DEBUG_INFO( COMPID_APP, SEVERITY_INFORMATION, 3, rxAccum, (uint16)msecs, (uint16)rxTotal ); #endif if ( (rxAccum == 0) && (txAccum == 0) ) { osal_stop_timerEx( TransmitApp_TaskID, TRANSMITAPP_RCVTIMER_EVT ); timerOn = FALSE; } rxAccum = txAccum = 0; }
void SampleApp_Init( uint8 task_id ) { SampleApp_TaskID = task_id; SampleApp_NwkState = DEV_INIT; SampleApp_TransID = 0; //uart open(SampleApp_TaskID); // Device hardware initialization can be added here or in main() (Zmain.c). // If the hardware is application specific - add it here. // If the hardware is other parts of the device add it in main(). #if defined ( SOFT_START ) // The "Demo" target is setup to have SOFT_START and HOLD_AUTO_START // SOFT_START is a compile option that allows the device to start // as a coordinator if one isn't found. // We are looking at a jumper (defined in SampleAppHw.c) to be jumpered // together - if they are - we will start up a coordinator. Otherwise, // the device will start as a router. if ( readCoordinatorJumper() ) zgDeviceLogicalType = ZG_DEVICETYPE_COORDINATOR; else zgDeviceLogicalType = ZG_DEVICETYPE_ROUTER; #endif // SOFT_START #if defined ( HOLD_AUTO_START ) // HOLD_AUTO_START is a compile option that will surpress ZDApp // from starting the device and wait for the application to // start the device. ZDOInitDevice(0); #endif // Setup for the periodic message's destination address // Broadcast to everyone SampleApp_Periodic_DstAddr.addrMode = (afAddrMode_t)AddrBroadcast; SampleApp_Periodic_DstAddr.endPoint = SAMPLEAPP_ENDPOINT; SampleApp_Periodic_DstAddr.addr.shortAddr = 0xFFFF; // Setup for the flash command's destination address - Group 1 SampleApp_Flash_DstAddr.addrMode = (afAddrMode_t)Addr16Bit; SampleApp_Flash_DstAddr.endPoint = SAMPLEAPP_ENDPOINT; SampleApp_Flash_DstAddr.addr.shortAddr = 0xFFFF; //�s�� //end device /* coordinator to end device must 0xffff end device to coordinator must 0x0000 */ //mpleApp_Flash_DstAddr.addr.shortAddr = 0x0000; //SampleApp_Flash_DstAddr.addr.shortAddr =SAMPLEAPP_FLASH_GROUP; //coordinator // Fill out the endpoint description. SampleApp_epDesc.endPoint = SAMPLEAPP_ENDPOINT; SampleApp_epDesc.task_id = &SampleApp_TaskID; SampleApp_epDesc.simpleDesc = (SimpleDescriptionFormat_t *)&SampleApp_SimpleDesc; SampleApp_epDesc.latencyReq = noLatencyReqs; // Register the endpoint description with the AF afRegister( &SampleApp_epDesc ); // Register for all key events - This app will handle all key events RegisterForKeys( SampleApp_TaskID ); // By default, all devices start out in Group 1 SampleApp_Group.ID = SAMPLEAPP_FLASH_GROUP; osal_memcpy( SampleApp_Group.name, "Group 1", 7 ); aps_AddGroup( SAMPLEAPP_ENDPOINT, &SampleApp_Group ); #if defined( HAL_UART ) open(SampleApp_TaskID); #endif #if defined ( LCD_SUPPORTED ) HalLcdWriteString( "SampleApp", HAL_LCD_LINE_1 ); #endif }
/********************************************************************* * @fn loadcontrol_event_loop * * @brief Event Loop Processor for loadcontrol. * * @param uint8 task id - load control task id * @param uint16 events - event bitmask * * @return none */ uint16 loadcontrol_event_loop( uint8 task_id, uint16 events ) { afIncomingMSGPacket_t *MSGpkt; if ( events & SYS_EVENT_MSG ) { while ( (MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( loadControlTaskID )) ) { switch ( MSGpkt->hdr.event ) { case ZDO_CB_MSG: loadcontrol_ProcessZDOMsgs( (zdoIncomingMsg_t *)MSGpkt ); break; case ZCL_INCOMING_MSG: // Incoming ZCL foundation command/response messages loadcontrol_ProcessZCLMsg( (zclIncomingMsg_t *)MSGpkt ); break; case KEY_CHANGE: loadcontrol_HandleKeys( ((keyChange_t *)MSGpkt)->state, ((keyChange_t *)MSGpkt)->keys ); break; case ZDO_STATE_CHANGE: if (DEV_ROUTER == (devStates_t)(MSGpkt->hdr.status)) { #if SECURE { // check to see if link key had already been established linkKeyStatus = loadcontrol_KeyEstablish_ReturnLinkKey(ESPAddr.addr.shortAddr); if (linkKeyStatus != ZSuccess) { cId_t cbkeCluster = ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT; zAddrType_t dstAddr; // Send out a match for the key establishment dstAddr.addrMode = AddrBroadcast; dstAddr.addr.shortAddr = NWK_BROADCAST_SHORTADDR; ZDP_MatchDescReq( &dstAddr, NWK_BROADCAST_SHORTADDR, ZCL_SE_PROFILE_ID, 1, &cbkeCluster, 0, NULL, FALSE ); } } #endif } break; #if defined( ZCL_KEY_ESTABLISH ) case ZCL_KEY_ESTABLISH_IND: if ((MSGpkt->hdr.status) == TermKeyStatus_Success) { ESPAddr.endPoint = LOADCONTROL_ENDPOINT; // set destination endpoint back to application endpoint } break; #endif default: break; } // Release the memory osal_msg_deallocate( (uint8 *)MSGpkt ); } // return unprocessed events return (events ^ SYS_EVENT_MSG); } // event to intiate key establishment request if ( events & LOADCONTROL_KEY_ESTABLISHMENT_REQUEST_EVT ) { zclGeneral_KeyEstablish_InitiateKeyEstablishment(loadControlTaskID, &ESPAddr, loadControlTransID); return ( events ^ LOADCONTROL_KEY_ESTABLISHMENT_REQUEST_EVT ); } // handle processing of identify timeout event triggered by an identify command if ( events & LOADCONTROL_IDENTIFY_TIMEOUT_EVT ) { if ( loadControlIdentifyTime > 0 ) { loadControlIdentifyTime--; } loadcontrol_ProcessIdentifyTimeChange(); return ( events ^ LOADCONTROL_IDENTIFY_TIMEOUT_EVT ); } // event to get current time if ( events & LOADCONTROL_UPDATE_TIME_EVT ) { loadControlTime = osal_getClock(); osal_start_timerEx( loadControlTaskID, LOADCONTROL_UPDATE_TIME_EVT, LOADCONTROL_UPDATE_TIME_PERIOD ); return ( events ^ LOADCONTROL_UPDATE_TIME_EVT ); } // event to handle load control complete event if ( events & LOADCONTROL_LOAD_CTRL_EVT ) { // load control evt completed // Send response back // DisableDefaultResponse is set to FALSE - it is recommended to turn on // default response since Report Event Status Command does not have // a response. rsp.eventStatus = EVENT_STATUS_LOAD_CONTROL_EVENT_COMPLETED; zclSE_LoadControl_Send_ReportEventStatus( LOADCONTROL_ENDPOINT, &ESPAddr, &rsp, FALSE, loadControlTransID ); HalLcdWriteString("Load Evt Complete", HAL_LCD_LINE_3); HalLedSet(HAL_LED_4, HAL_LED_MODE_OFF); return ( events ^ LOADCONTROL_LOAD_CTRL_EVT ); } // Discard unknown events return 0; }
/********************************************************************* * @fn SimpleBLEBroadcaster_Init * * @brief Initialization function for the Simple BLE Broadcaster 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 SimpleBLEBroadcaster_Init( uint8 task_id ) { simpleBLEBroadcaster_TaskID = task_id; // Setup the GAP Broadcaster 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 advType = GAP_ADTYPE_ADV_NONCONN_IND; // use non-connectable advertisements uint8 advType = GAP_ADTYPE_ADV_SCAN_IND; // use scannable unidirected advertisements // 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_ADV_EVENT_TYPE, sizeof( uint8 ), &advType ); } // 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 ); } #if defined( CC2540_MINIDK ) // Register for all key events - This app will handle all key events RegisterForKeys( simpleBLEBroadcaster_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) HalLcdWriteString( "BLE Broadcaster", HAL_LCD_LINE_1 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) // Setup a delayed profile startup osal_set_event( simpleBLEBroadcaster_TaskID, SBP_START_DEVICE_EVT ); }
/********************************************************************************************* * @fn simpleBLECentralEventCB * * @brief Central event callback function. * * @param pEvent - pointer to event structure * * @return none **********************************************************************************************/ static void simpleBLECentralEventCB( gapCentralRoleEvent_t *pEvent ){ switch ( pEvent->gap.opcode ){ case GAP_DEVICE_INIT_DONE_EVENT:{ //LCDPrintText("Central Initialized",0,PRINT_STRING); osal_memcpy(mac_buffer[0],pEvent->initDone.devAddr, MAC_LEN); HalLcdWriteString(bdAddr2Str( mac_buffer[0]), HAL_LCD_LINE_1); uint32 random_scan_duration =500;//to avoid normal scan be discarded by the timer,so its lasting-time should be short GAP_SetParamValue( TGAP_GEN_DISC_SCAN, random_scan_duration ); //random scan duration //LCDPrintText("discovering",0,PRINT_STRING); uint32 timeout_value = 200; // timeout_value - in milliseconds. osal_start_timerEx(MasterSlaveSwitchTaskID, PERIOD_DETECH_EVT, timeout_value); uint8 return_status; if(return_status = GAPCentralRole_StartDiscovery(DISCOVERY_MODE, ACTIVE_SCAN, DISCOVERY_WHITE_LIST )) LCDPrintText("discovery error:",return_status,PRINT_VALUE); break; } case GAP_DEVICE_INFO_EVENT:{ //find a new device // filtering device discovery results based on service UUID //LCDPrintText("find new device",0,PRINT_STRING); if(simpleBLEScanRes >= MAX_SCAN_RES){ GAPCentralRole_CancelDiscovery(); break; } if ( simpleBLEFindSvcUuid(WANTED_SERVICE_UUID, pEvent->deviceInfo.pEvtData, pEvent->deviceInfo.dataLen) ){ simpleBLEAddDeviceInfo( pEvent->deviceInfo.addr, pEvent->deviceInfo.addrType ); //GAPCentralRole_CancelDiscovery(); //stop discoverying } break; } case GAP_DEVICE_DISCOVERY_EVENT:{ //discaovery has completed osal_stop_timerEx(MasterSlaveSwitchTaskID,PERIOD_DETECH_EVT); //LCDPrintText("disca completed ",0,PRINT_STRING); if ( simpleBLEScanRes > 0 ){ // connect to current device in scan result uint8 random_select = random_num%simpleBLEScanRes; //LCDPrintText("random_select ",random_select,PRINT_STRING); CurrentConnectionInfo.MacType= simpleBLEDevList[random_select].addrType; CurrentConnectionInfo.MacAddr= simpleBLEDevList[random_select].addr; uint8 return_status; if(return_status = GAPCentralRole_EstablishLink( LINK_HIGH_DUTY_CYCLE, LINK_WHITE_LIST, CurrentConnectionInfo.MacType, CurrentConnectionInfo.MacAddr)){ LCDPrintText("Link Error",return_status,PRINT_VALUE); osal_set_event(MasterSlaveSwitchTaskID, MSS_CHANGE_ROLE_EVT); } } else{ //LCDPrintText("no device found",0,PRINT_STRING); osal_set_event(MasterSlaveSwitchTaskID, MSS_CHANGE_ROLE_EVT); //switch to periperal } break; } case GAP_LINK_ESTABLISHED_EVENT:{ if ( pEvent->gap.hdr.status == SUCCESS ){ //LCDPrintText("Connected",0,PRINT_STRING); CurrentConnectionInfo.Handle= pEvent->linkCmpl.connectionHandle; if(CharHandleSearchFlag == 1) simpleBLECentralStartDiscovery(); else{ ClientWriteValue(); CharSendingFlag =1; //LCDPrintText("NO NEED TO",0,PRINT_STRING); } } else{ LCDPrintText("Connect Failed ",pEvent->gap.hdr.status,PRINT_VALUE); osal_set_event(MasterSlaveSwitchTaskID, MSS_CHANGE_ROLE_EVT); } break; } case GAP_LINK_TERMINATED_EVENT:{ osal_set_event(MasterSlaveSwitchTaskID, MSS_CHANGE_ROLE_EVT); break; } case GAP_LINK_PARAM_UPDATE_EVENT: break; default: break; } }
/********************************************************************* * @fn loadcontrol_event_loop * * @brief Event Loop Processor for loadcontrol. * * @param uint8 task id - load control task id * @param uint16 events - event bitmask * * @return none */ uint16 loadcontrol_event_loop( uint8 task_id, uint16 events ) { afIncomingMSGPacket_t *MSGpkt; if ( events & SYS_EVENT_MSG ) { while ( (MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( loadControlTaskID )) ) { switch ( MSGpkt->hdr.event ) { case ZCL_INCOMING_MSG: // Incoming ZCL foundation command/response messages loadcontrol_ProcessZCLMsg( (zclIncomingMsg_t *)MSGpkt ); break; case KEY_CHANGE: loadcontrol_HandleKeys( ((keyChange_t *)MSGpkt)->state, ((keyChange_t *)MSGpkt)->keys ); break; case ZDO_STATE_CHANGE: if (DEV_ROUTER == (devStates_t)(MSGpkt->hdr.status)) { #if SECURE { // check to see if link key had already been established linkKeyStatus = loadcontrol_KeyEstablish_ReturnLinkKey(ESPAddr.addr.shortAddr); if (linkKeyStatus != ZSuccess) { // send out key establishment request osal_set_event( loadControlTaskID, LOADCONTROL_KEY_ESTABLISHMENT_REQUEST_EVT); } } #endif } break; default: break; } // Release the memory osal_msg_deallocate( (uint8 *)MSGpkt ); } // return unprocessed events return (events ^ SYS_EVENT_MSG); } // event to intiate key establishment request if ( events & LOADCONTROL_KEY_ESTABLISHMENT_REQUEST_EVT ) { zclGeneral_KeyEstablish_InitiateKeyEstablishment(loadControlTaskID, &ESPAddr, loadControlTransID); return ( events ^ LOADCONTROL_KEY_ESTABLISHMENT_REQUEST_EVT ); } // handle processing of identify timeout event triggered by an identify command if ( events & LOADCONTROL_IDENTIFY_TIMEOUT_EVT ) { if ( loadControlIdentifyTime > 0 ) { loadControlIdentifyTime--; } loadcontrol_ProcessIdentifyTimeChange(); return ( events ^ LOADCONTROL_IDENTIFY_TIMEOUT_EVT ); } // event to get current time if ( events & LOADCONTROL_UPDATE_TIME_EVT ) { loadControlTime = osal_getClock(); osal_start_timerEx( loadControlTaskID, LOADCONTROL_UPDATE_TIME_EVT, LOADCONTROL_UPDATE_TIME_PERIOD ); return ( events ^ LOADCONTROL_UPDATE_TIME_EVT ); } // event to handle load control complete event if ( events & LOADCONTROL_LOAD_CTRL_EVT ) { // load control evt completed // Send response back // DisableDefaultResponse is set to false - it is recommended to turn on // default response since Report Event Status Command does not have // a response. rsp.eventStatus = EVENT_STATUS_LOAD_CONTROL_EVENT_COMPLETED; zclSE_LoadControl_Send_ReportEventStatus( LOADCONTROL_ENDPOINT, &ESPAddr, &rsp, false, loadControlTransID ); HalLcdWriteString("Load Evt Complete", HAL_LCD_LINE_3); HalLedSet(HAL_LED_4, HAL_LED_MODE_OFF); return ( events ^ LOADCONTROL_LOAD_CTRL_EVT ); } // Discard unknown events return 0; }
static void peripheralStateNotificationCB( gaprole_States_t newState ) { switch ( newState ) { case GAPROLE_STARTED: { #if defined UART_debug uartWriteString("In sim BLE start\r\n"); #endif } break; case GAPROLE_ADVERTISING: { #if defined UART_debug uartWriteString("In sim BLE adv\r\n"); #endif } break; case GAPROLE_CONNECTED: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Connected", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_WAITING: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Disconnected", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_WAITING_AFTER_TIMEOUT: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Timed Out", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; case GAPROLE_ERROR: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "Error", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; default: { #if (defined HAL_LCD) && (HAL_LCD == TRUE) HalLcdWriteString( "", HAL_LCD_LINE_3 ); #endif // (defined HAL_LCD) && (HAL_LCD == TRUE) } break; } gapProfileState = newState; }