/******************************************************************************* * Function Name: Ancs_UpdateOutputInformation() ******************************************************************************** * Summary: * This function prints data onto the UART terminal. * * Parameters: * None * * Return: * None * * Theory: * The function prints the number of Missed calls, Voicemails and Emails on the * screen. The same line on the terminal is updated with new data if no other * notification came up. * *******************************************************************************/ static void Ancs_UpdateOutputInformation(void) { /* Update the same line if no new notification since. */ if(printStatus == PRINT_SAME_LINE) { /* Go back to the same line */ UART_UartPutChar(13); } else { UART_UartPutString("\n\r"); } printStatus = PRINT_SAME_LINE; UART_UartPutString("Missed calls: "); UART_UartPutChar(HexToDecimal(missedCallCount, 1)); UART_UartPutChar(HexToDecimal(missedCallCount, 0)); UART_UartPutString(" Voicemails: "); UART_UartPutChar(HexToDecimal(voiceMailCount, 1)); UART_UartPutChar(HexToDecimal(voiceMailCount, 0)); UART_UartPutString(" Emails: "); UART_UartPutChar(HexToDecimal(emailCount, 1)); UART_UartPutChar(HexToDecimal(emailCount, 0)); }
//############################################################################## void tr_cls(uint8_t cur_onoff) { UART_UartPutString(U_ATTR_OFF); tr_cursor_hide(cur_onoff); UART_UartPutString(UCLS); tr_attr(0,7,0); UART_UartPutString(UHOME); }
int main() { char c; int note=0; // current Notes int printFlag=0; // if set to 0 it prints the notes when they change CyGlobalIntEnable; /* Enable global interrupts. */ CySysTickStart(); Music_Start(0); UART_Start(); sprintf(buff,"Started\n"); UART_UartPutString(buff); for(;;) { c = UART_UartGetChar(); switch(c) { case 's': UART_UartPutString("Start\n"); Music_PlaySong(0); break; case 'S': UART_UartPutString("Stop\n"); Music_Stop(); break; case 'p': printFlag=0; break; case 'P': printFlag = 1; break; case 't': // put it back to the default Music_SetBPM(0); break; case 'T': Music_SetBPM(60); break; case '1': Music_PlaySong(0); break; case '2': Music_PlaySong(1); break; } if(note != Music_GetNote() && printFlag) { note = Music_GetNote(); sprintf(buff,"Note = %d\n",note); UART_UartPutString(buff); } } }
void CandyCaneSmooth ( uint16_t count , led_color c1, led_color c2 ) { int i,x,percentage; uint8_t flip =0; uint32 t1,t2; // Candy cane if (0 ) { char buffer[256]; sprintf(buffer,"c1 = %02x %02x %02x\n",c1.c.r,c1.c.g,c1.c.b); UART_UartPutString( buffer ); sprintf(buffer,"c2 = %02x %02x %02x\n",c2.c.r,c2.c.g,c2.c.b); UART_UartPutString( buffer ); } // loop effect for this many times for( i=0; i < count ; i++ ) { for( percentage = 0 ; percentage <= 100 ; percentage+=5 ) { // calculate target colours t1 = TweenC1toC2( c1, c2, percentage ) ; t2 = TweenC1toC2( c2, c1, percentage ) ; // all strip, for every other led for(x = StripLights_MIN_X; x <= StripLights_MAX_X; x+=2) { // if flipped. draw c1,c2 otherwise c2,c1 if( flip ) { StripLights_Pixel(x, 0, t1); StripLights_Pixel(x+1, 0, t2); } else { StripLights_Pixel(x, 0, t2); StripLights_Pixel(x+1, 0, t1); } } // toggle flip flip = 1 - flip; // wait and trigger while( StripLights_Ready() == 0); StripLights_Trigger(1); // delay between transitions CyDelay( 120 ); BOOT_CHECK(); } } }
/******************************************************************************* * Function Name: ConnectToPeripheralDevice ******************************************************************************** * Summary: * Connects to Peripheral device with given BD Address. * * Parameters: * void * * Return: * void * *******************************************************************************/ void ConnectToPeripheralDevice(void) { CYBLE_API_RESULT_T apiResult; /* If flag has been set to connect to a device... */ if(clientConnectToDevice) { /* Process pending BLE events */ CyBle_ProcessEvents(); #if 0 if(CYBLE_STATE_SCANNING == CyBle_GetState()) { CyBle_GapcStopScan(); #ifdef DEBUG_ENABLED UART_UartPutString("Stop Scan called from clientConnectToDevice "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif CyBle_ProcessEvents(); } #endif if(CYBLE_STATE_DISCONNECTED == CyBle_GetState()) { /* Reset the flag to connect to a device*/ clientConnectToDevice = FALSE; /* Connect to the device whose address has been saved as part of * potential node search */ apiResult = CyBle_GapcConnectDevice(&peripAddr); if(apiResult != CYBLE_ERROR_OK) { #ifdef DEBUG_ENABLED UART_UartPutString("Connect Request failed "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } else { #ifdef DEBUG_ENABLED UART_UartPutString("Connect Request Sent "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } /* Process pending BLE events */ CyBle_ProcessEvents(); } } }
void fsmIfaceWaterControl_sendStats(){ comm_ScheduleMessage("Info", 4, 'X', '0'); // int temp; char tmpstr[25]; // temp = PressureSensor1_Read(); sprintf(tmpstr, "Pressure 1 = %d\r\n", PressureSensor1_Read()); UART_UartPutString(tmpstr); sprintf(tmpstr, "Pressure 2 = %d\r\n", PressureSensor2_Read()); UART_UartPutString(tmpstr); sprintf(tmpstr, "Flow = %d\r\n", FlowSensor1_Read()); UART_UartPutString(tmpstr); }
/******************************************************************************* * Function Name: PrintHex ******************************************************************************** * Summary: * Converts HEX number to characters in ASCII that can be printed on * terminal. * * Parameters: * num: HEX to be converted to string. * * Return: * void * *******************************************************************************/ void PrintHex(uint8 num) { #if (DEBUG_ENABLED == 1) uint8 temp[2]; temp[0] = num%16; num = num/16; temp[1] = num%16; UART_UartPutString("0x"); if(temp[1] < 10) { UART_UartPutChar('0' + temp[1]); } else { UART_UartPutChar('A' + (temp[1] - 10)); } if(temp[0] < 10) { UART_UartPutChar('0' + temp[0]); } else { UART_UartPutChar('A' + (temp[0] - 10)); } #else num = num; #endif }
/******************************************************************************* * Function Name: UpdateSFlashNodeAddress ******************************************************************************** * Summary: * This routine calls the PSoC 4 BLE device supervisory ROM APIs to add the * node address * * Parameters: * node_addr: the address to be added to the SFLAH * * Return: * void * *******************************************************************************/ void UpdateSFlashNodeAddress(uint16 node_addr) { #ifdef STORE_SFLASH_NODE_ADDRESS uint32 *sflashPtr; uint32 readData[USER_SFLASH_ROW_SIZE/4]; uint16 dataIndex; uint32 status; /* Set the SFLASH read pointer to start of Row 1 of user SFLASH*/ sflashPtr = (uint32 *)USER_SFLASH_BASE_ADDRESS + USER_SFLASH_ROW_SIZE/4; for(dataIndex = 0; dataIndex < USER_SFLASH_ROW_SIZE/4; dataIndex++) { /* Read the complete row 1 data of SFLASH. Only the required field * will be changed and rest will be restored */ readData[dataIndex] = *sflashPtr++; } /* Modify the first index of read data to store the set Node address */ readData[SFLASH_NODE_ADDRESS_INDEX] = (uint32)node_addr; /* Write the row 1 of user SFLASH with the new data. Note that this function * will internally change the IMO frequency to 48 MHz while actual SFLASH * write operation. Any component that is being driven using IMO should not * be used during this period. */ status = WriteUserSFlashRow(NODE_ADDRESS_SFLASH_ROW, &readData[0]); if(status == USER_SFLASH_WRITE_SUCCESSFUL) { #if (DEBUG_ENABLED == 1) /* If SFLASH write was successfull */ UART_UartPutString(" SFLASH Node Address Update successful"); UART_UartPutCRLF(' '); #endif } else { #if (DEBUG_ENABLED == 1) /* If SFLASH write was not successfull */ UART_UartPutString(" SFLASH Node Address Update failed - "); UART_UartPutCRLF(' '); #endif } #endif }
int main() { char c; int note=0; // current note int printFlag=0; // if set to 0 it prints the notes when they change CyGlobalIntEnable; CySysTickStart(); Music_Start(0); UART_Start(); UART_UartPutString("Started\n"); Music_AddSong(1,&scale); for(;;) { c = UART_UartGetChar(); switch(c) { #ifdef Music_TWOCHANNELS case 'b': Music_BuzzOn(300,0); break; // turn on the buzzer 1 case 'B': Music_BuzzOff(); break; // turn off the buzzer 1 case 'n': Music_BuzzOn(200,500); break; // turn on the buzzer for 500ms #endif case 'p': printFlag=0; break; // turn off the note printer case 'P': printFlag = 1; break; // turn on the note printer case 't': Music_SetBPM(0); break; // Put the song back to the default case 'T': Music_SetBPM(60); break; // Put the current song to 60BPM case '1': Music_PlaySong(0,0); break; // Play the 1st Song case '2': Music_PlaySong(1,0); break; // Play the 2nd Song case 's': UART_UartPutString("Stop\n"); Music_Stop(); break; } if(note != Music_GetNote() && printFlag) { note = Music_GetNote(); sprintf(buff,"Note = %d\n",note); UART_UartPutString(buff); } } }
/******************************************************************************* * Function Name: RestartCentralScanning ******************************************************************************** * Summary: * Restarts Central scanning. Also, if the time that the device has remained * in Central role exceeds pre-determined value, then the switch role flag is set. * * Parameters: * void * * Return: * void * *******************************************************************************/ void RestartCentralScanning(void) { /* If the current role is Central and the Central time has exceeded the preset time, * then set the flag to switch role to Peripheral */ if((BLE_CENTRAL == ble_gap_state) && (WatchDog_CurrentCount() - centralStartedTime > CENTRAL_STATE_SPAN) && ((CYBLE_STATE_DISCONNECTED == CyBle_GetState()) || (CYBLE_STATE_SCANNING == CyBle_GetState()))) { /* Switch role flag set */ switch_Role = TRUE; #ifdef DEBUG_ENABLED UART_UartPutString("switchRole from restartScanning loop "); UART_UartPutCRLF(' '); #endif return; } /* If restart scanning flag is set, the restart the Central scanning */ if(restartScanning) { /* Process pending BLE events */ CyBle_ProcessEvents(); if(CYBLE_STATE_DISCONNECTED == CyBle_GetState()) { /* Reset the restart scanning flag */ restartScanning = FALSE; #ifdef DEBUG_ENABLED UART_UartPutString("restartScanning loop "); UART_UartPutCRLF(' '); #endif /* Start Central scan and process the event */ CyBle_GapcStartScan(CYBLE_SCANNING_FAST); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Start Scan from restartScanning loop "); UART_UartPutCRLF(' '); #endif } } }
/******************************************************************************* * Function Name: Ancs_HandleData() ******************************************************************************** * Summary: * The function handles the GATT notifications on the Data Source * characteristic. * * Parameters: * uint8 * value: Pointer to the data as part of the notification * * Return: * None * * Theory: * The function takes the GATT notification coming on the Data Source and * displays it to the user. * *******************************************************************************/ void Ancs_HandleData(uint8 * value) { uint8 * uid = value + 1; uint16 counter; switch(value[0]) { case ANCS_COMMAND_ID_GET_NOTIFICATION_ATTRIBUTES: if(memcmp(uid, ancsNotification.notificationUid, 4) == 0) { if(value[5] == ANCS_NOTIFICATION_ATTRIBUTE_ID_TITLE) { uint16 length = value[6] + (value[7] << 8); UART_UartPutString("from "); for(counter = 0; counter < length; counter++) { UART_UartPutChar(value[8 + counter]); } } } /* If positive and negative actions can be taken up */ if((ancsNotification.eventFlags & ANCS_EVENT_FLAG_POSITIVE_ACTION) && (ancsNotification.eventFlags & ANCS_EVENT_FLAG_NEGATIVE_ACTION)) { UART_UartPutString(". Accept (Y) or Decline (N)? "); ancsUsageState = ANCS_USAGE_INCOMING_CALL_WAITING_FOR_INPUT; } break; /* The case GET_APP_ATTRIBUTES is not shown in this example. * The case PERFORM_NOTIFICATION_ACTION is not a valid case. */ default: break; } }
/******************************************************************************* * Function Name: Ancs_HandleNotifications() ******************************************************************************** * Summary: * The function handles the GATT notifications on the Notification Source * characteristic. * * Parameters: * uint8 * value: Pointer to the data as part of the notification * * Return: * None * * Theory: * The function responds to the incoming GATT notifications on the Notification * Source characteristic by displaying it to the user on the UART output. * For some of the notification types, it asks iOS to provide more information. * For example, in case of an incoming call, it asks iOS to provide the caller's * name (for which the response comes as a notification on the Data Source). * *******************************************************************************/ void Ancs_HandleNotifications(uint8 * value) { ancsNotification.eventId = value[0]; ancsNotification.eventFlags = value[1]; ancsNotification.categoryId = value[2]; ancsNotification.categoryCount = value[3]; ancsNotification.notificationUid[0] = value[4]; ancsNotification.notificationUid[1] = value[5]; ancsNotification.notificationUid[2] = value[6]; ancsNotification.notificationUid[3] = value[7]; switch(ancsNotification.categoryId) { case ANCS_CATEGORY_ID_INCOMING_CALL: if(ancsNotification.eventId == ANCS_EVENT_ID_NOTIFICATION_ADDED) { printStatus = PRINT_NEW_LINE; UART_UartPutString("\n\n\rIncoming call "); /* Ask for the caller information */ if((ancsControlPointCharHandle != CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE) && (ancsDataSourceCharHandle != CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE)) { Ancs_CmdGetNotificationAttributeTitle(ancsNotification.notificationUid); } } break; case ANCS_CATEGORY_ID_MISSED_CALL: missedCallCount = ancsNotification.categoryCount; Ancs_UpdateOutputInformation(); break; case ANCS_CATEGORY_ID_VOICEMAIL: voiceMailCount = ancsNotification.categoryCount; Ancs_UpdateOutputInformation(); break; case ANCS_CATEGORY_ID_EMAIL: emailCount = ancsNotification.categoryCount; Ancs_UpdateOutputInformation(); break; /* Other cases of ANCS notifications are not shown in this example. */ default: break; } }
/******************************************************************************* * Function Name: Ancs_StateMachine() ******************************************************************************** * Summary: * The function handles the ANCS state machine. * * Parameters: * None * * Return: * None * * Theory: * The function decides the steps to do for each state of ANCS notifications. * *******************************************************************************/ void Ancs_StateMachine(void) { uint8 command; switch(ancsUsageState) { case ANCS_USAGE_INCOMING_CALL_WAITING_FOR_INPUT: command = UART_UartGetChar(); /* Check whether the user wants to accept the incoming * call or decline it. */ if(command != 0u) { if((command == 'y') || (command == 'Y')) { /* User wants to accept the call. */ Ancs_CmdPerformNotificationAction(ancsNotification.notificationUid, ANCS_ACTION_ID_POSITIVE); UART_UartPutString("Accepted. "); } else if((command == 'n') || (command == 'N')) { /* User wants to decline the call. */ Ancs_CmdPerformNotificationAction(ancsNotification.notificationUid, ANCS_ACTION_ID_NEGATIVE); UART_UartPutString("Declined. "); } ancsUsageState = ANCS_USAGE_IDLE; } break; default: break; } }
/******************************************************************************* * Function Name: SendBLEStatetoUART ******************************************************************************** * Summary: * Sends the string to UART corresponding to the present BLE state * * Parameters: * ble_state: current state of the BLE. * * Return: * void * *******************************************************************************/ void SendBLEStatetoUART(CYBLE_STATE_T ble_state) { #if (DEBUG_ENABLED == 1) /* Depending on current BLE state sent, place the string on UART */ switch(ble_state) { case CYBLE_STATE_STOPPED: UART_UartPutString(" |BLE State: CYBLE_STATE_STOPPED "); break; case CYBLE_STATE_INITIALIZING: UART_UartPutString(" |BLE State: CYBLE_STATE_INITIALIZING "); break; case CYBLE_STATE_CONNECTED: UART_UartPutString(" |BLE State: CYBLE_STATE_CONNECTED "); break; case CYBLE_STATE_ADVERTISING: UART_UartPutString(" |BLE State: CYBLE_STATE_ADVERTISING "); break; case CYBLE_STATE_SCANNING: UART_UartPutString(" |BLE State: CYBLE_STATE_SCANNING "); break; case CYBLE_STATE_CONNECTING: UART_UartPutString(" |BLE State: CYBLE_STATE_CONNECTING "); break; case CYBLE_STATE_DISCONNECTED: UART_UartPutString(" |BLE State: CYBLE_STATE_DISCONNECTED "); break; default: UART_UartPutString(" |BLE State: UNKNOWN STATE "); break; } UART_UartPutCRLF(' '); #else ble_state = ble_state; #endif }
void BLE_Status() { char Comand[10] = "AT"; uint16 Inc = 0; UART_UartPutString(Comand); while(UART_SpiUartGetRxBufferSize() == 0) { Inc++; if(Inc>1000) return; } Inc = 0; while(UART_SpiUartGetRxBufferSize() > 0) { Comand[Inc] = (char)UART_SpiUartReadRxData(); Inc++; } Add_To_DDR(Comand); Print_DDR(); }
/******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * Main function. * * Parameters: * None * * Return: * None * *******************************************************************************/ int main() { CYBLE_API_RESULT_T apiResult; CYBLE_STATE_T bleState; CyGlobalIntEnable; PWM_Start(); UART_Start(); UART_UartPutString("Welcome to BLE OOB Pairing Demo\r\n"); apiResult = CyBle_Start(StackEventHandler); if(apiResult != CYBLE_ERROR_OK) { /* BLE stack initialization failed, check your configuration */ CYASSERT(0); } CyBle_IasRegisterAttrCallback(IasEventHandler); for(;;) { /* Single API call to service all the BLE stack events. Must be * called at least once in a BLE connection interval */ CyBle_ProcessEvents(); bleState = CyBle_GetState(); if(bleState != CYBLE_STATE_STOPPED && bleState != CYBLE_STATE_INITIALIZING) { /* Configure BLESS in DeepSleep mode */ CyBle_EnterLPM(CYBLE_BLESS_DEEPSLEEP); /* Configure PSoC 4 BLE system in sleep mode */ CySysPmSleep(); /* BLE link layer timing interrupt will wake up the system */ } } }
uint16_t at_getstr( char *const buffer ,uint16_t length,uint16_t timeout) { int it = 0; if( buffer == NULL || length == 0 ) return 0; memset(buffer,0,length); do{ // fetch from uWIFI while ( uWIFI_SpiUartGetRxBufferSize() == 0 ) { timeout--; if( timeout == 0 ) { if( 0 ) { UART_UartPutString("at_getstr timedout\n"); } return 0; } CyDelay( 5 ); } buffer[it]=uWIFI_UartGetChar(); it++; // max if( it == length ){ return it; } }while (buffer[it-1] != '\n'); return it; }
uint8_t send_command( const char *const text, const char *const command, const char *const wait, uint16_t timeout) { int length; // if text passed in, send to host if( text ){ UART_UartPutString( text ); } // if command passed in, send to host and wifi uarts if( command) { UART_UartPutString( command); uWIFI_UartPutString( command); } // if wait for reply text, supplied, scan buffer for command if ( wait ) { while( 1 ) { // attempt to get a string (needs timeout) length = at_getstr(rx_buffer,MAX_BUFFER,50); timeout -- ; // return 0 on timed out if( timeout == 0 ) { UART_UartPutString("\nTimed out waiting for correct reply\n"); return 0; } // got a return if( length ) { if ( 1 ) { UART_UartPutString( "buff = [\n"); UART_UartPutString( rx_buffer); UART_UartPutString( "]\n"); } // look for string if(strstr( rx_buffer, wait ) != NULL ) { UART_UartPutString("\nfound - ["); UART_UartPutString( rx_buffer ) ; // found break; } } else { if ( 0 ) { UART_UartPutString("\nEmpty buffer\n"); } } } } while( uWIFI_SpiUartGetRxBufferSize() ) { UART_UartPutChar( uWIFI_UartGetChar() ); } while( uWIFI_SpiUartGetRxBufferSize() ) { UART_UartPutChar( uWIFI_UartGetChar() ); } return 1; }
void Loop_Master_WaitingSPort() { char itoastr[5]; uint8 tmpbyte; uint8 uartchar = UART_UartGetChar(); if (uartchar != 0) { UART_UartPutChar(uartchar); UART_UartPutChar('\n'); // Remember, when using address filtering, the node address have to be the first byte // of the payload. // Slave 1 is node address 100. // Slave 2 is node address 200. switch (uartchar) { case '1': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 1; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '2': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 2; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '3': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 3; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '4': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 1; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '5': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 2; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '6': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 3; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case 'a': case 'A': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 0xAB; RFM69_DataPacket_TX(rfdatabytes, 64); /* Enter in RX state until response from slave is received or timeout. ¡¡¡ Remember !!! At Master we don´t use address filtering, so we can received data from different slaves. */ UART_UartPutString("Waiting data from Slave 1..."); RFM69_SetMode(OP_MODE_RX); timercnt = 1000; // set timout = 1000ms = 1s. master_state = 1; }; break; case 'b': case 'B': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 0xAB; RFM69_DataPacket_TX(rfdatabytes, 64); /* Enter in RX state until response from slave is received or timeout. ¡¡¡ Remember !!! At Master we don´t use address filtering, so we can received data from different slaves. */ UART_UartPutString("Waiting data from Slave 2..."); RFM69_SetMode(OP_MODE_RX); timercnt = 1000; // set timout = 1000ms = 1s. master_state = 1; }; break; case '9': { tmpbyte = RFM69_GetTemperature(); itoa(tmpbyte, itoastr, 10); UART_UartPutString("Temperature: register raw value = "); UART_UartPutString(itoastr); UART_UartPutChar('\n'); }; break; case '?': { TerminalSend_Master(); }; break; } if (master_state == 0) UART_UartPutString("Select test :> "); } }
void TerminalSend_Master() { UART_UartPutString("\nPSoC RFM69 Test... PSoC 4/4M... MASTER\n\n"); UART_UartPutString("Options:\n"); UART_UartPutString("\t1 - Slave 1: Toggle red led.\n"); UART_UartPutString("\t2 - Slave 1: Toggle green led.\n"); UART_UartPutString("\t3 - Slave 1: Toggle blue led.\n"); UART_UartPutString("\t4 - Slave 2: Toggle red led.\n"); UART_UartPutString("\t5 - Slave 2: Toggle green led.\n"); UART_UartPutString("\t6 - Slave 2: Toggle blue led.\n"); UART_UartPutString("\tA - Slave 1: Read from...\n"); UART_UartPutString("\tB - Slave 2: Read from...\n"); UART_UartPutString("\t9 - Read this (master) temperature.\n"); UART_UartPutString("\t? - This menu.\n\n"); UART_UartPutString("\nSelect test :> "); }
void Loop_Master_WaitingSlaveResponse() { uint8 frame_len = 0; char itoastr[5]; uint8 rssi; /* Testing with interrupts? */ #ifdef TEST_USING_INTERRUPTS if (rfrxirqflag == 1) { frame_len = RFM69_DataPacket_RX(rfdatabytes, &rssi); UART_UartPutString("OK...(using ints)\n"); UART_UartPutString("Slave: "); itoa(rfdatabytes[0], itoastr, 10); UART_UartPutString(itoastr); UART_UartPutString(" RSSI: "); itoa(rfdatabytes[1], itoastr, 10); UART_UartPutString(itoastr); UART_UartPutString(" Temperature: "); itoa(rfdatabytes[2], itoastr, 10); UART_UartPutString(itoastr); UART_UartPutString("\nSelect test :> "); // change to TX state. master_state = 0; rfrxirqflag = 0; } else { if (timercnt == 0) // timed out? { // change to TX state. master_state = 0; UART_SpiUartClearRxBuffer(); // discard received data while in rx mode. UART_UartPutString("TimedOut...\n"); UART_UartPutString("Select test :> "); } } #else // Waiting a packet from a slave containing // Slave address + RSSI at slave when master data received + temperature. frame_len = RFM69_DataPacket_RX(rfdatabytes, &rssi); if (frame_len != 0) { UART_UartPutString("OK...(polling rfm module)\n"); UART_UartPutString("Slave: "); itoa(rfdatabytes[0], itoastr, 10); UART_UartPutString(itoastr); UART_UartPutString(" RSSI: "); itoa(rfdatabytes[1], itoastr, 10); UART_UartPutString(itoastr); UART_UartPutString(" Temperature: "); itoa(rfdatabytes[2], itoastr, 10); UART_UartPutString(itoastr); UART_UartPutString("\nSelect test :> "); // change to TX state. master_state = 0; } else { if (timercnt == 0) // timed out? { // change to TX state. master_state = 0; UART_SpiUartClearRxBuffer(); // discard received data while in rx mode. UART_UartPutString("TimedOut...\n"); UART_UartPutString("Select test :> "); } } #endif }
/******************************************************************************* * Function Name: AppCallBack ******************************************************************************** * * Summary: * Call back function for BLE stack to handle BLESS events * * Parameters: * event - the event generated by stack * eventParam - the parameters related to the corresponding event * * Return: * None. * *******************************************************************************/ void AppCallBack(uint32 event, void *eventParam) { CYBLE_GATTC_READ_BY_TYPE_RSP_PARAM_T *readResponse; CYBLE_GAPC_ADV_REPORT_T *advReport; CYBLE_GATTC_FIND_BY_TYPE_RSP_PARAM_T *findResponse; CYBLE_GATTC_FIND_INFO_RSP_PARAM_T *findInfoResponse; switch (event) { case CYBLE_EVT_STACK_ON: break; case CYBLE_EVT_GAPC_SCAN_PROGRESS_RESULT: advReport = (CYBLE_GAPC_ADV_REPORT_T *) eventParam; /* check if report has manfacturing data corresponding to the intended matching peer */ if((advReport->eventType == CYBLE_GAPC_SCAN_RSP) && (advReport->dataLen == 0x06) \ && (advReport->data[1] == 0xff) && (advReport->data[2] == 0x31) \ && (advReport->data[3] == 0x01) && (advReport->data[4] == 0x3b) \ && (advReport->data[5] == 0x04)) { peerDeviceFound = true; memcpy(peerAddr.bdAddr, advReport->peerBdAddr, sizeof(peerAddr.bdAddr)); peerAddr.type = advReport->peerAddrType; #ifdef PRINT_MESSAGE_LOG UART_UartPutString("\n\r\n\rServer with matching custom service discovered..."); #endif } break; case CYBLE_EVT_GAP_DEVICE_DISCONNECTED: /* RESET all flags */ peerDeviceFound = false; notificationEnabled = false; infoExchangeState = INFO_EXCHANGE_START; #ifdef PRINT_MESSAGE_LOG UART_UartPutString("\n\r DISCONNECTED!!! \n\r "); while(0 != (UART_SpiUartGetTxBufferSize() + UART_GET_TX_FIFO_SR_VALID)); #endif /* RESET Uart and flush all buffers */ UART_Stop(); UART_SpiUartClearTxBuffer(); UART_SpiUartClearRxBuffer(); UART_Start(); break; case CYBLE_EVT_GATTC_READ_BY_TYPE_RSP: readResponse = (CYBLE_GATTC_READ_BY_TYPE_RSP_PARAM_T *) eventParam; if(0 == memcmp((uint8 *)&(readResponse->attrData.attrValue[5]), (uint8 *)uartTxAttrUuid, 16)) { txCharHandle = readResponse->attrData.attrValue[3]; txCharHandle |= (readResponse->attrData.attrValue[4] << 8); infoExchangeState |= TX_ATTR_HANDLE_FOUND; } else if(0 == memcmp((uint8 *)&(readResponse->attrData.attrValue[5]), (uint8 *)uartRxAttrUuid, 16)) { rxCharHandle = readResponse->attrData.attrValue[3]; rxCharHandle |= (readResponse->attrData.attrValue[4] << 8); infoExchangeState |= RX_ATTR_HANDLE_FOUND; } break; case CYBLE_EVT_GATTC_FIND_INFO_RSP: findInfoResponse = (CYBLE_GATTC_FIND_INFO_RSP_PARAM_T *) eventParam; if((0x29 == findInfoResponse->handleValueList.list[3]) && \ (0x02 == findInfoResponse->handleValueList.list[2])) { txCharDescHandle = findInfoResponse->handleValueList.list[0]; txCharDescHandle |= findInfoResponse->handleValueList.list[1] << 8; infoExchangeState |= TX_CCCD_HANDLE_FOUND; } break; case CYBLE_EVT_GATTC_XCHNG_MTU_RSP: /*set the 'mtuSize' variable based on the minimum MTU supported by both devices */ if(CYBLE_GATT_MTU > ((CYBLE_GATT_XCHG_MTU_PARAM_T *)eventParam)->mtu) { mtuSize = ((CYBLE_GATT_XCHG_MTU_PARAM_T *)eventParam)->mtu; } else { mtuSize = CYBLE_GATT_MTU; } infoExchangeState |= MTU_XCHNG_COMPLETE; break; case CYBLE_EVT_GATTC_HANDLE_VALUE_NTF: HandleUartRxTraffic((CYBLE_GATTC_HANDLE_VALUE_NTF_PARAM_T *)eventParam); break; case CYBLE_EVT_GATTC_FIND_BY_TYPE_VALUE_RSP: findResponse = (CYBLE_GATTC_FIND_BY_TYPE_RSP_PARAM_T *) eventParam; bleUartServiceHandle = findResponse->range->startHandle; bleUartServiceEndHandle = findResponse->range->endHandle; infoExchangeState |= BLE_UART_SERVICE_HANDLE_FOUND; break; case CYBLE_EVT_GATTS_XCNHG_MTU_REQ: /*set the 'mtuSize' variable based on the minimum MTU supported by both devices */ if(CYBLE_GATT_MTU > ((CYBLE_GATT_XCHG_MTU_PARAM_T *)eventParam)->mtu) { mtuSize = ((CYBLE_GATT_XCHG_MTU_PARAM_T *)eventParam)->mtu; } else { mtuSize = CYBLE_GATT_MTU; } break; case CYBLE_EVT_GATTC_WRITE_RSP: notificationEnabled = true; #ifdef PRINT_MESSAGE_LOG UART_UartPutString("\n\rNotifications enabled\n\r"); UART_UartPutString("\n\rStart entering data:\n\r"); #endif break; case CYBLE_EVT_GATT_CONNECT_IND: #ifdef PRINT_MESSAGE_LOG UART_UartPutString("\n\rConnection established"); #endif break; default: break; } }
/******************************************************************************* * Function Name: StackEventHandler ******************************************************************************** * * Summary: * This is an event callback function to receive events from the BLE Component. * * Parameters: * uint8 event: Event from the CYBLE component * void* eventParams: A structure instance for corresponding event type. The * list of event structure is described in the component * datasheet. * * Return: * None * *******************************************************************************/ void StackEventHandler(uint32 event, void *eventParam) { char authFailReasonCode[3]; CYBLE_GAP_AUTH_FAILED_REASON_T *authFailReason; switch(event) { /* Mandatory events to be handled by Find Me Target design */ case CYBLE_EVT_STACK_ON: case CYBLE_EVT_GAP_DEVICE_DISCONNECTED: /* Start BLE advertisement for 30 seconds and update link * status on LEDs */ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); Advertising_LED_Write(LED_ON); PWM_WriteCompare(LED_NO_ALERT); break; case CYBLE_EVT_GAP_DEVICE_CONNECTED: UART_UartPutString("GAP Device Connected\r\n"); /* BLE link is established */ Advertising_LED_Write(LED_OFF); break; case CYBLE_EVT_TIMEOUT: if(*(uint8 *) eventParam == CYBLE_GAP_ADV_MODE_TO) { /* Advertisement event timed out, go to low power * mode (Hibernate mode) and wait for an external * user event to wake up the device again */ Advertising_LED_Write(LED_OFF); Hibernate_LED_Write(LED_ON); PWM_Stop(); Wakeup_SW_ClearInterrupt(); Wakeup_Interrupt_ClearPending(); Wakeup_Interrupt_Start(); CySysPmHibernate(); } break; /********************************************************** * GAP Events ***********************************************************/ case CYBLE_EVT_GAP_AUTH_REQ: UART_UartPutString("Authorization Requested\r\n"); break; case CYBLE_EVT_GAP_AUTH_COMPLETE: UART_UartPutString("Pairing is Successful!\r\n"); break; case CYBLE_EVT_GAP_AUTH_FAILED: authFailReason = ((CYBLE_GAP_AUTH_FAILED_REASON_T *)eventParam); UART_UartPutString("Authentication Failed with Reason Code: "); snprintf(authFailReasonCode, sizeof(authFailReasonCode), "%lu", (uint32)(*authFailReason)); UART_UartPutString(authFailReasonCode); UART_UartPutChar("\r\n"); break; /********************************************************** * GATT Events ***********************************************************/ case CYBLE_EVT_GATT_CONNECT_IND: UART_UartPutString("GATT Connection Indication\r\n"); /* Set OOB data after the connection indication but before the authorization * request is received. */ if(CyBle_GapSetOobData(cyBle_connHandle.bdHandle, CYBLE_GAP_OOB_ENABLE, securityKey, NULL, NULL) != CYBLE_ERROR_OK) { UART_UartPutString("Error in Setting OOB Data\r\n"); } else { UART_UartPutString("OOB Data is Set\r\n"); } break; default: break; } }
//############################################################################## void uart_putlong( uint32_t value, uint8_t base ) { char buf[17]; ltoa( value, buf, base ); UART_UartPutString( buf ); }
//############################################################################## void tr_cursor_hide( uint8_t hide ) { if(hide) UART_UartPutString(UCUR_HIDE); else UART_UartPutString(UCUR_SHOW); }
void fsmIfaceWaterControl_updateOpVals(){ //TODO //Update the operation vals based on Info coming from mc200 UART_UartPutString("updateOpVals\n\r"); }
/******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * This is the main entry point for this application. This function initializes all the * components used in the project. It computes the frequency whenever a capture event is * * Parameters: * None * * Return: * None * *******************************************************************************/ int main() { #if(UART_DEBUG_ENABLE) /* Variable to store the loop number */ uint8 loopNo = 0; #endif /* Enable global interrupt mask */ CyGlobalIntEnable; /* Disable ILO as it is not used */ CySysClkIloStop(); /* Initialize components related to BLE communication */ InitializeBLESystem(); /* Initialize components related to frequency counting */ Initialize_Freq_Meas_System(); /* Start UART component if UART debug is enabled */ #if(UART_DEBUG_ENABLE) /* Start UART component and send welcome string to hyper terminal on PC */ UART_Start(); UART_UartPutString("Welcome to Frequency Measurement Using PSoC 4 BLE\n"); UART_PutCRLF(); #endif while(1) { /* Compute frequency once in every PWM interval(2s) */ if(Calculate_Frequency == TRUE) { /* Check if valid capture event is detected */ if((Input_Sig_Ctr_Capture == 1) && (Ref_Clk_Ctr_Capture == 1)) { /* Compute frequency using the latched count value, computed frequency will be stored in ASCII format in a global array */ Compute_Frequency(); #if(UART_DEBUG_ENABLE) /* Print input signal counter value in hexadecimal */ UART_UartPutString("Input Signal Counter Value: "); UART_SendDebugData(Input_Signal_Count); UART_UartPutString(" "); /* Print input signal counter value in ASCII format */ /* Reset the array before storing the ASCII character */ Reset_Array(InputCounter_ASCII, DATA_END); Convert_HextoDec(Input_Signal_Count, InputCounter_ASCII); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(InputCounter_ASCII[DATA_END - loopNo -1]); } UART_PutCRLF(); /* Print reference clock counter value */ UART_UartPutString("Reference Clock Counter Value: "); UART_SendDebugData(Ref_Clock_Count); UART_UartPutString(" "); /* Print input signal counter value in ASCII format */ /* Reset the array before storing the ASCII character */ Reset_Array(RefCounter_ASCII, DATA_END); Convert_HextoDec(Ref_Clock_Count, RefCounter_ASCII); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(RefCounter_ASCII[DATA_END - loopNo -1]); } UART_PutCRLF(); /* Print Input Signal Frequency in decimal format */ UART_UartPutString("Input Frequency: "); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(Input_Frequency[DATA_END - loopNo -1]); } UART_PutCRLF(); #endif /* Reset the capture flag after computing the frequency */ Input_Sig_Ctr_Capture = 0; Ref_Clk_Ctr_Capture = 0; } /* If valid capture event is not registered, set the value of frequency to zero */ else { /* Reset the input_frequency array before storing the frequency value */ Reset_Array(Input_Frequency, DATA_END); /* If no capture event is detected in the 1s interval, set the frequency to zero */ FormatFrequencyData(ZERO_HZ); #if(UART_DEBUG_ENABLE) /* Print Input Signal Frequency in decimal format */ UART_UartPutString("Input Frequency: "); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(Input_Frequency[DATA_END - loopNo -1]); } UART_PutCRLF(); #endif } /* Reset the 2s interval flag for computing the frequency in the next interval */ Calculate_Frequency = 0; /* Send frequency value only if BLE device is connected */ if(TRUE == deviceConnected) { /* Send frequency value when notifications are enabled */ if((startNotification & CCCD_NTF_BIT_MASK)) { /* Send the frequency value to BLE central device by notifications */ SendDataOverFreqCounterNotification(Input_Frequency); } } } /* Function to handle LED status depending on BLE state */ HandleStatusLED(); /* Handle CCCD value update only if BLE device is connected */ if(TRUE == deviceConnected) { /* When the Client Characteristic Configuration descriptor (CCCD) is written * by Central device for enabling/disabling notifications, then the same * descriptor value has to be explicitly updated in application so that * it reflects the correct value when the descriptor is read */ UpdateNotificationCCCD(); } if(restartAdvertisement) { /* Reset 'restartAdvertisement' flag*/ restartAdvertisement = FALSE; /* Start Advertisement and enter Discoverable mode*/ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); } /*Process Event callback to handle BLE events. The events generated and * used for this application are inside the 'CustomEventHandler' routine*/ CyBle_ProcessEvents(); /* Put CPU to sleep */ CySysPmSleep(); } }
/******************************************************************************* * Function Name: SwitchRole ******************************************************************************** * Summary: * This function switches the role between Central and Peripheral. If device * is connected while switching role, then it is first disconnected. * * Parameters: * void * * Return: * void * *******************************************************************************/ void SwitchRole(void) { CYBLE_API_RESULT_T apiResult; /* if the switch role flag is set... */ if(switch_Role == TRUE) { /* Process pending BLE events */ CyBle_ProcessEvents(); /* If there is an existing connection, then disconnect before switching * role. */ if((cyBle_connHandle.bdHandle != 0)) { /* Disconnect the device and process the event */ CyBle_GapDisconnect(cyBle_connHandle.bdHandle); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Peripheral closed connection "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } switch(ble_gap_state) { case BLE_PERIPHERAL: /* If the current role is Peripheral and system is advertising, * then stop advertisement before switching role */ if(CyBle_GetState() == CYBLE_STATE_ADVERTISING) { CyBle_GappStopAdvertisement(); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Peripheral Advertisment Stopped "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } if(CyBle_GetState() == CYBLE_STATE_DISCONNECTED) { /* Switch BLE role by starting scan. This way, the system is set * to Central role */ apiResult = CyBle_GapcStartScan(CYBLE_SCANNING_FAST); if(CYBLE_ERROR_OK == apiResult) { #ifdef DEBUG_ENABLED UART_UartPutString("Start Scan API called "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif /* Record the time at which Central role was started. This will be * used for timeout and switching to Peripheral operation*/ centralStartedTime = WatchDog_CurrentCount(); /* Update the current BLE role to Central */ ble_gap_state = BLE_CENTRAL; /* Reset the switch role flag*/ switch_Role = FALSE; } else { /* If scanning did not start, maintain the current role and retry later */ ble_gap_state = BLE_PERIPHERAL; #ifdef DEBUG_ENABLED UART_UartPutString("Start Scan API failed "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } } /* Process Pending BLE Events */ CyBle_ProcessEvents(); break; case BLE_CENTRAL: /* If the current role is Central and system is scanning, * then stop scanning before switching role */ if(CyBle_GetState() == CYBLE_STATE_SCANNING) { CyBle_GapcStopScan(); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Central Scan stopped "); UART_UartPutCRLF(' '); #endif } if(CyBle_GetState() == CYBLE_STATE_DISCONNECTED) { #ifdef ENABLE_ADV_DATA_COUNTER /* Increment data counter */ new_advData.advData[new_advData.advDataLen - 1] = dataADVCounter; cyBle_discoveryModeInfo.advData = &new_advData; #ifdef DEBUG_ENABLED UART_UartPutString("Updated ADV data = "); PrintNum(dataADVCounter); UART_UartPutCRLF(' '); #endif #endif /* Switch BLE role by starting advertisement. This way, the system is * set to Peripheral role */ apiResult = CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); if(apiResult == CYBLE_ERROR_OK) { /* If advertisement started successfully, set the BLE state and * reset the switch role flag*/ ble_gap_state = BLE_PERIPHERAL; clientConnectToDevice = FALSE; switch_Role = FALSE; #ifdef DEBUG_ENABLED UART_UartPutString("Peripheral Advertisment called "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } else { /* If advertisement did not start, maintain the current role and retry later */ ble_gap_state = BLE_CENTRAL; #ifdef DEBUG_ENABLED UART_UartPutString("Start Peripheral Advertisment Failed "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } } /* Process Pending BLE Events */ CyBle_ProcessEvents(); break; default: break; } } }
/** * @brief Does all the work of getting data, simple parse and sending to LED's * * @return none */ void run_server(void) { uint8_t *buf_ptr; uint8_t ret = 0; //Set to black StripLights_DisplayClear(0); // LED off P1_6_Write(0); // this caused all sorts of issues, so i removed it #if 0 while( ret == 0 ) { ret = send_command("resetting\r\n", "AT+RST\r\n\n","ready",5000); //.com on later firmware, ready on others } P1_6_Write(0); #endif // Simple progress meter StripLights_SetXToColour( getColor(1) ,1 ); // returns "no change" , 1 CONNECT TO AP, 2 BE AN AP, 3 BOTH send_command("cwmode=3\r\n", "AT+CWMODE=1\r\n",NULL,DEFAULT_TIMEOUT); // Simple progress meter, stage 2 StripLights_SetXToColour( getColor(1) ,5 ); do { // LED On P1_6_Write(1); // Not really used, can be used to see if already connected send_command("get ip\r\n","AT+CIFSR\r\n",NULL,0); CyDelay(400); // wireless AP settings, first param is ap name, second password ret =send_command("connecting\r\n","AT+CWJAP=\"monkeysee\",\"monkeydo\"\r\n","OK",1000); // LED Off P1_6_Write(0); }while( ret == 0 ); // progress meter, stage 3 StripLights_SetXToColour( getColor(1) ,10 ); do { CyDelay(400); ret= send_command("check connection\r\n","AT+CWJAP?\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 4 StripLights_SetXToColour( getColor(1) ,15 ); //GET LOCAL IP ADDRESS do { CyDelay(400); ret= send_command("get ip\r\n","AT+CIFSR\r\n",NULL,0); } while( ret == 0 ); // progress meter, stage 5 StripLights_SetXToColour( getColor(1) ,20 ); //START UP MULTI-IP CONNECTION // 0 Single IP connection // 1 Multi IP connection do { CyDelay(400); ret= send_command("multip\r\n","AT+CIPMUX=1\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 6 StripLights_SetXToColour( getColor(1) ,25 ); do { CyDelay(400); ret= send_command("cipserver\r\n","AT+CIPSERVER=1,40002\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 7 StripLights_SetXToColour( getColor(1) ,30 ); // switch into UDP listen/receive mode, all data passed in will be of +IDT,0,length:data format do { CyDelay(400); ret= send_command("cipsto\r\n","AT+CIPSTO=9000\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 8 StripLights_SetXToColour( getColor(1) ,45 ); do { CyDelay(400); ret= send_command("cipmux\r\n","AT+CIPMUX=0\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 9 StripLights_SetXToColour( getColor(1) ,50 ); // setup done, tell host (if connected) UART_UartPutString("\nSetup and ready!\n"); // progress meter, stage 10, done StripLights_SetXToColour( getColor(2) ,StripLights_MAX_X ); CyDelay(200); // all off StripLights_DisplayClear(0); while(1) { int i ; uint8_t ch; // if switch is help, run into bootloader , mostly for dev BOOT_CHECK(); //led off P1_6_Write(0); // wait for data from ESP UART while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); // fetch one byte of data ch = uWIFI_UartGetChar(); // find start of +IPD,0,450: if( ch == '+' ) { //wait, this could be set to < 4 instead and then can drop the other checks. while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); if( ch == 'I' ) { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); if( ch == 'P' ) { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); if( ch == 'D' ) { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); //UART_UartPutString("Found +IPD\n"); // illformatted if( ch != ',' ) { UART_UartPutString("Unexpected char #1\n"); break; } //led on P1_6_Write(1); // scan for end of descriptive // 10 will be enough 0,450: i = 10 ; do { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); i--; if( i ==0 ) { UART_UartPutString("couldn't find : marker\n"); break; } } while( ch != ':' ); //UART_UartPutString("Found Start of data block\n"); // point to start or end of LED buffer #if defined(REVERSE_DIRECTION) buf_ptr = (uint8_t*)&StripLights_ledArray[0][StripLights_MAX_X-1]; for( i = 0 ; i <= StripLights_MAX_X ; i++ ) { #else buf_ptr = (uint8_t*)&StripLights_ledArray[0][0]; for( i = 0 ; i <= StripLights_MAX_X ; i++ ) { #endif // fill in rx_buffer from ESP UART //gbr while ( uWIFI_SpiUartGetRxBufferSize() < 3 ); // 0 = green // 1 = red // 2 = blue buf_ptr[1] = uWIFI_UartGetChar(); buf_ptr[0] = uWIFI_UartGetChar(); buf_ptr[2] = uWIFI_UartGetChar(); #if defined(REVERSE_DIRECTION) buf_ptr -= sizeof(uint32_t); #else buf_ptr += sizeof(uint32_t); #endif } //end of buffer while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); // check this char for sanity if wanted /* UART_UartPutChar( ch) ; UART_UartPutString(" - Buffer filled\n"); UART_UartPutString( rx_buffer ); UART_UartPutString("END\n"); */ //send to LED strip while( StripLights_Ready() == 0); StripLights_Trigger(1); //CyDelay(4); BOOT_CHECK(); } } } } } } /** * @brief Just echo across UARTs * * * @return none */ void echo_uart(void) { while(1) { int ret; BOOT_CHECK(); ret = 0 ; while( ret == 0 ) { ret = send_command("resetting\r\n", "AT+RST\r\n\n","ready",5000); //.com on later firmware, ready on others } // echo from usb uart to wifi uart if( UART_SpiUartGetRxBufferSize() ) { uWIFI_UartPutChar( UART_UartGetChar() ); } //echo from wifi uart to usb uart if( uWIFI_SpiUartGetRxBufferSize() ) { UART_UartPutChar( uWIFI_UartGetChar() ); } } } // various simple effects (not used, sending PC does work) could be offline mode void ColorFader( int count , uint32 color) { while(count--){ FadeToColor( 0,StripLights_COLUMNS, color, 50,1 ); } } void Tween1( void ) { hsv_color tween; static led_color src; static hsv_color result ; src.c.r = rand()%255; src.c.g = rand()%255; src.c.b = rand()%255; tween = rgb_to_hsv((led_color)getColor(rand()%StripLights_COLOR_WHEEL_SIZE)); result.hsv = TweenerHSV( 0, StripLights_COLUMNS, result.hsv, tween.hsv, 10 ,1); // Tweener( 100,src.rgb ); src.c.r += 5-(rand()%10); src.c.g += 5-(rand()%10); src.c.b += 5-(rand()%10); result.hsv = TweenerHSV( StripLights_COLUMNS, StripLights_COLUMNS, result.hsv, tween.hsv, 10 ,-1 ); }
/******************************************************************************* * Function Name: GenericEventHandler ******************************************************************************** * Summary: * Event handler function for the BLE stack. All the events by BLE stack * are received by application through this function. For this, CyBle_ProcessEvents() * should be called continuously in main loop. * * Parameters: * event: event value * eventParame: pointer to the location where relevant event data is stored * * Return: * void * *******************************************************************************/ void GenericEventHandler(uint32 event, void * eventParam) { /* Local variables and data structures*/ CYBLE_GATTS_WRITE_REQ_PARAM_T writeReqData; CYBLE_GATTC_WRITE_REQ_T writeADVcounterdata; CYBLE_GAPC_ADV_REPORT_T scan_report; CYBLE_GATTS_WRITE_CMD_REQ_PARAM_T writeCmdData; CYBLE_API_RESULT_T apiResult; CYBLE_GATTC_WRITE_REQ_T writeRGBdata; switch(event) { case CYBLE_EVT_STACK_ON: #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_STACK_ON "); UART_UartPutCRLF(' '); #endif /* At the start of the BLE stack, start advertisement */ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); break; case CYBLE_EVT_GAPP_ADVERTISEMENT_START_STOP: /* This event is received at every start or stop of peripheral advertisement*/ #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GAPP_ADVERTISEMENT_START_STOP "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif if((CYBLE_STATE_DISCONNECTED == CyBle_GetState()) && (switch_Role == FALSE)) { /* If the current state of the BLE is Disconnected, then restart advertisement. * Note that the advertisement should only be restarted if the switch flag is not * TRUE. If switch role flag is TRUE, then there is no need to start advertisement * as the GAP role has to be switched*/ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); if(apiResult == CYBLE_ERROR_OK) { #ifdef DEBUG_ENABLED UART_UartPutString("Restart Advertisement "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } } break; case CYBLE_EVT_GAPC_SCAN_START_STOP: /* This event is received at every start or stop of central scanning*/ #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GAPC_SCAN_START_STOP "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif break; case CYBLE_EVT_GATT_CONNECT_IND: /* This event is received at GATT connection with a device. This event * is received for both Client or Server role */ #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GATT_CONNECT_IND "); UART_UartPutCRLF(' '); #endif break; case CYBLE_EVT_GATT_DISCONNECT_IND: /* This event is received at GATT disconnection with a device. This event * is received for both Client or Server role */ #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GATT_DISCONNECT_IND "); UART_UartPutCRLF(' '); #endif break; case CYBLE_EVT_GATTS_WRITE_REQ: /* This event is received at when Server receives a Write request from * connected Client device */ /* Save the associated event parameter in local variable */ writeReqData = *(CYBLE_GATTS_WRITE_REQ_PARAM_T*)eventParam; if(writeReqData.handleValPair.attrHandle == CYBLE_RGB_LED_CONTROL_CHAR_HANDLE) { /* If the Write request is on RGB LED Control Characteristic, then Client is * trying to set a new color to the device. */ if(writeReqData.handleValPair.value.len == RGB_LED_DATA_LEN) { #ifdef DEBUG_ENABLED UART_UartPutString("RGB CYBLE_EVT_GATTS_WRITE_REQ "); UART_UartPutCRLF(' '); #endif /* Extract the four bytes containing the color value and store it */ RGBData[RGB_RED_INDEX] = writeReqData.handleValPair.value.val[0]; RGBData[RGB_GREEN_INDEX] = writeReqData.handleValPair.value.val[1]; RGBData[RGB_BLUE_INDEX] = writeReqData.handleValPair.value.val[2]; RGBData[RGB_INTENSITY_INDEX] = writeReqData.handleValPair.value.val[3]; /* Modify RGB Color my configuring the PrISM components with new density * value*/ UpdateRGBled(RGBData, RGB_LED_DATA_LEN); /* Update the RGB LED Control characteristic in GATT DB to allow * Client to read the latest RGB LED color value set */ CyBle_GattsWriteAttributeValue(&writeReqData.handleValPair,0,&cyBle_connHandle,CYBLE_GATT_DB_LOCALLY_INITIATED); #ifdef ENABLE_ADV_DATA_COUNTER /* Increment the ADV data counter so that scanning Central device knows * if this device has updated RGB LED data or not */ dataADVCounter++; #endif #ifdef DEBUG_ENABLED UART_UartPutString("incremented dataADVCounter value in CYBLE_EVT_GATTS_WRITE_REQ= "); PrintNum(dataADVCounter); UART_UartPutCRLF(' '); #endif /* After receiveing the color value, set the switch role flag to allow the system * to switch role to Central role */ switch_Role = TRUE; #ifdef DEBUG_ENABLED UART_UartPutString("switchRole to Central"); UART_UartPutCRLF(' '); #endif } else { /* Send the error code for invalid attribute length packet */ SendErrorCode(CYBLE_GATT_WRITE_REQ, writeReqData.handleValPair.attrHandle, ERR_INVALID_ATT_LEN); return; } } /* As part of every write request, the server needs to send a write response. Note * that this will be sent only if all the application layer conditions are met on a * write request. Else, an appropriate error code is sent. */ CyBle_GattsWriteRsp(cyBle_connHandle); break; case CYBLE_EVT_GATTS_WRITE_CMD_REQ: /* This event is generated whenever a Client device sends a Write Command (Write * without response) to a connected Server. Save the associated event parameter in * local variable. */ writeCmdData = *(CYBLE_GATTS_WRITE_CMD_REQ_PARAM_T*)eventParam; /* Check if the Write command is for ADV Data counter characteristic */ if(writeCmdData.handleValPair.attrHandle == CYBLE_RGB_DATA_COUNT_CHAR_HANDLE) { /* If the data sent is of one byte, then proceed. */ if(writeCmdData.handleValPair.value.len == 1) { /* Extract and save the set ADV data counter value */ dataADVCounter = *(writeCmdData.handleValPair.value.val); /* This increment is done to balance the ++ done as part of CYBLE_EVT_GATTS_WRITE_REQ */ dataADVCounter--; /* Update the ADV data counter characteristic in GATT DB to allow * Client to read the latest ADV data counter value */ CyBle_GattsWriteAttributeValue(&writeCmdData.handleValPair, 0, &cyBle_connHandle, CYBLE_GATT_DB_LOCALLY_INITIATED); #ifdef DEBUG_ENABLED UART_UartPutString("dataADVCounter from CYBLE_EVT_GATTS_WRITE_CMD_REQ = "); PrintNum(dataADVCounter); UART_UartPutCRLF(' '); #endif } /* if(writeCmdData.handleValPair.value.len == 1) */ } break; case CYBLE_EVT_GAPC_SCAN_PROGRESS_RESULT: /* This event is generated whenever there is a peripheral device found by * while scanning */ if(CYBLE_STATE_CONNECTED != CyBle_GetState()) { /* If we are not connected to any peripheral device, then save the new device * information so to add it to our list */ scan_report = *(CYBLE_GAPC_ADV_REPORT_T*)eventParam; #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GAPC_SCAN_PROGRESS_RESULT "); UART_UartPutCRLF(' '); #endif #ifdef ENABLE_ADV_DATA_COUNTER /* If ADV DATA COUNTER is enabled, then the central device would check * if the counter in ADV packet of peripheral is less than its own counter * or not. If yes, then it will consider the peripheral as a potential * device to connect to.*/ if(scan_report.eventType == CYBLE_GAPC_CONN_UNDIRECTED_ADV) { /* If the scan report received is of advertising nature and the data * length is as expected... */ if(scan_report.dataLen == new_advData.advDataLen) { /* If the second last value of the advertising data matches the custom * marker, then the peripheral is a node of the network */ if(scan_report.data[scan_report.dataLen-2] == CUSTOM_ADV_DATA_MARKER) { /* If the ADV counter data in Advertising data is less than that of * the value in this scanning device, then the node is a potential node * whose color has to be updated. */ if((scan_report.data[scan_report.dataLen-1] < dataADVCounter) || ((scan_report.data[scan_report.dataLen-1] == 255) && (dataADVCounter == 0))) { /* Potential node found*/ potential_node_found = TRUE; /* Save the advertising peripheral address and type*/ memcpy(potential_node_bdAddr, scan_report.peerBdAddr, 6); potential_node_bdAddrType = scan_report.peerAddrType; #ifdef DEBUG_ENABLED UART_UartPutString("potential_node_found "); UART_UartPutCRLF(' '); #endif } else { /* If the ADV data counter is equal or more than the data counter * in this scanning device, then the node has latest RGB LED data * and does not need to be connected to. Reset the potential node * address */ potential_node_found = FALSE; potential_node_bdAddrType = 0; potential_node_bdAddr[0] = 0x00; potential_node_bdAddr[1] = 0x00; potential_node_bdAddr[2] = 0x00; potential_node_bdAddr[3] = 0x00; potential_node_bdAddr[4] = 0x00; potential_node_bdAddr[5] = 0x00; } } } } #endif /* If the received scan data is part of scan response from a peripheral... */ if(scan_report.eventType == CYBLE_GAPC_SCAN_RSP) { /* If the data lenght of the scan reponse packet is equal to expected * scan response data lenght...*/ if(scan_report.dataLen == SCAN_TAG_DATA_LEN) { #ifdef ENABLE_ADV_DATA_COUNTER /* If a potential node had been found earlier as part of received * advertising data, then compare the address of stored potential * node and received address of the scan response */ if(potential_node_found) { /* Compare the two addresses and type */ if((!memcmp(scan_report.peerBdAddr, potential_node_bdAddr, 6)) && (potential_node_bdAddrType == scan_report.peerAddrType)) { #endif /* If the scan report data matches the expected data (scan_tag), * then it is our desired node */ if(!memcmp(scan_report.data, scan_tag, scan_report.dataLen)) { #ifdef DEBUG_ENABLED UART_UartPutString("Titan Found "); UART_UartPutCRLF(' '); #endif /* Stop existing scan */ CyBle_GapcStopScan(); #ifdef DEBUG_ENABLED UART_UartPutString("Stop Scan called "); UART_UartPutCRLF(' '); #endif /* Save the peripheral BD address and type*/ peripAddr.type = scan_report.peerAddrType; peripAddr.bdAddr[0] = scan_report.peerBdAddr[0]; peripAddr.bdAddr[1] = scan_report.peerBdAddr[1]; peripAddr.bdAddr[2] = scan_report.peerBdAddr[2]; peripAddr.bdAddr[3] = scan_report.peerBdAddr[3]; peripAddr.bdAddr[4] = scan_report.peerBdAddr[4]; peripAddr.bdAddr[5] = scan_report.peerBdAddr[5]; /* Set the flag to allow application to connect to the * peripheral found */ clientConnectToDevice = TRUE; #ifdef ENABLE_ADV_DATA_COUNTER /* Reset the potential node flag*/ potential_node_found = FALSE; #endif } #ifdef ENABLE_ADV_DATA_COUNTER } } #endif } } } break; case CYBLE_EVT_GAP_DEVICE_CONNECTED: /* This event is received whenever the device connect on GAP layer */ if(ble_gap_state == BLE_CENTRAL) { #ifdef ENABLE_CENTRAL_DISCOVERY /* The Device is connected now. Start Attributes discovery process.*/ CyBle_GattcStartDiscovery(cyBle_connHandle); #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GAP_DEVICE_CONNECTED "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif #else /* If this system is currently acting in Central role and has connected * to a peripheral device, then write directly the ADV counter data and * RGB LED control data using attribute handles */ /* Set the device connected flag */ deviceConnected = TRUE; #ifdef DEBUG_ENABLED UART_UartPutString("Directly write RGB using Attr handle "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif /* Write the Data Counter value */ writeADVcounterdata.attrHandle = CYBLE_RGB_DATA_COUNT_CHAR_HANDLE; writeADVcounterdata.value.val = &dataADVCounter; writeADVcounterdata.value.len = 1; CyBle_GattcWriteWithoutResponse(cyBle_connHandle, &writeADVcounterdata); /* Write the RGB LED Value */ writeRGBdata.attrHandle = CYBLE_RGB_LED_CONTROL_CHAR_HANDLE; writeRGBdata.value.val = RGBData; writeRGBdata.value.len = RGB_LED_DATA_LEN; CyBle_GattcWriteCharacteristicValue(cyBle_connHandle, &writeRGBdata); #endif } break; case CYBLE_EVT_GATTC_DISCOVERY_COMPLETE: /* This event is generated whenever the discovery procedure is complete*/ #ifdef ENABLE_CENTRAL_DISCOVERY deviceConnected = TRUE; #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GATTC_DISCOVERY_COMPLETE "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif /* Write the Data Counter value */ writeADVcounterdata.attrHandle = CYBLE_RGB_DATA_COUNT_CHAR_HANDLE; writeADVcounterdata.value.val = &dataADVCounter; writeADVcounterdata.value.len = 1; CyBle_GattcWriteWithoutResponse(cyBle_connHandle, &writeADVcounterdata); /* Write the RGB LED Value */ writeRGBdata.attrHandle = CYBLE_RGB_LED_CONTROL_CHAR_HANDLE; writeRGBdata.value.val = RGBData; writeRGBdata.value.len = RGB_LED_DATA_LEN; CyBle_GattcWriteCharacteristicValue(cyBle_connHandle, &writeRGBdata); #endif break; case CYBLE_EVT_GATTC_WRITE_RSP: /* This event is generated when the Client device receives a response * as part of the Write request sent earlier. This indicates that * the RGB LED data was written successfully */ #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GATTC_WRITE_RSP "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif /* Disconnect the existing connection and restart scanning */ if((cyBle_connHandle.bdHandle != 0)) { CyBle_GapDisconnect(cyBle_connHandle.bdHandle); restartScanning = TRUE; #ifdef DEBUG_ENABLED UART_UartPutString("Disconnect from CYBLE_EVT_GATTC_WRITE_RSP "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } break; case CYBLE_EVT_GAP_DEVICE_DISCONNECTED: /* This event is generated when the device disconnects from an * existing connection */ deviceConnected = FALSE; #ifdef DEBUG_ENABLED UART_UartPutString("CYBLE_EVT_GAP_DEVICE_DISCONNECTED "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif if((ble_gap_state == BLE_PERIPHERAL) && (switch_Role != TRUE)) { /* If the current role of this system was Peripheral and the role * is not to be switched, then restart advertisement */ if(CYBLE_STATE_DISCONNECTED == CyBle_GetState()) { CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); #ifdef DEBUG_ENABLED UART_UartPutString("Restart Advertisement "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } } else if((ble_gap_state == BLE_CENTRAL) && (switch_Role != TRUE)) { /* If the current role of this system was Central and the role * is not to be switched, then restart scanning */ if(CYBLE_STATE_DISCONNECTED == CyBle_GetState()) { CyBle_GapcStartScan(CYBLE_SCANNING_FAST); #ifdef DEBUG_ENABLED UART_UartPutString("Restart Scanning "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } } break; default: eventParam = eventParam; break; } }