void StartWirelessConnection(void) { Read_MAC_Address(); LED_1 = 0; LED_2 = 0; //ConsolePutROMString((ROM char *)"\r\n<MAC Addr:"); //PrintChar(myLongAddress[3]); //PrintChar(myLongAddress[2]); //PrintChar(myLongAddress[1]); //PrintChar(myLongAddress[0]); //ConsolePutROMString((ROM char *)"\r>"); //ConsolePutROMString((ROM char *)"\r\n Board role: "); // if the node are Coordinator ConsolePutROMString((ROM char *)"COORDINATOR >> "); PrintChar(myNodeNumber); ConsolePutROMString((ROM char *)"\r\n<MAC Addr:"); PrintChar(myLongAddress[3]); PrintChar(myLongAddress[2]); PrintChar(myLongAddress[1]); PrintChar(myLongAddress[0]); ConsolePutROMString((ROM char *)"\r>"); MiApp_ProtocolInit(FALSE); // Force PANID & SHORT ADDRESS if( MiApp_SetChannel(myChannel) == FALSE ) { return; } MiApp_ConnectionMode(ENABLE_ALL_CONN); myPANID.v[0] = 0x34; myPANID.v[1] = 0x12; myShortAddress.v[0] = 0x00; myShortAddress.v[1] = myNodeNumber; myChannel = PanCoordToCoordChan; //role = ROLE_COORDINATOR; if( MiApp_SetChannel(myChannel) == FALSE ) { return; } }
int main(void) { BYTE i; GOL_MSG msg; // GOL message structure to interact with GOL InitializeBoard(); TRISGbits.TRISG3 = 1; TRISGbits.TRISG2 = 0; Nop(); PORTGbits.RG2 = 1; Nop(); //RADIO SETUP // Function MiApp_ProtocolInit initialize the protocol stack.// MiApp_ProtocolInit(FALSE); //setting the frequency at whick this wx will transmit over comes back as false if the set channel fails if( MiApp_SetChannel(myChannel) == FALSE ) { return 0; } //Enables all connection types MiApp_ConnectionMode(ENABLE_ALL_CONN); //try to establish connection with peer device: p1=0xff=establish connection with any device, p2=direct connection //returns 0xFF if it false i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT); if( i == 0xFF ) { //starting a connecton: direct connect, duration of scan, channel to start connection on MiApp_StartConnection(START_CONN_DIRECT, 10, 24); } //END RADIO SETUP LED = 1; // i2cRec(2); while(1) { //i2cSend(3,2); if(GOLDraw()) // Draw GOL object { TouchGetMsg(&msg); // Get message from touch screen GOLMsg(&msg); // Process message } /* MiApp_MessageAvailable returns a bool*/ if( MiApp_MessageAvailable() ) { Incoming=*rxMessage.Payload; /* Function MiApp_DiscardMessage is used to release the current received packet.*/ MiApp_DiscardMessage(); } }//end while }
uint8_t miwiInit(uint8_t reset) { // Simple check to see if it could be valid if ((myLongAddress[MY_ADDRESS_LENGTH - 1] == 0x00) || (myLongAddress[MY_ADDRESS_LENGTH - 1] == 0xFF)) { return MAC_ADDRESS_FAIL; } // +++++++++++++++++++++++++++++++++++ // Radio Setup // ----------------------------------- if ((MiApp_ProtocolInit(true) == false) || (reset == true)) { // First time MiApp_ProtocolInit(false); // Set default channel if (MiApp_SetChannel(myChannel) == false) { return MY_CHANNEL_FAIL; } if (MiApp_StartConnection(START_CONN_DIRECT, 10, 0)) { // Set Connection Mode MiApp_ConnectionMode(ENABLE_PREV_CONN); return MIWI_SUCCESS; } else { return MIWI_FAIL; } } else { return MIWI_SUCCESS; } return MIWI_FAIL; }
int main(void) #endif { BYTE i; static DWORD t = 0; static DWORD dwLastIP = 0; static UINT8 updateDisplay = 0; #if defined (EZ_CONFIG_STORE) static DWORD ButtonPushStart = 0; #endif #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) UINT8 channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN; // WF_PRESCAN tWFScanResult bssDesc; #endif // Initialize application specific hardware InitializeBoard(); // Initiates board setup process if button is depressed // on startup if (BUTTON1_IO == 0u) { while (BUTTON1_IO == 0); SelfTestMode(); } //#if defined(USE_LCD) /*******************************************************************/ // Initialize the LCD /*******************************************************************/ ConfigureLCD_SPI(); LCDInit(); /*******************************************************************/ // Display Start-up Splash Screen /*******************************************************************/ LCDBacklightON(); LEDS_ON(); LCDErase(); sprintf((char *) LCDText, (char*) " MiWi - WiFi "); sprintf((char *) &(LCDText[16]), (char*) " Gateway Demo"); LCDUpdate(); /*******************************************************************/ // Initialize the MiWi Protocol Stack. The only input parameter indicates // if previous network configuration should be restored. /*******************************************************************/ MiApp_ProtocolInit(FALSE); /*******************************************************************/ // Set Device Communication Channel /*******************************************************************/ if (MiApp_SetChannel(myChannel) == FALSE) { LCDDisplay((char *) "ERROR: Unable to Set Channel..", 0, TRUE); while (1); } /*******************************************************************/ // Set the connection mode. The possible connection modes are: // ENABLE_ALL_CONN: Enable all kinds of connection // ENABLE_PREV_CONN: Only allow connection already exists in // connection table // ENABL_ACTIVE_SCAN_RSP: Allow response to Active scan // DISABLE_ALL_CONN: Disable all connections. /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, // which is acquired by discovery process (active scan). If // the value of the index is 0xFF, try to establish a // connection with any peer. // The second parameter is the mode to establish connection, // either direct or indirect. Direct mode means connection // within the radio range; indirect mode means connection // may or may not in the radio range. /*******************************************************************/ i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT); /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ if (i != 0xFF) { ; // Connected Peer on Channel } else { /*******************************************************************/ // If no network can be found and join, we need to start a new // network by calling function MiApp_StartConnection // // The first parameter is the mode of start connection. There are // two valid connection modes: // - START_CONN_DIRECT start the connection on current // channel // - START_CONN_ENERGY_SCN perform an energy scan first, // before starting the connection on // the channel with least noise // - START_CONN_CS_SCN perform a carrier sense scan // first, before starting the // connection on the channel with // least carrier sense noise. Not // supported for current radios // // The second parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a // half second and 11 is 2 seconds. Maximum scan duration is // 14, or roughly 16 seconds. // // The third parameter is the channel map. Bit 0 of the // double word parameter represents channel 0. For the 2.4GHz // frequency band, all possible channels are channel 11 to // channel 26. As the result, the bit map is 0x07FFF800. Stack // will filter out all invalid channels, so the application // only needs to pay attention to the channels that are not // preferred. /*******************************************************************/ MiApp_StartConnection(START_CONN_DIRECT, 10, 0); } // Turn OFF LCD after setting up MiWi Connection LCDBacklightOFF(); // Initialize stack-related hardware components that may be // required by the UART configuration routines TickInit(); #if defined(STACK_USE_MPFS2) MPFSInit(); #endif // Initialize Stack and application related NV variables into AppConfig. InitAppConfig(); dwLastIP = AppConfig.MyIPAddr.Val; // Initialize core stack layers (MAC, ARP, TCP, UDP) and // application modules (HTTP, SNMP, etc.) StackInit(); #if defined ( EZ_CONFIG_SCAN ) WFInitScan(); #endif #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) // WF_PRESCAN: Pre-scan before starting up as SoftAP mode WF_CASetScanType(MY_DEFAULT_SCAN_TYPE); WF_CASetChannelList(channelList, sizeof (channelList)); if (WFStartScan() == WF_SUCCESS) { SCAN_SET_DISPLAY(SCANCXT.scanState); SCANCXT.displayIdx = 0; //putsUART("main: Prescan WFStartScan() success ................. \r\n"); } // Needed to trigger g_scan_done WFRetrieveScanResult(0, &bssDesc); #else #if defined(WF_CS_TRIS) WF_Connect(); #endif // defined(WF_CS_TRIS) #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) // Initialize any application-specific modules or functions/ // For this demo application, this only includes the // UART 2 TCP Bridge #if defined(STACK_USE_UART2TCP_BRIDGE) UART2TCPBridgeInit(); #endif #if defined(STACK_USE_ZEROCONF_LINK_LOCAL) ZeroconfLLInitialize(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSInitialize(MY_DEFAULT_HOST_NAME); mDNSServiceRegister( (const char *) AppConfig.NetBIOSName, // base name of the service "_http._tcp.local", // type of the service 80, // TCP or UDP port, at which this service is available ((const BYTE *) "path=/index.htm"), // TXT info 1, // auto rename the service when if needed NULL, // no callback function NULL // no application context ); mDNSMulticastFilterRegister(); #endif #if defined(WF_CONSOLE) WFConsoleInit(); #endif // Now that all items are initialized, begin the co-operative // multitasking loop. This infinite loop will continuously // execute all stack-related tasks, as well as your own // application's functions. Custom functions should be added // at the end of this loop. // Note that this is a "co-operative mult-tasking" mechanism // where every task performs its tasks (whether all in one shot // or part of it) and returns so that other tasks can do their // job. // If a task needs very long time to do its job, it must be broken // down into smaller pieces so that other tasks can have CPU time. LEDS_OFF(); while (1) { /*******************************************************************/ // Check Button Events /*******************************************************************/ if (BUTTON1_IO == 0u) { while (BUTTON1_IO == 0); LCDErase(); sprintf((char *) LCDText, (char*) "Erase Room Info?"); sprintf((char *) &(LCDText[16]), (char*) "SW0:Yes SW2:No"); LCDUpdate(); while (1) { if (BUTTON1_IO == 0u) { while (BUTTON1_IO == 0); LCDDisplay((char *) "STATUS: Erasing...", 0, TRUE); EraseRoomInfo(); DisplaySSID(); break; } else if (BUTTON2_IO == 0u) { while (BUTTON2_IO == 0); DisplaySSID(); break; } } } // Blink LED0 twice per sec when unconfigured, once per sec after config if ((TickGet() - t >= TICK_SECOND / (4ul - (CFGCXT.isWifiDoneConfigure * 2ul)))) { t = TickGet(); LED0_INV(); } if(CFGCXT.isWifiNeedToConfigure) updateDisplay = 1; #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) if (g_scan_done) { if (g_prescan_waiting) { SCANCXT.displayIdx = 0; while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) { WFDisplayScanMgr(); } #if defined(WF_CS_TRIS) WF_Connect(); #endif DisplaySSID(); g_scan_done = 0; g_prescan_waiting = 0; } } #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) // This task performs normal stack task including checking // for incoming packet, type of packet and calling // appropriate stack entity to process it. StackTask(); WiFiTask(); // This tasks invokes each of the core stack application tasks StackApplications(); #if defined(STACK_USE_ZEROCONF_LINK_LOCAL) ZeroconfLLProcess(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSProcess(); // Use this function to exercise service update function // HTTPUpdateRecord(); #endif // Process application specific tasks here. // For this demo app, this will include the Generic TCP // client and servers, and the SNMP, Ping, and SNMP Trap // demos. Following that, we will process any IO from // the inputs on the board itself. // Any custom modules or processing you need to do should // go here. #if defined(WF_CONSOLE) //WFConsoleProcess(); // #if !defined(STACK_USE_EZ_CONFIG) // IperfAppCall(); // #endif //WFConsoleProcessEpilogue(); wait_console_input: #endif #if defined(STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE) GenericTCPClient(); #endif #if defined(STACK_USE_GENERIC_TCP_SERVER_EXAMPLE) GenericTCPServer(); #endif #if defined(STACK_USE_SMTP_CLIENT) SMTPDemo(); #endif #if defined(STACK_USE_ICMP_CLIENT) PingDemo(); //PingConsole(); #endif #if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED) //User should use one of the following SNMP demo // This routine demonstrates V1 or V2 trap formats with one variable binding. SNMPTrapDemo(); #if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3) //This routine provides V2 format notifications with multiple (3) variable bindings //User should modify this routine to send v2 trap format notifications with the required varbinds. //SNMPV2TrapDemo(); #endif if (gSendTrapFlag) SNMPSendTrap(); #endif #if defined ( WF_CONSOLE ) && defined ( EZ_CONFIG_SCAN ) WFDisplayScanMgr(); #endif #if defined(STACK_USE_BERKELEY_API) BerkeleyTCPClientDemo(); BerkeleyTCPServerDemo(); BerkeleyUDPClientDemo(); #endif if((updateDisplay && CFGCXT.isWifiDoneConfigure) || (dwLastIP != AppConfig.MyIPAddr.Val)) { if(dwLastIP != AppConfig.MyIPAddr.Val) dwLastIP = AppConfig.MyIPAddr.Val; if(updateDisplay && CFGCXT.isWifiDoneConfigure) updateDisplay = 0; #if defined(STACK_USE_ANNOUNCE) AnnounceIP(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSFillHostRecord(); #endif DisplaySSID(); } } }
/********************************************************************* * Function: void main(void) * * PreCondition: none * * Input: none * * Output: none * * Side Effects: none * * Overview: This is the main function that runs the simple * example demo. The purpose of this example is to * demonstrate the simple application programming * interface for the MiWi(TM) Development * Environment. By virtually total of less than 30 * lines of code, we can develop a complete * application using MiApp interface. The * application will first try to establish a P2P * link with another device and then process the * received information as well as transmit its own * information. * MiWi(TM) DE also support a set of rich * features. Example code FeatureExample will * demonstrate how to implement the rich features * through MiApp programming interfaces. * * Note: **********************************************************************/ void main (void) { BYTE i; BYTE TxSynCount = 0; BYTE TxSynCount2 = 0; BoardInit(); //Has LCDInit() also covered in this, need to make this separate to ensure that if there was a problem with I2C the board hangs up ConsoleInit(); // Initialize the system /*******************************************************************/ LCDBacklightON(); LCDDisplay((char *)"8-Bit Wireless Development Kit ", 0, TRUE); DelayMs(5000); LCDBacklightOFF(); Printf("\r\nInput Configuration:"); Printf("\r\n Button 1: RB0"); Printf("\r\n Button 2: RB2"); Printf("\r\nOutput Configuration:"); Printf("\r\n LED 1: RA2"); Printf("\r\n LED 2: RA3"); Printf("\r\n LED 3: RB1"); #if defined(MRF24J40) Printf("\r\n RF Transceiver: MRF24J40"); #elif defined(MRF49XA) Printf("\r\n RF Transceiver: MRF49XA"); #elif defined(MRF89XA) Printf("\r\n RF Transceiver: MRF89XA"); #endif Printf("\r\n Demo Instruction:"); Printf("\r\n Power on the board until LED 1 lights up "); Printf("\r\n to indicate connecting with peer. "); Printf("\r\n Ping Pong Results will be displayed on LCD"); Printf("\r\n Use MCLR + RB2 to switch to Self Test Mode. "); Printf("\r\n\r\n"); LED_1 = 0; LED_2 = 0; MiApp_ProtocolInit(FALSE); // Set default channel if(MiApp_SetChannel(myChannel) == FALSE) { #if defined(__18CXX) return; #else return (0); #endif } /*******************************************************************/ // Function MiApp_ConnectionMode defines the connection mode. The // possible connection modes are: // ENABLE_ALL_CONN: Enable all kinds of connection // ENABLE_PREV_CONN: Only allow connection already exists in // connection table // ENABL_ACTIVE_SCAN_RSP: Allow response to Active scan // DISABLE_ALL_CONN: Disable all connections. /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ LCDDisplay((char *)"Connecting Peer on Channel %d ", myChannel, TRUE); /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, // which is acquired by discovery process (active scan). If // the value of the index is 0xFF, try to establish a // connection with any peer. // The second parameter is the mode to establish connection, // either direct or indirect. Direct mode means connection // within the radio range; indirect mode means connection // may or may not in the radio range. /*******************************************************************/ #ifdef ENABLE_HAND_SHAKE i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT); #endif /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ if(i != 0xFF) { LCDDisplay((char *)"Joined Network Successfully..", 0, TRUE); } else { MiApp_StartConnection(START_CONN_DIRECT, 10, 0); } /*******************************************************************/ // Function DumpConnection is used to print out the content of the // Connection Entry on the hyperterminal. It may be useful in // the debugging phase. // The only parameter of this function is the index of the // Connection Entry. The value of 0xFF means to print out all // valid Connection Entry; otherwise, the Connection Entry // of the input index will be printed out. /*******************************************************************/ #ifdef ENABLE_DUMP DumpConnection(0xFF); #endif #ifndef ENABLE_POWERSAVE // Turn on LED 1 to indicate P2P connection established LED_1 = 1; #endif DelayMs(20); LCDDisplay((char *)"Ping Pong Demo RB0(TX) RB2(RX)", 0, TRUE); /*******************************************************************/ // Following block display demo instructions on LCD based on the // demo board used. /*******************************************************************/ /*Configure the device in transmit or Receive Mode*/ ReadButtonPress(); while(1) { PingPongStateMachine(); } //end of while(1) } //end of main
void MyMIWI_Start(void) { BYTE i; char theStr[64]; /*******************************************************************/ // Initialize Microchip proprietary protocol. Which protocol to use // depends on the configuration in ConfigApp.h /*******************************************************************/ /*******************************************************************/ // Function MiApp_ProtocolInit initialize the protocol stack. The // only input parameter indicates if previous network configuration // should be restored. In this simple example, we assume that the // network starts from scratch. /*******************************************************************/ MiApp_ProtocolInit(FALSE); // Set default channel if( MiApp_SetChannel(myMIWI_Channel) == FALSE ) { Printf("\r\nSelection of channel "); PrintDec(myMIWI_Channel); Printf(" is not supported in current condition.\r\n"); return; } /*******************************************************************/ // Function MiApp_ConnectionMode defines the connection mode. The // possible connection modes are: // ENABLE_ALL_CONN: Enable all kinds of connection // ENABLE_PREV_CONN: Only allow connection already exists in // connection table // ENABL_ACTIVE_SCAN_RSP: Allow response to Active scan // DISABLE_ALL_CONN: Disable all connections. /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, which // is acquired by discovery process (active scan). If the value // of the index is 0xFF, try to establish a connection with any // peer. // The second parameter is the mode to establish connection, either // direct or indirect. Direct mode means connection within the // radio range; Indirect mode means connection may or may not // in the radio range. /*******************************************************************/ #if defined(MyMIWI_NODE1) i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT); #else while( (i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT)) == 0xFF ); #endif if(i != 0xFF) { sprintf(theStr, "Connected Peer on Channel %d\n>", myMIWI_Channel); MyConsole_SendMsg(theStr); } else { /*******************************************************************/ // If no network can be found and join, we need to start a new // network by calling function MiApp_StartConnection // // The first parameter is the mode of start connection. There are // two valid connection modes: // - START_CONN_DIRECT start the connection on current // channel // - START_CONN_ENERGY_SCN perform an energy scan first, // before starting the connection on // the channel with least noise // - START_CONN_CS_SCN perform a carrier sense scan // first, before starting the // connection on the channel with // least carrier sense noise. Not // supported for current radios // // The second parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a // half second and 11 is 2 seconds. Maximum scan duration is // 14, or roughly 16 seconds. // // The third parameter is the channel map. Bit 0 of the // double word parameter represents channel 0. For the 2.4GHz // frequency band, all possible channels are channel 11 to // channel 26. As the result, the bit map is 0x07FFF800. Stack // will filter out all invalid channels, so the application // only needs to pay attention to the channels that are not // preferred. /*******************************************************************/ MiApp_StartConnection(START_CONN_DIRECT, 10, 0); MyConsole_SendMsg("Start Connection\n>"); } /*******************************************************************/ // Function DumpConnection is used to print out the content of the // Connection Entry on the hyperterminal. It may be useful in // the debugging phase. // The only parameter of this function is the index of the // Connection Entry. The value of 0xFF means to print out all // valid Connection Entry; otherwise, the Connection Entry // of the input index will be printed out. /*******************************************************************/ DumpConnection(0xFF); }
void main (void) { uint8_t i; SYSTEM_Initialize(); CONSOLE_Initialize(); /*******************************************************************/ // Initialize the system /*******************************************************************/ /*******************************************************************/ // Following block display demo information on LCD of Explore 16 or // PIC18 Explorer demo board. /*******************************************************************/ LCDDisplay((char *)"Chat Demo", 0, true); // Clear the screen (VT100) Printf("\x1b[2J"); // Send the cursor home (VT100) Printf("\x1b[H"); Printf("\r\nChat Demo"); #if defined(MRF24J40) Printf("\r\nRF Transceiver: MRF24J40"); #elif defined(MRF49XA) Printf("\r\nRF Transceiver: MRF49XA"); #elif defined(MRF89XA) Printf("\r\nRF Transceiver: MRF89XA"); #endif Printf("\r\n\r\nDemo Instruction:"); Printf("\r\nUse Console to Chat with the Peer Device"); Printf("\r\n"); LED_1 = 0; LED_2 = 0; /******************************************************************/ // Read the MAC address from the MAC EEPROM on the PICTail Card ReadMacAddress(); // ..and display on terminal Printf("\r\n\r\nMy MAC Address: 0x"); for(i = 0; i < MY_ADDRESS_LENGTH; i++) { CONSOLE_PrintHex(myLongAddress[MY_ADDRESS_LENGTH-1-i]); } /*******************************************************************/ // Initialize Microchip proprietary protocol. Which protocol to use // depends on the configuration in ConfigApp.h /*******************************************************************/ /*******************************************************************/ // Function MiApp_ProtocolInit initialize the protocol stack. The // only input parameter indicates if previous network configuration // should be restored. In this simple example, we assume that the // network starts from scratch. /*******************************************************************/ MiApp_ProtocolInit(false); // Set default channel if(MiApp_SetChannel(myChannel) == false) { Printf("\r\nERROR: Unable to program the channel\r\n"); Printf("\r\nPress MCLR to start again\r\n"); LCDDisplay((char *)"Error: Unable to Program Channel ", 0, TRUE); while(1); //Display error message on LCD and Console } /*******************************************************************/ // Function MiApp_ConnectionMode defines the connection mode. The // possible connection modes are: // ENABLE_ALL_CONN: Enable all kinds of connection // ENABLE_PREV_CONN: Only allow connection already exists in // connection table // ENABL_ACTIVE_SCAN_RSP: Allow response to Active scan // DISABLE_ALL_CONN: Disable all connections. /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ LCDDisplay((char *)"Connecting Peer on Channel %d ", myChannel, true); Printf("\r\n\r\nConnecting to Peer...\r\n"); /*******************************************************************/ // Function MiApp_StartConnection will enable a node to start operating // in a variety of ways. Usually, this fucntion is called by the // PAN Coordinator who is the first in the PAN. // // The first parameter defines the mode to start the PAN in // // The second parameter defines the scan duration (if energy/carrier // sense scan is enabled). 0 if START_CONN_DIRECT used. // // The third parameter is a bit map of of the channels to perform the // noise scan on. 0 if START_CONN_DIRECT used. /*******************************************************************/ MiApp_StartConnection(START_CONN_DIRECT, 0, 0) ; /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, // which is acquired by discovery process (active scan). If // the value of the index is 0xFF, try to establish a // connection with any peer. // The second parameter is the mode to establish connection, // either direct or indirect. Direct mode means connection // within the radio range; indirect mode means connection // may or may not in the radio range. /*******************************************************************/ #ifdef ENABLE_HAND_SHAKE i = 0xFF; while(i == 0xFF) { i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT); } #endif /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ LCDDisplay((char *)"Joined Network Successfully..", 0, true); /*******************************************************************/ // Function DumpConnection is used to print out the content of the // Connection Entry on the hyperterminal. It may be useful in // the debugging phase. // The only parameter of this function is the index of the // Connection Entry. The value of 0xFF means to print out all // valid Connection Entry; otherwise, the Connection Entry // of the input index will be printed out. /*******************************************************************/ #ifdef ENABLE_DUMP DumpConnection(0xFF); #endif #ifndef ENABLE_POWERSAVE // Turn on LED 1 to indicate P2P connection established LED_1 = 1; #endif DELAY_ms(100); LCDBacklightON(); LCD_Erase(); sprintf((char *)LCDText, (char *)"MyAddr: %02x%02x%02x", myLongAddress[2], myLongAddress[1], myLongAddress[0]); sprintf((char *) &(LCDText[16]), (char *)"PeerAddr: %02x%02x%02x", ConnectionTable[i].Address[2], ConnectionTable[i].Address[1], ConnectionTable[i].Address[0]); LCD_Update(); /*******************************************************************/ // Following block display demo instructions on LCD based on the // demo board used. /*******************************************************************/ Printf("-------------------------------------------------------\r\n"); Printf("Chat Window: \r\n"); Printf("-------------------------------------------------------\r\n"); Printf("$$"); while(1) { if(MiApp_MessageAvailable()) { ProcessRxMessage(); } if(CONSOLE_IsGetReady()) { FormatTxMessage(); } if(messagePending) { tickCurrent = MiWi_TickGet(); if ( (MiWi_TickGetDiff(tickCurrent, tickPrevious) > (ONE_SECOND * 30)) || (TxMessageSize >= MAX_MESSAGE_LEN) || (transmitPending == true) ) { TransmitMessage(); } } // Display connection table if RB0 is pressed if(PUSH_BUTTON_1 == 0) { while(PUSH_BUTTON_1 == 0); Printf("\r\n\r\nDumping Connection Table...\r\n"); DumpConnection(0xFF); Printf("-------------------------------------------------------\r\n"); Printf("Chat Window: \r\n"); Printf("-------------------------------------------------------\r\n"); Printf("$$ "); } } //Enable device to foward the received packet information to the console } //end of main
int main(void) #endif { BYTE i, j; BYTE OperatingChannel = 0xFF; BYTE TxSynCount = 0; BYTE TxSynCount2 = 0; BYTE TxPersistFailures = 0; BOOL ReadyToSleep = FALSE; BYTE TxNum = 0; BYTE RxNum = 0; BYTE PressedButton = 0; /*******************************************************************/ // Initialize the system /*******************************************************************/ BoardInit(); ConsoleInit(); DemoOutput_Greeting(); /*********************************************************************/ // Function MiApp_ProtocolInit intialize the protocol stack. // The return value is a boolean to indicate the status of the // operation. // The only parameter indicates if Network Freezer should be invoked. // When Network Freezer feature is invoked, all previous network // configurations will be restored to the states before the // reset or power cycle // // In this example, we assume that the user wants to apply Network // Freezer feature and restore the network configuration if // button 1 is pressed and hold when powering up. /*********************************************************************/ if( (PUSH_BUTTON_1 == 0) && ( MiApp_ProtocolInit(TRUE) == TRUE ) ) { DemoOutput_NetworkFreezer(); while(PUSH_BUTTON_1 == 0 ); } else { /*********************************************************************/ // Function MiApp_ProtocolInit intialize the protocol stack. // The return value is a boolean to indicate the status of the // operation. // The only parameter indicates if Network Freezer should be invoked. // When Network Freezer feature is invoked, all previous network // configurations will be restored to the states before the // reset or power cycle // // In this example, we assume that the user wants to start from // scratch and ignore previous network configuration if button 1 // is released when powering up. /*********************************************************************/ MiApp_ProtocolInit(FALSE); DemoOutput_StartActiveScan(); while(1) { /*********************************************************************/ // Function MiApp_SearchConnection will return the number of existing // connections in all channels. It will help to decide which channel // to operate on and which connection to add // The return value is the number of connections. The connection data // are stored in global variable ActiveScanResults. Maximum active // scan result is defined as ACTIVE_SCAN_RESULT_SIZE // The first parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a half // second and 11 is 2 seconds. Maximum scan duration is 14, or // roughly 16 seconds. // The second parameter is the channel map. Bit 0 of the double // word parameter represents channel 0. For the 2.4GHz frequency // band, all possible channels are channel 11 to channel 26. // As the result, the bit map is 0x07FFF800. Stack will filter // out all invalid channels, so the application only needs to pay // attention to the channels that are not preferred. /*********************************************************************/ j = MiApp_SearchConnection(10, 0xFFFFFFFF); OperatingChannel = DemoOutput_ActiveScanResults(j); if( OperatingChannel != 0xFF ) { /*******************************************************************/ // Function MiApp_SetChannel assign the operation channel(frequency) // for the transceiver. Channels 0 - 31 has been defined for the // wireless protocols, but not all channels are valid for all // transceivers, depending on their hardware design, operating // frequency band, data rate and other RF parameters. Check the // definition of FULL_CHANNEL_MAP for details. /*******************************************************************/ MiApp_SetChannel(OperatingChannel); break; } DemoOutput_Rescan(); } /*********************************************************************/ // Function MiApp_ConnectionMode sets the connection mode for the // protocol stack. Possible connection modes are: // - ENABLE_ALL_CONN accept all connection request // - ENABLE_PREV_CONN accept only known device to connect // - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but allow // response to active scan // - DISABLE_ALL_CONN disable all connection request, including // active scan request /*********************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Function MiApp_EstablishConnection establish connections between // two devices. It has two input parameters: // The first parameter is the index of the target device in the // active scan table. It requires a MiApp_SearchConnection call // before hand. If seraching connection is not performed in // advance, user can apply 0xFF to the first parameter to // indicate that it is OK to establish connection with any // device. // The second parameter is the connection mode, either directly or // indirectly. Direct connection is a connection in the radio // range. All protocol stack support this connection mode. // Indirect connection is the connection out of radio range. // An indirect connection has to rely on other device to route // the messages between two connected devices. Indirect // connection is also called "Socket" connection in MiWi // Protocol. Since MiWi P2P protocol only handles connection // of one hop, indirect connection is not supported in MiWi // P2P protocol, but supported in other networking protocols. // Function MiApp_EstablishConnection returns the index of the // connected device in the connection table. If no connection // is established after predefined retry times // CONNECTION_RETRY_TIMES, it will return 0xFF. If multiple // connections have been established, it will return the one // of the indexes of the connected device. /*******************************************************************/ i = MiApp_EstablishConnection(0, CONN_MODE_DIRECT); DemoOutput_Connected(); } // Turn on LED 1 to indicate connection established LED_1 = 1; /*******************************************************************/ // Function DumpConnection is used to print out the content of the // P2P Connection Entry on the hyperterminal. It may be useful in // the debugging phase. // The only parameter of this function is the index of the // Connection Entry. The value of 0xFF means to print out all // valid Connection Entries; otherwise, the Connection Entry // of the input index will be printed out. /*******************************************************************/ DumpConnection(0xFF); DemoOutput_Instruction(); while(1) { /*******************************************************************/ // Function MiApp_MessageAvailable will return a boolean to indicate // if a message for application layer has been received by the // transceiver. If a message has been received, all information will // be stored in rxMessage, structure of RECEIVED_MESSAGE. /*******************************************************************/ if( MiApp_MessageAvailable() ) { DemoOutput_HandleMessage(); /*******************************************************************/ // Function MiApp_DiscardMessage is used to release the current // received message. After calling this function, the stack can // start to process the next received message. /*******************************************************************/ MiApp_DiscardMessage(); // Toggle LED2 to indicate receiving a packet. LED_2 ^= 1; DemoOutput_UpdateTxRx(TxNum, ++RxNum); } else { /***********************************************************************/ // TxPersistFailures is the local variable to track the transmission // failure because no acknowledgement frame is received. Typically, // this is the indication of either very strong noise, or the PAN // has hopped to another channel. /***********************************************************************/ if( TxPersistFailures > 3 ) { DemoOutput_StartResync(); /*******************************************************************/ // Function MiApp_TransceiverPowerState is used to set the power state // of RF transceiver. There are three possible states: // - POWER_STATE_SLEEP Put transceiver into sleep // - POWER_STATE_WAKEUP Wake up the transceiver only // - POWER_STATE_WAKEUP_DR Wake up and send Data Request command /*******************************************************************/ MiApp_TransceiverPowerState(POWER_STATE_WAKEUP); /***********************************************************************/ // Function MiApp_ResyncConnection is used to synchronized connection // if one side of communication jumped to another channel, when // frequency agility is performed. Usually, this is done by the // sleeping device, since the sleeping device cannot hear the broadcast // of channel hopping command. // // The first parameter is the index of connection table for the peer // node, which we would like to resynchronize to. // The second parameter is the bit map of channels to be scanned /***********************************************************************/ MiApp_ResyncConnection(0, 0xFFFFFFFF); TxPersistFailures = 0; ReadyToSleep = FALSE; DemoOutput_EndResync(); } else { ReadyToSleep = TRUE; } /*******************************************************************/ // If Data Request command and data transmision has been handled, // as the RFD device, it is time to consider put both the radio and // MCU into sleep mode to conserve power. /*******************************************************************/ if( ReadyToSleep ) { ReadyToSleep = FALSE; /*******************************************************************/ // Function MiApp_TransceiverPowerState is used to set the power // state of RF transceiver. There are three possible states: // - POWER_STATE_SLEEP Put transceiver into sleep // - POWER_STATE_WAKEUP Wake up the transceiver only // - POWER_STATE_WAKEUP_DR Wake up and send Data Request // command /*******************************************************************/ MiApp_TransceiverPowerState(POWER_STATE_SLEEP); /*******************************************************************/ // Prepare the condition to wake up the MCU. The MCU can either be // waken up by the timeout of watch dog timer (Time Synchronization // off), timeout of counter with external 32KHz crystal (Time // Synchronization on), or by the pin change notification interrupt // by pushing the button. MCU handling of sleep preparing for // different demo boards can be found in HardwareProfile.c /*******************************************************************/ PrepareWakeup(); // Put MCU into sleep mode Sleep(); /*******************************************************************/ // Handling the wakeup procedure. The steps differ for different // demo boards and families of MCUs. Details can be found in // HardwareProfile.c /*******************************************************************/ AfterWakeup(); PressedButton = ButtonPressed(); /*******************************************************************/ // Function MiApp_TransceiverPowerState is used to set the power // state of RF transceiver. There are three possible states: // - POWER_STATE_SLEEP Put transceiver into sleep // - POWER_STATE_WAKEUP Wake up the transceiver only // - POWER_STATE_WAKEUP_DR Wake up and send Data Request // command /*******************************************************************/ if( MiApp_TransceiverPowerState(POWER_STATE_WAKEUP_DR) > SUCCESS ) { TxPersistFailures++; DemoOutput_ConnectionLost(TxPersistFailures); } else { if( TxPersistFailures > 0 ) { DemoOutput_UpdateTxRx(TxNum, RxNum); } TxPersistFailures = 0; } switch( PressedButton ) { case 1: /*******************************************************************/ // Button 1 pressed. // First use MiApp_FlushTx to reset the Transmit buffer. Then fill // the TX buffer by calling function MiApp_WriteData /*******************************************************************/ MiApp_FlushTx(); for(i = 0; i < 21; i++) { MiApp_WriteData(MiWi[(TxSynCount%6)][i]); } TxSynCount++; /*******************************************************************/ // Function MiApp_BroadcastPacket is used to broadcast a message // The only parameter is the boolean to indicate if we need to // secure the message /*******************************************************************/ MiApp_BroadcastPacket(FALSE); DemoOutput_UpdateTxRx(++TxNum, RxNum); break; case 2: /*******************************************************************/ // Button 2 pressed. // First use MiApp_FlushTx to reset the Transmit buffer. Then fill // the TX buffer by calling function MiApp_WriteData /*******************************************************************/ MiApp_FlushTx(); for(i = 0; i < 11; i++) { MiApp_WriteData(DE[(TxSynCount2%6)][i]); } TxSynCount2++; /*******************************************************************/ // Function MiApp_UnicastConnection is one of the functions to // unicast a message. // The first parameter is the index of connection table for // the peer device. In this demo, since there are only two // devices involved, the peer device must be stored in the // first Connection Entry in the connection table. // The second parameter is the boolean to indicate if we need // to secure the frame. If encryption is applied, the // security level and security key are defined in the // configuration file for the transceiver // // Another way to unicast a message is by calling function // MiApp_UnicastAddress. Instead of supplying the index of the // connection table of the peer device, this function requires the // input parameter of destination address directly. /*******************************************************************/ if( MiApp_UnicastConnection(0, TRUE) == FALSE ) { DemoOutput_UnicastFail(); } else { TxNum++; } DemoOutput_UpdateTxRx(TxNum, RxNum); break; default: break; } } } } }