/***************************************************************************** * FUNCTION: WF_Connect * * RETURNS: None * * PARAMS: None * * NOTES: Connects to an 802.11 network. Customize this function as needed * for your application. *****************************************************************************/ static void WF_Connect(void) { UINT8 ConnectionProfileID; UINT8 channelList[] = MY_DEFAULT_CHANNEL_LIST; #if defined(WF_USE_POWER_SAVE_FUNCTIONS) BOOL PsPollEnabled; #endif /* create a Connection Profile */ WF_CPCreate(&ConnectionProfileID); #if defined(STACK_USE_UART) putrsUART("Set SSID ("); putsUART(AppConfig.MySSID); putrsUART(")\r\n"); #endif WF_CPSetSsid(ConnectionProfileID, AppConfig.MySSID, AppConfig.SsidLength); #if defined(STACK_USE_UART) putrsUART("Set Network Type\r\n"); #endif WF_CPSetNetworkType(ConnectionProfileID, MY_DEFAULT_NETWORK_TYPE); #if defined(STACK_USE_UART) putrsUART("Set Scan Type\r\n"); #endif WF_CASetScanType(MY_DEFAULT_SCAN_TYPE); #if defined(STACK_USE_UART) putrsUART("Set Channel List\r\n"); #endif WF_CASetChannelList(channelList, sizeof(channelList)); #if defined(STACK_USE_UART) putrsUART("Set list retry count\r\n"); #endif // The Retry Count parameter tells the WiFi Connection manager how many attempts to make when trying // to connect to an existing network. In the Infrastructure case, the default is to retry forever so that // if the AP is turned off or out of range, the radio will continue to attempt a connection until the // AP is eventually back on or in range. In the Adhoc case, the default is to retry 3 times since the // purpose of attempting to establish a network in the Adhoc case is only to verify that one does not // initially exist. If the retry count was set to WF_RETRY_FOREVER in the AdHoc mode, an AdHoc network // would never be established. The constants MY_DEFAULT_LIST_RETRY_COUNT_ADHOC and // MY_DEFAULT_LIST_RETRY_COUNT_INFRASTRUCTURE have been created specifically for the June 2011 MAL release. #if defined(EZ_CONFIG_STORE) if (AppConfig.networkType == WF_ADHOC) WF_CASetListRetryCount(MY_DEFAULT_LIST_RETRY_COUNT_ADHOC); else WF_CASetListRetryCount(MY_DEFAULT_LIST_RETRY_COUNT_INFRASTRUCTURE); #else #if (MY_DEFAULT_NETWORK_TYPE == WF_ADHOC) WF_CASetListRetryCount(MY_DEFAULT_LIST_RETRY_COUNT_ADHOC); #else WF_CASetListRetryCount(MY_DEFAULT_LIST_RETRY_COUNT_INFRASTRUCTURE); #endif #endif #if defined(STACK_USE_UART) putrsUART("Set Event Notify\r\n"); #endif WF_CASetEventNotificationAction(MY_DEFAULT_EVENT_NOTIFICATION_LIST); #if defined(WF_USE_POWER_SAVE_FUNCTIONS) PsPollEnabled = (MY_DEFAULT_PS_POLL == WF_ENABLED); if (!PsPollEnabled) { /* disable low power (PS-Poll) mode */ #if defined(STACK_USE_UART) putrsUART("Disable PS-Poll\r\n"); #endif WF_PsPollDisable(); } else { /* Enable low power (PS-Poll) mode */ #if defined(STACK_USE_UART) putrsUART("Enable PS-Poll\r\n"); #endif WF_PsPollEnable(TRUE); } #endif #if defined(STACK_USE_UART) putrsUART("Set Beacon Timeout\r\n"); #endif WF_CASetBeaconTimeout(40); /* Set Security */ #if (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_OPEN) #if defined(STACK_USE_UART) putrsUART("Set Security (Open)\r\n"); #endif #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WEP_40) #if defined(STACK_USE_UART) putrsUART("Set Security (WEP40)\r\n"); #endif #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WEP_104) #if defined(STACK_USE_UART) putrsUART("Set Security (WEP104)\r\n"); #endif #elif MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_WITH_KEY #if defined(STACK_USE_UART) putrsUART("Set Security (WPA with key)\r\n"); #endif #elif MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA2_WITH_KEY #if defined(STACK_USE_UART) putrsUART("Set Security (WPA2 with key)\r\n"); #endif #elif MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_WITH_PASS_PHRASE #if defined(STACK_USE_UART) putrsUART("Set Security (WPA with pass phrase)\r\n"); #endif #elif MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA2_WITH_PASS_PHRASE #if defined(STACK_USE_UART) putrsUART("Set Security (WPA2 with pass phrase)\r\n"); #endif #elif MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_AUTO_WITH_KEY #if defined(STACK_USE_UART) putrsUART("Set Security (WPA with key, auto-select)\r\n"); #endif #elif MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE #if defined(STACK_USE_UART) putrsUART("Set Security (WPA with pass phrase, auto-select)\r\n"); #endif #endif /* MY_DEFAULT_WIFI_SECURITY_MODE */ WF_CPSetSecurity(ConnectionProfileID, AppConfig.SecurityMode, AppConfig.WepKeyIndex, /* only used if WEP enabled */ AppConfig.SecurityKey, AppConfig.SecurityKeyLength); #if defined(STACK_USE_UART) putrsUART("Start WiFi Connect\r\n"); #endif WF_CMConnect(ConnectionProfileID); }
static void OutputConnectionFailedMsg(UINT16 eventInfo) { #if defined(MRF24WG) UINT8 status; UINT8 reason; status = (UINT8)(eventInfo >> 8); reason = (UINT8)(eventInfo & 0xff); if (status == WF_RECV_DEAUTH || status == WF_RECV_DISASSOC) { putrsUART("Event: Connection Failed : "); putrsUART(connectionFailureStrings[status]); putrsUART(" : "); #if !defined(__18CXX) putrsUART(deauthDisssocReasonCodes[reason]); #endif } else if (status == WF_AUTHENTICATION_FAILURE || status == WF_ASSOCIATION_FAILURE) { putrsUART("Event: Connection Failed : "); putrsUART(connectionFailureStrings[status]); putrsUART(" : "); #if !defined(__18CXX) putrsUART(statusCodes[reason]); #endif } else if (status == WF_WPS_FAILURE) { putrsUART("Event: Connection Failed : "); putrsUART(connectionFailureStrings[status]); putrsUART(" : "); #if !defined(__18CXX) putrsUART(wpsState[reason >> 4]); putrsUART(" : "); putrsUART(wpsConfigErr[reason & 0x0f]); #endif }
/***************************************************************************** Function: void DHCPTask(void) Summary: Performs periodic DHCP tasks for all interfaces. Description: This function performs any periodic tasks requied by the DHCP module, such as sending and receiving messages involved with obtaining and maintaining a lease. Precondition: None Parameters: None Returns: None ***************************************************************************/ void DHCPTask(void) { BYTE i; for(i = 0; i < NETWORK_INTERFACES; i++) { LoadState(i); switch(DHCPClient.smState) { case SM_DHCP_DISABLED: // When the module is disabled, do absolutely nothing break; case SM_DHCP_GET_SOCKET: // Open a socket to send and receive broadcast messages on //DHCPClient.hDHCPSocket = UDPOpen(DHCP_CLIENT_PORT, NULL, DHCP_SERVER_PORT); DHCPClient.hDHCPSocket = UDPOpenEx(0,UDP_OPEN_SERVER,DHCP_CLIENT_PORT, DHCP_SERVER_PORT); if(DHCPClient.hDHCPSocket == INVALID_UDP_SOCKET) break; DHCPClient.smState = SM_DHCP_SEND_DISCOVERY; // No break case SM_DHCP_SEND_DISCOVERY: // Assume default IP Lease time of 60 seconds. // This should be minimum possible to make sure that if the // server did not specify lease time, we try again after this // minimum time. DHCPClient.dwLeaseTime = 60; DHCPClient.validValues.val = 0x00; DHCPClient.flags.bits.bIsBound = FALSE; DHCPClient.flags.bits.bOfferReceived = FALSE; // No point in wasting time transmitting a discovery if we are // unlinked. No one will see it. if(!MACIsLinked()) break; #if defined(WF_CS_IO) && defined(STACK_USE_UART) // Note: Use this debug message out to UART with caution. It can prevent slow down stack // performance and possibly prevent STA from properly receiving DHCP IP. // putrsUART("DHCP Send Discovery...\r\n"); #endif // Ensure transmitter is ready to accept data if(UDPIsPutReady(DHCPClient.hDHCPSocket) < 300u) break; // Toggle the BOOTP Broadcast flag to ensure compatibility with // bad DHCP servers that don't know how to handle broadcast // responses. This results in the next discovery attempt to be // made using the opposite mode. DHCPClient.flags.bits.bUseUnicastMode ^= 1; // Ensure that we transmit to the broadcast IP and MAC addresses // The UDP Socket remembers who it was last talking to memset((void*)&UDPSocketInfo[DHCPClient.hDHCPSocket].remote.remoteNode, 0xFF, sizeof(UDPSocketInfo[0].remote.remoteNode)); // Send the DHCP Discover broadcast _DHCPSend(DHCP_DISCOVER_MESSAGE, FALSE); // Start a timer and begin looking for a response DHCPClient.dwTimer = TickGet(); DHCPClient.smState = SM_DHCP_GET_OFFER; break; case SM_DHCP_GET_OFFER: // Check to see if a packet has arrived if(UDPIsGetReady(DHCPClient.hDHCPSocket) < 250u) { // Go back and transmit a new discovery if we didn't get an offer after 2 seconds if(TickGet() - DHCPClient.dwTimer >= DHCP_TIMEOUT) DHCPClient.smState = SM_DHCP_SEND_DISCOVERY; break; } // Let the DHCP server module know that there is a DHCP server // on this network DHCPClient.flags.bits.bDHCPServerDetected = TRUE; // Check to see if we received an offer if(_DHCPReceive() != DHCP_OFFER_MESSAGE) break; DHCPClient.smState = SM_DHCP_SEND_REQUEST; // No break case SM_DHCP_SEND_REQUEST: if(UDPIsPutReady(DHCPClient.hDHCPSocket) < 258u) break; // Ensure that we transmit to the broadcast IP and MAC addresses // The UDP Socket remembers who it was last talking to, so // we must set this back to the broadcast address since the // current socket values are the unicast addresses of the DHCP // server. memset((void*)&UDPSocketInfo[DHCPClient.hDHCPSocket].remote.remoteNode, 0xFF, sizeof(UDPSocketInfo[0].remote.remoteNode)); // Send the DHCP request message _DHCPSend(DHCP_REQUEST_MESSAGE, FALSE); // Start a timer and begin looking for a response DHCPClient.dwTimer = TickGet(); DHCPClient.smState = SM_DHCP_GET_REQUEST_ACK; break; case SM_DHCP_GET_REQUEST_ACK: // Check to see if a packet has arrived if(UDPIsGetReady(DHCPClient.hDHCPSocket) < 250u) { // Go back and transmit a new discovery if we didn't get an ACK after 2 seconds if(TickGet() - DHCPClient.dwTimer >= DHCP_TIMEOUT) DHCPClient.smState = SM_DHCP_SEND_DISCOVERY; break; } // Check to see if we received an offer switch(_DHCPReceive()) { case DHCP_ACK_MESSAGE: UDPClose(DHCPClient.hDHCPSocket); DHCPClient.hDHCPSocket = INVALID_UDP_SOCKET; DHCPClient.dwTimer = TickGet(); DHCPClient.smState = SM_DHCP_BOUND; DHCPClient.flags.bits.bEvent = 1; DHCPClient.flags.bits.bIsBound = TRUE; if(DHCPClient.validValues.bits.IPAddress) { AppConfig.MyIPAddr = DHCPClient.tempIPAddress; #if defined(WF_CS_IO) #if defined(STACK_USE_UART ) putrsUART("DHCP client successful\r\n"); #endif SignalDHCPSuccessful(); #endif } if(DHCPClient.validValues.bits.Mask) AppConfig.MyMask = DHCPClient.tempMask; if(DHCPClient.validValues.bits.Gateway) AppConfig.MyGateway = DHCPClient.tempGateway; #if defined(STACK_USE_DNS) if(DHCPClient.validValues.bits.DNS) AppConfig.PrimaryDNSServer.Val = DHCPClient.tempDNS.Val; AppConfig.SecondaryDNSServer.Val = 0x00000000ul; if(DHCPClient.validValues.bits.DNS2) AppConfig.SecondaryDNSServer.Val = DHCPClient.tempDNS2.Val; #endif //if(DHCPClient.validValues.bits.HostName) // memcpy(AppConfig.NetBIOSName, (void*)DHCPClient.tempHostName, sizeof(AppConfig.NetBIOSName)); break; case DHCP_NAK_MESSAGE: DHCPClient.smState = SM_DHCP_SEND_DISCOVERY; break; } break; case SM_DHCP_BOUND: if(TickGet() - DHCPClient.dwTimer < TICK_SECOND) break; // Check to see if our lease is still valid, if so, decrement lease // time if(DHCPClient.dwLeaseTime >= 2ul) { DHCPClient.dwTimer += TICK_SECOND; DHCPClient.dwLeaseTime--; break; } // Open a socket to send and receive DHCP messages on //DHCPClient.hDHCPSocket = UDPOpen(DHCP_CLIENT_PORT, NULL, DHCP_SERVER_PORT); DHCPClient.hDHCPSocket = UDPOpenEx(0,UDP_OPEN_SERVER,DHCP_CLIENT_PORT, DHCP_SERVER_PORT); if(DHCPClient.hDHCPSocket == INVALID_UDP_SOCKET) break; DHCPClient.smState = SM_DHCP_SEND_RENEW; // No break case SM_DHCP_SEND_RENEW: case SM_DHCP_SEND_RENEW2: case SM_DHCP_SEND_RENEW3: if(UDPIsPutReady(DHCPClient.hDHCPSocket) < 258u) break; // Send the DHCP request message _DHCPSend(DHCP_REQUEST_MESSAGE, TRUE); DHCPClient.flags.bits.bOfferReceived = FALSE; // Start a timer and begin looking for a response DHCPClient.dwTimer = TickGet(); DHCPClient.smState++; break; case SM_DHCP_GET_RENEW_ACK: case SM_DHCP_GET_RENEW_ACK2: case SM_DHCP_GET_RENEW_ACK3: // Check to see if a packet has arrived if(UDPIsGetReady(DHCPClient.hDHCPSocket) < 250u) { // Go back and transmit a new discovery if we didn't get an ACK after 2 seconds if(TickGet() - DHCPClient.dwTimer >= DHCP_TIMEOUT) { if(++DHCPClient.smState > SM_DHCP_GET_RENEW_ACK3) DHCPClient.smState = SM_DHCP_SEND_DISCOVERY; } break; } // Check to see if we received an offer switch(_DHCPReceive()) { case DHCP_ACK_MESSAGE: UDPClose(DHCPClient.hDHCPSocket); DHCPClient.hDHCPSocket = INVALID_UDP_SOCKET; DHCPClient.dwTimer = TickGet(); DHCPClient.smState = SM_DHCP_BOUND; DHCPClient.flags.bits.bEvent = 1; break; case DHCP_NAK_MESSAGE: DHCPClient.smState = SM_DHCP_SEND_DISCOVERY; break; } break; } } }
/* move cursor to point of backspace */ CursorRight_N(orig_index - 1 - gCmdLinePromptLength); } } static void EraseEntireLine() { // int i; putrsUART( (ROM FAR char*) eraseEntireLineEscapeSequence); CursorLeft_N(GET_CURSOR()); SET_CURSOR(0); } #if 0 /* add back if you want this feature */ static void EraseEntireScreen() { putrsUART( (ROM FAR char*) eraseEntireScreenEscapeSequence); }
/******************************************************************************* Function: void WaitForMgmtResponse(UINT8 expectedSubtype, UINT8 freeAction) Summary: Waits for a management response Description: Called after sending a mgmt request. This function waits for a mgmt response. The caller can optionally request the the management response be freed immediately (by this function) or not freed. If not freed, the caller is responsible to free the response buffer. Precondition: MACInit must be called. Parameters: expectedSubtype -- Expected subtype of the mgmt response freeAction -- FREE_MGMT_BUFFER or DO_NOT_FREE_MGMT_BUFFER Returns: None Remarks: *****************************************************************************/ void WaitForMgmtResponse(UINT8 expectedSubtype, UINT8 freeAction) { #if defined(__18CXX) static tMgmtMsgRxHdr hdr; #else tMgmtMsgRxHdr hdr; #endif g_WaitingForMgmtResponse = TRUE; /* Wait until mgmt response is received */ while (gMgmtConfirmMsgReceived == FALSE) { WFProcess(); /* if received a data packet while waiting for mgmt packet */ if (g_HostRAWDataPacketReceived) { // We can't let the StackTask processs data messages that come in while waiting for mgmt // response because the application might send another mgmt message, which is illegal until the response // is received for the first mgmt msg. And, we can't prevent the race condition where a data message // comes in before a mgmt response is received. Thus, the only solution is to throw away a data message // that comes in while waiting for a mgmt response. This should happen very infrequently. If using TCP then the // stack takes care of retries. If using UDP, the application has to deal with occasional data messages not being // received. Also, applications typically do not send a lot of management messages after connected. // throw away the data rx RawMountRxBuffer(RAW_DATA_RX_ID); DeallocateDataRxBuffer(); g_HostRAWDataPacketReceived = FALSE; /* ensure interrupts enabled */ WF_EintEnable(); } } g_WaitingForMgmtResponse = FALSE; /* set this back to FALSE so the next mgmt send won't think he has a response before one is received */ gMgmtConfirmMsgReceived = FALSE; /* if the caller wants to delete the response immediately (doesn't need any data from it */ if (freeAction == FREE_MGMT_BUFFER) { /* read and verify result before freeing up buffer to ensure our message send was successful */ RawRead(RAW_MGMT_RX_ID, 0, (UINT16)(sizeof(tMgmtMsgRxHdr)), (UINT8 *)&hdr); /* mgmt response subtype had better match subtype we were expecting */ WF_ASSERT(hdr.subtype == expectedSubtype); /* Mgmt response 'result' field should always indicate success. If this assert is hit the error codes are located */ /* WFApi.h. Search for WF_SUCCESS for the list of error codes. */ if (hdr.result == WF_ERROR_HOST_SCAN_NOT_ALLOWED) { #if defined(STACK_USE_UART) putrsUART("Host Scan Failed. Host scan is allowed only in idle or connected state\r\n"); #endif } else if (hdr.result == WF_ERROR_INVALID_WPS_PIN) { #if defined(STACK_USE_UART) putrsUART("WPS failed : Invalid WPS PIN data\r\n"); #endif } else if (hdr.result == WF_ERROR_DISCONNECT_FAILED) { #if defined(STACK_USE_UART) putrsUART("Disconnect failed. Disconnect is allowed only when module is in connected state\r\n"); #endif } else if (hdr.result == WF_ERROR_NO_STORED_BSS_DESCRIPTOR) { #if defined(STACK_USE_UART) putrsUART("No stored scan results\r\n"); #endif } else if (hdr.result != WF_SUCCESS) { #if defined(STACK_USE_UART) UINT8 buf[8]; putrsUART("WaitForMgmtResponse result error: "); sprintf((char *)buf, "%d",hdr.result); putrsUART((char *)buf); putrsUART("\r\n"); #endif //WF_ASSERT(FALSE); } /* free mgmt buffer */ DeallocateMgmtRxBuffer(); } }
static void UnderlineMode(void) { putrsUART(inverseVideoEscapeSequence); }
/*= InsertCharacter ========================================================= Purpose: Inserts and echoes an printable character into the command line at the cursor location. Inputs: c -- char to insert Returns: none ============================================================================*/ static void InsertCharacter(INT8 c) { UINT8 len; UINT8 i; UINT8 orig_cursor_index = GET_CURSOR(); UINT8 count; /* throw away characters if exceeded cmd line length */ if (GET_LEN_RX_CMD_STRING() >= sizeof(g_ConsoleContext.rxBuf)-1) { return; } len = GET_LEN_RX_CMD_STRING() + gCmdLinePromptLength; /* if inserting a character at end of cmd line */ if (GET_CURSOR() == len) { g_ConsoleContext.rxBuf[GET_CURSOR() - gCmdLinePromptLength] = c; SET_CURSOR(GET_CURSOR() + 1); EchoCharacter(c); } /* inserting a character somewhere before the end of command line */ else { /* Null out tmp cmd line */ memset(gTmpCmdLine, 0x00, sizeof(gTmpCmdLine)); /* copy up to the point of insertion */ strncpy( (char *) gTmpCmdLine, (const char *) g_ConsoleContext.rxBuf, GET_CURSOR() - gCmdLinePromptLength); /* insert the new character */ gTmpCmdLine[GET_CURSOR() - gCmdLinePromptLength] = c; /* copy the chars after the new character */ strncpy( (char *) &gTmpCmdLine[GET_CURSOR() - gCmdLinePromptLength + 1], (const char *) &g_ConsoleContext.rxBuf[GET_CURSOR() - gCmdLinePromptLength], len - GET_CURSOR()); /* put the first part of new string in the cmd line buffer */ strcpy( (char *) g_ConsoleContext.rxBuf, (const char *) gTmpCmdLine); /* erase entire line, put the cursor at index 0 */ EraseEntireLine(); /* output the prompt */ putrsUART( (ROM FAR char *) gCmdLinePrompt); /* Output the updated command line */ putsUART( (char *) &g_ConsoleContext.rxBuf[0]); /* move the cursor to the next insert location */ count = (len + 1) - orig_cursor_index - 1; for (i = 0; i < count; ++i) { putrsUART( (ROM FAR char *) cursorLeftEscapeSequence); } SET_CURSOR(orig_cursor_index + 1); } }
Zone_States IsZoneTriggered (int ZoneID) { Zone_States TheZoneState, PreviousZoneState; WORD Ignore; //ensure zone is not bypassed or isolated, if so return nothing if ((ZoneConfig[ZoneID].IsIsolated) || (ZoneConfig[ZoneID].IsBypassed)) return StateNothing; // What is the previous state if (ZoneConfig[ZoneID].IsTampered) PreviousZoneState = StateTamper; else if (ZoneConfig[ZoneID].IsTriggered) PreviousZoneState = StateTrigger; else PreviousZoneState = StateNormal; // Determine the state of the zone TheZoneState = CheckEOL(ZoneID, &Ignore); //If the state is the same as the previous check and bounce timer not active return nothing. if ((PreviousZoneState == TheZoneState ) && (ZoneConfig[ZoneID].BounceDelay == (unsigned) 0)) return StateNothing; // *** TAMPER *** // Zone is Tampered if (TheZoneState == StateTamper) { ZoneConfig[ZoneID].IsTampered = TRUE; ZoneConfig[ZoneID].BounceDelay = 0; // Will cause a loop always returning StateTamper if left out // find out what Areas the zone is a part of and set them to tampered for(iCount = 0; iCount < AREACOUNT; iCount++) { if (isZoneMemberOfArea(ZoneID, iCount)) { AreaConfig[iCount].IsTampered = TRUE; #if defined(DEBUG_UART) putrsUART((ROM char*)" Area "); uitoa(iCount, xPLMsgKey); putsUART(xPLMsgKey); putrsUART((ROM char*)" is Tampered. \r\n"); #endif }// isZoneMemberOfArea(ZoneID, iCount) }// iCount return StateTamper; } // StateTamper // Return from Tamper if (PreviousZoneState == StateTamper) { ZoneConfig[ZoneID].IsTampered = FALSE; ZoneConfig[ZoneID].BounceDelay = 0; // find out what Areas the zone is a part and set tamper to false if no other zones in the area are tampered for(iCount = 0; iCount < AREACOUNT; iCount++) { if (isZoneMemberOfArea(ZoneID, iCount)) { for(i2Count=0; i2Count < ZONECOUNT; i2Count++) { if ((i2Count != ZoneID) && isZoneMemberOfArea(i2Count, iCount)) { if( ZoneConfig[i2Count].IsTampered == TRUE) { i2Count = 1; break; }// is triggered }// is member of the zone }//i2Count, Area in question if (i2Count >= ZONECOUNT) { // no zones in the area found to be triggered AreaConfig[iCount].IsTampered = FALSE; #if defined(DEBUG_UART) putrsUART((ROM char*)" Area "); uitoa(iCount, xPLMsgKey); putsUART(xPLMsgKey); putrsUART((ROM char*)" is not tampered. \r\n"); #endif }// i2Count >= ZONECOUNT }// isZoneMemberOfArea(ZoneID, iCount) }// iCount // When changing from Tampered to Triggered this will generate a Triggered event after the tamper cleared event ZoneConfig[ZoneID].IsTriggered = FALSE; // Return as normal even if triggered to ensure message sequence is correct return StateNormal; } // *** BOUNCE / TRIGGER CLEARED *** //Every time we return from Triggered to Normal there is a delay of .5 Second, this limits bouncing speed. //If BounceTimer not expired return Nothing. If we are bouncing it will only send 2 msg per 1/2 second. Do not change previous state if (ZoneConfig[ZoneID].BounceDelay > (unsigned) 1) { ZoneConfig[ZoneID].BounceDelay--; if (TheZoneState == StateTrigger) ZoneConfig[ZoneID].BounceDelay = 0; return StateNothing; } //if BounceTimer is expired clear BounceTimer if (ZoneConfig[ZoneID].BounceDelay == (unsigned) 1) { // if state = Trigger then return nothing as we have bounced back (Trigger, Normal Trigger) if (TheZoneState == StateTrigger) { ZoneConfig[ZoneID].BounceDelay = 0; #if defined(DEBUG_UART) putrsUART((ROM char*)" Bounce prevented. Zone "); uitoa(ZoneID, xPLMsgKey); putsUART(xPLMsgKey); putrsUART((ROM char*)" remains triggered.\r\n"); #endif return StateNothing; } // if state = normal return Normal and set the state flag on the zone if (TheZoneState == StateNormal) { ZoneConfig[ZoneID].BounceDelay = 0; ZoneConfig[ZoneID].IsTriggered = FALSE; ZoneConfig[ZoneID].IsTampered = FALSE; #if defined(DEBUG_UART) putrsUART((ROM char*)" Bounce Cleared. Zone "); uitoa(ZoneID, xPLMsgKey); putsUART(xPLMsgKey); putrsUART((ROM char*)" is normal. \r\n"); #endif // find out what Areas the zone is a part and set triggered to false if no other zones in the area // are also triggered at the same time for(iCount = 0; iCount < AREACOUNT; iCount++) { if (isZoneMemberOfArea(ZoneID, iCount)) { for(i2Count=0; i2Count < ZONECOUNT; i2Count++) { if ((i2Count != ZoneID) && isZoneMemberOfArea(i2Count, iCount)) { if( ZoneConfig[i2Count].IsTriggered == TRUE) { i2Count = 1; break; }// is triggered }// is member of the zone }//i2Count, Area in question if (i2Count >= ZONECOUNT) { // no zones in the area found to be triggered AreaConfig[iCount].IsTriggered = FALSE; #if defined(DEBUG_UART) putrsUART((ROM char*)" Area "); uitoa(iCount, xPLMsgKey); putsUART(xPLMsgKey); putrsUART((ROM char*)" is normal. \r\n"); #endif }// i2Count >= ZONECOUNT }// isZoneMemberOfArea(ZoneID, iCount) }// iCount return StateNormal; } } //If current state Normal, set the BounceTimer, return Nothing if (TheZoneState == StateNormal) { ZoneConfig[ZoneID].BounceDelay = BOUNCEDELAY; #if defined(DEBUG_UART) if (ZoneID == 0) putrsUART((ROM char*)" Bounce Set. \r\n"); #endif return StateNothing; } // *** TRIGGER *** //The only thing left should be a normal trigger, return trigger and set the state flag on the zone if (TheZoneState == StateTrigger) { ZoneConfig[ZoneID].BounceDelay = 0; ZoneConfig[ZoneID].IsTriggered = TRUE; #if defined(DEBUG_UART) putrsUART((ROM char*)"Zone "); uitoa(ZoneID, xPLMsgKey); putsUART(xPLMsgKey); putrsUART((ROM char*)"triggered. "); #endif // find out what Areas the zone is a part of and set them to triggered for(iCount = 0; iCount < AREACOUNT; iCount++) { if (isZoneMemberOfArea(ZoneID, iCount)) { AreaConfig[iCount].IsTriggered = TRUE; #if defined(DEBUG_UART) putrsUART((ROM char*)" Area "); uitoa(iCount, xPLMsgKey); putsUART(xPLMsgKey); putrsUART((ROM char*)" is Triggered. \r\n"); #endif }// isZoneMemberOfArea(ZoneID, iCount) }// iCount return StateTrigger; } } //IsZoneTriggered
Zone_States CheckEOL (int ZoneID, WORD* ADval) { char AN0String[7]; char DebugTemp[7]; int PlexerDevice, BinaryValue; // Disable all analogue multiplexer PLEXERA_S_IO = 1; // High = disabled PLEXERB_S_IO = 1; PLEXERC_S_IO = 1; // Select the analogue multiplexer PlexerDevice = ZoneID / 8; BinaryValue = ZoneID - ((ZoneID / 8) * 8); // The value can now be expressed as a 3 bit value if (PlexerDevice == 0) { PLEXERA_S_IO = 0; //enable this device PLEXERA_2_IO = ((BinaryValue / 4 > 0)?TRUE:FALSE); BinaryValue -= (BinaryValue / 4) * 4; PLEXERA_1_IO = ((BinaryValue / 2 > 0)?TRUE:FALSE); BinaryValue -= (BinaryValue / 2) * 2; PLEXERA_0_IO = ((BinaryValue > 0)?TRUE:FALSE); } // PlexerDevice ==0 else if (PlexerDevice == 1) { PLEXERB_S_IO = 0; //enable this device PLEXERB_2_IO = BinaryValue / 4; BinaryValue -= (BinaryValue / 4) * 4; PLEXERB_1_IO = BinaryValue / 2; BinaryValue -= (BinaryValue / 2) * 2; PLEXERB_0_IO = BinaryValue; } // PlexerDevice == 1 else if (PlexerDevice == 2) { PLEXERC_S_IO = 0; //enable this device PLEXERC_2_IO = BinaryValue / 4; BinaryValue -= (BinaryValue / 4) * 4; PLEXERC_1_IO = BinaryValue / 2; BinaryValue -= (BinaryValue / 2) * 2; PLEXERC_0_IO = BinaryValue; } // PlexerDevice == 2 else { #if defined(DEBUG_UART) putrsUART((ROM char*)" !!! CheckEOL is out of range !!!!! "); #endif *ADval = 0; return StateNormal; } //60 ns delay is required for the Multiplexer to swith analogue channels //Nop();Nop();Nop();Nop();Nop(); // Select A/D channel AN4 ADCON0 = 0b00010000; // ADON = On(1), GO/DONE = Idle (0), AN4 selected (0100), not used (0), calibration off (0) ADCON0bits.ADON = 1; ADCON0bits.GO = 1; // Wait until A/D conversion is done while(ADCON0bits.GO); // Convert 10-bit value into ASCII string *ADval = (WORD)ADRES; uitoa(*ADval, AN0String); if (ZoneID == 1) { memset(LCDText, '\0', 32); if (strlen(AN0String) < (unsigned int)4 ) strcatpgm2ram(AN0String, (rom char *) " "); if (strlen(AN0String) < (unsigned int)4 ) strcatpgm2ram(AN0String, (rom char *) " "); if (strlen(AN0String) < (unsigned int)4 ) strcatpgm2ram(AN0String, (rom char *) " "); strcat(LCDText, AN0String); strcatpgm2ram(LCDText, (rom char *) "->"); } if ( (*ADval >= (WORD)(EOLNORMAL - EOLTOLERANCE)) && (*ADval <= (WORD)(EOLNORMAL + EOLTOLERANCE))) { if (ZoneID == 1) { strcatpgm2ram(LCDText, (rom char *) "Normal"); LCDUpdate(); } // Need to consider if the zone is Normaly Open or Normaly Closed if (ZoneConfig[ZoneID].IsNO == FALSE) return StateNormal; else return StateTrigger; } else if ( (*ADval >= (WORD)(EOLTRIGGER - EOLTOLERANCE)) && (*ADval <= (WORD)(EOLTRIGGER + EOLTOLERANCE))) { if (ZoneID == 1) { strcatpgm2ram(LCDText, (rom char *) "Trigger"); LCDUpdate(); } // Need to consider if the zone is Normaly Open or Normaly Closed if (ZoneConfig[ZoneID].IsNO == FALSE) return StateTrigger; else return StateNormal; } else { if (ZoneID == 1) { strcatpgm2ram(LCDText, (rom char *) "Tamper"); LCDUpdate(); } return StateTamper; } } // CheckEOL
/***************************************************************************** * FUNCTION: WF_Connect * * RETURNS: None * * PARAMS: None * * NOTES: Connects to an 802.11 network. Customize this function as needed * for your application. *****************************************************************************/ static void WF_Connect(void) { UINT8 ConnectionProfileID; UINT8 channelList[] = MY_DEFAULT_CHANNEL_LIST; #if defined(WF_USE_POWER_SAVE_FUNCTIONS) BOOL PsPollEnabled; #endif /* create a Connection Profile */ WF_CPCreate(&ConnectionProfileID); #if defined(STACK_USE_UART) putrsUART("Set SSID ("); putsUART(AppConfig.MySSID); putrsUART(")\r\n"); #endif WF_CPSetSsid(ConnectionProfileID, AppConfig.MySSID, AppConfig.SsidLength); #if defined(STACK_USE_UART) putrsUART("Set Network Type\r\n"); #endif WF_CPSetNetworkType(ConnectionProfileID, AppConfig.networkType); if (AppConfig.networkType == WF_ADHOC) { WF_CPSetAdHocBehavior(ConnectionProfileID, WF_ADHOC_CONNECT_THEN_START); } #if defined(STACK_USE_UART) putrsUART("Set Security\r\n"); #endif switch(AppConfig.SecurityMode) { case WF_SECURITY_OPEN: WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_OPEN, 0, NULL, 0); break; case WF_SECURITY_WEP_40: // assume key 0 WF_CPSetSecurity(ConnectionProfileID, AppConfig.SecurityMode, 0, AppConfig.SecurityKey, 5); break; case WF_SECURITY_WEP_104: // assume key 0 WF_CPSetSecurity(ConnectionProfileID, AppConfig.SecurityMode, 0, AppConfig.SecurityKey, 13); break; case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE: WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE, 0, AppConfig.SecurityKey, strlen((char*)AppConfig.SecurityKey)); break; case WF_SECURITY_WPA_AUTO_WITH_KEY: WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_KEY, 0, AppConfig.SecurityKey, 32); break; default: { } //#if defined(STACK_USE_UART) // putrsUART("\r\n\r\nCaptain this should NOT happen.\r\n\r\n"); //#endif } #if defined(STACK_USE_UART) putrsUART("Set Scan Type\r\n"); #endif WF_CASetScanType(MY_DEFAULT_SCAN_TYPE); #if defined(STACK_USE_UART) putrsUART("Set Channel List\r\n"); #endif WF_CASetChannelList(channelList, sizeof(channelList)); #if defined(STACK_USE_UART) putrsUART("Set list retry count\r\n"); #endif WF_CASetListRetryCount(MY_DEFAULT_LIST_RETRY_COUNT); #if defined(STACK_USE_UART) putrsUART("Set Event Notify\r\n"); #endif WF_CASetEventNotificationAction(MY_DEFAULT_EVENT_NOTIFICATION_LIST); #if defined(WF_USE_POWER_SAVE_FUNCTIONS) PsPollEnabled = (MY_DEFAULT_PS_POLL == WF_ENABLED); if (!PsPollEnabled) { /* disable low power (PS-Poll) mode */ #if defined(STACK_USE_UART) putrsUART("Disable PS-Poll\r\n"); #endif WF_PsPollDisable(); } else { /* Enable low power (PS-Poll) mode */ #if defined(STACK_USE_UART) putrsUART("Enable PS-Poll\r\n"); #endif WF_PsPollEnable(TRUE); } #endif #if defined(STACK_USE_UART) putrsUART("Set Beacon Timeout\r\n"); #endif WF_CASetBeaconTimeout(40); #if defined(STACK_USE_UART) putrsUART("Start WiFi Connect\r\n"); #endif WF_CMConnect(ConnectionProfileID); }
/***************************************************************************** * FUNCTION: ChipReset * * RETURNS: N/A * * PARAMS: * N/A * * * NOTES: Performs the necessary SPI operations to cause the MRF24W to reset. * This function also implements a delay so that it will not return until * the WiFi device is ready to receive messages again. The delay time will * vary depending on the amount of code that must be loaded from serial * flash. *****************************************************************************/ static void ChipReset(void) { UINT16 value; UINT32 timeoutPeriod; UINT32 startTickCount; #if 0 putrsUART(" **** Bypass chip reset\r\n"); return; #endif timeoutPeriod = TICKS_PER_SECOND * 3; /* 3000 ms */ /* needed for Microchip PICTail (chip enable active low) */ WF_SetCE_N(WF_LOW); /* set low to enable regulator */ /* Configure reset pin */ WF_SetRST_N(WF_HIGH); /* Let SPI lines settle before first SPI transaction */ DelayMs(1); /* clear the power bit to disable low power mode on the MRF24W */ Write16BitWFRegister(WF_PSPOLL_H_REG, 0x0000); /* Set HOST_RESET bit in register to put device in reset */ Write16BitWFRegister(WF_HOST_RESET_REG, Read16BitWFRegister(WF_HOST_RESET_REG) | WF_HOST_RESET_MASK); /* Clear HOST_RESET bit in register to take device out of reset */ Write16BitWFRegister(WF_HOST_RESET_REG, Read16BitWFRegister(WF_HOST_RESET_REG) & ~WF_HOST_RESET_MASK); /* after reset is started poll register to determine when HW reset has completed */ startTickCount = (UINT32)TickGet(); do { Write16BitWFRegister(WF_INDEX_ADDR_REG, WF_HW_STATUS_REG); value = Read16BitWFRegister(WF_INDEX_DATA_REG); if (TickGet() - startTickCount >= timeoutPeriod) { WF_ASSERT(FALSE); } } while ( (value & WF_HW_STATUS_NOT_IN_RESET_MASK) == 0); /* if SPI not connected will read all 1's */ WF_ASSERT(value != 0xffff); /* now that chip has come out of HW reset, poll the FIFO byte count register */ /* which will be set to a non-zero value when the MRF24W initialization is */ /* complete. */ startTickCount = (UINT32)TickGet(); do { value = Read16BitWFRegister(WF_HOST_WFIFO_BCNT0_REG); if (TickGet() - startTickCount >= timeoutPeriod) { WF_ASSERT(FALSE); } } while (value == 0); }
int main(void) #endif { // static DWORD t = 0; static DWORD dwLastIP = 0; #if defined (EZ_CONFIG_STORE) // static DWORD ButtonPushStart = 0; #endif // Initialize application specific hardware InitializeBoard(); // Initialize stack-related hardware components that may be // required by the UART configuration routines TickInit(); MPFSInit(); InitDataBuffers(); Slave_SpiInit(); // Initialize Stack and application related NV variables into AppConfig. InitAppConfig(); // Initiates board setup process if button is depressed // on startup /* #if defined (WIFI_BOARD_FOC_HUB) XEEBeginWrite(0x0000); XEEWrite(0xFF); XEEWrite(0xFF); XEEEndWrite(); #else if(BUTTON0_IO == 0u) { #if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS) // Invalidate the EEPROM contents if BUTTON0 is held down for more than 4 seconds DWORD StartTime = TickGet(); LED_PUT(0x00); while(BUTTON0_IO == 0u) { if(TickGet() - StartTime > 4*TICK_SECOND) { #if defined(EEPROM_CS_TRIS) XEEBeginWrite(0x0000); XEEWrite(0xFF); XEEWrite(0xFF); XEEEndWrite(); #elif defined(SPIFLASH_CS_TRIS) SPIFlashBeginWrite(0x0000); SPIFlashWrite(0xFF); SPIFlashWrite(0xFF); #endif #if defined(STACK_USE_UART) putrsUART("\r\n\r\nBUTTON0 held for more than 4 seconds. Default settings restored.\r\n\r\n"); #endif LED_PUT(0x0F); while((LONG)(TickGet() - StartTime) <= (LONG)(9*TICK_SECOND/2)); LED_PUT(0x00); while(BUTTON0_IO == 0u); Reset(); break; } } #endif #if defined(STACK_USE_UART) DoUARTConfig(); #endif } #endif */ // Initialize core stack layers (MAC, ARP, TCP, UDP) and // application modules (HTTP, SNMP, etc.) StackInit(); #if defined ( EZ_CONFIG_SCAN ) WFInitScan(); #endif #if defined(WF_CS_TRIS) WF_Connect(); #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 *) "DemoWebServer", // 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 // 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. while(1) { /* #if defined (EZ_CONFIG_STORE) // Hold button3 for 4 seconds to reset to defaults. if (BUTTON3_IO == 0u) { // Button is pressed if (ButtonPushStart == 0) //Just pressed ButtonPushStart = TickGet(); else if(TickGet() - ButtonPushStart > 4*TICK_SECOND) RestoreWifiConfig(); } else { ButtonPushStart = 0; //Button release reset the clock } if (AppConfig.saveSecurityInfo) { // set true by WF_ProcessEvent after connecting to a new network // get the security info, and if required, push the PSK to EEPROM if ((AppConfig.SecurityMode == WF_SECURITY_WPA_WITH_PASS_PHRASE) || (AppConfig.SecurityMode == WF_SECURITY_WPA2_WITH_PASS_PHRASE) || (AppConfig.SecurityMode == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE)) { // only need to save when doing passphrase tWFCPElements profile; UINT8 connState; UINT8 connID; WF_CMGetConnectionState(&connState, &connID); WF_CPGetElements(connID, &profile); memcpy((char*)AppConfig.SecurityKey, (char*)profile.securityKey, 32); AppConfig.SecurityMode--; // the calc psk is exactly one below for each passphrase option AppConfig.SecurityKeyLength = 32; SaveAppConfig(&AppConfig); } AppConfig.saveSecurityInfo = FALSE; } #endif // EZ_CONFIG_STORE #if defined (STACK_USE_EZ_CONFIG) // Blink LED0 twice per sec when unconfigured, once per sec after config if((TickGet() - t >= TICK_SECOND/(4ul - (CFGCXT.isWifiDoneConfigure*2ul)))) #else // Blink LED0 (right most one) every second. if(TickGet() - t >= TICK_SECOND/2ul) #endif // STACK_USE_EZ_CONFIG { t = TickGet(); LED0_IO ^= 1; } */ // This task performs normal stack task including checking // for incoming packet, type of packet and calling // appropriate stack entity to process it. StackTask(); // This tasks invokes each of the core stack application tasks StackApplications(); // Process command received from Motherboad via SPI interface. //ProcessReceivedSpiCmds(); #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 (WIFI_BOARD_FOC_HUB) ProcessWiFiTransfers(); // Handles TCP/IP transfers DoWiFiWork(); // Handles SPI incoming requests #endif #if defined(WF_CONSOLE) WFConsoleProcess(); IperfAppCall(); WFConsoleProcessEpilogue(); #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(); #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 the local IP address has changed (ex: due to DHCP lease change) // write the new IP address to the LCD display, UART, and Announce // service if(dwLastIP != AppConfig.MyIPAddr.Val) { dwLastIP = AppConfig.MyIPAddr.Val; WiFiInfo.CurrentConfigPtr->MyIPAddr.Val = AppConfig.MyIPAddr.Val; #if defined(STACK_USE_UART) putrsUART((ROM char*)"\r\nNew IP Address: "); #endif DisplayIPValue(AppConfig.MyIPAddr); #if defined(STACK_USE_UART) putrsUART((ROM char*)"\r\n"); #endif #if defined(STACK_USE_ANNOUNCE) AnnounceIP(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSFillHostRecord(); #endif } } }
void timeSync(void) { BYTE i; signed char j; static TICK Timer; static TICK perodicTick = 0; static TICK t = 0; static TCP_SOCKET MySocket = INVALID_SOCKET; static NODE_INFO Server; static int arp_tries = 0; static int tcp_tries = 0; BYTE rcnt=0; BYTE ncnt=0; char foundData=0; if ((tickGet()-t) >= TICK_1S ) { t = tickGet(); timeNow++; } switch(smTS) { case SM_START: #if defined(TIMESYNC_DEBUG) putrsUART("Start!\r\n"); #endif // Set IP adress to connect to. Server.IPAddr.v[0]=193; Server.IPAddr.v[1]=11; Server.IPAddr.v[2]=249; Server.IPAddr.v[3]=54; arp_tries = 0; tcp_tries = 0; smTS = SM_ARP_RESOLVE; break; case SM_ARP_RESOLVE: #if defined(TIMESYNC_DEBUG) putrsUART("Resolve..\r\n"); #endif // If ARP is redy.. if (ARPIsTxReady()) { // Resolve the IP adress.. ARPResolve(&Server.IPAddr); arp_tries++; Timer = tickGet(); smTS = SM_ARP_RESOLVED; } break; case SM_ARP_RESOLVED: #if defined(TIMESYNC_DEBUG) putrsUART("Resolved..\r\n"); #endif // If IP adress is resolved, go to next state if (ARPIsResolved(&Server.IPAddr, &Server.MACAddr)) { smTS = SM_CONNECT; } // If not resolved and spent long time here, // Go back to previous state and re-resolve. else if (tickGet()-Timer > 1*TICK_1S) { smTS = SM_ARP_RESOLVE; } else if (arp_tries>=MAX_ARP_TRIES) { //Abort smTS = SM_ABORT; } break; case SM_CONNECT: #if defined(TIMESYNC_DEBUG) putrsUART("Connect..\r\n"); #endif // We have an sucessfull ARP, connect.. MySocket = TCPConnect(&Server, ServerPort); tcp_tries++; if(MySocket == INVALID_SOCKET) { // Do something. } Timer = tickGet(); smTS = SM_CONNECT_WAIT; break; case SM_CONNECT_WAIT: #if defined(TIMESYNC_DEBUG) putrsUART("Connect wait..\r\n"); #endif // Wait for connection.. if (TCPIsConnected(MySocket)) { smTS = SM_CONNECTED; } // If not connected and spent long time here, // Go back to previous state and re-connect. else if (tickGet()-Timer > 5*TICK_1S) { TCPDisconnect(MySocket); MySocket = INVALID_SOCKET; smTS = SM_CONNECT; } else if (tcp_tries>=MAX_TCP_TRIES) { //Abort TCPDisconnect(MySocket); MySocket = INVALID_SOCKET; smTS = SM_ABORT; } break; case SM_CONNECTED: #if defined(TIMESYNC_DEBUG) putrsUART("Connected..\r\n"); #endif // Send data. Timer = tickGet(); if(TCPIsPutReady(MySocket)) { TCPPut(MySocket, 'G'); TCPPut(MySocket, 'E'); TCPPut(MySocket, 'T'); TCPPut(MySocket, ' '); TCPPut(MySocket, '/'); TCPPut(MySocket, 't'); TCPPut(MySocket, 'i'); TCPPut(MySocket, 'm'); TCPPut(MySocket, 'e'); TCPPut(MySocket, '.'); TCPPut(MySocket, 'p'); TCPPut(MySocket, 'h'); TCPPut(MySocket, 'p'); TCPPut(MySocket, ' '); TCPPut(MySocket, 'H'); TCPPut(MySocket, 'T'); TCPPut(MySocket, 'T'); TCPPut(MySocket, 'P'); TCPPut(MySocket, '/'); TCPPut(MySocket, '1'); TCPPut(MySocket, '.'); TCPPut(MySocket, '0'); TCPPut(MySocket, '\r'); TCPPut(MySocket, '\n'); TCPPut(MySocket, '\r'); TCPPut(MySocket, '\n'); // Send the packet TCPFlush(MySocket); smTS = SM_RECEIVE; } break; case SM_RECEIVE: #if defined(TIMESYNC_DEBUG) putrsUART("Receive..\r\n"); #endif // Client disconnected. if(!TCPIsConnected(MySocket)) { smTS = SM_ABORT; break; } if(TCPIsGetReady(MySocket)) { while(TCPGet(MySocket, &i)) { if (i==CR) rcnt++; else if(i==LF) ncnt++; else { rcnt=0; ncnt=0; } if (foundData==1) { if (j>=0) { timeNow=timeNow+(((DWORD)i)<<(8*j--)); #if defined(TIMESYNC_DEBUG) while(BusyUART()); WriteUART(i); #endif } } if(rcnt>1 && ncnt>1) {j=3; timeNow=0; foundData=1;} } smTS = SM_DISCONNECT; } break; case SM_DISCONNECT: #if defined(TIMESYNC_DEBUG) putrsUART("\r\nDisconnect\r\n"); #endif foundData=0; t = tickGet(); lastSync = timeNow; perodicTick=tickGet(); TCPDisconnect(MySocket); MySocket = INVALID_SOCKET; smTS = SM_DONE; break; case SM_ABORT: #if defined(TIMESYNC_DEBUG) putrsUART("Abort...\r\n"); #endif smTS = SM_START; break; case SM_DONE: if (tickGet()-perodicTick > SYNC_INTERVAL*TICK_1S) { #if defined(TIMESYNC_DEBUG) putrsUART("GO!\r\n"); #endif smTS = SM_START; } break; default: smTS = SM_START; break; } }
/***************************************************************************** * FUNCTION: iwconfigDisplayStatus * * RETURNS: None * * PARAMS: None * * NOTES: Responds to the user invoking iwconfig with no parameters *****************************************************************************/ static void iwconfigDisplayStatus(void) { UINT8 *p; UINT8 tmp; UINT8 connectionState; UINT8 cpId; #if defined(MRF24WG) char buf[6]; #endif union { struct { UINT8 List[WF_CHANNEL_LIST_LENGTH]; UINT8 Num; } Channel; UINT8 Domain; struct { UINT8 String[WF_MAX_SSID_LENGTH+1]; UINT8 Len; } Ssid; struct { UINT8 NetworkType; } Mode; struct { UINT16 Threshold; } Rts; } ws; // workspace // cpId { WFConsolePrintRomStr("\tcpid: ", FALSE); WFConsolePrintInteger(iwconfigCb.cpId, 'd'); WFConsolePrintRomStr("", TRUE); } // channel { WF_CAGetChannelList(ws.Channel.List, &ws.Channel.Num); WFConsolePrintRomStr("\tchannel: ", FALSE); p = ws.Channel.List; tmp = ws.Channel.Num; while ( --tmp > 0u ) { WFConsolePrintInteger(*p, 'd'); WFConsolePrintRomStr(",", FALSE); p++; } WFConsolePrintInteger(*p, 'd'); WFConsolePrintRomStr("", TRUE); } #if defined(MRF24WG) // domain { WF_GetRegionalDomain(&ws.Domain); WFConsolePrintRomStr("\tdomain: ", FALSE); if ( ws.Domain == WF_DOMAIN_FCC ) { WFConsolePrintRomStr("fcc", TRUE); } else if ( ws.Domain == WF_DOMAIN_ETSI ) { WFConsolePrintRomStr("etsi", TRUE); } else if ( ws.Domain == WF_DOMAIN_JAPAN ) { WFConsolePrintRomStr("japan", TRUE); } else if ( ws.Domain == WF_DOMAIN_OTHER ) { WFConsolePrintRomStr("other", TRUE); } else { WFConsolePrintRomStr("unknown", TRUE); } } #else // domain { WF_GetRegionalDomain(&ws.Domain); WFConsolePrintRomStr("\tdomain: ", FALSE); if ( ws.Domain == WF_DOMAIN_FCC ) { WFConsolePrintRomStr("fcc", TRUE); } else if ( ws.Domain == WF_DOMAIN_IC ) { WFConsolePrintRomStr("ic", TRUE); } else if ( ws.Domain == WF_DOMAIN_ETSI ) { WFConsolePrintRomStr("etsi", TRUE); } else if ( ws.Domain == WF_DOMAIN_SPAIN ) { WFConsolePrintRomStr("spain", TRUE); } else if ( ws.Domain == WF_DOMAIN_FRANCE ) { WFConsolePrintRomStr("france", TRUE); } else if ( ws.Domain == WF_DOMAIN_JAPAN_A ) { WFConsolePrintRomStr("japana", TRUE); } else if ( ws.Domain == WF_DOMAIN_JAPAN_B ) { WFConsolePrintRomStr("japanb", TRUE); } else { WFConsolePrintRomStr("unknown", TRUE); } } #endif // rts { WF_GetRtsThreshold(&ws.Rts.Threshold); WFConsolePrintRomStr("\trts: ", FALSE); WFConsolePrintInteger(ws.Rts.Threshold, 'd'); WFConsolePrintRomStr("", TRUE); } // mode { WF_CMGetConnectionState(&connectionState, &cpId); WF_CPGetNetworkType(iwconfigCb.cpId, &ws.Mode.NetworkType); WFConsolePrintRomStr("\tmode: ", FALSE); if (iwconfigCb.isIdle) { if (iwconfigCb.connState == WF_CSTATE_NOT_CONNECTED) { WFConsolePrintRomStr("idle", TRUE); } else if (iwconfigCb.connState == WF_CSTATE_CONNECTION_PERMANENTLY_LOST) { WFConsolePrintRomStr("idle (connection permanently lost)", TRUE); } else { WFConsolePrintRomStr("idle (?)", TRUE); } } else { WF_CPGetNetworkType(iwconfigCb.cpId, &ws.Mode.NetworkType); if (ws.Mode.NetworkType == WF_INFRASTRUCTURE) { if (iwconfigCb.connState == WF_CSTATE_CONNECTION_IN_PROGRESS) { WFConsolePrintRomStr("managed (connection in progress)", TRUE); } else if (iwconfigCb.connState == WF_CSTATE_CONNECTED_INFRASTRUCTURE) { WFConsolePrintRomStr("managed", TRUE); } else if (iwconfigCb.connState == WF_CSTATE_RECONNECTION_IN_PROGRESS) { WFConsolePrintRomStr("managed (reconnection in progress)", TRUE); } else { WFConsolePrintRomStr("managed (?)", TRUE); } } else if (ws.Mode.NetworkType == WF_ADHOC) { if (iwconfigCb.connState == WF_CSTATE_CONNECTION_IN_PROGRESS) { WFConsolePrintRomStr("adhoc (connection in progress)", TRUE); } else if (iwconfigCb.connState == WF_CSTATE_CONNECTED_ADHOC) { WFConsolePrintRomStr("adhoc", TRUE); } else if (iwconfigCb.connState == WF_CSTATE_RECONNECTION_IN_PROGRESS) { WFConsolePrintRomStr("adhoc (reconnection in progress)", TRUE); } else { WFConsolePrintRomStr("adhoc (?)", TRUE); } } else { WFConsolePrintRomStr("unknown", TRUE); } } } // ssid { WF_CPGetSsid(iwconfigCb.cpId, ws.Ssid.String, &ws.Ssid.Len); ws.Ssid.String[ws.Ssid.Len] = '\0'; WFConsolePrintRomStr("\tssid: ", FALSE); WFConsolePrintRamStr(ws.Ssid.String, TRUE); } // power { switch (iwconfigCb.powerSaveState) { case WF_PS_PS_POLL_DTIM_ENABLED: WFConsolePrintRomStr("\tpwrsave: enabled", TRUE); WFConsolePrintRomStr("\tdtim rx: enabled", TRUE); break; case WF_PS_PS_POLL_DTIM_DISABLED: WFConsolePrintRomStr("\tpwrsave: enabled", TRUE); WFConsolePrintRomStr("\tdtim rx: disabled", TRUE); break; case WF_PS_OFF: WFConsolePrintRomStr("\tpwrsave: disabled", TRUE); break; default: WFConsolePrintRomStr("\tpwrsave: unknown(", FALSE); WFConsolePrintInteger(iwconfigCb.powerSaveState, 'd'); WFConsolePrintRomStr(")", TRUE); break; } } #if defined(MRF24WG) // context WF_OutputConnectionContext(); // Network Type putrsUART("\tNetwork: "); #if defined(EZ_CONFIG_STORE) && !defined(WF_CONSOLE_DEMO) /* if EZConfig demo */ if (AppConfig.networkType == WF_ADHOC) { putrsUART("AdHoc\r\n"); } else { putrsUART("Infrastructure\r\n"); } #else #if (MY_DEFAULT_NETWORK_TYPE == WF_ADHOC) putrsUART("AdHoc\r\n"); #elif (MY_DEFAULT_NETWORK_TYPE == WF_P2P) putrsUART("P2P\r\n"); #elif (MY_DEFAULT_NETWORK_TYPE == WF_INFRASTRUCTURE) #if (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PUSH_BUTTON) putrsUART("Infrastructure (using WPS Push Button)\r\n"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PIN) putrsUART("Infrastructure (using WPS Pin)\r\n"); #else putrsUART("Infrastructure\r\n"); #endif #endif #endif /* EZ_CONFIG_STORE */ // Retry Count putrsUART("\tRetries "); #if (MY_DEFAULT_NETWORK_TYPE == WF_ADHOC) sprintf(buf, "%d\r\n", ADHOC_RETRY_COUNT); putsUART(buf); #elif (MY_DEFAULT_NETWORK_TYPE == WF_INFRASTRUCTURE) #if (INFRASTRUCTURE_RETRY_COUNT == WF_RETRY_FOREVER) sprintf(buf, "Retry Forever\r\n"); putsUART(buf); #else sprintf(buf, "%d\r\n", INFRASTRUCTURE_RETRY_COUNT); putsUART(buf); #endif #endif /* (MY_DEFAULT_NETWORK_TYPE == WF_ADHOC) */ // Security putrsUART("\tSecurity: "); #if (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_OPEN) putrsUART("WF_SECURITY_OPEN"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WEP_40) putrsUART("WF_SECURITY_WEP_40"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WEP_104) putrsUART("WF_SECURITY_WEP_104"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_WITH_KEY) putrsUART("WF_SECURITY_WPA_WITH_KEY"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_WITH_PASS_PHRASE) putrsUART("WF_SECURITY_WPA_WITH_PASS_PHRASE"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA2_WITH_KEY) putrsUART("WF_SECURITY_WPA2_WITH_KEY"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA2_WITH_PASS_PHRASE) putrsUART("WF_SECURITY_WPA2_WITH_PASS_PHRASE"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_AUTO_WITH_KEY) putrsUART("WF_SECURITY_WPA_AUTO_WITH_KEY"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE) putrsUART("WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PUSH_BUTTON) putrsUART("WF_SECURITY_WPS_PUSH_BUTTON"); #elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PIN) putrsUART("WF_SECURITY_WPS_PIN"); #else putrsUART("Unknown"); #endif putrsUART("\r\n"); // scan type putrsUART("\tScan: "); #if (MY_DEFAULT_SCAN_TYPE == WF_ACTIVE_SCAN) putrsUART("Active Scan\r\n"); #else putrsUART("Passive Scan\r\n"); #endif // MAC address putrsUART("\tMAC: "); OutputMacAddress(); #endif /* MRF24WG */ }
/***************************************************************************** * FUNCTION: WaitForMgmtResponse * * RETURNS: None * * PARAMS: expectedSubtype -- The expected subtype of the mgmt response * freeAction -- FREE_MGMT_BUFFER or DO_NOT_FREE_MGMT_BUFFER * * NOTES: Called after sending a mgmt request. This function waits for a mgmt * response. The caller can optionally request the the management * response be freed immediately (by this function) or not freed. If not * freed the caller is responsible to free the response buffer. *****************************************************************************/ void WaitForMgmtResponse(UINT8 expectedSubtype, UINT8 freeAction) { #if defined(__18CXX) static tMgmtMsgRxHdr hdr; #else tMgmtMsgRxHdr hdr; #endif g_WaitingForMgmtResponse = TRUE; /* Wait until mgmt response is received */ while (gMgmtConfirmMsgReceived == FALSE) { WFProcess(); /* if received a data packet while waiting for mgmt packet */ if (g_HostRAWDataPacketReceived) { // We can't let the StackTask processs data messages that come in while waiting for mgmt // response because the application might send another mgmt message, which is illegal until the response // is received for the first mgmt msg. And, we can't prevent the race condition where a data message // comes in before a mgmt response is received. Thus, the only solution is to throw away a data message // that comes in while waiting for a mgmt response. This should happen very infrequently. If using TCP then the // stack takes care of retries. If using UDP, the application has to deal with occasional data messages not being // received. Also, applications typically do not send a lot of management messages after connected. // throw away the data rx RawMountRxBuffer(); DeallocateDataRxBuffer(); g_HostRAWDataPacketReceived = FALSE; /* ensure interrupts enabled */ WF_EintEnable(); } } /* set this back to FALSE so the next mgmt send won't think he has a response before one is received */ gMgmtConfirmMsgReceived = FALSE; /* if the caller wants to delete the response immediately (doesn't need any data from it */ if (freeAction == FREE_MGMT_BUFFER) { /* read and verify result before freeing up buffer to ensure our message send was successful */ RawRead(RAW_RX_ID, 0, (UINT16)(sizeof(tMgmtMsgRxHdr)), (UINT8 *)&hdr); /* mgmt response subtype had better match subtype we were expecting */ WF_ASSERT(hdr.subtype == expectedSubtype); if (hdr.result == WF_ERROR_DISCONNECT_FAILED || hdr.result == WF_ERROR_NOT_CONNECTED) { #if defined(STACK_USE_UART) putrsUART("Disconnect failed. Disconnect is allowed only when module is in connected state\r\n"); #endif } else if (hdr.result == WF_ERROR_NO_STORED_BSS_DESCRIPTOR) { #if defined(STACK_USE_UART) putrsUART("No stored scan results\r\n"); #endif } else { WF_ASSERT(hdr.result == WF_SUCCESS); } /* free mgmt buffer */ DeallocateMgmtRxBuffer(); /* if there was a mounted data packet prior to the mgmt tx/rx transaction, then restore it */ if (RestoreRxData == TRUE) { RestoreRxData = FALSE; PopRawWindow(RAW_RX_ID); SetRawWindowState(RAW_RX_ID, WF_RAW_DATA_MOUNTED); } } }
/***************************************************************************** * FUNCTION: WF_ProcessEvent * * RETURNS: None * * PARAMS: event -- event that occurred * eventInfo -- additional information about the event. Not all events * have associated info, in which case this value will be * set to WF_NO_ADDITIONAL_INFO (0xff) * * NOTES: The Host application must NOT directly call this function. This * function is called by the WiFi Driver code when an event occurs * that may need processing by the Host CPU. * * No other WiFi Driver function should be called from this function, with the * exception of WF_ASSERT. It is recommended that if the application wishes to be * notified of an event that it simply set a flag and let application code in the * main loop handle the event. * * WFSetFuncState must be called when entering and leaving this function. * When WF_ASSERT is enabled this allows a runtime check if any illegal WF functions * are called from within this function. * * For events that the application is not interested in simply leave the * case statement empty. * * Customize this function as needed for your application. *****************************************************************************/ void WF_ProcessEvent(UINT8 event, UINT16 eventInfo) { #if defined(STACK_USE_UART) char buf[8]; #endif /* this function tells the WF driver that we are in this function */ WFSetFuncState(WF_PROCESS_EVENT_FUNC, WF_ENTERING_FUNCTION); switch (event) { /*--------------------------------------*/ case WF_EVENT_CONNECTION_SUCCESSFUL: /*--------------------------------------*/ #if defined(STACK_USE_UART) putrsUART("Event: Connection Successful\r\n"); #endif break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_FAILED: /*--------------------------------------*/ /* eventInfo will contain value from tWFConnectionFailureCodes */ #if defined(STACK_USE_UART) putrsUART("Event: Connection Failed -- eventInfo = "); sprintf(buf, "%d\r\n", eventInfo); putsUART(buf); #endif break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_TEMPORARILY_LOST: /*--------------------------------------*/ /* eventInfo will contain value from tWFConnectionLostCodes */ #if defined(STACK_USE_UART) putrsUART("Event: Connection Temporarily Lost -- eventInfo = "); sprintf(buf, "%d\r\n", eventInfo); putsUART(buf); #endif break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_PERMANENTLY_LOST: /*--------------------------------------*/ /* eventInfo will contain value from tWFConnectionLostCodes */ #if defined(STACK_USE_UART) putrsUART("Event: Connection Permanently Lost -- eventInfo = "); sprintf(buf, "%d\r\n", eventInfo); putsUART(buf); #endif break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_REESTABLISHED: /*--------------------------------------*/ #if defined(STACK_USE_UART) putrsUART("Event: Connection Reestablished\r\n"); #endif break; /*--------------------------------------*/ case WF_EVENT_SCAN_RESULTS_READY: /*--------------------------------------*/ #if defined(STACK_USE_UART) putrsUART("Event: Scan Results Ready,"); sprintf(buf, "%d", eventInfo); putsUART(buf); putrsUART("results\r\n"); #endif #if defined ( EZ_CONFIG_SCAN ) WFScanEventHandler(eventInfo); #endif /* EZ_CONFIG_SCAN */ break; /*--------------------------------------*/ case WF_EVENT_RX_PACKET_RECEIVED: /*--------------------------------------*/ #if defined(STACK_USE_UART) // putrsUART("Event: Rx Packet Received - length = "); // sprintf(buf, "%d\r\n", eventInfo); // putsUART(buf); #endif break; default: WF_ASSERT(FALSE); /* unknown event */ break; } /* Informs the WF driver that we are leaving this function */ WFSetFuncState(WF_PROCESS_EVENT_FUNC, WF_LEAVING_FUNCTION); }
/***************************************************************************** * FUNCTION: WF_ProcessEvent * * RETURNS: None * * PARAMS: event -- event that occurred * eventInfo -- additional information about the event. Not all events * have associated info, in which case this value will be * set to WF_NO_ADDITIONAL_INFO (0xff) * extraInfo - more additional information about the event * * NOTES: The Host application must NOT directly call this function. This * function is called by the WiFi Driver code when an event occurs * that may need processing by the Host CPU. * * No other WiFi Driver function should be called from this function, with the * exception of WF_ASSERT. It is recommended that if the application wishes to be * notified of an event that it simply set a flag and let application code in the * main loop handle the event. * * WFSetFuncState must be called when entering and leaving this function. * When WF_DEBUG is enabled this allows a runtime check if any illegal WF functions * are called from within this function. * * For events that the application is not interested in simply leave the * case statement empty. * * Customize this function as needed for your application. *****************************************************************************/ void WF_ProcessEvent(uint8_t event, uint16_t eventInfo, uint8_t *extraInfo) { #if defined(STACK_USE_UART) char buf[8]; #endif tMgmtIndicateSoftAPEvent *softAPEvent; /* this function tells the WF driver that we are in this function */ WFSetFuncState(WF_PROCESS_EVENT_FUNC, WF_ENTERING_FUNCTION); switch (event) { /*--------------------------------------*/ case WF_EVENT_CONNECTION_SUCCESSFUL: /*--------------------------------------*/ #if defined(EZ_CONFIG_STORE) AppConfig.saveSecurityInfo = true; #endif break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_FAILED: case WF_EVENT_CONNECTION_TEMPORARILY_LOST: case WF_EVENT_CONNECTION_PERMANENTLY_LOST: /*--------------------------------------*/ break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_REESTABLISHED: /*--------------------------------------*/ break; /*--------------------------------------*/ case WF_EVENT_SCAN_RESULTS_READY: /*--------------------------------------*/ #if defined ( EZ_CONFIG_SCAN ) WFScanEventHandler(eventInfo); #endif /* EZ_CONFIG_SCAN */ g_scan_done = 1; // WF_PRESCAN break; case WF_EVENT_SOFT_AP_EVENT: softAPEvent = (tMgmtIndicateSoftAPEvent *) extraInfo; #if defined(STACK_USE_UART) { char str[96]; char *result = "None"; char *reason = "None"; uint8_t *addr = softAPEvent->address; putrsUART("Event: SoftAP, "); if (softAPEvent->event == SOFTAP_EVENT_CONNECTED) { result = "Connected"; } else if (softAPEvent->event == SOFTAP_EVENT_DISCONNECTED) { result = "Disconnected"; if (softAPEvent->reason == SOFTAP_EVENT_LINK_LOST) reason = "LinkLost"; else if (softAPEvent->reason == SOFTAP_EVENT_RECEIVED_DEAUTH) reason = "ReceivedDeauth"; } sprintf(str, "%s, %s, %x:%x:%x:%x:%x:%x", result, reason, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); putsUART(str); putrsUART("\r\n"); } #endif /* STACK_USE_UART */ break; default: WF_ASSERT(false); /* unknown event */ break; } /* Informs the WF driver that we are leaving this function */ WFSetFuncState(WF_PROCESS_EVENT_FUNC, WF_LEAVING_FUNCTION); }
/***************************************************************************** * FUNCTION: process_cmd * * RETURNS: None * * PARAMS: None * * NOTES: Determines which command has been received and processes it. *****************************************************************************/ void process_cmd(void) { BOOL new_arg; UINT8 i; g_ConsoleContext.argc = 0; new_arg = TRUE; // Get pointers to each token in the command string TokenizeCmdLine(g_ConsoleContext.rxBuf); // if command line nothing but white kWFSpace or a linefeed if ( g_ConsoleContext.argc == 0u ) { return; // nothing to do } // change the command itself (token[0]) to lower case for (i = 0; i < strlen((char *)g_ConsoleContext.argv[0]); ++i) { g_ConsoleContext.argv[0][i] = tolower(g_ConsoleContext.argv[0][i]); } if ( IS_ECHO_ON() ) { putrsUART("\n\r"); } switch (GetCmdId()) { case HELP_MSG: do_help_msg(); WFConsoleSetMsgFlag(); break; case GET_WF_VERSION_MSG: do_get_wfver_cmd(); break; case RESET_HOST: Reset(); break; case CLEAR_SCREEN_MSG: do_cls_cmd(); break; #if defined(MRF24WG) case WPS_PIN_MSG: do_wps_pin_cmd(); break; case WPS_PUSHBUTTON_MSG: do_wps_push_button_cmd(); break; case WPS_GET_CREDENTIALS_MSG: do_wps_get_credentials_cmd(); break; #endif /* MRF24WG */ #if defined(WF_CONSOLE_IFCFGUTIL) case IFCONFIG_MSG: do_ifconfig_cmd(); break; case IWCONFIG_MSG: do_iwconfig_cmd(); break; case IWPRIV_MSG: do_iwpriv_cmd(); break; #endif // WF_CONSOLE_IFCFGUTIL case PING_MSG: do_ping_cmd(); break; #if defined(STACK_USE_CERTIFICATE_DEBUG) case KILLPING_MSG: do_KillPing_cmd(); break; #endif default: WFConsoleSetMsgFlag(); break; } }
static void NormalMode(void) { putrsUART(normalModeEscapeSequence); }
static void do_wps_get_credentials_cmd(void) { tWFWpsCred cred; int i; char buf[6]; WF_CPGetWPSCredentials(1, &cred); if (cred.ssidLen > 0) { if (cred.ssidLen > 32) { putrsUART("SSID length is greater than 32, probably bad credential data\r\n"); return; } putrsUART("SSID: "); for (i = 0; i < cred.ssidLen; ++i) { sprintf(buf, "%c", cred.ssid[i]); putsUART(buf); } putrsUART("'\r\n"); } putrsUART("Net Key:\r\n "); for (i = 0; i < sizeof(cred.netKey); ++i) { if ( ((i % 16) == 0) && ( i != 0) ) { putrsUART("\r\n "); } sprintf(buf, "%02X ", cred.netKey[i]); putsUART(buf); } putrsUART("\r\n"); putrsUART("Auth Type: "); sprintf(buf, "%d\r\n", cred.authType); putsUART(buf); putrsUART("Enc Type: "); sprintf(buf, "%d\r\n", cred.encType); putsUART(buf); putrsUART("Net ID: "); sprintf(buf, "%d\r\n", cred.netIdx); putsUART(buf); putrsUART("Key ID: "); sprintf(buf, "%d\r\n", cred.keyIdx); putsUART(buf); putrsUART("BSSID: "); for (i = 0; i < 6; ++i) { sprintf(buf, "%02X ", cred.bssid[i]); putsUART(buf); } putrsUART("\r\n"); }
/***************************************************************************** * FUNCTION: DisplayHistoryEntry * * RETURNS: None * * PARAMS: action -- PREV_HISTORY or NEXT_HISTORY * * NOTES: In response to the user pressing up or down arrow key, display * corresponding entry in history buffer. * *****************************************************************************/ static void DisplayHistoryEntry(UINT8 action) { BOOL foundEntry = FALSE; // if nothing in history buffer if (history.seeded == FALSE) { return; } if (action == (UINT8)kWFPrevHistory) { --history.recallIndex; if (history.recallIndex < 0) { history.recallIndex = kWFNumHistoryEntries - 1; } /* search until found a history entry or searched all entries */ while (foundEntry == FALSE) { /* if found a history entry */ if (history.buf[history.recallIndex][0] != 0) { foundEntry = TRUE; } else { --history.recallIndex; if (history.recallIndex < 0) { history.recallIndex = kWFNumHistoryEntries - 1; } } } } else /* action == kWFNextHistory */ { history.recallIndex = (history.recallIndex + 1) % kWFNumHistoryEntries; /* search until found a history entry or searched all entries */ while (foundEntry == FALSE) { /* if found a history entry */ if (history.buf[history.recallIndex][0] != 0) { foundEntry = TRUE; } else { history.recallIndex = (history.recallIndex + 1) % kWFNumHistoryEntries; } } } if (foundEntry) { // erase line on screen and output command from history EraseEntireLine(); /* leaves Cursor_Index at 0 */ putrsUART( (ROM FAR char *) gCmdLinePrompt ); putsUART( (char *) history.buf[history.recallIndex]); // copy history command to console buffer (so they match) and put cursor // at end of line memset(g_ConsoleContext.rxBuf, 0x00, GET_LEN_RX_CMD_STRING() ); strcpy( (char *) g_ConsoleContext.rxBuf, (const char *) history.buf[history.recallIndex]); SET_CURSOR(gCmdLinePromptLength + strlen( (char *) history.buf[history.recallIndex])); } }
void DoUARTConfig(void) { BYTE response[MAX_USER_RESPONSE_LEN]; IP_ADDR tempIPValue; IP_ADDR *destIPValue; WORD_VAL wvTemp; BOOL bQuit = FALSE; while(!bQuit) { // Display the menu putrsUART("\r\n\r\n\rMicrochip TCP/IP Config Application ("TCPIP_STACK_VERSION", " __DATE__ ")\r\n\r\n"); putrsUART("\t1: Change serial number:\t\t"); wvTemp.v[1] = AppConfig.MyMACAddr.v[4]; wvTemp.v[0] = AppConfig.MyMACAddr.v[5]; uitoa(wvTemp.Val, response); putsUART(response); putrsUART("\r\n\t2: Change host name:\t\t\t"); putsUART(AppConfig.NetBIOSName); putrsUART("\r\n\t3: Change static IP address:\t\t"); DisplayIPValue(AppConfig.MyIPAddr); putrsUART("\r\n\t4: Change static gateway address:\t"); DisplayIPValue(AppConfig.MyGateway); putrsUART("\r\n\t5: Change static subnet mask:\t\t"); DisplayIPValue(AppConfig.MyMask); putrsUART("\r\n\t6: Change static primary DNS server:\t"); DisplayIPValue(AppConfig.PrimaryDNSServer); putrsUART("\r\n\t7: Change static secondary DNS server:\t"); DisplayIPValue(AppConfig.SecondaryDNSServer); putrsUART("\r\n\t8: "); putrsUART((ROM BYTE*)(AppConfig.Flags.bIsDHCPEnabled ? "Dis" : "En")); putrsUART("able DHCP & IP Gleaning:\t\tDHCP is currently "); putrsUART((ROM BYTE*)(AppConfig.Flags.bIsDHCPEnabled ? "enabled" : "disabled")); putrsUART("\r\n\t9: Download MPFS image."); putrsUART("\r\n\t0: Save & Quit."); putrsUART("\r\nEnter a menu choice: "); // Wait for the user to press a key while(!DataRdyUART()); putrsUART((ROM char*)"\r\n"); // Execute the user selection switch(ReadUART()) { case '1': putrsUART("New setting: "); if(ReadStringUART(response, sizeof(response))) { wvTemp.Val = atoi((char*)response); AppConfig.MyMACAddr.v[4] = wvTemp.v[1]; AppConfig.MyMACAddr.v[5] = wvTemp.v[0]; } break; case '2': putrsUART("New setting: "); ReadStringUART(response, sizeof(response) > sizeof(AppConfig.NetBIOSName) ? sizeof(AppConfig.NetBIOSName) : sizeof(response)); if(response[0] != '\0') { memcpy(AppConfig.NetBIOSName, (void*)response, sizeof(AppConfig.NetBIOSName)); FormatNetBIOSName(AppConfig.NetBIOSName); } break; case '3': destIPValue = &AppConfig.MyIPAddr; goto ReadIPConfig; case '4': destIPValue = &AppConfig.MyGateway; goto ReadIPConfig; case '5': destIPValue = &AppConfig.MyMask; goto ReadIPConfig; case '6': destIPValue = &AppConfig.PrimaryDNSServer; goto ReadIPConfig; case '7': destIPValue = &AppConfig.SecondaryDNSServer; goto ReadIPConfig; ReadIPConfig: putrsUART("New setting: "); ReadStringUART(response, sizeof(response)); if(StringToIPAddress(response, &tempIPValue)) destIPValue->Val = tempIPValue.Val; else putrsUART("Invalid input.\r\n"); break; case '8': AppConfig.Flags.bIsDHCPEnabled = !AppConfig.Flags.bIsDHCPEnabled; break; case '9': #if defined(MPFS_USE_EEPROM) && defined(STACK_USE_MPFS) DownloadMPFS(); #endif break; case '0': bQuit = TRUE; #if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS) SaveAppConfig(); putrsUART("Settings saved.\r\n"); #else putrsUART("External EEPROM/Flash not present -- settings will be lost at reset.\r\n"); #endif break; } } }
/***************************************************************************** * FUNCTION: WF_ProcessEvent * * RETURNS: None * * PARAMS: event -- event that occurred * eventInfo -- additional information about the event. Not all events * have associated info, in which case this value will be * set to WF_NO_ADDITIONAL_INFO (0xff) * extraInfo - more additional information about the event * * NOTES: The Host application must NOT directly call this function. This * function is called by the WiFi Driver code when an event occurs * that may need processing by the Host CPU. * * No other WiFi Driver function should be called from this function, with the * exception of WF_ASSERT. It is recommended that if the application wishes to be * notified of an event that it simply set a flag and let application code in the * main loop handle the event. * * WFSetFuncState must be called when entering and leaving this function. * When WF_DEBUG is enabled this allows a runtime check if any illegal WF functions * are called from within this function. * * For events that the application is not interested in simply leave the * case statement empty. * * Customize this function as needed for your application. *****************************************************************************/ void WF_ProcessEvent(uint8_t event, uint16_t eventInfo, uint8_t *extraInfo) { #if defined(STACK_USE_UART) char buf[8]; #endif tMgmtIndicateSoftAPEvent *softAPEvent; /* this function tells the WF driver that we are in this function */ WFSetFuncState(WF_PROCESS_EVENT_FUNC, WF_ENTERING_FUNCTION); switch (event) { /*--------------------------------------*/ case WF_EVENT_CONNECTION_SUCCESSFUL: /*--------------------------------------*/ #if defined(STACK_USE_UART) putrsUART("Event: Connection Successful\r\n"); #if defined(EZ_CONFIG_STORE) AppConfig.saveSecurityInfo = true; #endif #endif break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_FAILED: case WF_EVENT_CONNECTION_TEMPORARILY_LOST: case WF_EVENT_CONNECTION_PERMANENTLY_LOST: /*--------------------------------------*/ #if defined(STACK_USE_UART) WF_OutputConnectionDebugMsg(event, eventInfo); #endif break; /*--------------------------------------*/ case WF_EVENT_CONNECTION_REESTABLISHED: /*--------------------------------------*/ #if defined(STACK_USE_UART) putrsUART("Event: Connection Reestablished\r\n"); #endif #if 0 //This code will cause assert, so I mask them -- Jian Wan #if defined(WF_USE_POWER_SAVE_FUNCTIONS) { bool PsPollEnabled; PsPollEnabled = (MY_DEFAULT_PS_POLL == WF_ENABLED); if (!PsPollEnabled) { /* disable low power (PS-Poll) mode */ #if defined(STACK_USE_UART) putrsUART("Disable PS-Poll\r\n"); #endif WF_PsPollDisable(); } else { /* Enable low power (PS-Poll) mode */ #if defined(STACK_USE_UART) putrsUART("Enable PS-Poll\r\n"); #endif WF_PsPollEnable(true); } } #endif #endif break; /*--------------------------------------*/ case WF_EVENT_SCAN_RESULTS_READY: /*--------------------------------------*/ #if defined(STACK_USE_UART) putrsUART("Event: Scan Results Ready,"); sprintf(buf, " %d", eventInfo); putsUART(buf); putrsUART("results\r\n"); #endif /* STACK_USE_UART */ #if defined ( EZ_CONFIG_SCAN ) && !defined(__XC8) WFScanEventHandler(eventInfo); #endif /* EZ_CONFIG_SCAN */ #if MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP g_scan_done = 1; // WF_PRESCAN #endif #if defined(WF_PRE_SCAN_IN_ADHOC) g_prescan_adhoc_done = 1; #endif break; case WF_EVENT_SOFT_AP_EVENT: softAPEvent = (tMgmtIndicateSoftAPEvent *)extraInfo; #if defined(STACK_USE_UART) { char str[96]; char *result = "None"; char *reason = "None"; uint8_t *addr = softAPEvent->address; putrsUART("Event: SoftAP, "); if (softAPEvent->event == SOFTAP_EVENT_CONNECTED) { result = "Connected"; } else if (softAPEvent->event == SOFTAP_EVENT_DISCONNECTED) { result = "Disconnected"; if (softAPEvent->reason == SOFTAP_EVENT_LINK_LOST) reason = "LinkLost"; else if (softAPEvent->reason == SOFTAP_EVENT_RECEIVED_DEAUTH) reason = "ReceivedDeauth"; } sprintf(str, "%s, %s, %x:%x:%x:%x:%x:%x", result, reason, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); putsUART(str); putrsUART("\r\n"); } #endif /* STACK_USE_UART */ break; default: WF_ASSERT(false); /* unknown event */ break; } /* Informs the WF driver that we are leaving this function */ WFSetFuncState(WF_PROCESS_EVENT_FUNC, WF_LEAVING_FUNCTION); }
void BigIntModROM(BIGINT *n, BIGINT_ROM* m) { BIGINT_DATA_TYPE *ptrMSBn, MSBm; BIGINT_DATA_TYPE_2 qHatInt, topTwoWords; // Find the starting MSBs ptrMSBn = BigIntMSB(n); MSBm = *m->ptrMSB; // Set up assembly pointers for m // _iBr and _xBr are limiters in the _masROM function _iBr = m->ptrLSB; _xBr = m->ptrMSB; // Find out how many bytes we need to shift and move the LSB up _iR = n->ptrLSB + (BigIntMagnitudeDifferenceROM(n, m) - 1); // This loops while the order of magnitude (in words) of n > m // Each iteration modulos off one word of magnitude from n while(_iR >= n->ptrLSB) { // Find qHat = MSBn:MSBn-1/MSBm topTwoWords = *((BIGINT_DATA_TYPE_2*)(ptrMSBn - 1)); qHatInt = topTwoWords / MSBm; if(qHatInt > BIGINT_DATA_MAX) qHatInt = BIGINT_DATA_MAX; #if BIGINT_DEBUG putrsUART("\r\n\r\n n = "); BigIntPrint(n); putrsUART("\r\n m = "); BigIntPrintROM(m); putrsUART("\r\n qHat ("); putulhexUART(qHatInt); putrsUART(") = topTwo("); putulhexUART(topTwoWords); putrsUART(") / ("); putulhexUART(MSBm); putrsUART(") "); #endif // Once qHat is determined, we multiply M by qHat, shift it up // as many bytes as possible, and subtract the result. // In essence, qHat is a rough estimation of the quotient, divided // by a power of 2^8 (PIC18) or 2^16 (PIC24/dsPIC) or 2^32 (PIC32) // This implementation multiplies and subtracts in the same step // using a _mas function which saves about 30% of clock cycles. // Save the old MSB and set up the ASM pointers _wC = (BIGINT_DATA_TYPE)qHatInt; // Do the multiply and subtract // Occassionally this results in underflow...this is solved below. masBIROM(); // qHat may have been 1 or 2 greater than possible. If so, // the new MSB will be greater than the old one, so we *add* // M back to N in the shifted position until overflow occurs // and this case corrects itself. while(((BIGINT_DATA_TYPE*)&topTwoWords)[1] < *BigIntMSB(n)) { _iA = _iR; _xA = BigIntMSB(n); addBIROM(); } // We should have modulated off a word (or two if we were lucky), // so move our MSB and LSB pointers as applicable while(*ptrMSBn == 0x0u) { _iR--; n->ptrMSB--; ptrMSBn--; } } // Iteration of the _mas function can only handle full-byte orders // of magnitude. The result may still be a little larger, so this // cleans up the last few multiples with simple subtraction. while(BigIntCompareROM(n, m) >= 0) { _iA = n->ptrLSB; _xA = n->ptrMSB; subBIROM(); // Invalidate MSB pointer n->bMSBValid = 0; } }
void WF_OutputConnectionContext(void) { tWFConnectContext context; int i; char buf[6]; #if defined(EZ_CONFIG_STORE) if (AppConfig.networkType == WF_INFRASTRUCTURE) { #else if (TRUE) { #endif WF_CMGetConnectContext(&context); putrsUART("\tbssid: "); for (i = 0; i < 6; ++i) { if (i < 5) { sprintf(buf, "%02X:", context.bssid[i]); putsUART(buf); } else { sprintf(buf, "%02X\r\n", context.bssid[i]); putsUART(buf); } } putrsUART("\tchannel: "); sprintf(buf, "%d\r\n", context.channel); putsUART(buf); } } #endif /* MRF24WG */ void WF_OutputConnectionDebugMsg(UINT8 event, UINT16 eventInfo) { if (event == WF_EVENT_CONNECTION_TEMPORARILY_LOST) { OutputConnectionTempLostMsg(eventInfo); } else if (event == WF_EVENT_CONNECTION_FAILED) { OutputConnectionFailedMsg(eventInfo); } else if (event == WF_EVENT_CONNECTION_PERMANENTLY_LOST) { OutputConnectionPermLostMsg(eventInfo); } } static void OutputConnectionTempLostMsg(UINT16 eventInfo) { char buf[8]; #if defined(MRF24WG) if (eventInfo & WF_MASK_DEAUTH_REASONCODE) { putrsUART("Event: Connection Temporarily Lost -- eventInfo = Received deauth : "); #if !defined(__18CXX) putrsUART(deauthDisssocReasonCodes[eventInfo & ~WF_MASK_DEAUTH_REASONCODE]); #endif } else if (eventInfo & WF_MASK_DISASSOC_REASONCODE) { putrsUART("Event: Connection Temporarily Lost -- eventInfo = Received disassoc : "); #if !defined(__18CXX) putrsUART(deauthDisssocReasonCodes[eventInfo & ~WF_MASK_DISASSOC_REASONCODE]); #endif } else { putrsUART("Event: Connection Temporarily Lost -- eventInfo = "); sprintf(buf, "%d, ", eventInfo); putsUART(buf); putrsUART(connectionLostStrings[eventInfo]); } #else /* !defined(MRF24WG) */ putrsUART("Event: Connection Temporarily Lost -- eventInfo = "); sprintf(buf, "%d, ", eventInfo); putsUART(buf); putrsUART(connectionLostStrings[eventInfo]); #endif /* defined(MRF24WG) */ putrsUART("\r\n"); }
CHAR BigIntCompareROM(BIGINT *a, BIGINT_ROM *b) { PTR_BASE magA, magB; BIGINT_DATA_TYPE valA, valB; BIGINT_DATA_TYPE *ptrA; ROM BIGINT_DATA_TYPE *ptrB; magA = BigIntMSB(a) - a->ptrLSB; magB = b->ptrMSB - b->ptrLSB; #if BIGINT_DEBUG_COMPARE putrsUART("\r\n Compared Magnitudes |a|:"); putulhexUART(w1); putrsUART(" |b|:"); putulhexUART(w2); putrsUART(" diff:"); putulhexUART(s); #endif if(magA > magB) { #if BIGINT_DEBUG_COMPARE putrsUART(" a > b"); #endif return 1; } else if(magA < magB) { #if BIGINT_DEBUG_COMPARE putrsUART(" a < b"); #endif return -1; } #if BIGINT_DEBUG_COMPARE putrsUART(" Checking further bytes..."); #endif // Loop through all words, looking for a non-equal word ptrA = BigIntMSB(a); ptrB = b->ptrMSB; while(ptrA >= a->ptrLSB) // Magnitude is same, no need to check ptrB bounds { valA = *ptrA--; valB = *ptrB--; if(valA > valB) { #if BIGINT_DEBUG_COMPARE putrsUART(" a > b"); #endif return 1; } else if (valA < valB) { #if BIGINT_DEBUG_COMPARE putrsUART(" a < b"); #endif return -1; } } // All words were exactly identical, return match return 0; }
void WFDisplayScanMgr() { tWFScanResult bssDesc; char ssid[WF_MAX_SSID_LENGTH+1]; char rssiChan[48]; int i; char st[80]; if (SCANCXT.numScanResults == 0) return; if (!IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) return; if (IS_SCAN_IN_PROGRESS(SCANCXT.scanState)) return; if (!IS_SCAN_STATE_VALID(SCANCXT.scanState)) return; WFRetrieveScanResult(SCANCXT.displayIdx, &bssDesc); sprintf(st,"%3d ",SCANCXT.displayIdx); putrsUART(st); if (bssDesc.bssType == 1) sprintf(st,"NetType: Infra."); else if (bssDesc.bssType == 2) sprintf(st,"NetType: Ad-hoc"); putrsUART(st); sprintf(st,", ESSID:"); putrsUART(st); /* Display SSID */ for(i=0;i<bssDesc.ssidLen;i++) ssid[i] = bssDesc.ssid[i]; ssid[bssDesc.ssidLen] = 0; putsUART(ssid); putrsUART("\r\n"); /* Display SSID & Channel */ #ifdef STACK_USE_CERTIFICATE_DEBUG sprintf(rssiChan, "\tRSSI: %3u, Channel: %2u", bssDesc.rssi, bssDesc.channel); putsUART(rssiChan); /* Display BSSID */ sprintf(rssiChan, ", BSSID: %02x:%02x:%02x:%02x:%02x:%02x", bssDesc.bssid[0],bssDesc.bssid[1],bssDesc.bssid[2], bssDesc.bssid[3],bssDesc.bssid[4],bssDesc.bssid[5]); putsUART(rssiChan); /* Display Security Mode */ if((bssDesc.apConfig & 0x10) == 0) // bit4==0: open (no security) { sprintf(rssiChan, ", SecMode: %s\r\n", "Open"); } else // bit4== 1: security { if ((bssDesc.apConfig & 0x80) == 0x80) // bit7 == 1: WPA2 { sprintf(rssiChan, ", SecMode: %s\r\n", "WPA2"); } else if((bssDesc.apConfig & 0x40) == 0x40)//bit6==1: WPA { sprintf(rssiChan, ", SecMode: %s\r\n", "WPA"); } else // bit7==0, bit6 ==0, WEP { sprintf(rssiChan, ", SecMode: %s\r\n", "WEP"); } } putsUART(rssiChan); #else sprintf(rssiChan, ", RSSI: %u, Channel: %u\r\n", bssDesc.rssi, bssDesc.channel); putsUART(rssiChan); #endif #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) preScanResult[SCANCXT.displayIdx]= bssDesc; // WF_PRESCAN #endif if (++SCANCXT.displayIdx == SCANCXT.numScanResults) { SCAN_CLEAR_DISPLAY(SCANCXT.scanState); SCANCXT.displayIdx = 0; #if defined(WF_CONSOLE) & defined(STACK_USE_UART) WFConsoleReleaseConsoleMsg(); #endif } return; }
/***************************************************************************** Function: void GenericTCPClient(void) Summary: Implements a simple HTTP client (over TCP). Description: This function implements a simple HTTP client, which operates over TCP. The function is called periodically by the stack, and waits for BUTTON1 to be pressed. When the button is pressed, the application opens a TCP connection to an Internet search engine, performs a search for the word "Microchip" on "microchip.com", and prints the resulting HTML page to the UART. This example can be used as a model for many TCP and HTTP client applications. Precondition: TCP is initialized. Parameters: None Returns: None ***************************************************************************/ void GenericTCPClient(void) { BYTE i; WORD w; BYTE vBuffer[9]; static DWORD Timer; static TCP_SOCKET MySocket = INVALID_SOCKET; static enum _GenericTCPExampleState { SM_HOME = 0, SM_SOCKET_OBTAINED, SM_PROCESS_RESPONSE, SM_DISCONNECT, SM_DONE } GenericTCPExampleState = SM_DONE; switch(GenericTCPExampleState) { case SM_HOME: // Connect a socket to the remote TCP server MySocket = TCPOpen((DWORD)&ServerName[0], TCP_OPEN_RAM_HOST, ServerPort, TCP_PURPOSE_GENERIC_TCP_CLIENT); // Abort operation if no TCP socket of type TCP_PURPOSE_GENERIC_TCP_CLIENT is available // If this ever happens, you need to go add one to TCPIPConfig.h if(MySocket == INVALID_SOCKET) break; #if defined(STACK_USE_UART) putrsUART((ROM char*)"\r\n\r\nConnecting using Microchip TCP API...\r\n"); #endif GenericTCPExampleState++; Timer = TickGet(); break; case SM_SOCKET_OBTAINED: // Wait for the remote server to accept our connection request if(!TCPIsConnected(MySocket)) { // Time out if too much time is spent in this state if(TickGet()-Timer > 5*TICK_SECOND) { // Close the socket so it can be used by other modules TCPDisconnect(MySocket); MySocket = INVALID_SOCKET; GenericTCPExampleState--; } break; } Timer = TickGet(); // Make certain the socket can be written to if(TCPIsPutReady(MySocket) < 125u) break; // Place the application protocol data into the transmit buffer. For this example, we are connected to an HTTP server, so we'll send an HTTP GET request. TCPPutROMString(MySocket, (ROM BYTE*)"GET "); TCPPutROMString(MySocket, RemoteURL); TCPPutROMString(MySocket, (ROM BYTE*)" HTTP/1.0\r\nHost: "); TCPPutString(MySocket, ServerName); TCPPutROMString(MySocket, (ROM BYTE*)"\r\nConnection: close\r\n\r\n"); // Send the packet TCPFlush(MySocket); GenericTCPExampleState++; break; case SM_PROCESS_RESPONSE: // Check to see if the remote node has disconnected from us or sent us any application data // If application data is available, write it to the UART if(!TCPIsConnected(MySocket)) { GenericTCPExampleState = SM_DISCONNECT; // Do not break; We might still have data in the TCP RX FIFO waiting for us } // Get count of RX bytes waiting w = TCPIsGetReady(MySocket); // Obtian and print the server reply i = sizeof(vBuffer)-1; vBuffer[i] = '\0'; while(w) { if(w < i) { i = w; vBuffer[i] = '\0'; } w -= TCPGetArray(MySocket, vBuffer, i); #if defined(STACK_USE_UART) putsUART((char*)vBuffer); #endif // putsUART is a blocking call which will slow down the rest of the stack // if we shovel the whole TCP RX FIFO into the serial port all at once. // Therefore, let's break out after only one chunk most of the time. The // only exception is when the remote node disconncets from us and we need to // use up all the data before changing states. if(GenericTCPExampleState == SM_PROCESS_RESPONSE) break; } break; case SM_DISCONNECT: // Close the socket so it can be used by other modules // For this application, we wish to stay connected, but this state will still get entered if the remote server decides to disconnect TCPDisconnect(MySocket); MySocket = INVALID_SOCKET; GenericTCPExampleState = SM_DONE; break; case SM_DONE: // Do nothing unless the user pushes BUTTON1 and wants to restart the whole connection/download process if(BUTTON1_IO == 0u) GenericTCPExampleState = SM_HOME; break; } }
/********************************************************************* * Function: void BerkeleyTCPClientDemo(void) * * PreCondition: Stack is initialized() * * Input: None * * Output: None * * Side Effects: None * * Overview: None * * Note: None ********************************************************************/ void BerkeleyTCPClientDemo(void) { #if defined(STACK_USE_DNS) static SOCKET bsdClientSocket; static struct sockaddr_in addr; char recvBuffer[9]; int i; int addrlen; static enum { DNS_START_RESOLUTION = 0, DNS_GET_RESULT, BSD_START, BSD_CONNECT, BSD_SEND, BSD_OPERATION, BSD_CLOSE, BSD_DONE } BSDClientState = BSD_DONE; switch(BSDClientState) { case DNS_START_RESOLUTION: if(DNSBeginUsage()) { //ML DNSResolveROM(ServerName, DNS_TYPE_A); DNSResolve(ServerName, DNS_TYPE_A); BSDClientState = DNS_GET_RESULT; } break; case DNS_GET_RESULT: if(!DNSIsResolved((IP_ADDR*)&addr.sin_addr.S_un.S_addr)) break; if(!DNSEndUsage()) { #if defined(STACK_USE_UART) putrsUART((ROM char*)"Could not resolve ServerName[] to IP address.\r\n"); #endif BSDClientState = BSD_DONE; break; } BSDClientState = BSD_START; // No break; here. case BSD_START: // Create a socket for this client to connect with if((bsdClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET ) return; #if defined(STACK_USE_UART) putrsUART((ROM char*)"\r\n\r\nConnecting using Berkeley Sockets TCP API...\r\n"); putrsUART((ROM char*)" Note: this demo will do nothing if an underlying TCP_PURPOSE_BERKELEY_CLIENT type \r\n" " socket is unavailable, as declared by the TCPSocketInitializer[] array in \r\n" " TCPIPConfig.h.\r\n\r\n"); #endif BSDClientState = BSD_CONNECT; break; case BSD_CONNECT: // addr.sin_addr.S_un.S_addr destination IP address was set earlier in DNS step addr.sin_port = PORTNUM; addrlen = sizeof(struct sockaddr); if(connect( bsdClientSocket, (struct sockaddr*)&addr, addrlen) < 0) return; BSDClientState = BSD_SEND; // No break needed case BSD_SEND: //send TCP data send(bsdClientSocket, (const char*)sendRequest, strlen((char*)sendRequest), 0); BSDClientState = BSD_OPERATION; break; case BSD_OPERATION: // Obtian and print the server reply while(1) { i = recv(bsdClientSocket, recvBuffer, sizeof(recvBuffer)-1, 0); //get the data from the recv queue if(i == 0) break; if(i< 0) //error condition { BSDClientState = BSD_CLOSE; break; } #if defined(STACK_USE_UART) recvBuffer[i] = '\0'; // Null terminate data putsUART((char*)recvBuffer); #endif if(BSDClientState == BSD_OPERATION) break; } break; case BSD_CLOSE: closesocket(bsdClientSocket); BSDClientState = BSD_DONE; // No break needed case BSD_DONE: if(BUTTON2_IO == 0u) BSDClientState = DNS_START_RESOLUTION; break; default: return; } //#if defined(STACK_USE_DNS) #else #warning You must define STACK_USE_DNS for BerkeleyTCPClientDemo to work #endif }
int main(void) #endif { static DWORD t = 0; static DWORD dwLastIP = 0; // Initialize application specific hardware InitializeBoard(); #if defined(USE_LCD) // Initialize and display the stack version on the LCD LCDInit(); DelayMs(100); strcpypgm2ram((char*)LCDText, "WebVend Demo App" " "); LCDUpdate(); #endif // 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(); // Initiates board setup process if button is depressed // on startup if(BUTTON0_IO == 0u) { #if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS) // Invalidate the EEPROM contents if BUTTON0 is held down for more than 4 seconds DWORD StartTime = TickGet(); LED_PUT(0x00); while(BUTTON0_IO == 0u) { if(TickGet() - StartTime > 4*TICK_SECOND) { #if defined(EEPROM_CS_TRIS) XEEBeginWrite(0x0000); XEEWrite(0xFF); XEEWrite(0xFF); XEEEndWrite(); #elif defined(SPIFLASH_CS_TRIS) SPIFlashBeginWrite(0x0000); SPIFlashWrite(0xFF); SPIFlashWrite(0xFF); #endif #if defined(STACK_USE_UART) putrsUART("\r\n\r\nBUTTON0 held for more than 4 seconds. Default settings restored.\r\n\r\n"); #endif LED_PUT(0x0F); while((LONG)(TickGet() - StartTime) <= (LONG)(9*TICK_SECOND/2)); LED_PUT(0x00); while(BUTTON0_IO == 0u); Reset(); break; } } #endif } // Initialize core stack layers (MAC, ARP, TCP, UDP) and // application modules (HTTP, SNMP, etc.) StackInit(); #if defined(WF_CS_TRIS) WF_Connect(); #endif // 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 *) "DemoWebServer", // 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 // 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. while(1) { // Blink LED0 (right most one) every second. if(TickGet() - t >= TICK_SECOND/2ul) { t = TickGet(); LED0_IO ^= 1; } // This task performs normal stack task including checking // for incoming packet, type of packet and calling // appropriate stack entity to process it. StackTask(); // 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. ProcessIO(); // If the local IP address has changed (ex: due to DHCP lease change) // write the new IP address to the LCD display, UART, and Announce // service if(dwLastIP != AppConfig.MyIPAddr.Val) { dwLastIP = AppConfig.MyIPAddr.Val; #if defined(STACK_USE_UART) putrsUART((ROM char*)"\r\nNew IP Address: "); #endif // If not vending, show the new IP if(smVend == SM_IDLE || smVend == SM_DISPLAY_WAIT) { memcpypgm2ram(LCDText, "WebVend Demo App", 16); DisplayIPValue(AppConfig.MyIPAddr); // Print to UART #if defined(STACK_USE_UART) putrsUART((ROM char*)"\r\n"); #endif displayTimeout = TickGet() + 2*TICK_SECOND; smVend = SM_DISPLAY_WAIT; } #if defined(STACK_USE_ANNOUNCE) AnnounceIP(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSFillHostRecord(); #endif } } }