Microchip TCP/IP Stack Help
Reklam
Reklam
Microchip TCP/IP Stack
Help
Copyright (c) 2012 Microchip Technology, Inc. All rights reserved.
Microchip TCP/IP Stack Help
Table of Contents
Uploading Pre-built MPFS2 Images
Hash Table Filter Entry Calculator
Explorer 16 and PIC32 Starter Kit
Configure your WiFi Access Point
ii
Microchip TCP/IP Stack Help
Accessing the Demo Application
TCPIP Demo App Features by Hardware Platform
iii
Microchip TCP/IP Stack Help
ARPDeRegisterCallbacks Function
iv
Microchip TCP/IP Stack Help
closesocket Function connect Function
SOCK_STREAM Macro sockaddr Structure
v
Microchip TCP/IP Stack Help
BSDSocketArray Variable gAutoPortNumber Variable
HandlePossibleTCPDisconnection Function
ResolvedInfo Variable smDNS Variable
vi
Microchip TCP/IP Stack Help
_updateIpSrvrResponse Variable
_MD5_r Variable lastBlock Variable
vii
Microchip TCP/IP Stack Help
btohexa_high Function btohexa_low Function
GenerateRandomDWORD Function hexatob Function
leftRotateDWORD Function leftRotateDWORD Macro
ROMStringToIPAddress Macro stricmppgm2ram Function
StringToIPAddress Function strupr Function
strnchr Function swapl Function
Variables dwLFSRRandSeed Variable
viii
Microchip TCP/IP Stack Help
HTTP_TIMEOUT Macro httpContentTypes Variable httpFileExtensions Variable
HTTPHeaderParseAuthorization Function
HTTPHeaderParseContentLength Function
HTTPHeaderParseCookie Function
HTTPHeaderParseLookup Function
HTTPSendFile Function httpStubs Variable
ix
Microchip TCP/IP Stack Help
ICMPSendPingToHostROM Function
x
Microchip TCP/IP Stack Help
MPFS_FAT_RECORD Structure fatCache Variable
fatCacheID Variable numFiles Variable
xi
Microchip TCP/IP Stack Help
SMTP_SERVER_REPLY_TIMEOUT Macro
xii
Microchip TCP/IP Stack Help
GENERIC_TRAP_NOTIFICATION_TYPE Enumeration
VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE Enumeration
TRAP_INFO Structure gSendTrapFlag Variable gSetTrapSendFlag Variable
SNMPValidateCommunity Function
xiii
Microchip TCP/IP Stack Help
AGENT_NOTIFY_PORT Macro appendZeroToOID Variable
DATA_TYPE_TABLE_SIZE Macro dataTypeTable Variable
GET_RESPONSE Macro hMPFS Variable
xiv
Microchip TCP/IP Stack Help
SNMPCheckIfPvtMibObjRequested Function
_IsSNMPv3ValidStructure Function
_Snmpv3IsValidAuthStructure Function
FindOIDsFromSnmpV3Request Function
xv
Microchip TCP/IP Stack Help
IsSNMPv3ValidStructure Function
SNMPIdRecrdValidation Function
Snmpv3AESDecryptRxedScopedPdu Function
Snmpv3AESEncryptResponseScopedPdu Function
Snmpv3AuthenticateRxedPduForDataIntegrity Function
Snmpv3AuthenticateTxPduForDataIntegrity Function
Snmpv3AuthKeyZeroing2HmacBufLen64 Function
Snmpv3CmprTrapSecNameAndSecLvlWithUSMDb Function
Snmpv3ComputeHMACIpadOpadForAuthLoclzedKey Function
Snmpv3ComputeHmacMD5Digest Function
Snmpv3ComputeHmacShaDigest Function
Snmpv3ComputeMd5HmacCode Function
Snmpv3ComputeShaHmacCode Function
Snmpv3FormulateEngineID Function
Snmpv3FreeDynAllocMem Function
Snmpv3GetAuthEngineTime Function
Snmpv3GetSecurityLevel Function
Snmpv3GetTrapSecurityLevel Function
Snmpv3InitializeUserDataBase Function
Snmpv3IsValidAuthStructure Function
Snmpv3MsgProcessingModelProcessPDU Function
Snmpv3Pswd2LocalizedAuthKeyMD5Hashing Function
Snmpv3Pswd2LocalizedAuthKeySHAHashing Function
Snmpv3ScopedPduProcessing Function
Snmpv3UserSecurityModelProcessPDU Function
xvi
Microchip TCP/IP Stack Help
Snmpv3UsmAesEncryptDecryptInitVector Function
Snmpv3UsmOutMsgAuthenticationParam Function
Snmpv3USMOutMsgPrivParam Function
Snmpv3UsmSnmpEngnAuthPrivPswdLocalization Function
Snmpv3ValidateEngineId Function
Snmpv3ValidateSecNameAndSecLvl Function
Snmpv3ValidateSecurityName Function
AccessCtrlSubSysIsAccessAllowed Structure
dispatcherProcessPdu Structure dispatcherStatusInfo Structure
dispathcerReturnResponsePdu Structure
MsgProcModPrepareDataElements Structure
MsgProcModPrepareOutgoingMessage Structure
MsgProcModPrepareResponseMessage Structure
SecuritySysGenerateRequestMsg Structure
SecuritySysGenerateResponseMsg Structure
unregisterContextEngineID Structure
REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS Enumeration
SecuritySysProcessIncomingMsg Structure
SNMP_ENGNID_OCTET_IDENTIFIER_VAL Enumeration
SNMPV3_HMAC_HASH_TYPE Enumeration
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT Enumeration
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT Enumeration
SNMPV3_PRIV_PROT_TYPE Enumeration
SNMPV3_REQUEST_WHOLEMSG Structure
SNMPV3_RESPONSE_WHOLEMSG Structure snmpV3EngnUserDataBase Structure
SNMPV3MSGDATA Structure snmpV3TrapConfigDataBase Structure statusInformation Structure
STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL Enumeration
STD_BASED_SNMP_SECURITY_MODEL Enumeration
STD_BASED_SNMPV3_SECURITY_LEVEL Enumeration
USM_SECURITY_LEVEL Enumeration
xvii
Microchip TCP/IP Stack Help
authKey_oPad Variable authoritativeSnmpEngineBoots Variable
HmacSHADigest Variable incomingPdu Variable incomingSnmpPDUmsgID Variable ivEncrptKeyOut Variable
xviii
Microchip TCP/IP Stack Help
AUTH_LOCALIZED_PASSWORD_KEY_LEN Macro
IS_SNMPV3_AUTH_STRUCTURE Macro
MSG_AUTHORITATIVE_HEADER_LEN Macro
PRIV_LOCALIZED_PASSWORD_KEY_LEN Macro
SNMP_ENGINE_MAX_MSG_SIZE Macro
SNMP_MAX_OID_LEN_MEM_USE Macro
SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE Macro
SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE Macro
SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE Macro
SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE Macro
SNMPV3MSG_AUTHENTICATION_FAIL Macro
SNMPV3MSG_AUTHENTICATION_SUCCESS Macro
xix
Microchip TCP/IP Stack Help
dwLastUpdateTick Variable dwSNTPSeconds Variable
Generating Server Certificates
SSL_SUPPLEMENTARY_DATA_TYPES Enumeration
TCPSSLGetPendingTxSize Function
TCPSSLHandshakeComplete Function
TCPSSLInPlaceMACEncrypt Function
TCPSSLPutRecordHeader Function
SSL_MIN_SESSION_LIFETIME Macro
SSL_RSA_LIFETIME_EXTENSION Macro
CalculateFinishedHash Function
xx
Microchip TCP/IP Stack Help
HSStart Function isBufferUsed Variable
isHashUsed Variable isStubUsed Variable masks Variable ptrHS Variable
SM_SSL_RX_SERVER_HELLO Enumeration
SSL_RSA_EXPORT_WITH_ARCFOUR_40_MD5 Macro
SSL_RSA_WITH_ARCFOUR_128_MD5 Macro
xxi
Microchip TCP/IP Stack Help
SSLFlushPartialRecord Macro sslHash Variable
SSLHashFree Function sslHashID Variable
sslKeys Variable sslKeysID Variable
SSLRSAOperation Function sslRSAStubID Variable
SSLRxAntiqueClientHello Function
SSLRxClientKeyExchange Function
SSLRxServerCertificate Function
sslSession Variable sslSessionID Variable
xxii
Microchip TCP/IP Stack Help
SSLSessionUpdated Macro sslSessionUpdated Variable
SSLStartPartialRecord Function
SSLTxClientKeyExchange Function
SSLTxServerCertificate Function
TCP_ADJUST_GIVE_REST_TO_RX Macro
TCP_ADJUST_GIVE_REST_TO_TX Macro
xxiii
Microchip TCP/IP Stack Help
xxiv
Microchip TCP/IP Stack Help
HandleTCPSeg Function hCurrentTCP Variable
TCP_AUTO_TRANSMIT_TIMEOUT_VAL Macro
TCP_WINDOW_UPDATE_TIMEOUT_VAL Macro
TCP_MAX_UNACKED_KEEP_ALIVES Macro
TCP_OPTIONS_MAX_SEG_SIZE Macro
TCP_SYN_QUEUE_MAX_ENTRIES Macro
xxv
Microchip TCP/IP Stack Help
TFTPUploadFragmentedRAMFileToHost Function
TFTPUploadRAMFileToHost Function
TFTP_CHUNK_DESCRIPTOR Structure
TFTP_UPLOAD_CONNECT_TIMEOUT Macro
TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT Macro
TFTP_UPLOAD_RESOLVE_HOST Macro
TFTP_UPLOAD_SEND_FILENAME Macro
TFTP_UPLOAD_SERVER_ERROR Macro
TFTP_UPLOAD_WAIT_FOR_CLOSURE Macro
xxvi
Microchip TCP/IP Stack Help
_tftpState Variable smUpload Variable
wUploadChunkOffset Variable wUploadChunkOffsetForRetransmit Variable
TickConvertToMilliseconds Function
Internal Members dwInternalTicks Variable
TICKS_PER_SECOND Macro vTickReading Variable
xxvii
Microchip TCP/IP Stack Help
LOCAL_UDP_PORT_END_NUMBER Macro
LOCAL_UDP_PORT_START_NUMBER Macro
xxviii
Microchip TCP/IP Stack Help
Connection Profile Public Members
WF_CPGetAdHocBehavior Function
WF_CPSetAdHocBehavior Function
Connection Profile Internal Members
LowLevel_CPGetElement Function
LowLevel_CPSetElement Function
Connection Algorithm Public Members
WF_CAGetBeaconTimeout Function
WF_CAGetBeaconTimeoutAction Function
WF_CAGetConnectionProfileList Function
WF_CAGetEventNotificationAction Function
WF_CAGetListenInterval Function
xxix
Microchip TCP/IP Stack Help
WF_CAGetListRetryCount Function
WF_CAGetMaxChannelTime Function
WF_CAGetMinChannelTime Function
WF_CASetBeaconTimeout Function
WF_CASetBeaconTimeoutAction Function
WF_CASetConnectionProfileList Function
WF_CASetEventNotificationAction Function
WF_CASetListenInterval Function
WF_CASetListRetryCount Function
WF_CASetMaxChannelTime Function
WF_CASetMinChannelTime Function
Connection Algorithm Internal Members
LowLevel_CAGetElement Function
LowLevel_CASetElement Function
SetEventNotificationMask Function
Connection Manager Public Members
WF_CMGetConnectionState Function
WF_CMGetConnectContext Function
WF_CMCheckConnectionState Function
xxx
Microchip TCP/IP Stack Help
Wired Equivalent Privacy (WEP)
WF_CPGetDefaultWepKeyIndex Function
WF_CPSetDefaultWepKeyIndex Function
Wi-Fi Protected Access (WPA/WPA2)
WF_ConvPassphrase2Key Function
WF_CPGetWPSCredentials Function
WF_YieldPassphrase2Host Function
Tx Power Control Public Members
WF_TxPowerGetFactoryMax Function
Types tWFPsPwrMode Type tWFPwrModeReq Type
g_AppPowerSaveModeEnabled Variable g_powerSaveState Variable
xxxi
Microchip TCP/IP Stack Help
g_psPollActive Variable g_rxDtim Variable
g_sleepNeeded Variable gRFModuleVer1209orLater Variable
REG_DISABLE_LOW_POWER_MASK Macro
Wi-Fi Miscellaneous Public Members
WF_GetMultiCastFilter Function
WF_SetMultiCastFilter Function
WF_SetRtsThreshold Function tWFDeviceInfoStruct Structure
WF_EnableSWMultiCastFilter Function
WF_MulticastSetConfig Function
WF_SetLinkDownThreshold Function
802.11 AP/Router Configuration Settings
Read back RF module FW version
Wi-Fi Protected Setup (WPS) Issues
Management Scan Message Conflict
Shorter Scan or Connection Duration
Scan Operation and Scan Results
xxxii
Microchip TCP/IP Stack Help
MRF24WB0M Compatibility with AP/router
Error Messages And Possible Causes
xxxiii
1.2 Directory Structure
1
Introduction
Microchip TCP/IP Stack Help
Welcome to the Microchip TCP/IP Stack!
The Microchip TCP/IP Stack provides a foundation for embedded network applications by handling most of the interaction required between the physical network port and your application. It includes modules for several commonly used application layers, including HTTP for serving web pages, SMTP for sending e-mails, SNMP for providing status and control, Telnet,
TFTP, Serial-to-Ethernet and much more. In addition, the stack includes light-weight and high-performance implementations of the TCP and UDP transport layers, as well as other supporting modules such as IP, ICMP, DHCP, ARP, and DNS.
This help file serves two purposes. The first is to be a guide for first-time users of the TCP/IP Stack. The Getting Started section begins a series of pages to help you become familiar with the stack and configure it for use on a Microchip development board.
The second purpose is to serve as a programmer's reference guide to the features and APIs available in the TCP/IP Stack.
Updates
The latest version of the Microchip TCP/IP Stack is always available at http://www.microchip.com/tcpip . New features are constantly being added, so check there periodically for updates and bug fixes.
Wi-Fi
®
is a registered trademark of the Wi-Fi Alliance.
1.1
Getting Help
The TCP/IP Stack is supported through Microchip's standard support channels. If you encounter difficulties, you may submit ticket requests at http://support.microchip.com
.
The Microchip forums are also an excellent source of information, with a very lively community dedicated specifically to
Ethernet and TCP/IP discussions at http://forum.microchip.com
.
Microchip also offers embedded network classes through Regional Training Centers. For more information, visit http://www.microchip.com/rtc .
1.2
Directory Structure
The TCP/IP Stack comes with many files, tools, documents, and project examples. Before getting started, take a moment to familiarize yourself with the directory structure so that you may find what you need quickly. Installing the stack will produce the following structure:
1
1.2 Directory Structure Microchip TCP/IP Stack Help
Several demonstration projects are installed into the TCPIP directory in the default Microchip Solutions v20xx-xx-xx directory. In your projects, you may wish to write your application code in a project folder located in the same place as the
file. These project folders may contain additional subdirectories:
• A Configs subdirectory will contain alternative copies of the TCPIPConfig.h and HardwareProfile.h configuration files, pre-configured to work with different demo boards. The default copies of these files in the demo folder will include one of these alternative files based on a macro defined in the demo project.
• An SSLKeys subdirectory will contain sample security keys and certificates.
• A WebPages2 subdirectory will contain sample web pages for use with the MPFS2 file system.
• An MPLAB.X project folder contains the MPLAB X project files for the demo.
• A Precompiled Hex subdirectory contains precompiled hex images of the demo project.
Other stack-specific folders include are:
• The Microchip folder contains stack files and components.
• The Include sub-folder under the Microchip folder contains header files for Microchip stack and library solutions. The
TCPIP Stack folder in the Include folder contains headers for the TCP/IP Stack.
• The TCPIP Stack folder in the Microchip folder contains C source files, documentation, and stack utilities.
run the TCP/IP stack.
In most cases, it will not be necessary to modify source or header files in the Microchip directory.
2
Microchip TCP/IP Stack Help 2
2
SW License Agreement
MICROCHIP IS WILLING TO LICENSE THE ACCOMPANYING SOFTWARE AND DOCUMENTATION TO YOU ONLY ON
THE CONDITION THAT YOU ACCEPT ALL OF THE FOLLOWING TERMS. TO ACCEPT THE TERMS OF THIS LICENSE,
CLICK "I ACCEPT" AND PROCEED WITH THE DOWNLOAD OR INSTALL. IF YOU DO NOT ACCEPT THESE LICENSE
TERMS, CLICK "I DO NOT ACCEPT," AND DO NOT DOWNLOAD OR INSTALL THIS SOFTWARE.
NON-EXCLUSIVE SOFTWARE LICENSE AGREEMENT
This Nonexclusive Software License Agreement ("Agreement") is a contract between you, your heirs, successors and assigns ("Licensee") and Microchip Technology Incorporated, a Delaware corporation, with a principal place of business at
2355 W. Chandler Blvd., Chandler, AZ 85224-6199, and its subsidiary, Microchip Technology (Barbados) II Incorporated
(collectively, "Microchip") for the accompanying Microchip software including, but not limited to, Graphics Library Software,
IrDA Stack Software, MCHPFSUSB Stack Software, Memory Disk Drive File System Software, mTouch(TM) Capacitive
Library Software, Smart Card Library Software, TCP/IP Stack Software, MiWi(TM) DE Software, Security Package Software, and/or any PC programs and any updates thereto (collectively, the "Software"), and accompanying documentation, including images and any other graphic resources provided by Microchip ("Documentation").
1. Definitions. As used in this Agreement, the following capitalized terms will have the meanings defined below: a. "Microchip Products" means Microchip microcontrollers and Microchip digital signal controllers.
b. "Licensee Products" means Licensee products that use or incorporate Microchip Products.
c. "Object Code" means the Software computer programming code that is in binary form (including related documentation, if any), and error corrections, improvements, modifications, and updates.
d. "Source Code" means the Software computer programming code that may be printed out or displayed in human readable form (including related programmer comments and documentation, if any), and error corrections, improvements, modifications, and updates.
e. "Third Party" means Licensee’s agents, representatives, consultants, clients, customers, or contract manufacturers.
f. "Third Party Products" means Third Party products that use or incorporate Microchip Products.
2. Software License Grant. Microchip grants strictly to Licensee a non-exclusive, non-transferable, worldwide license to: a. use the Software in connection with Licensee Products and/or Third Party Products; b. if Source Code is provided, modify the Software; provided that Licensee clearly notifies Third Parties regarding the source of such modifications; c. distribute the Software to Third Parties for use in Third Party Products, so long as such Third Party agrees to be bound by
d. sublicense to a Third Party to use the Software, so long as such Third Party agrees to be bound by this Agreement (in
writing or by "click to accept ( see page 174)");
e. with respect to the TCP/IP Stack Software, Licensee may port the ENC28J60.c, ENC28J60.h, ENCX24J600.c, and
ENCX24J600.h driver source files to a non-Microchip Product used in conjunction with a Microchip ethernet controller; f. with respect to the MiWi (TM) DE Software, Licensee may only exercise its rights when the Software is embedded on a
Microchip Product and used with a Microchip radio frequency transceiver or UBEC UZ2400 radio frequency transceiver which are integrated into Licensee Products or Third Party Products.
3
2 Microchip TCP/IP Stack Help
For purposes of clarity, Licensee may NOT embed the Software on a non-Microchip Product, except as described in this
Section.
3. Documentation License Grant. Microchip grants strictly to Licensee a non-exclusive, non-transferable, worldwide license to use the Documentation in support of Licensee's authorized use of the Software
4. Third Party Requirements. Licensee acknowledges that it is Licensee’s responsibility to comply with any third party license terms or requirements applicable to the use of such third party software, specifications, systems, or tools. This includes, by way of example but not as a limitation, any standards setting organizations requirements and, particularly with respect to the
Security Package Software, local encryption laws and requirements. Microchip is not responsible and will not be held responsible in any manner for Licensee’s failure to comply with such applicable terms or requirements.
5. Open Source Components. Notwithstanding the license grant in Section 1 above, Licensee further acknowledges that certain components of the Software may be covered by so-called "open source" software licenses ("Open Source
Components"). Open Source Components means any software licenses approved as open source licenses by the Open
Source Initiative or any substantially similar licenses, including without limitation any license that, as a condition of distribution of the software licensed under such license, requires that the distributor make the software available in source code format. To the extent required by the licenses covering Open Source Components, the terms of such license will apply in lieu of the terms of this Agreement. To the extent the terms of the licenses applicable to Open Source Components prohibit any of the restrictions in this Agreement with respect to such Open Source Components, such restrictions will not apply to such Open Source Component.
6. Licensee Obligations. Licensee will not: (a) engage in unauthorized use, modification, disclosure or distribution of
Software or Documentation, or its derivatives; (b) use all or any portion of the Software, Documentation, or its derivatives except in conjunction with Microchip Products, Licensee Products or Third Party Products; or (c) reverse engineer (by disassembly, decompilation or otherwise) Software or any portion thereof. Licensee may not remove or alter any Microchip copyright or other proprietary rights notice posted in any portion of the Software or Documentation. Licensee will defend, indemnify and hold Microchip and its subsidiaries harmless from and against any and all claims, costs, damages, expenses
(including reasonable attorney's fees), liabilities, and losses, including without limitation: (x) any claims directly or indirectly arising from or related to the use, modification, disclosure or distribution of the Software, Documentation, or any intellectual property rights related thereto; (y) the use, sale and distribution of Licensee Products or Third Party Products; and (z) breach of this Agreement.
7. Confidentiality. Licensee agrees that the Software (including but not limited to the Source Code, Object Code and library files) and its derivatives, Documentation and underlying inventions, algorithms, know-how and ideas relating to the Software and the Documentation are proprietary information belonging to Microchip and its licensors ("Proprietary Information").
Except as expressly and unambiguously allowed herein, Licensee will hold in confidence and not use or disclose any
Proprietary Information and will similarly bind its employees and Third Party(ies) in writing. Proprietary Information will not include information that: (i) is in or enters the public domain without breach of this Agreement and through no fault of the receiving party; (ii) the receiving party was legally in possession of prior to receiving it; (iii) the receiving party can demonstrate was developed by the receiving party independently and without use of or reference to the disclosing party's
Proprietary Information; or (iv) the receiving party receives from a third party without restriction on disclosure. If Licensee is required to disclose Proprietary Information by law, court order, or government agency, License will give Microchip prompt notice of such requirement in order to allow Microchip to object or limit such disclosure. Licensee agrees that the provisions of this Agreement regarding unauthorized use and nondisclosure of the Software, Documentation and related Proprietary
Rights are necessary to protect the legitimate business interests of Microchip and its licensors and that monetary damage alone cannot adequately compensate Microchip or its licensors if such provisions are violated. Licensee, therefore, agrees that if Microchip alleges that Licensee or Third Party has breached or violated such provision then Microchip will have the
4
2 Microchip TCP/IP Stack Help right to injunctive relief, without the requirement for the posting of a bond, in addition to all other remedies at law or in equity.
8. Ownership of Proprietary Rights. Microchip and its licensors retain all right, title and interest in and to the Software and
Documentation including, but not limited to all patent, copyright, trade secret and other intellectual property rights in the
Software, Documentation, and underlying technology and all copies and derivative works thereof (by whomever produced).
Licensee and Third Party use of such modifications and derivatives is limited to the license rights described in this
Agreement.
9. Termination of Agreement. Without prejudice to any other rights, this Agreement terminates immediately, without notice by
Microchip, upon a failure by Licensee or Third Party to comply with any provision of this Agreement. Upon termination,
Licensee and Third Party will immediately stop using the Software, Documentation, and derivatives thereof, and immediately destroy all such copies.
10. Warranty Disclaimers. THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. MICROCHIP AND
ITS LICENSORS ASSUME NO RESPONSIBILITY FOR THE ACCURACY, RELIABILITY OR APPLICATION OF THE
SOFTWARE OR DOCUMENTATION. MICROCHIP AND ITS LICENSORS DO NOT WARRANT THAT THE SOFTWARE
WILL MEET REQUIREMENTS OF LICENSEE OR THIRD PARTY, BE UNINTERRUPTED OR ERROR-FREE. MICROCHIP
AND ITS LICENSORS HAVE NO OBLIGATION TO CORRECT ANY DEFECTS IN THE SOFTWARE.
11. Limited Liability. IN NO EVENT WILL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER ANY
LEGAL OR EQUITABLE THEORY FOR ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT
LIMITED TO INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR
LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY
THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. The aggregate and cumulative liability of Microchip and its licensors for damages hereunder will in no event exceed $1000 or the amount Licensee paid Microchip for the Software and Documentation, whichever is greater. Licensee acknowledges that the foregoing limitations are reasonable and an essential part of this Agreement.
12. General. THIS AGREEMENT WILL BE GOVERNED BY AND CONSTRUED UNDER THE LAWS OF THE STATE OF
ARIZONA AND THE UNITED STATES WITHOUT REGARD TO CONFLICTS OF LAWS PROVISIONS. Licensee agrees that any disputes arising out of or related to this Agreement, Software or Documentation will be brought exclusively in either the U.S. District Court for the District of Arizona, Phoenix Division, or the Superior Court of Arizona located in Maricopa
County, Arizona. This Agreement will constitute the entire agreement between the parties with respect to the subject matter hereof. It will not be modified except by a written agreement signed by an authorized representative of Microchip. If any provision of this Agreement will be held by a court of competent jurisdiction to be illegal, invalid or unenforceable, that provision will be limited or eliminated to the minimum extent necessary so that this Agreement will otherwise remain in full force and effect and enforceable. No waiver of any breach of any provision of this Agreement will constitute a waiver of any prior, concurrent or subsequent breach of the same or any other provisions hereof, and no waiver will be effective unless made in writing and signed by an authorized representative of the waiving party. Licensee agrees to comply with all import and export laws and restrictions and regulations of the Department of Commerce or other United States or foreign agency or authority. The indemnities, obligations of confidentiality, and limitations on liability described herein, and any right of action for breach of this Agreement prior to termination, will survive any termination of this Agreement. Any prohibited assignment will be null and void. Use, duplication or disclosure by the United States Government is subject to restrictions set forth in subparagraphs (a) through (d) of the Commercial Computer-Restricted Rights clause of FAR 52.227-19 when applicable, or in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013, and in similar clauses in the NASA FAR Supplement. Contractor/manufacturer is Microchip Technology Inc., 2355 W. Chandler
Blvd., Chandler, AZ 85224-6199.
5
2 Microchip TCP/IP Stack Help
If Licensee has any questions about this Agreement, please write to Microchip Technology Inc., 2355 W. Chandler Blvd.,
Chandler, AZ 85224-6199 USA. ATTN: Marketing.
Copyright (c) 2012 Microchip Technology Inc. All rights reserved.
License Rev. No. 05-012412
6
3
3
Release Notes
Microchip TCP/IP Stack Help
******
Microchip TCP/IP Stack Version Log:
******
Remarks
Please file bug-reports/bug-fixes at http://support.microchip.com/ or post to the Microchip TCP/IP -> Ethernet Forum at http://forum.microchip.com/ Look for stack updates at http://www.microchip.com/mal/
******
v5.42.06 Feb 2013
******
Changes:
1. (MRF24WG) Due to memory constraints, all future RF module FW releases will follow this roll-out order (Odd number eg
0x3109, 0x310b) Differences: Supports Wi-Fi Direct (P2P). But no EAP and no multi-client support. (Even number eg
0x3108, 0x310a) Differences: Supports EAP (with MCHP approval) and multi-clients. But no Wi-Fi Direct support.
2. (MRF24WG) Added new project Wifi G demo. Wifi G demo currently only support softAP function,
3. (MRF24WG) In Wifi Console, for XC32-EX116-EAP_MRF24WG, supports security mode
WF_SECURITY_WPA2_ENTERPRISE (EAP-PEAP/MSCHAPv2 and EAP-TTLS/MSCHAPv2) . Requires RF module FW version 0x3108 and even number releases. This requires special approval submitted to marketing.
4. (MRF24WG) In EZConfig, added mobile application demo to Explorer16+PIC32. Refer to MobileTCPServer.c Supported devices : Android (version 4.0 or later), iOS6 or later Current functions supported are (i) Temperature reading (ii)
Potentiometer reading and (iii) LEDs ON/OFF toggling App name is "OpenWifiFog"
5. (MRF24WG) In WiFi Console, added cloud demo to Explorer16+PIC32. Refer to CloudTCPClient.c Current functions supported are (i) Temperature reading (ii) Potentiometer reading and (iii) LEDs ON/OFF toggling Reference web server is http://www.openwificloud.com
6. (MRF24WG) Supports multi-client DHCP server (max 4 clients). SoftAP supports up to max 4 client Requires RF module
FW version 0x3108 and even number releases.
7. (MRF24WG) softAP supports active scan. Requires RF module FW version 0x3108 and future releases.
8. (MRF24WG) RF module FW version 0x3107 and future releases will NO longer support programming of regional domain
programming of the regional domain.
9. (MRF24WB/G) Only WEP key index 0 is valid for security mode WEP.
10.(MRF24WG) Created new event WF_EVENT_SOFT_AP_EVENT_SUBTYPE / WF_EVENT_SOFT_AP_EVENT, for softAP mode, to indicate client's status (connected or disconnected to softAP). Requires RF module FW version 0x3108 and later releases. If prior MLA releases are used with this new RF module FW version release, you need to port over this event
handling in WFEVentHandler.c and WF_ProcessEvent ( see page 717)() (WiFi EZConfig).
11. Added full versions of RSA.c, ARCFOUR.c, and AES_PIC32MX.a to the TCP/IP Stack Distribution to support SSL and
SNMPv3. Previously these files were distributed in a separate cryptographic code distribution. These files are subject to the U.S. Export Administration Regulations and other U.S. law, and may not be exported or re-exported to certain countries or to persons or entities prohibited from receiving U.S. exports (including Denied Parties, entities on the Bureau of Export Administration Entity List, and Specially Designated Nationals).
Fixes:
1. (MRF24WG) In EZConfig, SoftAP now supports Zeroconf & mDNS. Resolves wrong port issue. Search for keyword
SOFTAP_ZEROCONF_SUPPORT.
7
3 Microchip TCP/IP Stack Help
******
v5.42.04 Oct 2012
******
Changes:
1. (MRF24WB/G) Patch update features are added into MRF24WB0MA/B and MRF24WG0MA/MB. MRF24WB0MA/B (no
RF module FW version update is necessary) Serial Port (Xmodem) MRF24WG0MA/B (Requires RF module FW version
3107 or later.) Serial Port (Xmodem), Web Client, Web Server
2. (MRF24WB/G) FTP client is added into WiFi console demo app.
3. (MRF24WB/G) Flexible scratch memory is used to allocate TCB.
4. SSL client with RSA 2048bits is enabled by default. Applies only for PIC24/32. Not supported for PIC18.
5. 16-bit mode feature is available on PIC32.
6. (MRF24WG) Enhance SoftAP with EZConfig features with pre-scan and redirection features. Change SoftAP address from 192.168.1.1 to 192.168.1.3 Added WEP security, which requires RF module FW version 3107 or later. Refer to
WF_Config.h for more information.
7. Added support for PIC32MX6XX external PHY's: RTL 8201FL. Only RMII configuration is supported with RTLPHY8201FL
PHY. This PHY driver works in Default Ethernet IO mode with PIC32MX675F512H . If Alternate Ethernet IO mode is used for other PIC devices, then configuration bit need to be changed w.r.t Alternate Ethernet IO. To get the status of MAC link with this PHY, PHY Link Status need to be read twice. EthPhyGetLinkStatus(int refresh) API is used to read the PHY link status and for this PHY to read link status twice, the parameter refresh should be 1.
Fixes:
1. (MRF24WG) SoftAP under EZConfig has pre-scan and redirection features. Able to be redirected to infrastructure mode
AP.
2. If SNMP_TRAP_DISABLED macro is enabled from TCPIP XXX.h file, there will be no TRAP table information for SNMP manager. That is SNMP agent won't send information related to trap. By default SNMP_TRAP_DISABLED macro is disabled.
3. Fix typo error in v5.42.02 (MRF24WG) SoftAP default address is changed from 169.254.1.1 to 192.168.1.1
4. Fixed SNMP tabular issue if SNMP instances starts other than 0.
5. Fixed ARP initialization bug that resulted in TCP packets sent to ETH MAC broadcast address.
******
v5.42.02 Aug 2012
******
Fixes:
1. (MRF24WB/G) TCPIPConfig.exe is modified to support changes in macro definitions (CFG_WF_INFRASTRUCTURE,
CFG_WF_ADHOC) used in WF_Config.h.
2. (MRF24WB/G) Ad-hoc mode was left out in the TCPIP-Demo app. This mode is reinstated back into TCPIP-Demo app. 2 files are changed. .MicrochipIncludeTCPIP StackWFDebugStrings.h .TCPIPDemo AppWF_Config.h
3. (MRF24WB/G) SoftAP default address is changed from 192.168.1.1 to 169.254.1.1
4. (MRF24WG) Apply SSL fix. Root cause is traced to be due to scratch pad memory to memory copy functions in
WFMac_24G.c
5. (MRF24WG) Reset fix. a. In file WFDriverCom_24G.c, MRF24WG reset sequence is modified.
• WFHardwareInit() does hard reset (putting I/O lines in correct state)
• ChipReset() does soft reset
8
3 Microchip TCP/IP Stack Help b. In file WFDriverPrv_24G.h, macros WF_SetCE_N() and WF_SetRST_N() modified to first set the output level, then set the
I/O direction
6. (MRF24WG) Applies to using PICDEMNet2 board and PIC18. Related to SPI interface settings. a. In file WF_Spi.c,
ConfigureSpiMRF24W() modified, for PIC18 only, to change the SPI clock idle state to low.
7. (MRF24WB/G) When host attempts to read scan results while the module FW is in reconnecting state, the module FW returns WF_ERROR_NO_STORED_BSS_DESCRIPTOR error. Reading scan results is only allowed in A) connected state; B) idle state. Fix is in WaitForMgmtResponseAndReadData(). void WaitForMgmtResponseAndReadData(UINT8 expectedSubtype, UINT8 numDataBytes, UINT8 startIndex, UINT8
*p_data) { .................................... /* check header result and subtype fields */ WF_ASSERT(hdr.result == WF_SUCCESS || hdr.result
== WF_ERROR_NO_STORED_BSS_DESCRIPTOR); WF_ASSERT(hdr.subtype
== expectedSubtype);
.................................... }
******
v5.42 Jul 2012
******
Changes:
1. All MPLAB 8 and MPLAB X projects have been modified to use the XC16 and XC32 compilers.
3. (MRF24WB/G) PIC18 is only supported with "TCPIP Demo App". MRF24WB0MA/MB works on PICDEM PIC18 Explorer.
MRF24WG0MA/MB works on PICDemNet2 PIC 18 but has issues with PICDEM PIC18 Explorer.
4. (MRF24WB/G) Enhanced debug messages providing more details such as authentication or association failues, etc.
5. (MRF24WB/G) Added option to disable module FW connection manager by adding "#define DISABLE_MODULE
_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE".
6. (MRF24WB/G) Added option to derive real key from pass-phrase in host side by adding "#define DERIVE
_KEY_FROM_PASSPHRASE_IN_HOST".
7. (MRF24WB/G) Enabled WEP security for EasyConfig Ad-hoc connection
8. (MRF24WB/G) Added support for MRF24WG0MA/MB, a superset of MRF24WB0MA/MB (MRF24WB). Required to add to project definition files (#define MRF24WG). Ranges are different from MRF24WB0MA/MB. i. Valid RSSI Range : 43 ~
MRF24WG0MA/MB enhancements are above and beyond on those features listed above. a. Added WPS(1.0) security method (#define WF_SECURITY_WPS_PUSH_BUTTON & WF_SECURITY_WPS_PIN ) (TCPIP demo + console demo). b.
Added Wi-Fi Direct (P2P) function in the GC (group client) role (#define MY_DEFAULT_NETWORK_TYPE CFG_WF_P2P)
(TCPIP demo + console demo) c. Added simplified basic SoftAP functionality (WF_SOFT_AP). Current features are 1 client
STA, open security and no routing. (Easy config demo) d. Selection of support for 16 (max) software multicast filters
(ENABLE_SOFTWARE_MULTICAST_FILTER ) or 2 hardware multicast filters. RTS or ES release requires software patch.
Fixes:
1. The BigInt_helper.S file will now correctly include the processor include files for the PIC24E and dsPIC33E architectures.
2. Fixed bug in TCP state machine that corrupted the sequence number when client socket is closed.
4. (All parts including RTS or ES release) MRF24WG0MA/MB requires PLL work-around initialization code. Please refer to
July/2012 release.
5. (All parts including RTS or ES release) MRF24WG0MA/MB needs to update stack from July/2012 release to cater for
SSL.
6. (MRF24WB/G) Fixed stack issues encountered in Stack version v2012-04-03 and older. Code fix is needed in
WF_CPSetElements ( see page 646)() API. Modification is as below.
9
3 Microchip TCP/IP Stack Help void
WF_CPSetElements ( see page 646)(UINT8
CpId, tWFCPElements *p_elements) { UINT8 elements[sizeof(tWFCPElements) + 2]; WF_ASSERT(p_elements->ssidLength <= WF_MAX_SSID_LENGTH);
sizeof(elements)); /* number of element data bytes */ }
Code fix is also needed in WaitForMgmtResponse() API (WFMgmtMsg.c). Refer to description of this fix is in the
Supplementary TCPIP Help folder.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
4. For PIC32 implementations, depending on the configuration, it is possible that the MACGetFreeRxSize() returns a value greater than 64 KB. For backward compatibility reasons the stack uses a 16 bit value to check the returned value and it won't work corretly.
5. Limiting the number of UDP sockets to 8 in the stack demos may prevent SNMP trap functionality. If this occurs, you can increase the MAX_UDP_SOCKETS definition in TCPIPConfig.h to 10 (if your system will support the increased data memory usage) to fix this issue.
6. The SNMP mib file's date and version parameter does not match the date/version of the current stack release.
7. (MRF24WG0MA/MB) RTS or ES release requires software patch for multicast filters.
mode AP.
9. Certain APs have power save issue with reconnect. Please refer to AP compatibility list.
******
v5.41.02 Apr 2012
******
Fixes:
1. Added the Bigint helper libraries for C30 into the stack source folder to prevent linker errors in 16-bit projects that include those libraries.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
10
3 Microchip TCP/IP Stack Help
4. For PIC32 implementations, depending on the configuration, it is possible that the MACGetFreeRxSize() returns a value greater than 64 KB. For backward compatibility reasons the stack uses a 16 bit value to check the returned value and it won't work corretly.
5. Limiting the number of UDP sockets to 8 in the stack demos may prevent SNMP trap functionality. If this occurs, you can increase the MAX_UDP_SOCKETS definition in TCPIPConfig.h to 10 (if your system will support the increased data memory usage) to fix this issue.
6. The SNMP mib file's date and version parameter does not match the date/version of the current stack release.
******
v5.41 Feb 2012
******
Changes:
1. Added socket number validation to TCP functions.
2. Removed the WiFi projects from the Energy Monitoring and WebVend demos.
3. Added the "-mperipheral-libs" linker option to C32 projects.
4. Moved AES library and header files used by SNMPv3 from the "Crypto" source and include folders to the to the "TCPIP
Stack" source and include folders.
5. Changed SNMP MIB trap number from 7 to 0.
6. Changed SNMP MIB SYOBJECTID to 43.6.1.4.1.17095.1 (added .1).
7. Updated MPFS2 Utility to make path settings persistent.
8. Changed default channel list from {1,6,11} to {1,2,3,4,5,6,7,8,9,10,11} for FCC domain
9. Added support for WEP with Shared Key
10. Added new command "iwconfig scan" & "iwconfig scanresults"
12. Added the following 1209 and later specific API: a) WF_CPSetWepKeyType ( see page 685)() b)
WF_CMGetConnectContext ( see page 678)() c) WFEnableBroadcastProbeResponse() d)
WF_FixTxRateWithMaxPower()
Fixes:
1. Updated MPFS2 Utility path strings for Mac/Linux compatibility.
2. Iperf - Resolved application crash due to network disconnection.
3. Host Scan - More robust and prevent system hang up. #define WF_HOST_SCAN.
4. Power Save - Improvements with Aggressive PS mode, and better handling of PS in host code.
5. Host connect ( see page 176) & disconnect - Prevent system hang.
6. DHCP Refresh - Better handling of DHCP session in PS mode, and issue DHCP renewal any STA reconnect with AP.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
11
3 Microchip TCP/IP Stack Help
4. For PIC32 implementations, depending on the configuration, it is possible that the MACGetFreeRxSize() returns a value greater than 64 KB. For backward compatibility reasons the stack uses a 16 bit value to check the returned value and it won't work corretly.
5. Limiting the number of UDP sockets to 8 in the stack demos may prevent SNMP trap functionality. If this occurs, you can increase the MAX_UDP_SOCKETS definition in TCPIPConfig.h to 10 (if your system will support the increased data memory usage) to fix this issue.
6. The SNMP mib file's date and version parameter does not match the date/version of the current stack release.
******
v5.36.4 Oct 2011
******
Changes:
2. The SSL module has been updated to support 1024-bit RSA key lengths for server and client on all architectures. PIC32 microcontrollers now support client/server RSA key lengths of 2048 bits. NOTE: To support these changes, you must manually modify your copy of RSA.c. A description of the required changes ("Required SSL Changes.pdf") can be found in your Microchip Applications Libraries installation directory in the "MicrochipHelpSupplementary TCPIP Help" subdirectory.
Fixes:
1. SNMP local variable community length increased with plus one.SNMP warnings has been removed for the compiler version C32 2.01 for zero optimisation.
2. Updated MPFS2.jar and mib2bib.jar to support Java version 1.7.
3. Fixed MPFS2.jar offset issue for fileRcrd.bin and dynRcrd.bin file and it was due to the file which has zero dynamic variable.Fixed Crimson editor problem with webPage2 folder where user couldn't save files using Crimson Editor if the
WebPages2 folder that contained those files was selected in the MPFS2 utility.
4. MPFS2.jar file was getting hanged for the zero file size access.Now Zero file size also is the part of the respective generated files.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
4. For PIC32 implementations, depending on the configuration, it is possible that the MACGetFreeRxSize() returns a value greater than 64 KB. For backward compatibility reasons the stack uses a 16 bit value to check the returned value and it won't work corretly.
5. Limiting the number of UDP sockets to 8 in the stack demos may prevent SNMP trap functionality. If this occurs, you can increase the MAX_UDP_SOCKETS definition in TCPIPConfig.h to 10 (if your system will support the increased data memory usage) to fix this issue.
6. The SNMP mib file's date and version parameter does not match the date/version of the current stack release.
******
v5.36.2 July 2011
12
3 Microchip TCP/IP Stack Help
******
Changes:
1. Removed the Google PowerMeter and Google PowerMeter EZConfig demos. Google, Inc. has deprecated Google
PowerMeter and has expressed the intent to remove access to it on September 16, 2011. To obtain Microchip
Technology's Google PowerMeter reference implementation, you can download the June 2011 Microchip Application
Libraries archived release from www.microchip.com/mal.
2. Modified the Energy Monitoring demo to remove Google PowerMeter functionality. The demo will still display measured power data on its internal web page.
3. Updated the TCP/IP Stack Performance table to use the testing methodology from previous releases. More information is available in the TCP/IP Stack Help file.
4. gSnmpNonMibRecInfo ( see page 121)[] has been moved from snmp.c file to CustomSNMPApp.c file and
file. This structure is used to restrict the access to the SNMPv3 objects from SNMPv2c and SNMPv1 version requests.
Macro STACK_USE_SMIV2 ( see page 122) is used to support gSnmpNonMibRecInfo ( see page 121)[] with
MODULE-IDENTITY number. For V5.31 STACK_USE_SMIV2 ( see page 122) need to commented.
5. Removed the SPI2CON register freeze-on-halt bit macro from the SPIFlash, RAM, and EEPROM driver files to provide compatibility with C32 v2.00.
Fixes:
1. Removed the MPFSImg2 files from the MPLAB X C18/C30 projects so that the projects will compile. Disabled
MPFSImg2.c for PIC32 Explorer 16 projects.
2. Added a heap and minimum stack size for the PIC32 Ethernet Starter Kit MPLAB X project.
3. The TCP/IP Stack Help File's performance table has been updated using the same test procedure used in previous releases.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
4. For PIC32 implementations, depending on the configuration, it is possible that the MACGetFreeRxSize() returns a value greater than 64 KB. For backward compatibility reasons the stack uses a 16 bit value to check the returned value and it won't work corretly.
5. Limiting the number of UDP sockets to 8 in the stack demos may prevent SNMP trap functionality. If this occurs, you can increase the MAX_UDP_SOCKETS definition in TCPIPConfig.h to 10 (if your system will support the increased data memory usage) to fix this issue.
6. The SNMP mib file's date and version parameter does not match the date/version of the current stack release.
******
v5.36 2 June 2011
******
Changes:
1. Because of changes to the SHOUTcast server configuration, the Internet Radio demo is no longer functional. This demo has been retained in the stack distribution to provide a TCP/IP code example.
13
3 Microchip TCP/IP Stack Help
2. The UDP module will now perform address resolution and DNS querying automatically. As a result, the UDP module APIs
TCP/IP Stack Help File's "Stack API > UDP" topic for more information.
SNMP, SNTP, TFTPc, UDPPerformanceTest, and ZeroConf modules have been updated to use the new UDP API. The iPerf demo has also been updated.
5. The MPFS Classic and HTTP(1) modules have been removed from the stack. Function- ality to support these modules has also been removed from the TCP/IP Stack software tools. MPFS2 and HTTP2 are still supported.
6. The UARTConfig demo module has been updated to upload MPFS2 images to the demo board in place of MPFS Classic images.
7. To facilitate linking on PIC18 platforms, the number of UDP sockets in demo projects has been reduced from 10 to 8.
8. The SNMP Stack application and mib2bib.jar PC utility now both support 1024 dynamic IDs.
9. SNMP_DEMO_TRAP is a new dynamic variable added to the snmp.mib file to support SMIv2 with TRAPv2. This will correct a previously existing issue viewing traps with the iReasoning MIB browser. As per those changes, the mchp.mib file has been modified to support the SMIv2 standard. This mib includes MODULE-IDENTITY which will provide
MICROCHIP and MIB information. snmp.mib also includes MODULE-IDENTIY(1), a new number (1) to the existing OID after ENTERPRISE-ID(17095).
10. Added a preprocessor check that will include the ultoa function if a version of the C32 compiler earlier than 1.12 is used.
11. Modified the WiFi module to use separate retry counters for AdHoc and Infrastructure modes.
socket function. The code will determine the protocol type from the socket type (datagram or stream).
13. Created MPLAB X projects corresponding to most MPLAB 8 projects and configurations. These projects are located in the MPLAB.X subfolder in the associated demo project directory. The MPLAB X import wizard can be used to create
MPLAB X projects from MPLAB 8 projects that don't have an analogue in the new demo project folders.
14. Added project support for the dsPIC33E and PIC24E architectures.
15. All TCP/IP Stack demo projects have been moved to the "TCPIP" subdirectory in the stack installation directory.
16. Created Java versions of several TCP/IP tools to provide cross-platform support. The TCP/IP Configuration Wizard has not been ported to Java; thus, it is only available for Windows users.
17. To prevent issues with path length, MPLAB 8 project names have been changed. A list of the abbreviations used in the project names is available in the MAL help folder (Microchip Solutions/Microchip/Help/Abbreviations.htm). The names of the HardwareProfile and TCPIPConfig configuration files have been abbreviated as well.
18. Changed the configuration inclusion macros used by the TCP/IP Stack demo projects to match the terms used in the project/configuration names.
19. The "Alternative Configurations" subfolders in most demo projects has been renamed to "Configs."
20. Added a Google PowerMeter demo for use with the PIC18F87J72 Energy Monitoring PICtail.
21. The Web Preview tool is no longer included with the stack.
Fixes:
1. Fixed a DHCP Server (DHCPs.c) lease leak problem that would occur when STACK_USE_ZEROCONF_LINK_LOCAL was defined. This problem would have resulted in the DHCP server stop giving out any leases until being rebooted.
2. Updated the PIC32MX6XX/7XX external PHY SMSC 8720LAN reference design.
3. Fixed bug with window expecting MACGetFreeRxSize() to return values < 32KB.
checksum if the checksum value overflowed again after adding the carry bits to the checksum value.
5. Fixed a bug in the AutoIP module that may have prevented the module from correctly defending its own address.
7. Fixed a bug in the ETH97J60 MACPut function.
8. Added an additional preprocessor check in a debug menu setting in WF_Spi.c to prevent a build error.
14
3 Microchip TCP/IP Stack Help
9. Added a fix to the Google PowerMeter demo code to restore SNTP timestamp sourcing if SNTP is enabled. Previously, it would be overwritten by a possibly invalid HTTP timestamp.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
4. For PIC32 implementations, depending on the configuration, it is possible that the MACGetFreeRxSize() returns a value greater than 64 KB. For backward compatibility reasons the stack uses a 16 bit value to check the returned value and it won't work corretly.
5. Limiting the number of UDP sockets to 8 in the stack demos may prevent SNMP trap functionality. If this occurs, you can increase the MAX_UDP_SOCKETS definition in TCPIPConfig.h to 10 (if your system will support the increased data memory usage) to fix this issue.
6. The SNMP mib file's date and version parameter does not match the date/version of the current stack release.
******
v5.31 19 October 2010
******
Changes:
1. Reorganized demo projects. The TCPIP ENCX24J600 Demo App, TCPIP PIC32 ETH Demo App, and TCPIP WiFi Demo
App projects in stack versions 5.25 and prior have all been merged into the TCPIP Demo App folder. All four of these projects were almost identical to each other, with the primary difference being the network interface controller the projects were preconfigured to support. In this 5.31 TCP/IP Stack release, each hardware combination now has its own MPLAB
IDE project in the TCPIP Demo App folder.
2. Reorganized HardwareProfile.h and TCPIPConfig.h structure for the TCPIP Demo App, TCPIP Google PowerMeter
Demo App, and TCPIP WebVend App projects. Now, instead of having one massive HardwareProfile.h file that supports a multitude of hardware platforms simultaneously, simple individual hardware profiles have been created for specific hardware combinations and placed in the "Alternative Configurations" sub-folder. The correct hardware profile or TCPIP config file is selected by #including "HardwareProfile.h" or "TCPIPConfig.h" as in previous stack versions. However, the active hardware profile or config file from the Alternative Configurations folder is selected by a preprocessor macro defined in the MPLAB project settings (passed on the command line to the compiler).
3. Added HTTP_SAVE_CONTEXT_IN_PIC_RAM option to TCPIPConfig.h (HTTP2 server module). This option, when enabled, will increase HTTP2 server performance when servicing multiple simultaneous connections at the expense of using more PIC RAM.
4. Added automatic TPIN+/- polarity swapping logic to ETH97J60.c driver for PIC18F97J60 family devices. Some 3rd party
Ethernet switches, routers, and end devices have their TX+/- pins wired backwards such that the remote TX+ signal connects to the PIC TPIN- pin and the remote TX- signal connects to the PIC TPIN+ pin. Because 10BaseT Ethernet signaling is polarized and the PIC18F97J60 family does not implement an auto-polarity feature, this normally prevents all
RX communications with these non-IEEE 802.3 compliant link partners. To work around this incompatibility, it is possible to implement circuitry to swap the RX+ and RX- signals before reaching the TPIN+ and TPIN- pins. The PICDEM.net 2
Rev 6 reference design includes this necessary circuitry (U6, U7, R54, and RX_SWAP GPIO output pin from PIC). This stack version automatically controls the RX_SWAP signal based on the ETH_RX_POLARITY_SWAP_TRIS and
ETH_RX_POLARITY_SWAP_IO definitions in HardwareProfile.h. If these macros are undefined, then the automatic polarity swapping feature is disabled in the ETH97J60.c driver.
removed all references to C rand() and srand() functions. The C rand() function returns a 15 bit integer on 8 and 16 bit
which PIC you are using.
15
3 Microchip TCP/IP Stack Help
6. Added support for various SST/Microchip brand SST25xxxxx SPI Flash chips to SPIFlash.c driver. Previously only
devices such as the SST2525VF010A should work, which require the AAI Byte program opcode (0xAF) instead.
7. Removed support for Spansion brand SPI Flash chips in the SPIFlash.c driver. If your application is already using one of these devices, continue to use the SPIFlash.c/.h files from TCP/IP Stack 5.25. These older files are API compatible with the current version, so can be dropped in by simply overwriting the SPIFlash.c and SPIFlash.h files.
9. For Wi-Fi projects in the TCPIP Demo App folder, changed MY_DEFAULT_LIST_RETRY_COUNT to
176) instead of just trying 3 times which makes more sense for demonstration.
10. Changed WF_Connect() beacon timeout to 40.
11. IFConfig command in TCPIP WiFi Console Demo App modified to return application-perspective MAC address from the
AppConfig structure, and not the Wi-Fi serialized MAC address (they may not match if user desired custom MAC).
12. Updated the TCP/IP Configuration Wizard. The user can now configure wireless settings and stack settings seperately.
Because of the changes to the TCPIPConfig.h file, the user must now select the specific copy of TCPIPConfig.h (or any of its variants) instead of selecting a project directory. Added the ability to select WF_RETRY_FOREVER in the Wi-Fi configuration settings. Added a selection parameter for BSD socket count. Added validation to check for the proper number of Berkeley sockets and TCP performance test sockets in the socket configuration screen (Advanced Settings) if either of these features are enabled. Added the ability to create sockets of the same type with different TX/RX buffer sizes in the socket configuration screen.
13. Updated the TCPIP WebVend Demo App to support Wi-Fi in several configurations.
14. Modified the Google PowerMeter demo to automatically determine the date/time from the HTTP module if the date/time cannot be obtained from the SNTP module.
15. Added a new Google Map project example to the Combo Demos folder. This example runs on a PIC24FJ256DA210
Development Board + Fast 100Mbps Ethernet PICtail Plus (or Ethernet PICtail Plus) + Truly 3.2" 240x320 display,
TFT_G240320LTSW_118W_E (or Powertip 4.3" 480x272 display, PH480272T_005_I11Q). It also can run on the PIC32
Multimedia Expansion Board + PIC32 Ethernet Starter Kit. This demo connects to the Internet, sends an HTTP query for a specific map tile to the Google Static Maps API, and then displays the compressed tile to the graphics display. For more information, see the "Getting Started - Running the Graphics Google Map Demo.htm" file in the Combo DemosGoogle
Map folder.
16. Added preliminary SNMPv3 module. This module, enabled with the STACK_USE_SNMPV3_SERVER option in
TCPIPConfig.h, implements the Simple Network Management Protocol, version 3. Among other things, SNMPv3 adds secure authentication and cryptographic privacy as compared to SNMPv2C. This implementation currently only supports
AES encryption (no DES support). It also has only been tested with the PIC32 Ethernet Starter Kit (TCPIP Demo App -
C32 - PIC32_ENET_SK_DM320004_INTERNAL_ETHERNET.mcp MPLAB IDE project). SNMPv3 on PIC18, PIC24, and dsPIC platforms are not supported at this time. Because AES encryption has specialized United States export requirements, this TCP/IP Stack release does not include the required AES library to enable SNMPv3. To obtain the needed AES library, you must purchase SW300052 v2.6 or later. Older v2.5 and previous versions include AES related files on them, but do not include the new AES files required by SNMPv3. For more information on using SNMP, refer to the TCP/IP Stack Help (Demo Information -> Available Demos -> TCPIP Demo App -> Demo Modules -> Network
Management (SNMP) Server).
17. Altered the SaveAppConfig() function in MainDemo.c to store a more robust signature to EEPROM/SPI Flash when saving the AppConfig structure. In v5.25 and prior stack versions, when EEPROM or SPI Flash memory was available, the stack would automatically write a one byte marker character to address 0x000000 in the EEPROM/Flash indicating if a valid AppConfig structure was stored in the non-volatile memory. This resulted in the EEPROM/Flash contents being
organized like the following: Address ( see page 152) Data Contents ===================
============================================== 0x000000: Marker Byte 0x000001: AppConfig structure
MPFS_RESERVE_BLOCK: Start of MPFS/MPFS2 image containing web pages In this stack version, EEPOM/Flash
contents will now contain: Address ( see page 152) Data Contents ===================
============================================== 0x000000: Length of AppConfig structure (16-bit integer)
0x000002: IP checksum of the AppConfig default values, as defined in TCPIPConfig.h and WF_Config.h (16-bit integer).
0x000004: IP checksum of the subsequent EEPROM/Flash bytes of the AppConfig values. 0x000006: AppConfig structure MPFS_RESERVE_BLOCK: Start of MPFS/MPFS2 image containing web pages
The additional checkums allow automatic detection to occur if you change one of the values in TCPIPConfig.h or
WF_Config.h that affects AppConfig. If you change one of the values in code, then upon boot up, the application will automatically detect this change and start using the values that you selected in code. If, at run time, you decide to change the AppConfig values and commit the changes to EEPROM/Flash, then the stack will subsequently use the run-time saved
16
3 Microchip TCP/IP Stack Help values on future reboots. The checksum at offset 0x000004 ensures that if any corrupted AppConfig contents are found in
EEPROM/Flash (ex: power is lost between writing the signature structure and actual AppConfig structure, or code unintentionally overwrites something in the AppConfig memory area), then the original defaults defined in TCPIPConfig.h
and WF_Config.h will be used instead of the corrupted values. This EEPROM/SPI Flash change affects all projects except
TCPIP Internet Radio App, TCPIP Internet Bootloader App, and all PIC32 Starter Kit projects since these projects do not have or use external EEPROM or SPI Flash memory.
Fixes:
1. Fixed a UDP bug in which a transmitted packet would have been addressed to the wrong destination node if the UDP socket received a broadcast packet from a different remote node from the last received packet, but using the same
always change the local socket parameters to send to the most recent remote node's unicast IP address, regardless of if the last received packet was addressed to a multicast or broadcast destination. Thanks go to Billy Walton for reporting this erroneous behavior. If you wish to change the destination IP/MAC addresses or port number for a UDP packet that
remote IP address/MAC address and remote UDP port, respectively. You can also read these values to obtain the remote addressing parameters for the last received packet on the given UDP socket. Note that "SocketHandle" refers to the UDP
socket handle returned by the UDPOpen ( see page 617)() API, not the literal string "SocketHandle".
and PIC32 platforms require the ADC ON/ADON bit to be cleared before modifying certain other ADC register contents.
3. Fixed an ENC28J60 MAC/MII register write timing violation when using a PIC24H or dsPIC at over 33MIPS. There was inadequate Chip Select hold time provided, violating the 210ns minimum specified in the ENC28J60 data sheet. This violation may have resulted in certain devices losing the ability to receive packets (due to the MARXEN bit, MACON1<0>, getting cleared unintentionally).
4. Fixed an ENCX24J600.c driver bug in which operating at 100Mbps with the ENC424J600/624J600 Ethernet controller, it would be possible for the MACGetHeader() function to issue a Reset() operation under rare circumstances. The PIC would reset whenever the PHY detected an illegal symbol during 4B5B decoding but guessed the correct 4B symbol such that no data corruption or CRC error occurred. This condition results in a valid packet being received but with the
Received Ok Receive Status Vector bit being clear (RSV<23> == 0). This issue would become more probable when using very long Ethernet cables (ex: 100 meters) and receiving a lot of data.
window was 0 bytes would have caused the stack to enter an infinite loop sending duplicate ACK packets.
6. Fixed Wi-Fi bug that caused assert condition if too many management messages were being received during data traffic.
7. Fixed Wi-Fi bug that caused WF_EVENT_CONNECTION_RESTABLISHED event case to send the wrong notification to the app.
8. Fixed Wi-Fi bug that caused assert failure with Scratch move failure.
10. Fixed Wi-Fi EasyConfig bug that required development boards to be manually reset even after new network was selected.
11. Fixed MRF24WB0 bug that caused assert if invalid WPA/WPA2 key was entered.
12. Fixed Wi-Fi power management bit behavior in PS-Poll frame that was causing some AP’s to never send data or disconnect when in power save mode.
13. Fixed a TCP bug in which attempting to open a client TCP socket to a remote server, specified by IP address (not DNS address), that was offline, but who's MAC address was already cached by the ARP client, would result in endless back-offs. For example, when attempting to contact the remote node (that was not responding), the TCP module would have transmitted a SYN at time T=0 seconds, T=1s, T=3s, T=7s, T=15s, T=31s, T=63s, T=127s, T=255s, etc. The exponential back-off between retransmissions would grow indefinitely until the retransmission interval would have grown so large that effectively no-retransmissions would be occurring. Assuming the application wasn't written with its own timeout to prevent endless waiting, this would prevent the socket from automatically establishing the connection to the remote server once the server came back online. With this TCP fix, the exponential back off now saturates after
means SYN transmissions will occur at T=0 seconds, T=1s, T=3s, T=7s, T=15s, T=31s, T=63s, T=95s, T=127s, etc. After
5 back-offs the retransmission interval stops growing and stays constant at 32 seconds.
14. Fixed an RSA computation bug that would cause the RSA module to never complete if you attempted to compute y = x^e
% n where e = 3 (or similar number < 256 with only 0, 1, or 2 bits set). Thanks go to Kevin Maidment for pointing this error out and suggesting a solution. Note, that this fix to RSA.c is not distributed with the ordinary TCP/IP Stack due to United
17
3 Microchip TCP/IP Stack Help
States export restrictions. To get this fix, you must repurchase SW300052. This fix is included in SW300052 v2.6 or later.
If you don't have CD media to identify the SW300052 version that you have, you can test the RSA.c file that you have.
RSA.c in SW300052 v2.6 has a CRC32 checksum of 0x91F66711. RSA.c in v2.5 and prior had a checksum of
0xB1E8B0CC.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
******
v5.25 07 May 2010
******
Changes:
1. Added support for the Microchip MRF24WB0 802.11 WiFi controller (module part number MRF24WB0MA). This product is intended as a backwards compatible, drop in replacement to the ZG2100. The MRF24WB0MA should work with previous TCP/IP Stack versions as if it were a ZG2100M, but when the MRF24WB0MA is used with this (5.25) and future
TCP/IP Stack versions, feature improvements inside the MRF24WB0 allow the TCP/IP Stack code/RAM size to be smaller and run faster.
2. Dropped support for the ZeroG ZG2100 802.11 WiFi controller. Applications that must stay with this device should continue to use TCP/IP Stack version 5.20b or earlier. All new projects or preexisting projects undergoing updates should be developed with the MRF24WB0 instead.
3. The WiFi connection management state machines now run on the MRF24WB0 instead of the PIC host, freeing up code and data space. Connection profiles can be created and the connection algorithm fine-tuned by the PIC application. In the
WiFi demos see the WF_Connect function in MainDemo.c for an example of how to configure and then establish a WiFi connection. The programming model has changed to an API model which is documented in 'TCPIP Stack Help.chm'.
4. Changed "VERSION" macro definition in TCPIP.h to "TCPIP_STACK_VERSION". "VERSION" is overly generic and will likely conflict with other identical tokens one may use in their application code or source libraries.
5. Added support for the PIC24FJ256GA110, PIC24FJ256GB110 and PIC24FJ256GB210 PIMs for the Explorer 16. Note that when using the PIC24FJ256GA110 general purpose PIM, the Ethernet PICtail Plus, Fast 100Mbps Ethernet PICtail
Plus, MRF24WB0MA Wi-Fi PICtail Plus, or other SPI PICtail daughter board should be installed in the middle SPI2 slot of the Explorer 16, not the ordinary topmost SPI1 slot used by other PIMs, including the PIC24FJ256GB110 and
PIC24FJ256GB210 ones. The software is set up to use SPI2 for the PIC24FJ256GA110 PIM to avoid incompatibilities with silicon revision A3, which does not allow the SCK1 pin to be configured as a PPS output.
6. Added support for the PIC24FJ256DA210 Development Board.
uploading a whole file to a remote TFTP server without requiring a great deal of application state machine logic. These
APIs require the DNS client module to be enabled (STACK_USE_DNS must be defined, in addition to
STACK_USE_TFTP_CLIENT).
8. Added a dummy DNS Server module. This server always sends the local IP address in response to all queries received.
When using the PIC DHCP server, its purpose is to allow a user to type anything into a web browser (ex: http://asdf/) and still receive the web page provided by the PIC, much as a hotel or airport WiFi router will serve to you before you've paid or agreed to the network's terms of service. This DNS server module is implemented in DNSs.c, requires one UDP socket, and is enabled via the STACK_USE_DNS_SERVER option in TCPIPConfig.h.
9. Changed SPIFlash.h file defaults to target an SST SPI Flash with 4096 byte sectors instead of a Spansion Flash with
18
3 Microchip TCP/IP Stack Help
65536 byte sectors. These new defaults are, among other reasons, in support of the PIC24FJ256DA210 Development
Board, which has an SST SST25VF016B on it.
seconds) after the last socket TX or RX activity. In earlier stack versions, if the local node transmitted some data and then
(default 1 second) timer value before getting sent. While benign in terms of application behavior, these faster than normal keep-alive transmissions were distracting when viewed in Wireshark or other packet capture tools.
11. Disabled STACK_USE_DYNAMICDNS_CLIENT option in TCPIPConfig.h by default for the TCPIP Demo App and
TCPIP ENCX24J600 Demo App projects. This option was enabled by default in earlier stack releases. This was done to save code size and allow out-of-box compilation on devices with 128KB of Flash when not using compiler optimizations.
The TCPIP PIC32 ETH Demo App project continutes to have this option enabled by default.
12. Added SNMP v2 TRAP PDU format. Macro SNMP_STACK_USE_V2_TRAP is used to enable the SNMP v2 trap format.
New API function SNMPV2TrapDemo() is included to support more than one variable binding to the SNMPv2 TRAP. This
API can be used for a single SNMPv2 TRAP variable varbind and is part of CustomSNMPApp.c. A multiple variable binding demo can be enabled MainDemo.c. One should not enable both SNMPTrapDemo and SNMPV2TrapDemo
available to be part of the SNMPv2 TRAP PDU.
13. Added support for PIC32MX6XX/7XX external PHY's: SMSC 8700LAN and National DP83640.
14. Added schematics and BOM for the PIC32 Ethernet Starter Kit.
15. Added the Google PowerMeter demo project. Consult the "Reference Implementation for Google PowerMeter.chm" help file for more information.
enable the SSL module to store supplementary data (currently only SSL Certificate Public Keys) in a structure.
17. Moved the HTTP_PORT ( see page 259), HTTPS_PORT ( see page 266), HTTP_MAX_DATA_LEN ( see page
259), and HTTP_MIN_CALLBACK_FREE ( see page 259) macros from HTTP2.c to TCPIPConfig.h.
Fixes:
1. The SPIFlashEraseSector() function in the SPIFlash.c file incorrectly erased the sector specified by the current write pointer (set by calling SPIFlashBeginWrite()) instead of the specified dwAddr parameter address. This error had no impact on any TCP/IP Stack code as these parameters always matched. However, application code using the API would have been affected. Thanks go to Marc Boon for reporting this issue on the Microchip Ethernet forum.
2. Fixed ENC424J600/624J600 driver for PSP modes 2, 4, 6, and 10. The PIC's PMP PMMODE<9:8> bits were not set correctly.
3. Removed from lingering references to TickGetDiff() in FTP.c, TFTPc.c and UARTConfig.c.
4. Fixed DNS client module from returning the DNS server IP address if the DNS query failed due to a server error (i.e. DNS did respond, but did not return any records, such as when attempting to resolve a name that isn't in the DNS).
DNSIsResolved ( see page 192)() will now return 0.0.0.0 on any non-recoverable DNS error or timeout.
5. Fixed HTTP2 MPFS upload page being accessible from URLs that weren't an exact match. For example, in 5.20 and earlier, accessing http://mchpboard/mpfsuploadASDF would still have opened the mpfsupload page. Thanks go to Andrea
Rivolta on the Microchip Ethernet Forum for identifying this error.
6. Improved UDP TX checksum code for the special case when the computed checksum was 0x0000. According to the UDP
RFC, for this corner case, the checksum should be converted to 0xFFFF before transmission to differentiate from the checksum disabled case, improving error detection by a minuscule amount.
7. Fixed GetCLKOUT() function in ENCX24J600.c driver file. Previously, 0x00 would always be returned, regardless of the value in the COCON bits of ECON2. The function documentation for SetCLKOUT() and GetCLKOUT() was also corrected
(had obsolete information ported over from ENC28J60 driver file).
8. Fixed DHCP client rebinding bug in which the DHCP client would request the wrong IP address if an unrelated DHCP
OFFER or ACK message were received after we transmitted a DHCP REQUEST but before we received our DHCP ACK.
Under rare conditions, this would have resulted in the TCP/IP stack reverting to the static or AutoIP assigned address for a few seconds between DHCP lease renewals.
9. Fixed TFTP Internet Bootloader bug in which uncommon .hex files containing a certain data pattern could not be uploaded correctly to the PIC18F97J60 family device. For these problem .hex files, a block of 32 program words (64 bytes) would remain unprogrammed (left as 0xFFFF) due to a parsing error in the bootloader's DecodeHex() function. The
TFTP upload operation would succeed without reporting a programming error. The problem can be detected by using an
19
3 Microchip TCP/IP Stack Help
ICD3 or similar ICSP programmer and reading the program Flash out of a device that is programmed with the bootloader and application .hex files. Compare the resulting memory dump to a device programmed only with the application .hex file. If you have devices deployed in the field with the previous bootloader and happen to generate a problem application
.hex file, you can potentially work around the bootloader bug by opening the application .hex file with Notepad and appending dummy address records to the beginning to move the data around in the file. For example, at the very top of the .hex file, add lines containing ":020000040000FA" until the bootload process works correctly. You may alternatively try adding spaces at the end of any line, although this may make the .hex file incompatible with some programming utilities.
Thanks go to Jonathan Seidmann for identifying and reporting this bug.
10. Fixed SNMPv2 TRAP format issue where SNMP browser was displaying all the SNMPv2 traps as SNMP version 1.
SNMP v2 TRAP pdu format is rectified. Macro SNMP_STACK_USE_V2_TRAP is used to form and send a SNMPv2
TRAP PDU. SNMPTrapDemo API is used for both SNMPv1 and SNMPv2 single variable varbind trap.
11. Fixed an HTTP2.c server module initialization bug when using the PIC32MX7XX/6XX series internal Ethernet module.
end of the reserved memory allocated for the HTTP2 module. This problem would manifest itself by locking up the TCPIP
PIC32 ETH Demo App-C32 demo shortly after power up if you compiled TCP/IP Stack version 5.20 with the MPLAB C
Compiler for PIC32 MCUs (C32) version 1.11.
12. Fixed SSL client from incorrectly parsing for the server's public key in rare cases where the RSA Public Key Algorithm identifier was received, but the key hadn't been received by TCP yet. Thanks go to Kevin Maimdnet for identifing this error in SSL.c and reporting it via http://support.microchip.com/.
sometimes returning the wrong value on PIC32 platforms. On the PIC32MX3XX/4XX family devices a wrong return result would sometimes occur if using -O3 compiler optimizations (maximum speed) with the Microchip MPLAB C Compiler for
PIC32 MCUs (C32). On the PIC32MX5XX/6XX/7XX family devices, such as the PIC32MX795F512L device used on the
PIC32 Ethernet Starter Kit, wrong values could be returned, regardless of the compiler optimization level.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 compilers are not supported in this release. The supplied HI-TECH PICC-18 MPLAB projects usually will not compile and/or link.
4. LCDBlocking.c timing for the LCD_E_IO enable signal is too fast to meet published data sheet limits for various LCD controllers when compiling for a PIC32 running at > 43MHz. Despite this potential timing violation, the LCD does normally work correctly on the precompiled PIC32 demos for the Explorer 16 at 80MHz.
******
v5.20 18 November 2009
******
Changes:
1. Added PIC32MX7XX/6XX Family integrated Ethernet controller support. The "TCPIP PIC32 ETH Demo App" folder was added to compile for the PIC32 Ethernet Starter Kit. Ethernet driver files "ETHPIC32ExtPhy.c" and "ETHPIC32IntMac.c" were added, in addition to the "ETHPIC32ExtPhyDP83848.c" file, which is a specific driver file for the National DP83848
10/100 PHY.
2. Added RFC 3927 Auto IP module. This module will automatically assign a local IP address to the node in the
169.254.xxx.xxx private address range (subnet mask 255.255.0.0) if a DHCP server is not present on the network or the
DHCP client is disable. The exact IP address chosen will be pseudo-random, but as required by the protocol, it will perform gratuatous ARPs to avoid clobbering anyone else's IP address. Also, unless there is an address collision with a preexisting node on the network, the IP address generated by the Auto IP module will not change between power cycle events (random number generator is seeded by local MAC address). To enable this module, STACK_USE_AUTO_IP must be defined in TCPIPConfig.h. When compiled in, the module defaults to enabled, but will automatically yield to the
20
3 Microchip TCP/IP Stack Help
DHCP client module, which has higher priority.
3. Added "TCPIP MDD Demo App" beta application projects. Projects in this folder store the HTTP2 web pages in external
FAT16/FAT32 formatted SD card or USB Mass Storage media instead of an MPFS2 formatted EEPROM or SPI Flash.
For more information on these projects, see the "Running the TCPIP MDD Demo App (Beta Release).pdf" file in the
MicrochipHelp folder.
4. Expanded XEEReadArray() API's third length parameter from a BYTE to a WORD.
5. Converted all variable declarations and type casts of TICK data type to DWORD. The TICK typedef is now deprecated and will be removed in a future stack release. This data type conflicts with the TICK structure used in certain other
Microchip software libraries.
overhead. If this adversely affects your application RX performance (unlikely, but possible for certain communications
patterns), set TCP_WINDOW_UPDATE_TIMEOUT_VAL ( see page 570) equal to or shorter than
versions.
to limit both the maximum size of transmit and receive packets. In cases where large TX FIFOs are allocated, and the remote node advirtises a large Maximum Segment Size TCP option, this change improves TCP transmit performance by roughly 10%.
8. Renamed "Internet Radio App", "Internet Bootloader App" and "WiFi Iperf App" folders to "TCPIP Internet Radio App",
"TCPIP Internet Bootloader App" and "TCPIP WiFi Iperf App" respectively. These new names ensure consistent folder placement when viewing the Microchip Solutions folder with other Microchip Application Libraries installed.
Fixes:
1. Fixed SSL functionality (ex: HTTPS server) from failing when using the ENC424J600 and ENC624J600 Ethernet controllers. In stack versions 5.00 and 5.10, the BFSReg() and BFCReg() functions were being incorrectly used to set and clear CRYPTEN (EIR<15>). ENC424J600/624J600 silicon errata #6 on production silicon revision A2 prevents BFSReg() and BFCReg() from being able to modify CRYPTEN. This resulted in the SSL RSA encrypt/decrypt operations from ever finishing. The ENC424J600/624J600 errata #6 workaround is now implemented in the ToggleCRYPTEN() function in
ENCX24J600.c.
2. Fixed an RSA padding error in the ENCX24J600.c's version of RSASetData() and RSASetE() functions. This fixes the
Bad Record MAC problem when using SSL client APIs with the ENC424J600 and ENC624J600, as mentioned in the 5.10 stack release notes' Known Problems section. Although unknown at the time of release this problem also occurred in stack version 5.00.
3. Fixed DNS client from mishandling DNS responses that did not use name compression. Thanks go to Will Stone on the
Microchip Ethernet forum for identifying this bug.
Ex: "http://www.google.com/search?q=http://www.microchip.com/"
potentially returning an incorrect time value (0x10000 ticks less than it should have) on rare occasions when using a
PIC32 and with compiler optimizations turned on. The Tick.c module was also revised so that the IEC0 register does not get written to via a load-modify-store operation on PIC32s so that it is now possible for other application ISR functions to write to IEC0 without risking state corruption.
6. Fixed PIC32 Starter Kit Debugger losing access to the PIC32 target when the project was run. JTAG was being disabled at run time, but the PIC32 Starter Kit Debugger requires JTAG to communicate with the debug executive. JTAG is now conditionally disabled on PIC32s when the __MPLAB_DEBUGGER_PIC32MXSK macro is undefined.
would leak a TCP socket each time the affected API calling sequence occurred and result in no FIN getting transmitted to the remote node.
8. Fixed an HTTP2 filename parsing bug that would occur when a web browser submitted a request for a file with hex encoded characters in it. For example, with stack version 5.10 and Firefox 3.5.3, typing "http://mchpboard/%70rotect" into the URL field would have resulted in an HTTP 404 not found error when "http://mchpboard/protect/index.htm" should have been returned instead. Thanks go to Steve Tuttle for reporting this issue and suggesting a solution.
21
3 Microchip TCP/IP Stack Help
return an incorrect remote IP address and port number when the from pointer was non-NULL.
name from URL encoding to plain-text. If the browser posted, for example, a field named "Stock Remaining", it would
have been incorrectly returned from HTTPReadPostName ( see page 252)() as "Stock+Remaining".
11. In Stack 5.10, any new values you saved into AppConfig via the Network Configuration demo web page would have
App and TCPIP Iperf Demo App projects were corrected so that they now write a magic 0x61 marker into EEPROM/SPI
Flash address 0x0000 to inidicate that the AppConfig structure is valid in EEPROM/SPI Flash. This prevents the
InitAppConfig() function in MainDemo.c from restoring the default settings when changing the values through the Network
Configuration page.
12. For WiFi projects, a Gratuitous ARP Work-around was implemented to work around cases where access points send
broadcast messages at data rates that the ZG2100 cannot listen ( see page 180) to. The define
USE_GRATUITOUS_ARP (in TCPIPConfig.h) turns this feature on or off.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 compilers are not supported in this release. The supplied HI-TECH PICC-18 MPLAB projects usually will not compile and/or link.
4. ENC624J600 PSP modes 2, 4, 6, and 10 do not work at this time. Some Parallel Bit Bang modes may not work either.
Some minor firmware changes are needed.
5. TCPIP ENCX24J600 Demo App-C18.mcp project does not compile by default using MPLAB C Compiler for PIC18 MCUs
(C18) version 3.34. There is not quite enough program memory available on the PIC18F97J60 for the large number of selected stack features to allow linking. To get this project to compile, turn on compiler optimizations or disable one of the modules in TCPIPConfig.h (ex: comment out STACK_USE_DYNAMICDNS_CLIENT).
******
v5.10 29 July 2009
******
Changes:
client, you can use an SSL proxy, such as stunnel (http://www.stunnel.org/) to add SSL/TLS support to any telnet client.
2. Moved a number of string pointer tables in the HTTP.c, HTTP2.c, FTP.c, and DynDNS.c files to allocate in ROM instead of RAM. This reduces around 120 bytes of RAM usage in the HTTP2 server when compiled for the PIC18 or PIC24/dsPIC platforms. The gains are even greater on PIC32 platforms.
3. Added redefinition of SPIRAM*(), SPIFlash*(), and XEEPROM*() functions so that when compiled and used without proper HardwareProfile.h definitions, a more descript linker error will be generated instead of a mysterious symbol not found error.
4. Added several new APIs:
extracting the protocol, hostname, port, file path, etc. Currently, this function is commented out to save code space as no stack modules require it. However, it should work correctly if you simply uncomment it (remove the #if 0...#endif around it).
maximum length before giving up.
22
3 Microchip TCP/IP Stack Help
buffer without removing the data from the stream.
resources, invalidating the socket handle.
5. Updated the DHCP client module:
• Modified so that it wouldn't attempt to transmit DHCP Discover packets when the MAC layer reports no link
(MACIsLinked() == FALSE). This avoids main() while(1) loop performance degredation when you unplug the Ethernet cable or lose association to your access point.
• Added capability of performing DHCP discovers and requests without setting the BOOTP broadcast flag. Now, the
DHCP client module will start up and attempt to obtain an IP address with the broadcast flag set, but if it fails the next
DHCP retry will attempt to obtain the IP address with the broadcast flag cleared. The flag will toggle back and fourth between unicast mode and broadcast mode if no DHCP server responds. This feature improves compatibility with certain DHCP servers and WiFi access points.
• Added several new APIs including DHCPInit(), DHCPIsEnabled(), DHCPStateChanged(), DHCPIsBound(), and
DHCPIsServerDetected().
• Removed the DHCPFlags DHCP_CLIENT_FLAGS global variable. Use the above named APIs now to get equivalent functionality.
• Removed the DHCPBindCount global variable. To detect if the DHCP state has changed, poll the new
DHCPStateChanged() function.
• Removed the DHCPReset() API. To perform this operation, now call the DHCPInit() API. Use 0x00 for the vInterface parameter.
6. Removed deprecated TickGetDiff() macro. To get a tick difference, just subtract the two values in-line. This macro was removed because it promoted confusing code. Ex: a-b is different from b-a. However, it was not contextually obvious which of the two was returned when TickGetDiff(a, b) was called.
7. Added PIC32MX460F512L USB and dsPIC33FJ256GP710 PIM support to the Explorer 16 hardware profile for the TCPIP
WiFi Demo App and WiFi IPerf App projects.
8. Added all files needed for SSL (assuming the crypto libraries are present) to the TCPIP WiFi Demo App-C30 and TCPIP
WiFi Demo App-C32 projects.
9. Converted TCPIP Demo App, TCPIP WebVend App, Internet Radio App, and Internet Bootloader App MPLAB Build
Directory Policy to compile in the project folder instead of the source folder. This reduces the depedancies on the MPLAB project include path and allows new projects to be created by copying one of the pre-existing folders (ex: copy "TCPIP
Demo App" to "My App") without having problems including the wrong HardwareProfile.h and TCPIPConfig.h files.
10. Changed EEPROM/SPI Flash AppConfig record valid flag from 0x60 to 0x61 in the TCPIP WiFi Demo App and WiFi
Iperf App projects. This will force the various EEPROM settings to get erased when switching between Ethernet and WiFi projects. This is done since the AppConfig structure changes when using WiFi (SSID string is added).
11. The Wifi Iperf App and TCPIP WiFi Demo App projects have been optimized for better performance.
Fixes:
This problem could have been observed in stack version 5.00's "TCPIP Demo App-C32 EXPLORER_16 32MX360F512L
ENC624J600 PSP 9.hex" precompiled application, among others, if you connected to the TCPPerformanceTest.c module and then attempted to simultaneously access the web server. The web server was returning data very slowly and failing to send the last parts of each file requested by the browser.
in HTTP2.c. If an oversized or malformed Content-Length header is sent from the web client, the function will now gracefully fail by returning an HTTP 400 Bad Request error page. Thanks go to Mark Philipp for identifying this error and suggesting a solution.
back-to-back ARP query packets if a client socket was created that specified a non-reachable remote IP address (ex: local gateway was offline, or for destinations on the same subnet, the actual remote node was offline). This problem would occur only after a few minutes (<10) had passed since the PIC was last reset. Thanks go to Sergey of DPS
23
3 Microchip TCP/IP Stack Help
TELECOM for reporting this problem.
4. Fixed linking problem with BigInt_helpers.S (PIC24/dsPIC only) when targeting a PIC with more than 8KB of RAM. The interface registers (_iA, _xA, _iB, _xB, _iR, and _wC) are now forced into near RAM.
5. Cleaned up some uninitialized variable warnings in SNMP.c ( see page 454).
6. Fixed a sequence variable traversal bug in SNMP.c ( see page 454).
7. Cleaned up a large number of unsigned integer to signed integer comparison warnings produced by the MPLAB C
Compiler for PIC18 MCUs (C18) version 3.32. With earlier versions of this compiler, these warnings would only be generated as messages, so they did not get displayed by default.
8. Some ENCX24J600 parallel bit bang modes work now. PSP Mode 5 indirect has been tested.
9. SSL client and server capabilities now work when using the ZeroG ZG2100M WiFi interface. In the 5.00 stack release, attempting to enable the STACK_USE_SSL_CLIENT or STACK_USE_SSL_SERVER TCPIPConfig.h options with this network controller would have resulted in an error trap. If an LCD was present, the LCD would display “encRdPtrRAWId = encWrPtrRAWId” when the error occurred.
10. The WiFi Iperf App demo locked up when an invalid command was entered at the serial port console. This is now fixed.
11. The WiFi Iperf App demo locked up when running with a PIC32 if iwconfig was typed at the serial port console. This is now fixed.
12. The Wifi Iperf App demo, when running on the PIC24 and PIC32, and compiled with the –Os option (min code size optimization), did not work. This is now fixed.
13. Change a lot of BerkeleyAPI.c internals. This may fix a number of BSD API problems.
14. Fix a problem with SNMP variables being inaccessible with certain unique PEN numbers.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 compilers are not supported in this release. The supplied HI-TECH PICC-18 MPLAB projects usually will not compile and/or link.
4. ENC624J600 PSP modes 2, 4, 6, and 10 do not work at this time. Some Parallel Bit Bang modes may not work either.
Some minor firmware changes are needed.
5. SSL client code doesn't work with ENC424J600/624J600 devices. The remote server terminates the connection reporting
******
v5.00 27 April 2009
******
Changes:
1. Added ZeroG ZG2100 802.11 WiFi controller support. The new TCPIP WiFi Demo App and WiFi Iperf App projects have been added, which default to using this controller.
2. Added Microchip ENC424J600/624J600 10/100 Ethernet controller support. Support for this controller is provided by the new ENCX24J600.c/.h files which perform the same role as the ENC28J60.c/.h or ETH97J60.c/.h files. Precompiled .hex files for the ENC624J600 controller require the use of the new Fast 100Mbps Ethernet PICtail Plus daughter card
(AC164132). This product is not available at the time of the 5.00 TCP/IP stack release. However, it is anticipated to be available for purchase on www.microchipdirect.com in CQ3 2009.
3. Significantly updated the Internet Radio App project. Previously, radio stations were hard coded into program memory at compile time. Now, a dynamic Shoutcast directory client has been implemented which allows retrieval of radio stations at
24
3 Microchip TCP/IP Stack Help run time, offering endless stations you can tune into. The web pages for the radio have also been updated to allow control and status reporting of the board from a web browser.
4. Update SNMP Server (Agent) module to support SNMPv2C. The default Demo App web pages now include an SNMP reconfiguration capability to set the read and write community strings.
(ping) client module. These two APIs are available only when STACK_USE_ICMP_CLIENT and STACK_USE_DNS is defined in TCPIPConfig.h. These functions allow pinging of DNS hostnames directly without the need for the application to convert the hostname to an IP address first by manually calling the DNS client APIs. With this addition, the PingDemo.c
www.microchip.com server dynamically changing. If the DNS module is not enabled, the ping demo will instead ping the local gateway IP address instead of ww1.microchip.com.
6. Updated TCPPerformanceTest.c code. The previous version would generate incorrect speed calculations at high data rates (ex: >1Mbyte/sec).
define MAX_SIMULTANEOUS_CONNECTIONS in Telnet.c greater than 1 and create an equal number of
TCP_PURPOSE_TELNET type TCP sockets in the TCPSocketInitializer[] definition in TCPIPConfig.h.
8. Added more randomness to the local port selection when opening a client-mode TCP socket. This reduces the risk of reusing a previously used port number if the user power cycles the device.
9. Updated XEE* SPI EEPROM API functions. Writes are no longer required to start on an EEPROM page boundary, and writes can now be arbitrarily long without having to call XEEEndWrite() at each page boundary. Additionally, the
XEEWriteArray() API has been added, which performs a similar operation to the SPIFlashWriteArray() API (but with no special erase cases to worry about).
10. Decoupled AppConfig storage in external SPI EEPROM or SPI Flash option from MPFS_USE_EEPROM and
MPFS_USE_SPI_FLASH options. MainDemo.c will now save the AppConfig structure in external non-volatile memory, even if MPFS is unused (no HTTP or SNMP server modules enabled) or MPFS is using internal Flash program memory to store web pages/bib information. This change also allows the XEE*() and SPIFlash*() non-volatile read/write functions to be available at all times (even if MPFS is unused), as long as the appropriate hardware pinout definitions are present in
HardwareProfile.h. SPI Flash and SPI EEPROM are no longer mutually exclusive with each other. However, if both are enabled simultaneously, AppConfig will be stored in the EEPROM, not the SPI Flash.
11. Added required SSL files to TCPIP Demo App MPLAB projects. SSL capabilities can now be turned on directly via the
STACK_USE_SSL_SERVER and STACK_USE_SSL_CLIENT options in TCPIPConfig.h for these projects, assuming appropriate crypto libraries are installed (SW300052 available from https://www.microchipdirect.com/). With this change, the historical "SSL Demo App" folder has been removed.
13. Updated HardwareProfile.h files. This includes the addition of PIC18 Explorer board support, removal of the PICDEM Z profile, changes to the HI-TECH PICC-18 profiles for newer compilers, among other changes.
14. Added a TCP and UDP performance test measurements table to TCPIP Stack Help (TCPIP Stack Help.chm). Access this from the "Microchip TCP/IP Stack" book, "Stack Performance" page.
15. Updated MPFSlib project (Microchip.MPFS.dll file) so that C18 and C32 output from the MPFS2.exe utility is now identical for MPFS2 images. The generated .c file is now compatible with both C18 and C32 compilers simultaneously.
Previously, the images generated for C18 would compile successfully for C32 projects, but would potentially operate incorrectly when compiler optimizations were turned on. Images generated for C32 would compile successfully and work on C18 projects, but the C18 compiler would take a very long time to process the file each time you rebuilt your MPLAB project. Now, the image generated for C18 matches the image generated for C32 and it will compile fast and work correctly on both platforms, even with compiler optimizations turned on.
16. Added schematics and BOMs for the Ethernet PICtail, Ethernet PICtail Plus, Fast 100Mbps Ethernet PICtail Plus,
Internet Radio, PICDEM.net 2, and ZeroG ZG2100M PICtail development boards to the "MicrochipTCPIP StackDemo
Board Files" folder.
Fixes:
a deliberately malformed packet was received, the PIC RAM could have become corrupted. Thanks go to David Talmage for finding this vulnerability.
2. Fixed Timer1 interrupt flag clearing code on PIC32 products. Previously, the Tick.c module was clearing the interrupt flag in an unsafe manner which could have corrupted other interrupt flags in the IFS0 register. Thanks go to Leon van
Snippenberg working on the AVIX-RT RTOS for pointing this error out on the Microchip forums.
3. Fixed SNMP up-time variable. Previously the CustomSNMPApp.c module would respond with the number of Tick API
25
3 Microchip TCP/IP Stack Help ticks that elapsed, not the number of 10ms time slices that elapsed. The SNMP standard uses 10ms as its time base.
4. Fixed BigInt_helper.asm's _masBI() and _masBIROM() functions when the Br parameter's length modulo 4 was equal to
1 or 2. This bug previously caused the BigIntMod() function to sometimes go into an endless calculation loop on PIC18 products when using the SSL libraries and certain combinations of modulus data and length were used. Thanks go to
Vasil Stoianov on the Microchip Ethernet forum for running into this defect and reporting it.
previously make it impossible to make new SSL connections after a while, but then after a few more hours, the sessions would become free again. Thanks go to Jim Stephens for identifying this issue and finding the solution.
6. Fixed an SSL 2.0 antique client hello record length calculation bug occurring when a received record was > 255 bytes.
119)() code would have deadlocked, and suppressed all future transmission of SNMP traps.
8. Fixed DNS client timeout if the DNS server is unable to be ARPed. Previously, the DNS client would retry ARPing the
DNS server indefinitely if it was offline. Now, the DNS client will correctly abort if too many attempts to ARP the DNS server fail. Thanks go to Phil "andersop" on the Microchip Ethernet forum for identifying this error.
Phil "andersop" on the Microchip Ethernet forum for pointing this behavior out.
called. Thanks go to Bob Topper for identifying this issue and suggesting a solution.
optimizations turned on. Wrong values were observed when using MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs version 3.12.
12. Fixed a number of SPI communications problems that could occur when compiler optimizations were turned on. The
ENC28J60 was observed to not work correctly on the dsPIC33FJ256GP710 processor when compiled with MPLAB C
Compiler for PIC24 MCUs and dsPIC DSCs version 3.12.
13. Fixed possible MPFS2 error when using an ASM30 .s image where MPFS_Start would be read using the wrong
PSVPAG setting. You must rebuild your MPFS2 image file (ex: MPFSImg2.s) with this stack version's MPFS2.exe utility to get this correction applied.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 compilers are not supported in this release. The supplied HI-TECH PICC-18 MPLAB projects usually will not compile and/or link.
4. ENC624J600 PSP modes 2, 4, 6, and 10 do not work at this time. Parallel Bit Bang mode does not work either. Some minor firmware changes are needed.
******
v4.55 10 November 2008
******
SSL Note: RSA.c and ARCFOUR.c have not changed between the 4.50 and 4.55 releases. Although the precompiled SSL
Demo App .hex files will differ, you can continue to use the previous TCP/IP Stack v4.50 Encryption Add-on with this 4.55
stack version.
Changes:
26
3 Microchip TCP/IP Stack Help
1. Added DNS client support for a secondary DNS server address. Previously, the AppConfig.SecondaryDNSServer setting was unused. Now, the DNS client module will automatically swap the AppConfig.PrimaryDNSServer and
AppConfig.SecondaryDNSServer values after any DNS query timeout (or ARP timeout for the DNS server) and attempt the query with the alternative server. If AppConfig.SecondaryDNSServer is disabled by setting it to the IP address 0.0.0.0, the DNS client will only use the AppConfig.PrimaryDNSServer value and never swap the values. With this change, the
DHCP client was also updated. If the DHCP server does not specify a secondary DNS server, then the DHCP client will now set the AppConfig.SecondaryDNSServer value to 0.0.0.0. Previously, it would change the
AppConfig.SecondaryDNSServer setting only if the remote DHCP server offered a secondary DNS server.
Fixes:
1. Updated Internet Bootloader App project to correctly detect if the configuration bits are being changed or not. Previously, the bootloader always thought the configuration bits were being changed and thus had to always erase the last Flash page (largest memory address) twice for each firmware update. This did not cause any functional problems or specification violations, but it would decrease the effective Flash endurance of the last page.
based on the current read location. This is the same behavior as stack versions 4.18 and earlier. In stack versions 4.50
solution.
4. Fixed demo admin web page in TCPIP Demo App project so that the last byte of the MAC address can be changed, independent of the format it was entered by the user.
5. Fixed a buffer overflow bug that would occur when using the SSL server during hashing of the server certificate for the initial handshake. This error previously caused several bytes of random variables elsewhere in the project to get overwritten for each SSL connection.
6. BSD sockets API was updated to fix some issues.
7. LCDBlocking.c was updated to relax start up timing. This timing fix is specifically needed to support Explorer 16 boards with a Truly TSB1G7000 display (Novatek NT7603H controller).
8. Removed four uses of Arial Black font in MPFS2.exe utility. On some rare PC configurations, the use of this font caused the executable to not run.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
4. MAC.h RXSIZE precompiler test for proper range doesn't work. This is not a functional problem, just a compile-time configuration test. Ensure that you don't over allocate TCP_ETH_RAM_SIZE or MAX_HTTP_CONNECTIONS.
5. HI-TECH PICC-18 STD 9.51PL1 cannot compile DynDNS.c. It raises an "inconsistent type" error while trying to perform a
ROM pointer to integer cast. The older 9.50PL3 compiler release is required to compile this file.
6. HI-TECH PICC-18 STD 9.50PL3 does not initialize several static variables correctly on reset. This behavior breaks many stack modules in the TCPIP Demo App and TCPIP WebVend App projects. Additionally, string printing functions do not work correctly, so the supplied "TCPIP Demo App-HITECHPICC18 PICDEMNET2 18F97J60.hex" and "TCPIP WebVend
App-HITECHPICC18 PICDEMNET2 18F97J60.hex" files may not correctly print the board's DHCP assigned IP address on the board's LCD (if present) and UART. To avoid these severe problems, use the Microchip MPLAB C Compiler for
PIC18 MCUs. A free student edition can be downloaded from http://www.microchip.com/c18.
27
3 Microchip TCP/IP Stack Help
******
v4.51 24 July 2008
******
IMPORTANT NOTE: You must use MPLAB 8.10 or higher to successfully open the MPLAB projects.
SSL Note: RSA.c and ARCFOUR.c have not changed between the 4.50 and 4.51 releases. Although the precompiled SSL
Demo App .hex files will differ, you can continue to use the previous TCP/IP Stack v4.50 Encryption Add-on with this 4.51
stack version.
Changes: None. This release includes bug fixes only. It is very important that applications using the ENC28J60 get fix item
7, below.
Fixes:
DNS module failed to resolve the remote address on the first try. This, for example, would occur if you powered up your
The Internet Radio application would sometimes not begin playing the default station upon power up because of this problem.
2. Set SEQ.ACK = 0 for outbound TCP SYN packets. This fixes a connection compatibility problem with certain paranoid
TCP/IP stacks that would validate this field even though the ACK flag was clear. This problem would previously cause the
servers/services. Thanks go to Jean LE TUTOUR for finding one of these problem servers.
hash matched but no complete file name did. This has been corrected to prevent potential DOS attacks on the HTTP2 web server. Thanks to David Tan on the Microchip Ethernet formus for identifying this issue.
4. Fixed a bug in MPFS2.1 that caused compile errors when MPFS Classic images were generated for ASM30 containing files whose length was either zero or a multiple of 12.
input was detected. This issue only affects the example configuration page and only exists in v4.50 (prior versions functioned correctly). Also corrected an issue where user input could potentially overflow into part of the shadow
AppConfig in the same function. Thanks to prinz3nroll3 on the Microchip Ethernet forums for identifying both of these issues.
6. Implemented Explorer 16 development board 5V LCD errata workaround to LCDBlocking.c. This corrects the A/D converter from returning erratic readings on certain Explorer 16 boards. LCD I/O pins are now continuously driven by the microcontroller instead of going high impedance when idle.
7. Fixed a critical ENC28J60 revision B7 errata workaround problem in the ENC28J60.c, MACFlush() function. Previously, the code was checking for an EREVID register value of 0x07 for silicon revision B7. This was incorrect. Silicon revision B7 actually has an EREVID value of 0x06. Note that this problem was caused by an incorrect EREVID value published in
DS80349A, the B7 silicon errata documentation. Make sure to use DS80349B or later.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
4. MAC.h RXSIZE precompiler test for proper range doesn't work. This is not a functional problem, just a compile-time configuration test. Ensure that you don't over allocate TCP_ETH_RAM_SIZE or MAX_HTTP_CONNECTIONS.
5. HI-TECH PICC-18 STD 9.51PL1 cannot compile DynDNS.c. It raises an "inconsistent type" error while trying to perform a
28
3 Microchip TCP/IP Stack Help
ROM pointer to integer cast. The older 9.50PL3 compiler release is required to compile this file.
6. HI-TECH PICC-18 STD 9.50PL3 does not initialize several static variables correctly on reset. This behavior breaks many stack modules in the TCPIP Demo App and TCPIP WebVend App projects. Additionally, string printing functions do not work correctly, so the supplied "TCPIP Demo App-HITECHPICC18 PICDEMNET2 18F97J60.hex" and "TCPIP WebVend
App-HITECHPICC18 PICDEMNET2 18F97J60.hex" files may not correctly print the board's DHCP assigned IP address on the board's LCD (if present) and UART. To avoid these severe problems, use the Microchip MPLAB C Compiler for
PIC18 MCUs. A free student edition can be downloaded from http://www.microchip.com/c18.
******
v4.50 02 June 2008
******
IMPORTANT NOTE: You must use MPLAB 8.10 or higher to successfully open the MPLAB projects. Also, ensure that the latest C compiler is used. This release was tested against MPLAB C Compiler for PIC18 MCUs version 3.20, MPLAB C
Compiler for PIC24 MCUs and dsPIC DSCs version 3.10, MPLAB C Compiler for PIC32 MCUs version 1.01, and HI-TECH
PICC-18 version 9.50PL3 (STD). Earlier compilers may not be able to compile this TCP/IP stack release.
Changes:
1. Added SSL 3.0 client capabilities, including SMTP over SSL. The SSL modules supports up to 1024-bit RSA handshakes and 128-bit ARCFOUR bulk encryption. This can be demonstrated using the SMTP client. SSL server support is functional, but a key generation utility is not yet provided and support over HTTPS is not yet reliable with all browsers.
IMPORTANT: Encryption software is covered by US Export Control law, so it is not directly downloadable from the
Microchip website. To use the encryption modules, you must order SW300052 from microchipDIRECT [ https://www.microchipdirect.com/ ] and install the required libraries.
Berkeley APIs instead of or in addition to the Microchip specific APIs. To use this new functionality, define
STACK_USE_BERKELEY_API and configure BSD_SOCKET_COUNT in TCPIPConfig.h. Three new source code demos are provided to demonstrate this API: BerkeleyTCPClientDemo.c, BerkeleyTCPServerDemo.c, and
BerkeleyUDPClientDemo.c. The TCP client demo is identical to the GenericTCPClient.c demo, but implemented using
demo listens on TCP port 9764 and will echo any traffic received back to the sender. It allows up to 3 simultaneous connections when there are an adequate number of sockets defined in the TCPSocketInitializer[] array in TCPIPConfig.h.
3. Added support for Dynamic DNS services. See the Dynamic DNS Client module in the TCP/IP Stack Help for details.
Presently, dyndns.org, dyndns.com, no-ip.com, and dns-o-matic.com are supported.
4. Added the Microchip TCP/IP Configuration Wizard to the Utilities folder, facilitating easier configuration of the TCP/IP
Stack through a graphical application.
5. Restructured TCPIPConfig.h to remove rule-enforcement logic, placing the removed sections in TCPIP.h. Many other project structure changes were also made to clean up the general distribution appearance.
6. Increased DHCP Server default lease duration to 60 seconds instead of 15 seconds. Some computers were losing their
IP lease before performing a renew operation with only a 15 second lease.
7. Removed CLOCK_FREQ, INSTR_FREQ, and PERIPHERAL_FREQ macro definitions. GetSystemClock(),
GetInstructionClock(), and GetPeripheralClock() now return these respective values. This change was made for compatibility with other Microchip software libraries.
8. Added TCP Fast Retransmission capability. Whenever three duplicate ACK packets arrive, the stack will now immediately perform a retransmit operation. This greatly improves recovery latency whenever the network loses a packet for applications that stream TX data using TCP.
9. Improved TCP Keep Alive mechanism to automatically close TCP sockets which do not receive any keep-alive responses
for TCP_MAX_UNACKED_KEEP_ALIVES ( see page 573) (default 6) times. This means that, by default, any
connection that catastrophically breaks without notifying us (ex: user unplugs cable, Internet connection goes down, etc.)
29
3 Microchip TCP/IP Stack Help only close sockets that are broken (remote node is not responding to TCP requests). It will not close or otherwise interfere with idle connections in which the application is not transmitting or receiving data and wishes to keep the connection open.
automatically saves incoming SYN packets destined for a local server port which is already connected to a different client.
has to retransmit the SYN request if it was unserviceable the first time around. This is most apparent with the HTTP/HTTP2 servers which previously performed poorly with certain modern web browsers which attempt to open many simultaneous connections to the web server, such as Mozilla Firefox 3 beta 5 and Apple Safari 3.1. Entries in the queue automatically time
permanently if several connection requests arrive for a service that is in use and will not be available for an extended period.
11.Modified the structure of the MPFS2 FAT (now known as MPFS2.1) to include name hashes first. This speeds up opening files by 25%, and makes opening index files nearly instant. 12.Updated the MPFS2 Utility. MPFS2.1 now supports the new FAT structure and provides a cleaner interface. It also writes images to disk as they are created, which eliminates the IndexOutOfBounds exceptions some users had reported. Finally, uploads are now truly multi-threaded. 13.Source code to the MPFS2.exe PC utility is now released. Find it in the Microchip SolutionsMicrochipTCPIP StackUtilitiesSourceMPFS21 folder. This project is designed to compile with Microsoft Visual C# 2008 Express Edition. 14.Added support for
SST25VFxxxB serial flash parts in 2, 4, 8, 16, and 32Mbit densities. These parts can be used to replace EEPROMs for
storing MPFS images (both versions) and custom data. 15.Added HTTPReadPostName ( see page 252),
17.Updated DHCP client to close its UDP socket when idle (bound state) to save a small amount of resources. 18.Removed
LED_IO macro from all hardware profiles because it is not suitable for use on certain hardware platforms that have non-contiguous LEDs or reversed bit ordering. Use the new LED_GET() and LED_PUT(val) macros to read and write to all of the LEDs at once. 19.Added Ethernet Hash Table Calculator.exe to the Utilities folder and start menu. This tool will calculate the correct bit that you must set in the EHT0-EHT7 registers on the ENC28J60 and PIC18F97J60 family devices for using the Hash Table RX filter. This is useful only for fixed MAC addresses known at design time. For addresses that are known at run time, use the SetRXHashTableEntry() function in the ENC28J60.c or ETH97J60.c files to set the correct
EHT0-EHT7 bit.
Fixes:
1. Fixed a buffer overflow data corruption issue in the FTP module that arises when too many parameters were passed on the command line.
would only execute when a socket reconnected, which caused the RX buffer to not resize until after data was received.
Some platforms (notably FF2 on Ubuntu) would stall if the initial advertised RX window was too small, and this change corrects that issue.
3. Updated SendSystemReset() and MACInit() initialization routine in ENC28J60.c. Previously, if the ENC28J60 was placed into sleep mode by calling MACPowerDown(), the SendSystemReset() command would not work anymore. This would leave the ENC28J60 in power down if the host PIC was ever reset. SendSystemReset() should work for all conditions with this update. Thanks go to Rob Haverkort on the Microchip Ethernet forum for identifying this problem.
4. Fixed an alignment bug in HTTP2 that caused redirects to fail when the MPFS2 image was stored in Flash program memory. Thanks to Todd Boaz on the Microchip Ethernet forum for identifying this bug, and Chen Qu for posting a solution.
since the last server synchronization. Thanks go to "pic123" on the Microchip Ethernet forum for noticing this error.
PIC24, dsPIC30/33, and PIC32 processors. This bug was previously fixed in stack versions 4.13 and 4.16, but it was unintentionally recreated in 4.18 due to PIC32 changes.
7. Fixed UART2TCPBridge module from failing to connect ( see page 176) to a remote server when
USE_REMOTE_TCP_SERVER was defined.
8. Fixed an issue that prevented SNMP SETs on 16 and 32 bit parts when using MPFS2. Thanks go to Milena K on the
Microchip Ethernet forum for identifying this problem.
30
3 Microchip TCP/IP Stack Help
9. Fixed a rare buffer corruption issue that could occur with UDP if TCP was also enabled.
10.Fixed a Tick rollover error in HTTP2. Thanks go to Paul Bixel on the Microchip Ethernet forum for identifying this problem.
11.Fixed an MPFS2 bug in which an excessive value to MPFS_SEEK_REWIND may have failed to return an error. Thanks go to Paul Bixel on the Microchip Ethernet forum for identifying this problem as well. 12.SMTP Client now sends EHLO when using authentication. Previously, the HELO command was used, even with authentication enabled. Using HELO with authentication creates incompatibilities with certain SMTP servers. 13.Improved Internet Bootloader robustness by retransmitting ACKs in response to data retransmissions by the remote sending node. Previously, if an ACK packet was lost before reaching the sending node, the TFTP upload would fail and need to be restarted. Thanks go to "coolvibe" Dave
Collier on the Microchip Ethernet forum for identifying this behavior. 14.Fixed TFTP Internet Bootloader from not being accessible from Linux TFTP clients which were setting the IP header "Don't Fragment" flag bit. 15.Changed TCP so that
the PSH flag. This improves GUI responsiveness for certain applications which rely on this automatic flush feature, such as the UART2TCPBridge module. 16.Fixed TCP socket loss issue which could occur if the TCP TX FIFO size was greater than
536 bytes (TCP_MAX_SEG_SIZE). Before the fix, the socket would have gotten tied up indefinitely performing retransmissions every 1.0 seconds without detecting that the remote node was disconnected. 17.Fixed TCP socket hang issue that would occur if the PIC sent out a FIN and the remote node never responded with a corresponding FIN. The socket would have gotten stuck indefinitely in the TCP_FIN_WAIT_2 state. Thanks go to Mr. Kyle Strickland with AW North Carolina
see page 619)() or UDPGetArray ( see page 620)() at least once. 19.Fixed an offset error of +2
Microchip Ethernet forum for finding this error. Note that due to integer truncation during division, this function can be off by
0.2% or so, depending on the value returned by GetPeripheralClock(). 20.Updated DelayMs() macro for MPLAB C Compiler for PIC18s to work correctly when a large parameter was given. You should now be able to delay between 0 and 65535 milliseconds across all supported compilers without ending up with an unexpectedly short delay.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
4. MAC.h RXSIZE precompiler test for proper range doesn't work. This is not a functional problem, just a compile-time configuration test. Ensure that you don't over allocate TCP_ETH_RAM_SIZE or MAX_HTTP_CONNECTIONS.
5. HI-TECH PICC-18 STD 9.51PL1 cannot compile DynDNS.c. It raises an "inconsistent type" error while trying to perform a
ROM pointer to integer cast. The older 9.50PL3 compiler release is required to compile this file.
6. HI-TECH PICC-18 STD 9.50PL3 does not initialize several static variables correctly on reset. This behavior breaks many stack modules in the TCPIP Demo App and TCPIP WebVend App projects. Additionally, string printing functions do not work correctly, so the supplied "TCPIP Demo App-HITECHPICC18 PICDEMNET2 18F97J60.hex" and "TCPIP WebVend
App-HITECHPICC18 PICDEMNET2 18F97J60.hex" files may not correctly print the board's DHCP assigned IP address on the board's LCD (if present) and UART. To avoid these severe problems, use the Microchip MPLAB C Compiler for
PIC18 MCUs. A free student edition can be downloaded from http://www.microchip.com/c18.
******
v4.18 28 November 2007
******
Changes:
31
3 Microchip TCP/IP Stack Help
1. Added C32 and PIC32MX support. Some things were cleaned up in the process.
2. Removed linker scripts from C30 MPLAB projects. MPLAB IDE 8.00 can automatically select the correct linker script for
16-bit and 32-bit products.
3. Updated TCPPerformanceTest.c module. Now it automatically calculates the TX throughput and displays it for you. Also, there is now an RX throughput testing mode, which listens on a separate TCP socket (port 9763) when a TCP socket of type TCP_PURPOSE_TCP_PERFORMANCE_RX is allocated in TCPIPConfig.h. The RX socket is by default not enabled to save memory, so you must create a TCP_PURPOSE_TCP_PERFORMANCE_RX socket in TCPIPConfig.h and ensure that enough memory is allocated to accommodate it to test the RX performance test. When connected to port
9763, send a large amount of data and the PIC microcontroller will send back a count of how many bytes were received per second.
4. UDPPerformanceTest.c module now transmits 1024 packets on start up and then stops to prevent continually broadcast flooding your network. To transmit more packets after 1024 is reached, hold down BUTTON3 (left-most button on most boards).
5. Significantly improved the speed of the MD5 and SHA-1 functions. Gains for the 8-bit compilers were 50-75%, while 16-bit parts saw more modest improvements (~10%).
6. Reimplemented TCP_CLOSE_WAIT TCP state ("CLOSE WAIT" in RFC793). Now, TCP sockets that receive a FIN from
socket becomes closed on our end. Similarly, it simplifies application usage of the last RX bytes received as these bytes
TCP_CLOSE_WAIT_TIMEOUT ( see page 570) defaults to 200ms in this stack version.
7. Pushed the SNTP requery on failure timeout up some. It was ~14 seconds and is now ~20 seconds.
products.
9. Added a fourth parameter to newAJAXCommand() in mchp.js, allowing data to be POSTed along with the AJAX request.
10.Deprecated the TCP Loopback functions, which includes TCPOpenLoopback, TCPCloseLoopback, TCPIsLoopback,
TCPInject, and TCPSteal. These functions were added in 4.10 for future SSL support, but have since become unnecessary.
They are of limited usefulness, and so are being removed to save code space. The functions are still available in this
This allows the remote server port number to be specified dynamically at run time instead of being hard coded to the
12.Added web interface to the SMTP module in the TCPIP Demo App applications. You can now configure the SMTP
CustomHTTPApp.c also demonstrates how to send MIME encoded attachments in emails. The default demo will send button states, LED states, and the current potentiometer reading as a CSV file attached to the email. 13.Changed
BUTTON0 only.
Fixes:
1. Fixed an ENC28J60.c MACGetArray() bug which would overwrite one byte of memory at address 0xFFFFFFFF if you provided NULL for the destination address pointer.
pointer was provided as the destination.
3. Fixed a bug in the HTTP2 server accessing incorrect sockets if an inadequate number of sockets were available on POR.
4. Fixed Internet Bootloader project from failing with a timeout if an ARP packet arrived during the Erase/Write operation.
5. Fixed DHCP client RFC non-compliance where it would send the ciaddr field in the initial SELECTING state. Also, in the
may fix compatibility problems with certain DHCP servers.
StackTsk() was called after TFTPIsFileOpened ( see page 587)() was last called.
7. Added two zero bytes to the ICMP echo request payload to improve compatibility with some buggy NAT routers.
Known Problems:
32
3 Microchip TCP/IP Stack Help
Microsoft telnet.exe utility which is provided with Microsoft Windows.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
3. HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
4. MAC.h RXSIZE precompiler test for proper range doesn't work. This is not a functional problem, just a compile-time configuration test. Ensure that you don't over allocate TCP_ETH_RAM_SIZE or MAX_HTTP_CONNECTIONS.
******
v4.16 06 November 2007
******
Changes:
1. Added Internet Radio application. This is a TCP client application which downloads streaming MP3 audio from a
Shoutcast server and then plays it back to stereo earphones via a VLSI VS1011 audio decoder.
2. Added SPIRAM.c module. This module is intended for interfacing to an AMI Semiconductor N256S0830HDA SPI RAM chip. The TCP module can now interface directly to this SPIRAM module to store TCP socket FIFO buffers and other TCB data in the external RAM.
for small code size, the TCP module ROM footprint shrinks up to 6KB, but performance may slow down on some processors (namely PIC18s, where the penalty is approximately 15%).
4. Added USE_EEPROM_25LC1024 compile time configuration macro to TCPIPConfig.h. Enable this definition if you are storing your MPFS[2] on a 1Mbit 25LC1024 or similar EEPROM device that uses 24-bit addressing and a 256 byte write page size.
5. Changed LCDBlocking.c module initialization code. It should now be possible to use 4-bit mode on certain "unusual" LCD controllers, like the Samsung S6A0032. Most PICDEM.net 2 and Explorer 16 boards use an LCD with this controller.
6. SNTP client now attempts to requery the SNTP server about every 14 seconds if the last query attempt fails. This allows the internal time value to become valid quickly should the board be powered up before an Ethernet cable is attached or if the DHCP client doesn't obtain an IP address quickly enough. Previously, it would take up to 10 minutes after plugging the Ethernet cable in to get a correct time value from the SNTP server.
7. Added UDP_USE_TX_CHECKSUM compile time configuration macro to TCPIPConfig.h. When enabled, all UDP packets will have a correct UDP checksum computed and inserted into the UDP header of outbound packets. If you do not define this macro, the UDP checksum will be disabled (left as 0x0000), which is how previous stack versions operated. Note that enabling checksum generation cuts your maximum UDP TX throughput by nearly half due to the required computations.
8. Substantially changed TCP socket RX and TX FIFO allocation. Now, sockets can be stored either in Ethernet RAM, PIC
RAM, or external (SPI) RAM. Previously, sockets could only be allocated in Ethernet RAM, which was not scalable.
sockets much easier. You can specify the remote node as a hostname that needs DNS and ARP resolution, an IP address that only needs ARP resolution, or legacy NODE_INFO pointer for direct compatibility with the previous
socket type parameter which will allow you to use the new TCP socket RAM allocation system.
10.Added TCP Keep Alive mechanism defined by RFC 1122 section 4.2.3.6 to the TCP module. This helps automatically detect lost connections. If the remote node sends back an RST, this immediately closes the lost connection on our end.
Currently, no action is taken if the keep alive gets no response. Note that this feature deviates from the standard by defaulting to only 10 seconds instead of over 2 hours. Also deviating from the standard, this feature is enabled by default. To
33
3 Microchip TCP/IP Stack Help module from default port 12345 to 9762. 12.Moved UDPPerformanceTest.c module from default port 12345 to 9, the
"discard" protocol port.
Fixes:
1. The DHCP client now specifically requests the previous IP address when a DHCP renewal occurs.
between an NTP requery event. Thanks go to Rob Haverkort on the Microchip Ethernet forum for noticing the time value incrementing far faster than it should have.
3. TCP module will not transmit a bunch of unnecessary duplicate ACK packets when data is ready to be transmitted but the remote RX window is zero. This previously didn't cause anything to break, but would waste CPU time and bandwidth sometimes.
4. TCP sockets will no longer automatically close if the remote RX window stays zero for several seconds.
5. Fixed TFTP Internet Bootloader project from corrupting the configuration fuses. Previously, this would result in the
Watchdog timer being enabled and causing an unintentional reboot every few minutes with the demo TCP/IP stack.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
2. TFTPc module has not been tested with this version.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
4. HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
5. MAC.h RXSIZE precompiler test for proper range doesn't work. This is not a functional problem, just a compile-time configuration test. Ensure that you don't over allocate MAX_TCP_SOCKETS, TCP_TX_FIFO_SIZE,
TCP_RX_FIFO_SIZE, or MAX_HTTP_CONNECTIONS.
******
v4.13 02 October 2007
******
Changes:
1. Added command line support to the MPFS2.exe tool. You can now generate MPFS output files using batch scripts or other console applications.
2. Added dynamic variable parameter capabilities to the MPFS2 utility. To use, add the parameters you wish to pass to the end of the dynamic variable. All parameters are passed as WORD values. (ex: ~myArray(2,5)~ )
new connection occurs on the same socket before the application can detect the original disconnection through the
TCPIsConnected ( see page 545)() API.
4. Added a counter to the UDPPerformanceTest module and made it supress transmission if an Ethernet link is not present.
5. Added TCPIP WebVend App example application to the main stack distribution. This corresponds to three new Microchip
Webinars being published on the HTTP2 server usage topic.
Fixes:
1. Fixed MPFS2.exe PC utility from crashing if you attempt to generate an MPFS classic .bin/.c/.s output file.
34
3 Microchip TCP/IP Stack Help
2. Fixed RCONbits definition for HPC_EXPLORER hardware profile when using the HI TECH PICC-18 compiler.
Thanks to Billy Walton on the Microchip Ethernet forum for identifying this issue.
4. Fixed a TCP RX FIFO corruption problem which would occur if the remote node sent more data than could fit in our RX
FIFO in a single packet. The GeneticTCPClient.c module was subject to experiencing this problem when connected to www.google.com's servers.
5. Fixed a DHCP client UDP socket leak if you called DHCPDisable() after the DHCP client had already obtained a UDP socket. Thanks go to Matthew Kendall on the Microchip Ethernet forum for identifying this problem.
forum for identifying this problem.
7. Cleaned up some C30 compiler warnings related to macro definitions with inadequate parenthesis in them.
8. Fixed HTTP2 module sometimes returning a 501 error instead of a correct web page when being bombarded with new connection requests.
PIC24 and dsPIC processors.
10.Fixed SMTP client module failing to send email when attempting to send an email with a `CC' or `BCC' field that was in
ROM while the `To' field was in RAM or visa versa. 11.Fixed TCP module sending an incorrect sequence number in RST packets sent when in the TCP_SYN_SENT state and an invalid segment arrives. In prior stack versions, some TCP client applications might take a very long time to recover in the event of a power failure, reset, and subsequent reconnect to a remote server that still thinks the old connection is still active. With this fix, reconnections should be possible almost immediately after a power failure because the correct RST packet will cause the old connection to get closed right away.
time with the same socket handle.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
2. TFTPc module has not been tested with this version.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
4. HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
5. HI-TECH PICC-18 projects will not correctly set the processor configuration fuses through code using the __CONFIG() macro. Ensure that the configuration fuses are manually set correctly via the MPLAB IDE Configuration Bits dialog. This problem has been observed with compiler version 9.50PL3.
6. MAC.h RXSIZE precompiler test for proper range doesn't work. This is not a functional problem, just a compile-time configuration test. Ensure that you don't over allocate MAX_TCP_SOCKETS, TCP_TX_FIFO_SIZE,
TCP_RX_FIFO_SIZE, or MAX_HTTP_CONNECTIONS.
remote server must retransmit a lot of data, slowing the transfer down a lot. Making TCP_RX_FIFO_SIZE 536 bytes or bigger and correspondingly shrinking MAX_TCP_SOCKETS will correct this problem.
35
3 Microchip TCP/IP Stack Help
******
v4.11 27 August 2007
******
IMPORTANT NOTE: You must use MPLAB 7.62 or higher to successfully open the MPLAB projects.
Changes:
1. Added a Microchip TCP/IP Stack Users' Guide to document the stack features/modules/and APIs and address the stale
AN833 documentation. Note that this is a work in progress. Many modules have yet to be documented in the Users'
Guide.
2. Added HTTP2 module. This HTTP module includes a whole new API and supreme new features, such as POST support, cookies support, browser authentication support, and more.
3. Added MPFS2 module. This module is required for the new HTTP2 module and performs better while having fewer limitations. Long filenames and folders are now supported.
4. Added a new GUI based MPFS2.exe PC utility. The older MPFSv2.exe GUI application and MPFS.exe command line tool has been retired. The new utility has advanced features, such as MPFS2 file format support, GZIP compress, etc.
5. Added a TFTP bootloader. This is a stand alone project and currently only supports the PIC18F97J60 family of PIC processors with internal Ethernet.
6. Added UART2TCPBridge.c file and STACK_USE_UART2TCP_BRIDGE option to TCPIPConfig.h. This new module acts as a TCP and UART bridge, with a high priority UART interrupt and dedicated UART TX and RX FIFOs for minimum
UART latency and maximum performance. By default, the bridge acts as a TCP server and listens on port 9761. The
UART baud rate defaults to 19200. The bridge can be reconfigured to act as a TCP client.
7. Added Simple Network Time Protocol (SNTP) client. This module automatically obtains the current time (date) from the
Internet. Enable this module by defining STACK_USE_SNTP_CLIENT in TCPIPConfig.h. Obtain the current time (in
seconds since 00:00:00 1970) by calling the SNTPGetUTCSeconds ( see page 462)() API.
64 is required for the new HTTP2 module, but of general use to many applications.
Applications implementing email transmission capabilities should expose these options to the end-user for configuration.
To use SMTP servers that do not support the AUTH LOGIN authentication command, simply leave the
SMTPClient.Username and SMTPClient.Password pointers as their default NULL value.
10.Converted DHCPDisable() from a macro to a real function and added the complementary DHCPEnable() function. These two functions can be used at run time to dynamically switch between using a static IP address and configuration and DHCP
the ability to decode host name strings and determine if they contain a valid IP address or not. Also, the complementary
address string to resolve, it will convert the string to an IP address and immediately return without querying the DNS.
13.Shrunk the advertised TCP Maximum Segment Size from 576 bytes to 528 bytes. This might improve compatibility if your
TCP data has to propagate over nodes with small MTUs and you have a correspondingly large TCP RX FIFO defined.
14.Performed some maintenance on the FTP.c file. No significant functionality has been changed, but some potential problems were corrected. 15.Altered Tick.c file and API. Now, the Tick module can operate maximum precision, returning the value of the actual Timer as it is counting, without disturbing the timer count by writing to it or disabling it. Three new
use it as a Real Time Clock. 16.Added PIC24FJ64GA004_PIM hardware profile. This hardware profile is intended for use with the PIC24FJ64GA004 PIM on the Explorer 16 development board. In this mode, BUTTON2 and BUTTON3 and several of the LEDs do not work correctly due to lack of I/O pins on this device. Also, you cannot have the POT and TEMP jumpers on the PIM bridged because these signals are multiplexed with the SDO1/SDI1 pins needed for the Ethernet PICtail Plus.
17.Removed most ROM APIs when using a 16-bit compiler (C30). PIC24s and dsPICs usually don't need separate ROM functions since the Program Space Visibility feature maps ROM into RAM space. All ROM APIs are still supported, but they are now macros to base RAM APIs. This change saves a couple of kilobytes of code space on PIC24 and dsPICs.
18.Improved MyTCB structure caching. This should reduce TCP packet processing overhead with the ENC28J60 where
36
3 Microchip TCP/IP Stack Help
TCBs are stored in the Ethernet RAM. 19.MAX_RETRY_COUNTS TCP configuration option has been renamed to
can upload new webpages through the /mpfsupload page now. FTP required two precious TCP sockets. 21.Began adding hooks for an SSL/TLS transport for secure HTTPS and other future stack modules. Note that these cryptographic modules are not available at this time. Configuration options such as MAX_SSL_CONNECTIONS do nothing and should not be modified. 22.Username has changed for all of the modules. Now all modules have a default username of "admin" and
the usernames.
Fixes:
1. Fixed a SendFile() bug in HTTP.c where parsing dynamic cgi files could send garbage back to the web browser sometimes. Thanks go to Matt Watkins on the Microchip Ethernet forum for identifying this issue.
2. Fixed an off by one error in the calculation of RESERVED_TCP_MEMORY. Previously, the last TCP socket's RX FIFO would incorrectly overlap with the Ethernet RX buffer, causing incoming packets to occasionally be corrupted or the incoming data on the last socket to get corrupted.
3. Fixed the QWORD_VAL's dword struct element types. dword.LD and dword.HD were incorrectly defined as WORDs instead of DWORDs. Thanks go to Iñaki Esparza on the Microchip Ethernet forum for identifying this issue.
4. Fixed the incorrect processing of received IP fragments with a non-zero offset. This stack does not support IP packet reconstruction due to the limited amount of available RAM. Thanks go to Iñaki Esparza on the Microchip Ethernet forum for noticing this behavior.
5. Board now only responds to ping requests to our IP address, the directed subnet broadcast address, or the broadcast address of 255.255.255.255. Previously, it would respond to any ping request to any IP address, assuming the MAC address was correct.
6. Fixed a memory corruption/UDP packet loss problem when handling incoming UDP packets. Previously, StackTask() would incorrectly continue processing more packets if it came upon a UDP packet. Thanks go to Iñaki Esparza on the
Microchip Ethernet forum for identifying this issue.
7. Fixed the SMTPClient.ROMPointers.Server flag having an inverted meaning. Previously, the SMTP client module would treat the SMTPClient.Server pointer as a ROM pointer if this bit was cleared. In most cases, this would cause the SMTP
8. Fixed the DHCP Server module from incorrectly parsing received packets which had a
DHCP_PARAM_REQUEST_IP_ADDRESS option followed by more options. Previously due to the length miscalculation, the parser would enter a random state, depending on the packet's contents. Thanks go to Iñaki Esparza on the Microchip
Ethernet forum for identifying this issue.
appropriate to let it know when it's old RX data is being thrown away. This fixes a potential bug in the DHCP Server module and makes the UDP API more robust. Thanks go to Iñaki Esparza on the Microchip Ethernet forum for identifying the potential DHCP server issue.
10.Fixed a potential ARP bug where the Gateway's MAC address would be returned for an IP address on the local subnet.
This unusual case would occur when two application tasks were using the ARP module at the same time and the second application was trying to resolve an IP address off of our subnet. Thanks go to Iñaki Esparza on the Microchip Ethernet forum for pointing this issue out. 11.Fixed an PIC18F97J60 family MAC layer bug where MACGetArray() might not correctly increment the Ethernet read pointer if a NULL pointer was given for the destination. The C compiler might have optimized the function so that it would increment the read pointer one less than it was supposed to. 12.The TCP module now acknowledges TCP Keep-Alive packets which will help prevent connection loss if the remote node fills up our RX FIFO and then our window-update packet gets lost on the network/Internet. In stack version 4.02, a zero-window probe would have been required to restore the communications. 13.Fixed a TCP RX FIFO corruption issue that would occur in (uncommon) circumstances when too many out-of-order segments arrived such that a second "hole" would have been required to accommodate the data. Thanks go to Iñaki Esparza and his eagle eyes on the Microchip Ethernet forum for finding this corner case bug. 14.Inline assembly in the ETH97J60.c file has been modified to accommodate the C18 Extended mode and C18 Auto default storage class. Previously, the Ethernet module would transmit garbage packets when using the C18
unexpected string length retrieved from the packet could cause random memory corruption. 16.Fixed some potential
PIC18F97J60 family Ethernet module transmit lockup conditions that occur on some networks. Previously blocking while() loops would wait indefinitely for the ECON1bit to become clear by hardware, which the hardware might never have done.
37
3 Microchip TCP/IP Stack Help
17.In MainDemo.c, a call to DelayMs() was being made using a value of 100ms. This was too long for the underlying
Delay1KTCYx() C18 function and would result in a shorter than expected delay when compiled with C18. This has been fixed with a loop. Thanks go to Andy123 on the Microchip Ethernet forum for pointing this problem out. 18.Fixed a potential
function might have been overlayed on other memory, resulting in random memory corruption as the ISR occurred. 19.The
demo AJAX web pages in the TCPIP Demo AppWebPages folder now correctly display and self-refresh in Firefox 2.
Previously, it would work in Firefox 1.5 and Microsoft Internet Explorer, but not Firefox 2. Thanks go to "gohsthb" on the
Microchip Ethernet forum for identifying this correction. 20.Rewrote the GenericTCPServer.c example to not use an application RAM FIFO for buffering. Since the TCP module implements its own FIFOing, the application has limited need for
incoming bytes with the remaining size available of the App FIFO. This would have previously resulted in a buffer overflow, corrupting the RX data if too much arrived all at once. 21.Fixed a potential MPFS classic inline ASM30 assembly code problem where web pages stored in internal Flash and C30 with optimizations enabled could result in data corruption.
some junk data at the end of its packets. 23.Fixed a potential TCP problem where transmitted FIN packets might not get retransmitted properly if the remote node never acknowledged the data that was transmitted just before the FIN was sent.
24.Fixed a NetBIOS Name Service bug where the response packet would sometimes get sent to an incorrect address. It now consistently responds to the unicast MAC/IP address of the NBNS query packet. 25.Added padding to all transmitted
DHCP messages to make the minimum UDP payload at least 300 bytes. This fixes compatibility with some older BOOTP relay devices which discard smaller packets. Thanks go to Dave Collier on the Microchip Ethernet forum for pointing this problem out. 26.Substantially shrunk the number of retransmission attempts made in the TCP_SYN_RECEIVED state. This improves recovery time when attacked by a SYN flood Denial of Service event. The recovery time is now 7 seconds (3 total packets) instead of 31 seconds (6 total packets) 27.Fixed the possibility of the NetBIOS Name Service module giving out the board's static IP address before a DHCP lease could be obtained. NBNS requests are now only serviced when originating from nodes on the same subnet. 28.Fixed storage of MPFS classic in internal program memory when using the HI-TECH
PICC-18 compiler. 29.Substantially revised TCP.c, fixing many TCP bugs and possibly adding new ones. Thanks go to
Michael Rubinstein for finding several of these TCP problems. 30.The DNS client module will now time out and return failure if the DNS server cannot be ARPed or does not respond to the DNS query. Each timeout is set to 1 second and 3 total ARP and 3 total DNS query attempts are possible. Previously, it would retry indefinitely, causing the calling application to deadlock.
Known Problems:
Microsoft telnet.exe utility which is provided with Microsoft Windows.
2. TFTPc module has not been tested with this version.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to reenable it's DHCP server.
4. HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
5. HI-TECH PICC-18 projects will not correctly set the processor configuration fuses through code using the __CONFIG() macro. Ensure that the configuration fuses are manually set correctly via the MPLAB IDE Configuration Bits dialog. This problem has been observed with compiler version 9.50PL3.
Testing and Performance Notes:
1. Make sure to use MPLAB IDE 7.62 or higher with this version. Versions below 7.61 will not work. Version 7.62 has cool new features like C auto-word complete and function parameter tooltips that can be enabled (disabled by default).
2. Testing was done using MPLAB C18 version 3.12, MPLAB C30 version 3.01, and HI-TECH PICC-18 version 9.50PL3.
Make sure to upgrade your tools to at least these versions.
38
3 Microchip TCP/IP Stack Help
******
v4.02 10 April 2007
******
IMPORTANT NOTE: You must use MPLAB 7.41 or higher to successfully open the MPLAB projects. IMPORTANT NOTE2:If an external serial EEPROM memory is used to store AppConfig, it's contents will be invalidated the first time you run this version, restoring the AppConfig defaults. The AppConfig structure has been optimized. IMPORTANT NOTE3:If an external serial EEPROM memory for MPFS, you will need to recreate the MPFS image and program your EEPROM. A 32 bit addressing format is now used.
Changes:
out-of-order without requiring the remote node to go through a retransmit cycle. This dramatically improves RX performance when communicating over the Internet.
addresses will be used for the remoteNode (destination address of outbound packets).
3. Recreated MPLAB projects for the HI-TECH PICC-18 compiler. These were temporarily absent from 4.00RC. This project works with the PIC18F97J60 with internal Ethernet module, assuming the correct compiler version is present.
4. Moved all the headers around. Most of them are in "Microchip SolutionsMicrochipIncludeTCPIP Stack" now. This change was made to again be more compatible with other (future) Microchip software libraries.
programming flexibility.
string pointer instead of a count of bytes successfully placed in the TX buffer.
8. Added UDPPerformanceTest.c. By default this module causes UDP packets containing 1024 bytes of application data to be broadcasted on UDP port
12345. Use a packet sniffer, such as Wireshark (http://www.wireshark.com/) to capture and derive stack overhead/UDP TX performance characteristics with this module. Note that this test uses the
be slower. To enable this module, #define STACK_USE_UDP_PERFORMANCE_TEST in TCPIPConfig.h.
9. Added TCPPerformanceTest.c. By default this module listens on TCP port
12345. When a remote client connects, this server module will being transmitting the maximum possible amount of application data that it can, given your TCP TX FIFO size. Use a packet sniffer, such as Wireshark (http://www.wireshark.com/) to capture and derive stack overhead/TCP TX performance characteristics with this module. Any TCP client can be used, including readily available utilities such as the telnet.exe utility
this module, #define STACK_USE_TCP_PERFORMANCE_TEST in TCPIPConfig.h. 10.Added Reboot.c module. By default, this module listens on UDP port 30304. If the application byte 0x00 arrives on this port, the PIC will reset. This is primarily useful for remote Bootloader entry. #define STACK_USE_REBOOT_SERVER in TCPIPConfig.h to enable this module. Note that since no encrypted challenge/response algorithm is currently implemented, this module is a Denial of Service
ISR routine execute in the low priority ISR instead of the default high priority ISR. The Microchip TCP/IP stack does not need any interrupts except this low priority timer. 12.Renamed STACK_USE_DHCP macro to STACK_USE_DHCP_CLIENT
39
3 Microchip TCP/IP Stack Help
16.Added a very simple DHCP Server module. This module has limitations and is useful for a single client only. Its purpose
nodes attached). The server is coded to automatically disable itself if the DHCP client is also enabled and another DHCP server is detected on the network. This allows both the DHCP server and DHCP client to coexist without any manual
program memory, ex: literal strings. 18.Added a TCP automatic transmit/window update timer. It defaults to
automatic transmit/window update. This timer enhances performance, especially when streaming data over the Internet where round trip times can be several tens to low hundreds of milliseconds. This also improves application coding flexibility
conserves bandwidth by transmitting fewer ACKs and prevents inadvertently influencing remote slow start/collision avoidance and fast retransmit algorithms. 20.Completely rewrote ICMP (ping) server module. It is now much smaller (ROM and RAM), faster, and can handle packets of 576 bytes or larger, if no IP fragmentation occurs. 21.Rewrote StackTsk() stack
manager. It is much simpler now. 22.Added TCPFind (
see page 538)(), TCPFindArray ( see page 539)(), and
(without removing anything) and looks for a particular byte or array of bytes. This should greatly simplify the creation of application code whenever variable length fields are used (ex: text strings terminated by rn). It supports case insensitive text
user API. It returns the number of bytes of free space in the TCP's RX FIFO. 24.Changed default TICK resolution to 1ms
(from 10ms) and improved accuracy. 25.Added outbound ping capabilities (i.e. board can now ping another board or a PC).
To enable these features, define STACK_USE_ICMP_CLIENT. This will enable several new APIs, including
see page 269)(), ICMPSendPing (
see page 270)(), ICMPGetReply ( see page 271)(), and
function in MainDemo.c for an example of how to use them. By default, pushing BUTTON3 (left-most one) will cause a ping to be sent to 4.78.194.159 (ww1.microchip.com). The response time will be displayed on the LCD (assuming your development board has an LCD).
26.Cleaned
up C30 3.00
signed/unsigned warnings.
27.Removed
PIC18F97J60_TEST_BOARD hardware profile support. This stack no longer supports it due to the old beta silicon (with errata) mounted on these boards. 28.Added support for ROM pointers for all of the SMTP strings (To, From, CC, Subject, etc.). If you use a ROM string, you must also set the corresponding SMTPClient.ROMPointers.xxx bit to let the SMTP
example calling sequence using both ROM and RAM strings for the various fields.
Fixes:
1. Fixed a critical TCP buffer corruption issue where the start of a TCB header overlapped with the last byte of the RX FIFO from the previous socket. This bug affected version 4.00RC only.
2. ETH97J60.c, TCPIP.h, and TCPIP Stack Version.txt were correctly readded to the TCPIP Demo App-C18 project using relative paths instead of absolute paths.
This should fix some UDP applications from not working (ex: DNS Client module) with some computers/routers/networks which throw away traffic originating from the invalid port 0x0000 value.
4. Fixed a ENC28J60 bank selection error that would occur if an application called GetCLKOUT() in ENC28J60. By default, this function is not called.
5. UnencodeURL ( see page 232)() function in Helpers.c is now tested and working.
performance could have been terrible on reception.
7. Fixed a unintended TCP connection close if the socket was idle for about a minute. Now, TCP sockets will remain open indefinitely if there is no traffic going on.
8. Serial numbers >32K are now displayed correctly on the serial port as a positive value when C18 is used and the board is placed in configuration mode (BUTTON0 is depressed on power up).
9. HI-TECH PICC-18 compiler would previously incorrectly initialize the AppConfig structure.
10.Previously a processor reset was possible when accessing items in the AppConfig strucutre on 16 bit MCUs (PIC24,
40
3 Microchip TCP/IP Stack Help dsPIC) due to unaligned word accesses. This was fixed by reordering the Flags byte in the APP_CONFIG structure.
11.Rewrote DHCP client state machine, fixing the previously known problem where it would not perform a new discovery if it was trying to renew a lease with an offline DHCP server. 12.Fixed a critical deadlock problem in the ETH97J60.c MAC layer driver for the PIC18F97J60 family Ethernet controller. Previously, it was possible (although rare) that the DMAST or TXRTS bits would get stuck set if too much Ethernet traffic was received within a short interval. Previously, the MACFlush() function was unnecessarily setting TXRST, which it should not do while the Ethernet interface or DMA is being used. 13.Fixed an
HTTP server state machine problem where a new connection occurring too soon on a previously used socket could cause the HTTP server to no longer respond. 14.Fixed a potential memory corruption error in the HTTPGetVar() callback which would exceed the bounds of the VarString array when returning the VAR_STACK_DATE variable. 15.Fixed a TCP transmission sequence tracking problem whenever data is retransmitted and new unflushed data is also in the TX FIFO.
Thanks go to Matt Watkins on the Microchip Ethernet forum for identifying this issue.
Known Problems:
1. RTL8019AS MAC layer driver has not been updated for new TCP module. Users requiring RTL8019AS support should continue to use stack version 3.75.
2. I2CEEPROM.c has not been tested or completed. Continue to use I2CEEPROM.c from stack version 3.75 if this file is needed.
Microsoft telnet.exe utility which is provided with Microsoft Windows.
4. TFTPc module has not been tested with this version.
5. The default demo web pages which use AJAX do not automatically refresh themselves when viewed in Firefox 2.0.0.1.
Earlier Firefox versions (1.5ish) probably work without any problem.
6. Files may be inaccessible in your MPFS if compiled with C18 for internal flash program memory and your total MPFS content is large (around 64KB or larger). The code attempts to access the ROM memory using a near rom pointer when a far rom pointer is needed.
7. If using MPLAB 7.52 all .s files that are compiled with C30 will not have the corresponding object file get stored in the correct directory. As a result, if you are compiling with C30 and with MPFS_USE_EEPROM not defined (i.e. storing web pages in internal program memory), the project won't link (throws a undefined reference to `MPFS_Start'). As a workaround, remove the Intermediates Directory in the MPLAB project. Alternatively upgrade MPLAB to a newer version.
MPLAB IDE 7.60+ may have this fixed.
each other (ex: two PICDEM.net 2 boards connected via a crossover cable), a race condition can occur where both nodes will disable their DHCP server and neither board will get a successful DHCP lease. If this unlikely scenario occurs, as a work around, simply reset one of the boards to renable it's DHCP server.
9. HI-TECH PICC-18 projects may not compile when MPFS_USE_EEPROM is not defined and you are trying to store web page data in internal FLASH program memory.
10.HI-TECH PICC-18 projects may not compile when targeting the external ENC28J60 chip on the PICDEM.net 2 development board (instead of the internal Ethernet controller). This problem only applies when a PIC18F97J60 family part is the target. I.e. it compiles correctly for the HPC_EXPLORER + Ethernet PICtail.
Testing and Performance Notes:
1. This stack version was compiled and tested with the following tool versions: -MPLAB IDE 7.52 -Microchip C30 version
3.00 -Microchip C18 version 3.10 -HI-TECH PICC-18 version 9.50PL3
2. Using the UDPPerformanceTest.c module, the stack can transmit around 220KBytes/second (1.75Mbits/second) of UDP application data on the PIC18F97J60 with internal Ethernet @ 41.66667MHz core clock, compiled using C18 3.10 with debug optimization settings.
3. Using the UDPPerformanceTest.c module, the stack can transmit around 392KBytes/second (3.14Mbits/second) of UDP application data on the PIC24HJ256GP610 with external ENC28J60 @ 40 MIPS, compiled using C30 3.00 with debug optimization settings.
4. Using the TCPPerformanceTest.c module, the stack can transmit around 58KBytes/second (464Kbits/second) of TCP application data on the PIC18F97J60 with internal Ethernet @ 41.66667MHz core clock, compiled using C18 3.10 with debug optimization settings, over Ethernet when using a tiny 200 byte TX TCP FIFO. Note that performance can be improved significantly by increasing the FIFO size and performance will drop significantly if the round trip TCP acknowledgement time is increased (ex: testing over the Internet instead of Ethernet).
41
3 Microchip TCP/IP Stack Help
5. Using the TCPPerformanceTest.c module, the stack can transmit around 69KBytes/second (558Kbits/second) of TCP application data on the PIC24HJ256GP610 with external ENC28J60 @ 40 MIPS, compiled using C30 3.00 with debug optimization settings, over Ethernet when using a tiny 200 byte TX TCP FIFO. Note that performance can be improved significantly by increasing the FIFO size and performance will drop significantly if the round trip TCP acknowledgement time is increased (ex: testing over the Internet instead of Ethernet).
6. Using the TCPPerformanceTest.c module, the stack can transmit around 178KBytes/second (1.42Mbits/second) of TCP application data on the PIC24HJ256GP610 with external ENC28J60 @ 40 MIPS, compiled using C30 3.00 with debug optimization settings, over Ethernet when using a larger 2000 byte TX TCP FIFO. Note that performance will drop significantly if the round trip TCP acknowledgement time is increased (ex: testing over the Internet instead of Ethernet).
******
v4.00RC 28 December 2006
******
IMPORTANT NOTE: If an external serial EEPROM memory is used to store AppConfig, it's contents will be invalidated the first time you run this version, restoring the AppConfig defaults. The AppConfig structure has been optimized. IMPORTANT
NOTE2: If an external serial EEPROM memory for MPFS, you will need to recreate the MPFS image and program your
EEPROM. A 32 bit addressing format is now used.
Changes:
1. Added Simple Mail Transfer Protocol (SMTP) client module and updated MainDemo.c to exercise the Email transmission functionality when a user pushes BUTTON0.
2. Added beta Telnet ( see page 577) server module. See Known Problems section.
3. Completely revamped the TCP module. A real transmit FIFO and receive FIFO are allocated for each TCP socket now.
This greatly enhances RFC compliance, communications robustness, and makes application development easier. New
APIs were added for putting and getting arrays and strings (including ROM variants). Several TCP related bugs are now fixed as a result. Please report any bugs found in the new implementation.
4. Added TCPPutArray ( see page 550)() API.
5. Added TCPPutROMArray ( see page 550)() API.
6. Added TCPPutString ( see page 552)() API.
7. Added TCPPutROMString ( see page 551)() API.
8. Added TCPGetArray ( see page 543)() API.
place in the output buffer. MAKE SURE THAT YOUR CODE DOES NOT COMPARE THE RETURN RESULT OF
MAKE SURE THAT YOUR CODE DOES NOT COMPARE THE RETURN RESULT OF TCPIsGetReady ( see page 546)()
disabled in the last two releases of the stack and is not needed with the new TCP module. 13.Updated DNS module to
functions control a one bit ownership semaphore to allow multiple applications to use the DNS module in series. If invoked correctly, this will prevent unintended bugs resulting from two applications trying to use the DNS module at the same time.
Old applications, such as those based around the GenericTCPClient.c example must be updated to use these functions.
14.Started using a new project structure and folders. You must use MPLAB 7.41 or higher (stack is tested on MPLAB 7.50) to use the default workspaces/projects, which include files using relative paths. This should improve compatibility with some future code libraries released by Microchip. StackTsk.h was broken into TCPIPConfig.h, HardwareProfile.h, and StackTsk.h.
TCPIPConfig.h now includes all stack configuration options and HardwareProfile.h contains all hardware options. No macros
42
3 Microchip TCP/IP Stack Help need be globally defined in MPLAB project now. TCPIP.h is the only header applications must include now, for any/all modules used. 15.Combined ARP.c/ARP.h and ARPTsk.c/ARPTsk.h into a single file pair: ARP.c/ARP.h. Applications built using a prior stack revision must remove all instances including "ARPTsk.h" and replace it with "ARP.h" instead. The ARP module is now simpler, more linear (easier to read), and being in one source file, allows the C compiler to optimize better.
16.Added PIC18F67J60_TEST_BOARD hardware profile to HardwareProfiles.h. This hardware profile is designed for
05-60091 (Rev 1), a development board that is not in production at this time. 17.Added DSPICDEMNET1 and
DSPICDEMNET2 hardware profiles to HardwareProfiles.h for eventual support of the Microchip dsPICDEM.net 1 and dsPICDEM.net 2 demo boards. These two boards use the RTL8019AS Ethernet controller and a 24LC515 EEPROM. These changes are currently incomplete and these profiles cannot be used. 18.Began rewriting I2CEEPROM.c to support 16 bit
CPUs, including the dsPIC30F6014 used on the dsPICDEM.net 1 and 2 demo boards. Note that work here is incomplete and cannot be used as a result -- see Known Problems section. 19.Partially updated RTL8019AS.c to support 16 bit CPUs, including the dsPIC30F6014 used on the dsPICDEM.net 1 and 2 demo board. Note that work here is incomplete and cannot
GenericTypedefs.h. Also SNMP was tested in this version. SNMP.mib was updated some to better reflect current hardware.
21.Added AN870 SNMP callbacks to MainDemo.c (a feature that was missing in 3.xx releases). This code will get compiled when STACK_USE_SNMP_SERVER is defined in TCPIPConfig.h. 22.Removed all instances of MPFS_USE_PGRM for storing in internal FLASH program memory. Storage in internal program memory is now the default. Define
MPFS_USE_EEPROM to override the default and store MPFS in an external EEPROM memory. 23.Decreased program
removed. 24.UDP checksum checking logic has been improved. The UDP layer now avoids writing the pseudo header checksum in the RX buffer. 25.Swapped endianess of the returned checksum from CalcIPBufferChecksum(). Rewrote
CalcIPBufferChecksum() in Helpers.c. This improves consistency. 26.Improved swapl() in Helpers.c. 27.Improved USART baud rate (SPBRG) calculation for PIC18s. Rounding is now done to chose the most optimal value and the code will automatically select high baud rate mode (BRGH=1) if possible. Additional improvements can be made if using a newer
PIC18 with the 16 bit baud rate generator. 28.Added GenericTCPServer.c example file to complement GenericTCPClient.c.
The server is enabled by defining STACK_USE_GENERIC_TCP_SERVER_EXAMPLE in TCPIPConfig.h. 29.Renamed
STACK_USE_GENERIC_TCP_EXAMPLE definition to STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE for consistency with new server example. 30.Defaulted MPFS.exe to generate binary MPFS images using 32 bit addressing. MPFS.h has been modified to also default to use 32 bit addressing of external EEPROM images. You must rebuild any old MPFS images and reprogram them if upgrading from a previous TCP/IP stack revision, which defaulted to use 16 bit addressing.
31.Updated MPFS.exe to #include "TCPIP.h" instead of "..HeadersCompiler.h" in C files generated by the utility. 32.Added
MPFSv2.exe PC utility for generating large MPFS images in program memory (ASM30 code) for C30 users. Previously, the
C30 compiler placed a limit of less than 32KB of total MPFS size due to the PSV window size limitation on PIC24/dsPIC devices. To get around the limitation, use the new MPFSv2.exe utility to generate an .s file which can be included in your project instead of the .c file generated by the traditional MPFS.exe utility.
Fixes:
address if a TX buffer wasn't immediately available.
3. Modified TCP state machine. Established connections will no longer automatically close if left idle for approximately 45 seconds. Note that your application needs to ensure that no sockets unintentionally get lost (For example: a server socket that received data only is established and the cable breaks while connected. In this case, the socket would never be detected as being disconnected since the server never attempts to transmit anything).
4. Stopped overclocking dsPIC33 and PIC24H devices. Previously PLLFBD was incorrectly set to 39 instead of 38 to yield a resulting Fosc of 84MHz (42MIPS) instead of 80MHz (40MIPS) with the default Explorer 16 development board. Thanks go to Matt Watkins on the Microchip Ethernet Forum for pointing this error out.
5. Corrected a bug in IP.c where IPHeaderLen would not be properly initialized if a NON_MCHP_MAC was used (ex:
RTL8019AS) and IPSetRxBuffer() was called. This bug did not affect ENC28J60 or PIC18F97J60 family support. Thanks go to Darren Rook for identifying this issue.
6. Updated checksum checking code in ENC28J60.c for latest silicon DMA checksum errata.
43
3 Microchip TCP/IP Stack Help to prevent rare inconsistency bugs.
8. Fixed Announce.c so the unicast remoteNode of the requesting packet would be used rather than the remoteNode of the last received packet, which may not be correct when transmitting. Thanks go to Brett Caulton for identifying this issue.
9. Fixed a DHCP bug which would cause DHCP renewals to continually occur after only 60 seconds once the original lease expired. Thanks go to Brett Caulton for identifying this issue and fix.
10.Fixed a potential TCP socket leak in the FTP module. Previously FTPDataSocket would not be reliably initialized nor closed if the connection was killed forcefully (user killed application, cable disconnected while transferring, etc.).
Known Problems:
1. RTL8019AS MAC layer driver has not been updated for new TCP module. Users requiring RTL8019AS support should continue to use stack version 3.75.
2. I2CEEPROM.c has not been tested or completed. Continue to use I2CEEPROM.c from stack version 3.75 if this file is needed.
Some telnet clients may render the telnet server output incorrectly (in the wrong locations or wrong colors). Testing has only been done with the Microsoft Windows telnet.exe utility that comes Windows XP.
4. DHCP will continually send out DHCP Request packets when the lease expires and the original DHCP server that gave the lease is offline. The board will continue to use the expired IP address until the DHCP server comes back online, at which point the lease will be renewed or a new discovery will occur. A new discovery should occur after timing out, instead. It is believed that this problem has always existed in previous stack revisions.
5. DHCP will continually send out DHCP Request packets when the lease expires and the original DHCP server that gave the lease does not include Option 54, the Server Identifier. A new discovery should occur after timing out. It is believed that this problem has always existed in previous stack revisions.
6. TFTPc module has not been tested with this version.
7. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
******
v3.75 14 August 2006
******
Changes:
1. Added beta DNS client module (DNS.c). DHCP was also updated to obtain a DNS server address. Added
AppConfig.PrimaryDNSServer IP address. Added STACK_USE_DNS configuration macro. To use the DNS client, call
module, the API or code may change before being finalized. No formal DNS API documentation is available yet.
2. Added beta NetBIOS Name Service responder module (NBNS.c). Added AppConfig.NetBIOSName string. Added
STACK_USE_NBNS configuration macro. Added MY_DEFAULT_HOST_NAME macro in StackTsk.h. Now, whenever a
NetBIOS broadcast attempting to resolve AppConfig.NetBIOSName arrives, a response will be made. This form of name resolution only works on a single subnet. Off the subnet, manual registration in a DNS server or other means will be needed to allow the local Host Name to be recognized and translated to an IP address. The default NetBIOS name for the board is "MCHPBOARD". To test the NetBIOS Name Service module, try entering http://MCHPBOARD/ into your web browser instead of the board's IP address.
3. Added beta HTTP client module (GenericTCPClient.c). This module demonstrates how to make a TCP client application.
To test this module, uncomment the STACK_USE_GENERIC_TCP_EXAMPLE macro in StackTsk.h, recompile, and then
written to the serial port. No formal documentation is available for this example yet.
4. Added Embedded Ethernet Device Discoverer PC project to aid in embedded product discovery when connected to a
44
3 Microchip TCP/IP Stack Help network and demonstrate how to write PC applications which can communicate with embedded devices. The source code for this device is included. It can be built using the Microsoft Visual C# 2005 Express Edition compiler. At the time of stack release, this 3rd party PC development tool can be downloaded at no cost from http://msdn.microsoft.com/vstudio/express/. If using only the Microchip Device Discoverer executable file without the
Visual C# compiler, the .NET Framework 2.0 must be installed on the local PC. The application setup utility should allow dynamic downloading of this component if the target machine does not already have it installed.
the character 'D'. To test this functionality, use the Embedded Ethernet Device Discoverer on a PC connected to the same subnet.
6. Updated UART configuration menu to accommodate the new beta module configuration options (DNS server address, device host name).
7. Increased MPFS reserve block to 64 bytes from 32. Also, because the APP_CONFIG structure was updated, all current
MPFS images and data stored in deployed EEPROMs needs to be updated.
8. Added a means to erase (invalidate) the onboard EEPROM using the BUTTON0 momentary switch (right-most switch on demo boards with multiple switches). To erase the EEPROM, hold down BUTTON0, RESET the board (press and release
MCLR switch), and then continue to hold down BUTTON0 for an additional 4 seconds. If you press MCLR again, the
EEPROM contents will now be invalid. If you press '0' on the UART, the same configuration that was read prior to invalidating the contents will be written back into the EEPROM. Invalidating the EEPROM allows the MY_DEFAULT_* constants to get loaded into a previously programmed EEPROM chip. Because of change #7, this procedure should be done for all currently programmed EEPROMs to prevent anomalous values from being read.
9. remoteNode in StackTsk.c was changed from private to global scope. Now external modules can reference the address of the last received packet. Announce.c uses this to send a unicast response to a broadcast discovery request.
10.All stack modules that can be disabled (DHCP.c, FTP.c, etc) now will no longer emit a compiler error if you have it in the project without defining the appropriate macro (STACK_USE_DHCP, STACK_USE_FTP, etc). It will simply generate no machine code when compiled and the stack will not use that module. Make sure the proper macro is defined for each module that you wish to use. 11.Added SetRXHashTableEntry() to ENC28J60.c. This function can be used to set the appropriate bit in the Hash Table registers to join a particular multicast group. 12.Added Realtek RTL8019AS Ethernet controller support to the stack. MAC.c was renamed to RTL8019AS.c. This Ethernet controller is not recommended for new designs. RTL8019AS support was reintroduced to provide ongoing assistance to former Application designs implementing this chip. For new applications, use the Microchip ENC28J60 or PIC18F97J60 family of microcontrollers. 13.Added I2C
EEPROM support for MPFS storage. In older 2.xx stack revisions, I2C EEPROM was supported by the XEEPROM.c file.
This file has been renamed to I2CEEPROM.c. It is mutually exclusive with SPIEEPROM.c, and only one may be included in the project at a time. 14.Added new hardware definitions to Compiler.h. Pin mappings for the PICDEMNET and
PIC18F97J60_TEST_BOARD boards have been added. FS_USB was also defined; however, it is untested and not recommended. See Compiler.h. The PIC18F97J60_TEST_BOARD is a non-production board that some Early Adopters of the PIC18F97J60 family parts have. 15.Changed type definitions for BYTE_VAL, WORD_VAL, DWORD_VAL, and moved the generic typedefs to GenericTypeDefs.h from StackTsk.h. This should improve compatibility with some future code libraries released by Microchip. 16.LCDBlocking.c module was modified to support 4-bit interfaces to LCD modules. The
PICDEM.net board has the module wired using a 4-bit bus.
Fixes:
1. Fixed a serious MAC TXBuffer leak in TCP.c. Previously TCP.c would allocate a buffer for each socket in use, but under heavy traffic conditions (ex: user holds down F5 on web browser), the buffer handle might have been discarded before releasing the buffer. As a result all TCP connections would have lost the ability to send any application data after the
TXBuffer pool ran out.
2. In the TCP_SYN_SENT TCP state, ACKs may only be received (as opposed to SYN+ACK packets) if the remote node thinks the connection is already open. A RST is now sent in response to an unexpected ACK, which may improve reconnection time when this (rare) condition occurs.
3. A bug was present in the UDP module where remote MAC addresses would be cached for each socket, even when
now properly initialized/closed.
4. Fixed a potential timing bug in LCDBlocking.c. For lower values of CLOCK_FREQ, insufficient delay time was given to the
LCD module, potentially causing improper operation.
5. Changed PIC24F to default to the XT oscillator fuse rather than HS. The PIC24FJ128GA010 data sheet, rev. C reports that 8MHz should be used with XT mode, not HS mode like prior data sheets.
45
3 Microchip TCP/IP Stack Help
6. Added a couple of wait states to the Realtek RTL8019AS MAC layer module for NICPut() and NICGet(). Previously, the
PICmicro could not operate above approximately 25MHz without losing communication with the RTL8019AS chip.
7. Updated PC based MPFS utility. When generating C files to be added to your MPLAB project, the include path to
"Compiler.h" is now "..IncludeCompiler.h". The output file, ex: "MPFSImg.c" should be placed in the "Source" subfolder before compiling. For example, if you are in the main stack folder with the MPLAB projects, type: "mpfs /c WebPages
SourceMPFSImg.c"
8. IP Gleaning will now get properly disabled when, through the RS232 configuration application, DHCP and IP Gleaning are disabled. The stack will still respond to ping requests which have the wrong destination IP address, but a correct MAC address. However, the stack will continue to keep its statically defined IP address when DHCP/IP Gleaning are disabled and the ping arrives.
9. SPIEEPROM.c now saves and reconfigures the EEPROM_SPICON1 register (SSPCON1) before reading or writing to the
SPI. After the read/write, it restores the saved state. This allows the SPI bus to operate at different speeds, depending on what peripheral is being accessed if other devices share the bus and can support different speeds. In particular, this fixes the SPI @ 10.4MHz problem on the PICDEM.net 2 board when using the ENC28J60.
Known Problems:
1. DHCP will continually send out DHCP Request packets when the lease expires and the original DHCP server that gave the lease is offline. The board will continue to use the expired IP address until the DHCP server comes back online, at which point the lease will be renewed or a new discovery will occur. A new discovery should occur after timing out, instead. It is believed that this problem has always existed in previous stack revisions.
2. DHCP will continually send out DHCP Request packets when the lease expires and the original DHCP server that gave the lease does not include Option 54, the Server Identifier. A new discovery should occur after timing out. It is believed that this problem has always existed in previous stack revisions.
3. When an MPFS .c image file is added to a C30 project, a linking error reporting insufficient contiguous .const memory may occur when too much data is in the MPFS image (PSV window size limitation). Using the PSV window, 1 out of every
3 program memory bytes is wasted.
4. MACSetPMFilter(), MACDisablePMFilter(), and MACCopyRxToTx() have not been tested and possibly do not work.
5. SNMP, TFTPc modules have not been tested with this version.
6. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
7. The C30 linker may misplace the __CONFIG2 section or disallow usage of MPFS images that are too big (add too much to the .const code section). The consequences of this are that the first configuration word at 0x157FC may not get set through code (must use the Configuration Bits dialog instead), and/or the project will not compile. This problem has been observed with C30 ver. 2.02 on the PIC24FJ128GA010 product. To work around this problem, the p24FJ128GA010.gld linker script has been modified. Specifically, line 68 has been commented out, which causes the linker to place all .text sections after placing all absolute sections. SSR 25966 in the C30 2.02 release notes may be related.
8. It is observed with the Realtek RTL8019AS Ethernet controller and the demo AJAX web page which self refreshes rapidly, that occasional HTTP GET requests sent by the computer do not get received by the HTTP server. This is believed to be a RTL8019AS MAC layer bug. The TCP protocol handles the packet loss, but application performance suffers while waiting for the TCP retransmission. This problem is not observed with ENC28J60.c or ETH97J60.c MAC layers.
9. The HI-TECH compiler version 9.50PL1 crashes when compiling LCDBlocking.c with 4 bit mode (PICDEMNET) and using a warning level of -3 or higher. To work around the problem, the HI TECH projects were set to use warning level -4.
Guiding Notes:
1. To use the stack on a classic PICDEM.net demo board with the Realtek Ethernet controller, a PIC18F452 processor, and
Microchip C18: -Use the C18EEPROM MPLAB project -Change the processor in the MPLAB IDE -Change linker script to
"18f452i.lkr" in the MPLAB project. Use the one provided in the Linker subfolder, it has been modified to make more RAM available. -Update the hardware definitions macro. Click on Project -> Build Options... -> Project -> MPLAB C18 -> Add
PICDEMNET, remove HPC_EXPLORER) -Remove ENC28J60.c from the project -Remove SPIEEPROM.c from the project -Add RTL8019AS.c to the project -Add I2CEEPROM.c to the project -Enable all compiler optimizations (Project ->
Build Options... -> Project -> MPLAB C18 -> Categories Optimization -> Enable all)
******
v3.60 12 July 2006
46
3 Microchip TCP/IP Stack Help
******
General Information: This stack version is being publicly released, so the following changes are with respect to the prior public stack release (v3.02). Interim stack changes for version 3.16 and 3.50 are documented below for those using non-public releases, but can be ignored by most people.
Troubleshooting notes:
1. If you have an Ethernet PICtail revision 2.1 and are having reliability issues when viewing the fast-refresh demo web page, you may need to install resistors in series with the ENC28J60 SI, nCS, and SCK pins. The recommended value is
100 to 200 ohms. This will reduce signal undershoot caused by long traces (parasitic inductance), which can violate the absolute maximum electrical specs and cause SPI data corruption. The HPC Explorer Rev 5 has fairly long traces to the
PICtail connector.
2. Enabling C30 2.02 compiler optimizations on the dsPIC33FJ256GP710, PIC24HJ256GP610 ES chips may produce unreliable code.
3. When changing a C30 project to a PIC24H or dsPIC33F processor on the Explorer 16 demo board, the JTAG configuration fuse should be disabled to free the I/O pins associated with it. JTAG is enabled by default.
4. This stack release was tested using MPLAB 7.40, C18 version 3.03, C30 version 2.02, and HI TECH PICC18 version
9.50PL1.
5. When using the Ethernet PICtail board and HPC Explorer demo boards, make sure to plug the power into the Ethernet
PICtail and not the HPC Explorer. The HPC Explorer's power regulator cannot provide enough current.
Changes:
1. Source files have been split into separate directories. To compile old applications with this new stack, application source files may need to be updated to include the proper path to the stack header files.
2. New MPLAB projects have been created: -C18EEPROM: Equivalent to the previously named "mpnicee" project.
Designed for PIC18's using the C18 compiler. Web page content, board's IP address, MAC address, DHCP enabled state, etc. is stored in an external SPI EEPROM (25LC256 on demo boards). FTP Server demo is included.
-C30EEPROM: New supporting PIC24 and dsPIC controllers using the C30 compiler. Similar to C18EEPROM.
-C18ProgramMem: Equivalent to the previously named "mpnicpg" project. Web page content stored in internal FLASH program memory. Board's IP address, MAC address, DHCP enabled state, etc. is stored only in RAM and defaults are loaded from MY_DEFAULT_* constants in StackTsk.h. FTP Server demo is not included. Web pages cannot be updated remotely. -C30ProgramMem: New supporting PIC24 and dsPIC controllers using the C30 compiler. Similar to
C18ProgramMem. -HTC18EEPROM: Equivalent to the previously named "htnicee" project. Designed for PIC18's using the HI TECH PICC18 compiler. Similar to C18EEPROM. -HTC18ProgramMem: Equivalent to the previously named
"htnicpg" project. Designed for PIC18's using the HI TECH PICC18 compiler. Similar to C18ProgramMem.
3. Created hardware definitions (pins, interrupt flags, special registers, etc) in Compiler.h for easy changing of hardware.
Four demo board combinations are supported out-of-box now: -EXPLORER_16: Explorer 16 motherboard + Ethernet
PICtail Plus daughter card. Tested with dsPIC33FJ256GP710, PIC24HJ256GP610, and PIC24F128GA010 ES PIMs.
-HPC_EXPLORER: PICDEM HPC Explorer motherboard + Ethernet PICtail daughter card. Tested with PIC18F8722 onboard and PIC18F87J10 PIM. -DSPICDEM11: dsPICDEM 1.1 motherboard + Ethernet PICtail daughter card (manually air wired). See Compiler.h for proper pins to air wire. Tested with dsPIC30F6014A PIM. -PICDEMNET2: PICDEM.net 2 motherboard (PIC18F97J60) Change boards by changing the defined macro (Project -> Build Options... -> Project ->
MPLAB Cxx -> Add macro). When moving to custom hardware, add an appropriate profile to Compiler.h. YOUR_BOARD is present as a placeholder.
4. Added Ethernet PICtail Plus schematic (reference ENC28J60 daughter card design for Explorer 16 demo board). These boards have a Microchip part number of AC164123.
5. Latest ENC28J60 rev. B5 errata workarounds added. The code checks the EREVID register and implements the appropriate workarounds as needed for the silicon revision, so rev. B1, B4, and B5 are all supported in this stack release.
6. Significantly revised demonstration web page content in WebPages folder to use AJAX technology. Using asynchronous
JavaScript code executing in the web browser, the status sections of the page are updated rapidly from the web server without doing a full page refresh. As a result, a virtually real time update of the potentiometer and button values can be displayed. Due to the constant use of new TCP sockets, multiple simultaneous users are not recommended. See the
Index.cgi file for a simple static method of retrieving dynamic variables from the HTTP server.
7. Changed IP Gleaning procedure. Now, if DHCP is enabled, the DHCP module will continue to look for a new IP address/renew existing IP address if the IP address is configured using IP Gleaning. Previously, the DHCP module would be disabled once a successful ICMP packet was received and used to configure the IP address.
8. MAX_RETRY_COUNTS is 3 (previously it was 3, but an interim release changed it to 5).
47
3 Microchip TCP/IP Stack Help
9. Updated TCP state machine. It now includes the TCP_FIN_WAIT_2 state. Some other changes were made to handle errors more robustly.
10.AN0String and AN1String now return all characters excluding the null terminator when the HTTP server calls
HTTPGetVar (except when the string is 0 length). Previously, the null terminator was returned as well. 11.Dynamic pages
(ie: .cgi files) are now served with an expired HTTP header to prevent browser caching and allow more dynamic content to be displayed. 12.Support for the HI TECH PICC18 compiler has changed. Special Function Register bits and other definitions have changed substantially from the previous HI TECH PICC18 projects in TCP/IP stack version 3.02 and earlier.
The C18/C30 SFR and SFRbits naming conventions are now used and special remapping macros in Compiler.h are used to maintain a consistent syntax. The HI TECH PICC18 projects were tested with compiler version 9.50PL1 on the HPC
Explorer board (PIC18F8722). 13.FTP client hash printing has been added to the FTP server. Now, whenever a chunk of data is successfully uploaded to the device, a '#' character will appear on the FTP client screen. The numbers of bytes each
'#' represents is variable. 14.To improve maintainability, built in support for the "Compatible" A/D converter present on older
PIC18 parts (ex: PIC18F452) has been removed. 15.Removed old LCD code originally provided for the PICDEM.net demo board. 16.Added LCDBlocking.c and LCDBlocking.h, which implement simple routines for writing to the LCD module on the
Explorer 16 and PICDEM.net 2 development boards. The LCD on the dsPICDEM 1.1 board is not supported. The stack version and IP address are shown on the LCD on power up. 17.UART functions in MainDemo.c were replaced with C18 and
C30 peripheral library functions. However, because the UART peripheral libraries are not being updated for newer silicon devices, the code was copied into UART.c and is compiled with the stack. 18.Multiple TX buffer support has been implemented. Most stack layers have been touched. ENC28J60.c has the most extensive changes. Each socket may use only one TX buffer. 19.Implemented TCP retransmission support regardless of if TCP_NO_WAIT_FOR_ACK is defined or not. 20.TCP_NO_WAIT_FOR_ACK in StackTsk.h has been undefined by default. This should increase default TCP connection robustness. Packets sent from the stack to the remote node will now be detected and retransmitted if lost or corrupted. 21.All TCP packets are now retransmitted immediately after being initially transmitted when
TCP_NO_WAIT_FOR_ACK is undefined. This improves throughput greatly when communicating with systems which wait a long time before transmitting ACKs. TCP/IP stacks, such as that used by Microsoft Windows, implement the TCP Delayed
Acknowledgement algorithm, which is why this retransmission is necessary for high performance. The double transmission feature can be disabled in the Microchip TCP/IP stack by defining "DEBUG" either in the TCP.c file or the project compiler macros section. Using DEBUG mode can be useful when trying to look for errors using Ethreal [ http://www.ethereal/ ].
long timeout for modern day network speeds. 23.Native support for the SLIP module has been dropped.
Fixes:
module (for MCHPDetect.exe), and output the new address out the RS232 port.
2. DHCP client will now correctly use the first DHCP offer received when connected to a network running multiple DHCP servers. Previously, the board would get no IP address when attached to a network with multiple DHCP servers (unless the DHCP request was transmitted before a second DHCP offer was received -- a relatively rare event). Additionally,
DHCPLeaseTime does not get reset to 60 seconds or the value stored in the last DHCP packet received prior to receiving the ACK.
3. UDPProces() will now correctly process received UDP packets that have a 0x0000 checksum field. The UDP protocol specifies that 0x0000 means the checksum is disabled. Packets with a 0x0000 checksum were previously thrown away unless the calculated checksum also happened to be 0x0000.
the remote application pauses or cannot handle the incoming data rate, the TCP flow control feature will correctly function. Previously, if the remote node ran out of incoming buffer memory, the TCP layer would still allow more data to be transmitted. This would result in the loss or corruption of application data, with a potentially broken connection. The change requires 2 more bytes of RAM per TCP socket (TCB array).
Known Problems:
1. On PICDEM.net 2 board ENC28J60 and 25LC256 EEPROM share the same SPI1 module. At 3.3V, the 25LC256 is only rated to 5MHz SPI clock, but the code is setting it to 10.4MHz because the MACInit() function reconfigures the same SPI1 module.
2. DHCP will continually send out DHCP Request packets when the lease expires and the original DHCP server that gave the lease is offline. The board will continue to use the expired IP address until the DHCP server comes back online, at which point the lease will be renewed or a new discovery will occur. A new discovery should occur after timing out,
48
3 Microchip TCP/IP Stack Help instead. It is believe that this problem has always existed in previous stack revisions.
3. DHCP will continually send out DHCP Request packets when the lease expires and the original DHCP server that gave the lease does not include Option 54, the Server Identifier. A new discovery should occur after timing out. It is believe that this problem has always existed in previous stack revisions.
4. The MPFS utility has not been updated. When creating a .c image file, the include path for the Compiler.h file will be incorrect and need to be manually updated to "..IncludeCompiler.h".
5. When an MPFS .c image file is added to a C30 project, a linking error reporting insufficient contiguous .const memory may occur when too much data is in the MPFS image (PSV window size limitation). Using the PSV window, 1 out of every
3 program memory bytes is wasted.
6. MACSetPMFilter(), MACDisablePMFilter(), and MACCopyRxToTx() have not been tested and possibly do not work.
7. SNMP, TFTPc modules have not been tested with this version.
8. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
9. IP Gleaning may not get disabled when, through the RS232 configuration application, DHCP and IP Gleaning are disabled.
10.The C30 linker may misplace the __CONFIG2 section or disallow usage of MPFS images that are too big (add too much to the .const code section). The consequences of this are that the first configuration word at 0x157FC may not get set through code (must use the Configuration Bits dialog instead), and/or the project will not compile. This problem has been observed with C30 ver. 2.02 on the PIC24FJ128GA010 product. To work around this problem, the p24FJ128GA010.gld
linker script has been modified. Specifically, line 68 has been commented out, which causes the linker to place all .text
sections after placing all absolute sections. SSR 25966 in the C30 2.02 release notes may be related.
Guiding Notes:
1. To change processors using a C18* project: -Change the processor in the MPLAB IDE -Change linker script (ex:
18f87j10i.lkr) in the MPLAB project. Use *i.lkr if the ICD2 is going to be used to debug with. -Update the hardware definitions in Compiler.h or change your demo board selection macro. (Project -> Build Options... -> Project -> MPLAB
Cxx -> PICDEMNET2, etc)
2. To change processors using a HTC18* project: -Change the processor in the MPLAB IDE -Update the hardware definitions in Compiler.h or change your demo board selection macro. (Project -> Build Options... -> Project -> MPLAB
Cxx -> PICDEMNET2, etc)
3. To change processors using a C30* project: -Change the processor in the MPLAB IDE -Change linker script (ex: p33FJ256GP710.gld) in the MPLAB project. -Update the hardware definitions in Compiler.h or change your demo board selection macro. (Project -> Build Options... -> Project -> MPLAB Cxx -> DSPICDEM11, etc) -Disable JTAG configuration fuse, if enabled
4. When using the PICDEM.net 2 board, to write code targeting the PIC18F97J60 family Ethernet module: -Remove
ENC28J60.c from the project -Add ETH97J60.c to the project -Plug the Ethernet cable into the left-most RJ45 jack (next to LCD)
5. When using the PICDEM.net 2 board, to write code targeting the ENC28J60 Ethernet device: -Make sure ENC28J60.c is in the project -Make sure that ETH97J60.c is not in the project -Plug the Ethernet cable into the right-most RJ45 jack (next to board edge)
6. When using the PICDEM.net 2 board, to write code targeting an Ethernet PICtail module (ENC28J60): -Make sure
ENC28J60.c is in the project -Make sure that ETH97J60.c is not in the project -Make sure that the Ethernet PICtail J9 jumper is in the 2-3 position (default). -Properly update the hardware profile in Compiler.h. ENC_CS_TRIS and
ENC_CS_IO need to be changed from D3 to B3. -Plug the Ethernet cable into the PICtail -Plug power into the
PICDEM.net 2 board
7. When using the Explorer 16 and Ethernet PICtail Plus demo boards, make sure to mate the PICtail to the motherboard using the topmost socket position, leaving the cable hanging over prototyping area. If SPI2 is desired, the PICtail should have the same orientation but be installed in the middle slot. Using SPI2, the hardware profile will need to be updated in
Compiler.h.
******
v3.50 13 April 2006
49
3 Microchip TCP/IP Stack Help
******
Changes:
1. Improved dsPIC33F and PIC24H support. UART functions are included now instead of precompiled object files for the
PIC24F. The 12-bit A/D converter is now shown in use on the demo web content. When changing a C30 project to a
PIC24H or dsPIC33F processor on the Explorer 16 demo board, the JTAG configuration fuse should be disabled to free the I/O pins associated with it. JTAG is enabled by default.
2. Added LCDBlocking.c and LCDBlocking.h, which implement simple routines for writing to the LCD module on the Explorer
16 development board. The stack version and IP address are shown on the LCD on power up.
3. Added "C18ProgramMem" and "C30ProgramMem" MPLAB projects for MPFS storage (web page content) on on-chip program memory. These projects are equivalent to the previously named "mpnicpg" project in prior stack releases.
4. Multiple TX buffer support has been implemented. Most stack layers have been touched. ENC28J60.c has the most extensive changes. Each socket may use only one TX buffer.
5. Implemented TCP retransmission support when TCP_NO_WAIT_FOR_ACK is undefined.
6. TCP_NO_WAIT_FOR_ACK in StackTsk.h has been undefined by default. This should increase default TCP connection robustness.
7. All TCP packets are now retransmitted immediately after being initially transmitted when TCP_NO_WAIT_FOR_ACK is undefined. This improves throughput greatly when communicating with systems which wait a long time before transmitting
ACKs.
8. Lowered TCP_START_TIMEOUT_VAL ( see page 575) from 60 seconds to 3 seconds.
9. Increased MAX_RETRY_COUNTS from 3 to 5 times.
10. The example HTTP server now returns a content expiration date which has already past. This prevents web browser caching and allows more dynamic content to be displayed.
11. Added WebPages_JScript folder, with new web pages that support dynamic page updates without a full page reload. A tiny page of dynamic variables is returned by the web server and Javascript executing on the target web browser changes
DOM elements as needed. Button S5 (RA7) on the Explorer 16 demo board and S1 (RB0) on the HPC Explorer demo board changes the page color scheme. The rapid dynamic updates do not work on some web browsers (Internet Explorer works, Firefox does not).
Known Problems:
1. MPFS utility has not been updated. When creating a .c image file, the include path for the compiler.h file will be incorrect and need to be manually updated.
2. When an MPFS .c image file is added to a C30 project, a linking error reporting insufficient contiguous .const memory may occur (PSV window size limitation).
3. MACSetPMFilter(), MACDisablePMFilter(), and MACCopyRxToTx() have not been tested and possibly do not work.
4. SNMP, TFTPc, SLIP modules have not been tested with this version.
5. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
6. IP Gleaning may not get disabled when, through the RS232 configuration application, DHCP and IP Gleaning are disabled.
happen when the IP address is configured using IP Gleaning.
8. On the PIC24F with C30 compiler optimizations enabled (such as Option 3, maximum speed), the project may not work.
The PIC24F headers that come with C30 ver. 2.01 declare several SFRs without using the volatile keyword.
9. dsPIC30 support is incomplete. Currently PIC18, PIC24F, PIC24H, and dsPIC33F processors are supported.
******
v3.16.00: 06 March 2006
50
3 Microchip TCP/IP Stack Help
******
Changes:
1. Added unified support for both the Microchip C18 and C30 compilers. The intention is to allow one code base to be compiled for any PIC18, PIC24F/H, dsPIC30, or dsPIC33 product (with adequate memory). See the "Tested Using" section for what is known to work.
2. To improve maintainability, support for the HI-TECH PICC18 compiler has been dropped.
3. New project workspaces have been created, "C30EEPROM.mcw" and "C18EEPROM.mcw". C18EEPROM.mcw is equivalent to the previously named "mpnicee.mcw." C30EEPROM is intended to be used for PIC24 and dsPIC 16-bit controllers.
4. Source files have been split into separate directories.
5. Latest ENC28J60 rev. B5 errata workarounds added. The code checks the EREVID register and implements the appropriate workarounds as needed for the silicon revision, so rev. B1, B4, and B5 are all supported in this stack release.
6. Removed old LCD code originally provided for the PICDEM.net demo board.
7. To improve maintainability, built in support for the "Compatable" A/D converter present on older PIC18 parts (ex:
PIC18F452) has been removed.
8. UART functions in MainDemo.c were replaced with C18 and C30 peripheral library functions.
Tested Using:
1. Software: -MPLAB version 7.31.01 -C18 version 3.02 -C30 version 2.01
2. Hardware: -PICDEM HPC Explorer rev. 4 (PIC18F8722) + Ethernet PICtail Daughter Board (ENC28J60
B1) -Explorer 16 rev. 4 (PIC24FJ128GA010 ES and dsPIC33FJ256GP710 ES) + Ethernet PICtail+ Daughter card
(ENC28J60 B1).
3. Notes: -MPLAB 7.31.01 is a development build. The publicly available version 7.31 should work fine, with the exception of being unable to program dsPIC33 and PIC24H parts with the ICD 2. -No dsPIC30 or PIC24H parts have been tested yet.
Known Problems:
1. MPFS utility has not been updated. When creating a .c image file, the include path for the compiler.h file will be incorrect and need to be manually updated.
2. When an MPFS .c image file is added to a C30 project, a linking error reporting insufficient contiguous .const memory may occur.
3. On the PIC24FJ128GA010, it is observed that some inbound packets are lost from time to time with no anticipated reason.
4. MACSetPMFilter(), MACDisablePMFilter(), and MACCopyRxToTx() have not been tested and possibly do not work.
5. SNMP, TFTPc, SLIP modules have not been tested with this version.
6. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
7. IP Gleaning may not get disabled when, through the RS232 configuration application, DHCP and IP Gleaning are disabled.
happen when the IP address is configured using IP Gleaning.
9. Multiple TX buffer support is not fully inplemented in the MAC layer, ENC28J60.c. Stack behavior when
TCP_NO_WAIT_FOR_ACK is undefined may be unexpected.
******
v3.02.00: 20 Feb 2006
******
Fixes:
51
3 Microchip TCP/IP Stack Help
1. Changed TXSTART in ENC28J60.c to stop wasting a byte.
2. Changed RXSTOP in ENC28J60.c to always be an odd value to properly implement an ENC28J60 silicon errata workaround.
3. Changed initialization of ERXRDPT in MACInit() to agree with the current errata.
Changes:
1. Licence agreement
2. Schematics and other board files to the Ethernet PICtail Daughter Board have been updated to revision 5. Of significant note, the nRESET pin has been freed and 200 ohm resistors were added to the ENC28J60 SI, nCS, and SCK pins. The added resistors reduce undershoot caused by stray trace inductance and strong host output drivers.
Known Problems:
1. Testing on the PICDEM.net demo board with the Realtek RTL8019AS Ethernet controller has not been done. Moving to the HPC Explorer demo board has resulted in pinout and other hardware changes.
2. MACSetPMFilter(), MACDisablePMFilter(), and MACCopyRxToTx() have not been tested and possibly do not work.
3. SNMP, TFTPc, LCD, SLIP modules have not been tested with this version.
4. The stack may behave incorrectly if compiled using the Hitech compiler with a high optimizations setting.
5. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
6. IP Gleaning may not get disabled when, through the RS232 configuration application, DHCP and IP Gleaning are disabled.
happen when the IP address is configured using IP Gleaning.
8. Multiple TX buffer support is not fully inplemented in the MAC layer, ENC28J60.c. Stack behavior when
TCP_NO_WAIT_FOR_ACK is undefined may be unexpected.
******
v3.01.00: 18 Jan 2006
******
Fixes:
1. Implemented latest ENC28J60 silicon errata workarounds.
2. Fixed a bug in TCP.c and UDP.c which would incorrectly write the packet checksum into the RX buffer incorrectly when the checksum field was exactly spanning the RX wrapparound boundary in the ENC28J60. This problem would have caused packets to be discarded in rare circumstances
Known Problems:
1. Testing on the PICDEM.net demo board with the Realtek RTL8019AS Ethernet controller has not been done. Moving to the HPC Explorer demo board has resulted in pinout and other hardware changes.
2. MACSetPMFilter(), MACDisablePMFilter(), and MACCopyRxToTx() have not been tested and possibly do not work.
3. SNMP, TFTPc, LCD, SLIP modules have not been tested with this version.
4. The stack may behave incorrectly if compiled using the Hitech compiler with a high optimizations setting.
5. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
6. IP Gleaning may not get disabled when, through the RS232 configuration application, DHCP and IP Gleaning are disabled.
happen when the IP address is configured using IP Gleaning.
8. Multiple TX buffer support is not fully inplemented in the MAC layer, ENC28J60.c. Stack behavior when
TCP_NO_WAIT_FOR_ACK is defined may be unexpected.
52
3 Microchip TCP/IP Stack Help
******
v3.00.00: 16 Jan 2006
******
Changes:
1. The stack now targets the PICDEM HPC Explorer demo board (PIC18F8722 MCU) with an attached Ethernet PICtail
Daughter Board (with the Microchip ENC28J60 Ethernet controller).
2. IP Gleaning is no longer enabled (STACK_USE_IP_GLEANING is not defined) by any of the default project files.
3. The IP address, whenever it changes, is outputted out the RS232 serial port in human readable form. Any terminal program, such as HyperTerminal can be used to read it. This allows the IP address to be easily determined when DHCP is used. The serial port defaults to 19200 baud when CLOCK_FREQ in Compiler.h is properly defined.
Additions:
1. Microchip ENC28J60 Ethernet controller support. Support is included through the ENC28J60.c and ENC28J60.h files.
Various other files were modified to take advantage of ENC28J60 specific features, like the hardware DMA/IP checksum engine. This new MAC driver incorporates several new functions which can be called from any layer above the MAC. The functions are: MACSetDuplex() MACPowerDown() MACPowerUp() MACSetPMFilter() MACDisablePMFilter()
CalcIPBufferChecksum() MACCalcRxChecksum() MACCalcTxChecksum() MACCopyRxToTx() See the ENC28J60.c file comments for function descriptions. The ENC28J60.c file also incroporates TestMemory() which can do a power on self test of various hardware functions. TestMemory() is included and used when MAC_POWER_ON_TEST is defined in
StackTsk.h. It is undefined by default. Defining it will require some program memory.
STACK_USE_ANNOUNCE must be defined. This module will broadcast a UDP message to port 30303 containing the local MAC address whenever the local IP address changes. This addition is intended to facilitate device discovery on
DHCP enabled networks and eliminate the need for an RS232 connection if board reconfiguration is not needed. To retrieve the UDP message on your computer, use the new MCHPDetect.exe program included in the MCHPDetect subfolder.
3. The spieeprom.c file was added to support SPI EEPROM chips for MPFS storage. ENC28J60.c and spieeprom.c may both be included and they will share the same SPI module.
Improvements:
1. Renamed files/edited files so that the HI-TECH compiler won't raise messages stating that include files were spelled wrong.
2. Moved MAX_ICMP_DATA_LEN from StackTsk.c to ICMP.h file for easier maintenance.
3. Corrected STACK_USE_SIIP typo in dhcp.c file - Thanks to Gisle J.B.
4. Implemented UDP checksum logic in UDPProcess ( see page 627)() in UDP.c file.
5. Renamed CalcTCPChecksum() in tcp.c file to CalcIPBufferChecksum().
6. Moved CalcIPBufferChecksum() to helpers.c to reuse it for UDP checksum calculation.
third new parameter. This makes pseudo header checksum calculation correct in both functions. StackTsk.h, UDP.h and
TCP.h files were also modified to reflect these changes.
8. Modified TCP.C file to include compile-time check of STACK_USE_TCP define. If it is not defined, an error will be displayed.
9. Removed an unnecessary call to MACDiscardRx() when an IP packet is received but fails version, options length, or header checksum tests.
10. Changed LCD code to be compile time removable by undefining USE_LCD.
Fixes:
1. IPHeaderLen in IP.c is initialized properly now when IPGetHeader() is called.
prevent this situation from occuring. *** Thanks go to Richard Shelquist for identifying this problem.
53
3 Microchip TCP/IP Stack Help
3. Fixed StackTsk.c file so that if a static IP address is used and the LINK is removed, the node IP address is not cleared.
4. Invalid ICMP echo replies are no longer generated for echo requests with a data length of 33 (one more than the configured maximum).
5. Changed MAX_OPTIONS_LEN from 20 to 40. The maximum IP options length is now in agreement with the IP RFC.
6. Changed IPSetRxBuffer() from a macro to a function. The function takes into account any options which may be present in the header of received IP packets. Previously, possible options were not taken into account when calculating the offset.
Known Problems:
1. Testing on the PICDEM.net demo board with the Realtek RTL8019AS Ethernet controller has not been done. Moving to the HPC Explorer demo board has resulted in pinout and other hardware changes.
2. Sometimes when the FTP sever is used, an attempt to put a file is unsuccessful. The problem may be caused when an
HTTP request to GET a file is made at the wrong time.
3. MACSetPMFilter(), MACDisablePMFilter(), and MACCopyRxToTx() have not been tested and possibly do not work.
4. SNMP, TFTPc, LCD, SLIP modules have not been tested with this version.
5. The stack may behave incorrectly if compiled using the Hitech compiler with a high optimizations setting.
6. Serial numbers >32K will be displayed on the serial port as a negative value when C18 is used and the board is placed in configuration mode (RB0 button is depressed on power up).
7. IP Gleaning may not get disabled when, through the RS232 configuration application, DHCP and IP Gleaning are disabled.
happen when the IP address is configured using IP Gleaning.
9. Multiple TX buffer support is not fully inplemented in the MAC layer, ENC28J60.c. Stack behavior when
TCP_NO_WAIT_FOR_ACK is defined may be unexpected.
******
v2.20.04.01: 9/24/03
******
1. Recreated MPLAB projects to avoid problems when source is not at MCHPStack location.
******
v2.20.04: 9/5/03
******
Fixes:
1. Modified DHCPReset() in DHCP.c to not reset DHCP state machine if it was previously disabled using DHCPDisable().
This would make sure that if DHCP module was enabled and application had run-time disabled DHCP and network cable is disconnected, stack will not clear its IP address.
2. Rebuilt mib2bib.exe file with static library options. This fixes problem where one tries to execute this exe, an error occurs about missing DLLs.
******
v2.20.03:
54
3 Microchip TCP/IP Stack Help
******
Improvements:
1. When DHCP is enabled, LINK is monitored and IP address is reset on disconnect. New IP configuration is obtained on
LINK reconnect. - For RealTek only. Modified DHCP.c to add DHCPReset() Modified MAC.c to add MACIsLinked()
Modified StackTsk.h to add BYTE_VAL def.
Changes:
1. Modified SMSC91c111.c to add empty MACIsLinked() - will be populated in next rev.
Bug Fixes:
1. Corrected DHCP logic to accept ( see page 174) first DHCP offer instead of second response.
3. Fixed UDPClose ( see page 618)() in UDP.c to use INVALID_UDP_PORT ( see page 615) instead of
INVALID_UDP_SOCKET ( see page 615) because of which a closed socket would not be scanned correctly.
4. Modified UDP.h to use long contsant designators for INVALID_UDP_OPRT to explicitly state that it is a long.
******
v2.20.02:
******
Beta version containing TFTP client module.
Addition:
1. TFTP Client module - See TFTPc.* and TFTPcDemo.c for more information. See MpTFTPcDemo and HtTFTPcDemo projects for build information.
Bug Fix:
non-zero condition.
2. ARPResolve ( see page 163)() in ARPTsk was fixed to clear Cache.IPAddr value.
******
v2.20.01:
******
Bug fix:
1. Fixed SMSC91C111.c where MACInit() would hand if ethernet link is not detected.
******
v2.20:
******
Bug Fixes:
1. General - Removed most of harmless warnings.
55
3 Microchip TCP/IP Stack Help
2. C18Cfg.asm - Fixed "include" instead of "define".
3. DHCP.c - Increased DHCP_TIMEOUT_VAL to 2 seconds. Fixed problem where UDP active socket was not set before calling UDP functions in SM_DHCP_BROADCAST state.
4. MAC.c - Fixed MACIsTxReady() where under heavy traffic it would always return
FALSE. This fixes bug where all high level applications would stop transmitting.
5. TCP.c - Enabled portion of code that performs timeout logic even if
TCP_NO_WAIT_ACK is defined. This fixes bug where occasionally, tcp applications such as HTTP server would stop working after few hours.
Added bFirstRead flag with UDP sockets similar to TCP sockets so that whenever first UDP byte is read, MAC read pointer will be reset to begining of correct packet. This change fixes problem where if one transmits a packet while UDP packet is pending in a socket, next get to pending UDP socket would return wrong data. (This is apparent only when there is heavy network traffic)
Known Issues:
1. HiTech v8.20 PL4 with all optimization enabled may not work properly.
2. C18 "Static" and "Auto" mode may not be used - there are too many local variables to fit in standard stack of 256 bytes. One may modify linker script file to avoid this limitation.
Improvements:
1. Modified TICK def. in Tick.h to unsigned long to support 32-bit wide SNMP tick.
2. Added SNMP Module (SNMP.c ( see page 454))
3. Added Two new demo projects - DemoSNMPApp and HtDemoSNMPApp.
4. Created MPLAB 6.X projects for different demo configurations.
5. MAC.c - Added MACGetTxOffset().
6. MPFS.c - Added MPFSSeek ( see page 288)(), MPFSTell ( see page 293)().
7. MPFSImg.*- Rebuilt to reflect v2.20, footprint changes etc.
8. StackTsk.h- Enhanced WORD_VAL, DWORD_VAL defs. Added STACK_USE_SNMP and related compile-time checks.
file.
10. WebSrvr.c- Modifed MCHPStack version message and added DATE info to BoardSetup menu.
11. Added support for SMSC LAN91C111 10/100 Non-PCI ethernet controller Use "SMSC91C111.C" instead of MAC.c.
"mpnicee_smsc" is a sample project that uses PIC18F8720 and SMSC NIC. "MasterDemo.c" is a main source file for above project that includes all modules - must use device with more than 32KB of memory.
******
v2.11:
******
Bug Fixes:
1. Fixed dhcp.c to make it work with new C18 startup code.
Improvements:
56
3 Microchip TCP/IP Stack Help
1. Modified websrvr.c DownloadMPFS() to make use of compiler allocated XMODEM data block rather than use fixed address block starting at 0x400.
******
v2.10: 7/9/02
******
Bug Fixes:
1. Fixed HTTP Server bug where a form submission with empty parameter value would not parse correctly.
******
v2.0: 5/22/02
******
******
New Modules:
******
1. Added UDP, DHCP, FTP and IP Gleaning
2. Added PICDEM.net LCD support
3. Added board setup through RS-232.
******
Improvements:
******
1. Optimized serial EEPROM access routines in terms of speed and size (Replaced ee256.* files with eeprom*.h)
2. Improved board setup through RS-232.
******
Known Issues:
******
1. LCD may not display properly on MCLR only. Workaround: 1. Debug XLCDInit() routine in "xlcdlh"
2. Always do POR reset.
2. SLIP connection is not very robust. Workaround: None at this time.
3. Hi-Tech Compiler:
1. Aggressive optimization breaks the functionality. Workaround: Apply optimization listed in each source file comment
57
3 Microchip TCP/IP Stack Help header.
2. In order to use V8.12, you will need to remove "FTP Server" from
Ht*.pjt. You will also need to disable all optimizations.
4. C18 Compler: 1. Static model does not compile. Workaround: None at this time.
2. Overlay model breaks the functionality. Workaround: None at this time.
3. All modules does not fit in 32KB memory. Workaround: 1. None at this time.
2. Sample project disables some modules.
******
New Files:
******
========================================================================================
==================================== File Purpose
========================================================================================
====================================
1. delay.* Provides CLOCK_FREQ depenent delay routines.
2. dhcp.* DHCP client support
3. ftp.* FTP server
4. udp.* UDP socket support
5. xeeprom.* Improved ee256.* and renamed.
6. xlcd.* External LCD support.
7. version.log To track changes and history.
******
Changes:
******
========================================================================================
==================================== File Change To-do for v1.0
stack applications
========================================================================================
====================================
1. arptsk.c 1. Fixed STACK_CLIENT_MODE compile errors.
None
2. Modifed ARPIsResolved ( see page 164)() to support IP Gleaning
None
2. c18cfg.asm 1. Added PIC18F452 configuration
None
2. Fixed "include" errors.
None
58
3 Microchip TCP/IP Stack Help
3. compiler.h 1. Included "stdlib.h" in both C18 and Hi-Tech compilers.
None
2. Moved CLOCK_FREQ from "stacktsk.h" to this file.
None
3. Added PORTA defs.
None
4. htnicee.pjt 1. Removed "ee256.c".
None
2. Added "udp.c", "dhcp.c", "ftp.c", "xlcd.c", "xeeprom.c" files
Add these files if needed.
5. htnicpg.pjt None
6. htslee.pjt 1. Removed "ee256.c".
None
2. Added "ftp.c", "xlcd.c", "xeeprom.c" files
None
7. http.c 1. Included compile-time verification that HTTP module is included.
None
2. Put HTTP message strings into one array "HTTPMessages".
None
3. Modified to return "Service Unavailable" message if MPFS is being
None remotely programmed.
4. Modified SendFile() to make use of sequential EEPROM read.
None
8. ip.c 1. Added one more paramter to IPGetHeader() to support IP Gleaning
Custom apps using IP needs to be modified.
9. mac.c 1. Replaced fixed delay routines with CLOCK_FREQ dependent
None routines
10. mpfs.c 1. Replaced ee256.h with xeeprom.h.
None
2. Added MPFSFormat ( see page 279)(), MPFSPut() etc. routines
59
3 Microchip TCP/IP Stack Help
None
3. Added sequential read and page write operations
Custom apps using MPFS directly needs to be modified.
4. Defined MPFS_WRITE_PAGE_SIZE ( see page 292) for MPFSPut operations.
Apps using different EEPROM page size needs to be modified.
11. mpnicee.pjt 1. Removed "ee256.c"
None
2. Added "xcld.c", "xeeprom.c" files
None
12. stacktsk.c 1. Replaced ee256.h with xeeprom.h
None
2. Added IP Gleaning and DHCP support.
None
13. stacktsk.h 1. Moved CLOCK_FREQ to compiler.h
None
2. Added STACK_USE_DHCP, STACK_USE_FTP_SERVER etc. options
None
3. Added compile-time enable/disable of modules based on selection of higher level modules.
None
4. Modified MY_DEFAULT_MAC_BYTE? to use Microchip OUI id.
None
5. Added compiler-time check to confirm available TCP sockets
None
6. Added MSB and LSB macros.
None
7. Added SerialNumber etc. to AppConfig structure
None
8. Commented module selection defines: They are defined by cmopiler
None command-line options. Real application should define them here in this file.
14. tcp.c 1. Moved TCP_STATE ( see page 558) and TCP_INFO to .h file.
None
2. Fixed TCPIsConnected ( see page 545)()
None
60
3.2 Memory Usage Microchip TCP/IP Stack Help
3. Fixed TCPDisconnect ( see page 538)()
None
4. Modified TransmitTCP() to set receive window of one segment
None
5. Modified TransmitTCP() to use max segment size equal to predefined value.
None
6. Improved TCP State machine
None
15. tick.c 1. Modified TICK type to 16-bit.
None
2. Made use of TICK_PRESCALE_VALUE
None
3. Added code to blink PICDEM.net "System LED"
Remove if not required.
16. websrvr.c 1. Added LCD support
N/A
2. Made TickUpdate ( see page 611)() on Timer0 interrupt
N/A
3. Added code to save/restore board configuration
N/A
4. Added board setup via RS-232.
N/A
5. Added call to FTP modules
If needed, add this.
3.1
Stack Performance
Note that this table will not appear in the PDF version of the help file; see the "TCPIP Stack Performance.htm" file in the
TCPIP documentation folder in the Microchip Application Library help folder.
3.2
Memory Usage
These tables contain the PIC program and data memory requirements for the TCP/IP stack. The first two rows list the
memory required to implement specific modules. These values are approximations; the program memory size may increase depending on application code, or decrease based on optimizations of modules with overlapping code. Modules that require user-implemented API functions (SNMP, HTTP) are tested without additional code. The global data memory column includes
61
3.3 Peripheral Usage Microchip TCP/IP Stack Help
The C18 code uses the PIC18F97J60 family Ethernet controller as the MAC/PHY chip; the C30 and C32 measurements are made using the ENC28J60 Ethernet controller (ENCX24J600 sizes are similar). All compilers include a separate Required
Stack Code line for Wi-Fi applications using the MRF24WB0M as the network controller. These two Required Stack Code lines are mutually exclusive -- do not add them together. Instead, chose the line representing your network controller.
These values are approximations obtained from TCP/IP Stack version 5.31. Note that these tables will not appear in the PDF version of the help file; see the "TCPIP Cxx Memory Usage.htm" files in the TCPIP documentation folder in the Microchip
Application Library help folder.
C18
C30
C32
3.3
Peripheral Usage
Several microcontroller peripherals can/must be used to implement a TCP/IP stack application.
Type Specific/Configurable
Timer Timer 0 for PIC18, Timer 1 otherwise
SPI or
PMP
Select via #define in HardwareProfile.h.
See Hardware Configuration ( see page 147).
SPI Select via #define in HardwareProfile.h.
See External Storage ( see page 147).
SPI Select via #define in HardwareProfile.h.
See External Storage ( see page 147).
Polled/Interrupt Purpose
Interrupt.
Used to implement a tick timer
Polled.
Polled.
Polled.
The SPI module is used to drive the ENC28J60 or
MRF24WB0M / MRF24WG0M. An ENCX24J600 can be driven by the SPI module or a PMP module.
Used to interface to an EEPROM or Serial Flash chip,
as an option to store web pages for MPFS/MPFS2 (
see page 276) or the AppConfig ( see page 143)
structure.
Used to interface to a serial RAM as a optional socket
( see page 157) allocation method.
62
Microchip TCP/IP Stack Help 4
4
Silicon Solutions
One of the first choices to make when designing your application is which hardware layer to use. Microchip supports a number of hardware TCP/IP solutions, each with an integrated MAC and/or PHY. The ENC28J60 and ENCX24J600 are stand-alone Ethernet controller chips, developed by Microchip Technology. The MRF24WB0M / MRF24WG0M is a stand-alone 802.11b/g wireless transceiver. The PIC18F97J60 is a PIC18 microcontroller with an integrated Ethernet peripheral. The PIC32MX7XX/6XX series of 32-bit microcontrollers are high performance devices with integrated Ethernet
MAC peripheral (MII/RMII interface to external PHY).
Feature ENC28J60 ENCX24J600 PIC18F97J60 MRF24WB0M
/
MRF24WG0M
PIC32MX7XX/6XX
Technology
MAC
PHY
Wired Ethernet
Internal
Internal
(10-Base-T)
Wired Ethernet
Internal
Internal
(10/100-Base-T)
24,576
Wired Ethernet 802.11b/g
Wireless
Internal
Internal
(10-Base-T)
Internal
Internal
Wired Ethernet
Internal
External PHY (MII/RMII
Interface)
RAM
(bytes)
Interface
Pins
Package
Buffer 8,192 3,808
No
(1)
14,170 Configurable descriptors in
Internal RAM (128k of
Internal RAM)
None (built-in Ethernet MAC) SPI
28
SPI, 8 or 16 bit multiplexed demultiplexed
or parallel interface
None (built-in
Ethernet
MAC/PHY)
SPI
44, 64 64/80/100
TQFP SOIC, SPDIP,
SSOP, QFN
(6x6 mm)
TQFP, QFN
Yes No
36 64/100/121
Surface
Mount WiFi
I/O module
TQFP, QFN (9x9 mm), BGA
No No Cryptographic
Engines
Pre-programmed
MAC address
No
No
(1)
Yes Yes Yes
1: For devices without a pre-programmed MAC address, you may consider using an EEPROM with a built-in MAC address, such as the
device family described here ( see page 152).
63
Microchip TCP/IP Stack Help 5.2 MPFS2 Utility
5
Software
This section will discuss the computer software applications included with Microchip's TCP/IP Stack.
These tools are implemented using the C# or Java programming languages, or both. The C# tools (*.exe) will require the
Microsoft® .NET Framework v2.0 to be installed on the local PC. The Java tools (*.jar) require Java Runtime Environment
(JRE) 1.6 or later to be installed on the target computer.
5.1
TCP/IP Configuration Wizard
The TCP/IP Configuration Wizard is the easiest, safest way to set up firmware (and some hardware) configuration options. It will read and parse configuration settings from a copy of
TCPIPConfig.h
and then provide a graphical user interface that will easily allow you to view and modify those settings. In addition, if a feature that you enable will require another resource or feature to operate, the additional features will be enabled automatically. The TCP/IP Configuration Wizard will be installed to the Start menu when the TCP/IP Stack is installed.
When you launch the configuration wizard, you will be prompted to enter the path to a copy of
TCPIPConfig.h
and given the opportunity to modify advanced configuration settings. The advanced setting option will give more precise control over stack features, but will also require a greater working knowledge of Microchip's TCP/IP Stack.
5.2
MPFS2 Utility
The MPFS2 Utility packages web pages into a format for efficient storage in an embedded system. It is a graphical application for PCs that can generate MPFS2 images for storage in external storage or internal Flash program memory.
When used to build MPFS2 images, the MPFS2 Utility also indexes the dynamic variables found. It uses this information to generate
HTTPPrint.h
, which ensures that the proper callback functions are invoked as necessary. It also stores this index information along with the file in the MPFS2 image, which alleviates the task of searching from the embedded device.
Finally, when developing an application that uses external storage, the MPFS2 Utility can upload images to the external
64
5.2 MPFS2 Utility Microchip TCP/IP Stack Help Uploading Pre-built MPFS2 Images storage device using the upload functionality built into the HTTP2 web server or FTP server.
The source code for this application is included in the Microchip Applications Libraries installer.
5.2.1
Building MPFS2 Images
The MPFS2 Utility has four steps, which are denoted on the left hand side of the dialog. To build an MPFS image, select
Start With: Webpage Directory in step 1 and choose the directory in which the web pages are stored.
Step 2 selects the output format. If storing the web pages in external EEPROM or serial Flash, choose the BIN Image output format. If internal program memory will be used, select C18/C32 Image for use with 8-bit and 32-bit parts, or ASM30 Array for 16-bit targets. To store the web pages on a device formatted with the FAT file system without compressing them into an
MPFS image, select MDD (see the Demo App MDD Getting Started guide for more information).
Step 3 asks for the MPLAB IDE project directory. The MPFS tool will write the image file to the project directory, and will also update the
HTTPPrint.h
file there if needed. Select the correct directory so that the right files are modified.
Step 4 controls the upload settings. When external EEPROM or serial flash is used for storage, the option to upload the newly created image to the board is available. Check the box next to Upload Image To to enable this feature. The target host name (or IP address), upload protocol, and upload path may need to be changed to the one chosen when the board was first configured. You may also need to modify the user name and password used to access the secured functionality in your application, like web page upload. Use the Settings button to edit these values.
If internal program memory is being used, the image will be compiled in with the project and so direct uploads are not available. Make sure to include the output source file indicated in step 3 as part of the project.
Once all the correct settings have been chosen, click the Generate button to create the image. If uploads are enabled, this will also attempt to upload the file to the device.
5.2.2
Uploading Pre-built MPFS2 Images
You can select HTTP or FTP uploading to match the protocol that your application uses.
To use the MPFS2 Utility to upload an image, begin by selecting Start With: Pre-Build MPFS Image in step 1 at the top.
65
5.2 MPFS2 Utility
Choose the image file to upload.
Microchip TCP/IP Stack Help MPFS2 Command Line Options
Steps 2 and 3 are not required for pre-built images. Proceed directly to step 4 and verify that the upload settings are correct.
The target host name (or IP address), upload protocol, and upload path may need to be changed to the one chosen when the board was first configured. You may also need to modify the user name and password used to access the secured functionality in your application, like web page upload. Use the Settings button to edit these values.
Once all the settings are correct, click the Upload button. The image will be uploaded to the board.
5.2.3
Advanced MPFS2 Settings
The Advanced Settings dialog found in step 2 provides greater control over how files are processed.
The Dynamic Files list indicates which file types to parse for dynamic variables. By default, all files with the extensions htm, html, cgi, or xml are parsed. If an application has dynamic variables in other file types, these types must be added to the list.
This field must be a comma-separated list of extensions and file names.
The Do Not Compress field indicates which file types should never be compressed. Compressing files with GZIP saves both storage space and transmission time. However, this is only suitable for static content such as CSS or JavaScript. Any files with dynamic variables will automatically be excluded. In addition, any file that the PIC may need to process internally should be excluded. Files included via ~inc:filename~ should not be compressed, nor should any BIB file used for the SNMP module (if present). Additional file types can be added to this list if a custom application will be accessing the MPFS.
The GZIP compressor will attempt to shrink all files. In some cases, especially with images, little or no compression is achieved. When this occurs the file is stored as-is in the MPFS image.
5.2.4
MPFS2 Command Line Options
To facilitate batch files and automation, the MPFS2 Utility also supports execution from the command line. The syntax is as follows:
MPFS2.jar [options] <SourceDir> <ProjectDir> <OutputFile>
The SourceDir, ProjectDir, and OutputFile options are required and should be enclosed in quotation marks. The
OutputFile option will be relative to ProjectDir, and cannot be a full path name.
The various option switches are described in the table below:
66
5.4 Microchip TCP/IP Discoverer Microchip TCP/IP Stack Help
Switch
/BIN
/C18_C32
/ASM16
/mpfs2
/html "..."
/xgzip "..."
Short
/b
/c
/s
/2
/h "..."
/z "..."
Description
Output a BIN image (Default)
Output a C18 or XC32 image
Output an ASM16 image
Use the MPFS2 format (Default)
File types to be parsed for dynamic variables (Default: "*.htm, *.html, *.cgi, *.xml")
File types to be excluded from GZIP compression (Default: "*.bib, *.inc")
The command-line interface does not support image uploads. For batch or production uploads, use a tool such as wget
to upload the generated BIN image.
5.3
Hash Table Filter Entry Calculator
This Hash Table receive filter on the ENC28J60, ENCX24J600, and PIC18F97J60 microcontroller family performs a CRC calculation over the six destination address bytes in a received packet, then uses that value as a pointer into the
EHT0-EHT7 registers. If the bit that the pointer points to is set, the packet will be received. The Microchip Hash Table Filter
Entry Calculator will determine the bit that must be set in this register bank for a given destination address. If you have a fixed MAC address, known at design time, you can set up your Hash Table receive filter in your code using the value obtained from this tool; otherwise, you must use the
SetRXHashTableEntry()
function to set it during runtime. To use this tool, specify the address of your device, click calculate, and the CRC value and the corresponding bit will be displayed in the output box.
5.4
Microchip TCP/IP Discoverer
The Microchip TCP/IP Discoverer PC project (fomerly known as the Embedded Ethernet Device Discoverer) will aid in
applications to communicate to embedded devices.
When the "Discover Devices" button is clicked, this application will transmit a broadcast UDP packet containing the
name (NBNS ( see page 295)) and MAC address.
The Java source code for this application is also included. This source code should provide a rough idea of how to write a
PC-based application to communicate with your embedded devices.
67
5.4 Microchip TCP/IP Discoverer Microchip TCP/IP Stack Help
68
Daughter Boards Microchip TCP/IP Stack Help 6.1 Hardware Setup
6
Getting Started
This section describes the steps necessary to begin using Microchip's TCP/IP Demo Applications. This section contains
can be applied to get started with other demo applications as well.
6.1
Hardware Setup
The first step to use the stack is to make sure an appropriate development board is configured. To get started, select a platform from the topics presented below.
6.1.1
Daughter Boards
Microchip offers four daughter boards that provide different Ethernet functionality to available demo boards. Each board is designed with:
and/or
Note that the PICDEM.net 2 is populated by default with an ENC28J60 and a PIC18F97J60.
Ethernet PICtail Daughter Board
The Ethernet PICtail Daughter board is populated with an ENC28J60, an RJ-45 connector (with integrated magnetics), and the few other components required for Ethernet operation. It provides a 10-Base-T Ethernet connection for any demo board
debugging Ethernet applications using the PIC18. Visit the Microchip web site to view the Ethernet PICtail Product Page .
Ethernet PICtail Plus Daughter Board
The Ethernet PICtail Plus Daughter Board is the PICtail Plus version of the Ethernet PICtail Daughter Board. It allows the
69
6.1 Hardware Setup Microchip TCP/IP Stack Help PICDEM.net 2 interface of an ENC28J60 to any demo board with a PICtail Plus connector. Visit the Microchip web site to view the Ethernet
PICtail Plus Daughter Board Product Page .
Fast 100Mbps Ethernet PICtail Plus Daughter Board
The Fast 100Mbps Ethernet PICtail Plus Daughter Board provides a method for testing and demonstrating the ENC624J600
Ethernet Controller. The board is designed for flexibility and can be connected to a PICtail or a PICtail plus connector. In addition, it is designed to allow the use of any of the parallel or SPI connection modes featured on the ENC624J600 on the
PICtail Plus connector. This daughter board provides 10/100-Base-T functionality. Visit the Microchip web site to view the
Fast 100Mbps Ethernet PICtail
TM
Plus Daughter Board Product Page .
Microchip 802.11b/g WiFi PICtail Plus Daughter Board
The Microchip 802.11b/g WiFi PICtail Plus Daughter Board is a demonstration board for evaluating Wi-Fi connectivity on boards with a PICtail or a PICtail Plus connector. The board features the Microchip MRF24WB0MA (802.11b: 1 to 2Mbps) or
MRF24WG0MA (802.11b/g) module, which includes a Wi-Fi transceiver and associated circuit elements.
MRF24WB0MA supports both infrastructure and adhoc network types. MRF24WG0MA supports more extensive features covering infrastructure, adhoc, Wi-Fi Direct (peer-to-peer) and softAP network types. In addition, MRF24WG0MA supports
Wi-Fi Protected Setup (WPS).
Visit the Microchip Web Site to view more information on Wireless Solutions and the 802.11b/g WiFi PICtail Product Page ..
6.1.2
PICDEM.net 2
Visit the Microchip web site to view the PICDEM.net 2 Product Page .
The PICDEM.net 2 development board comes populated with a PIC18F97J60 with an integrated Ethernet controller, as well as a standalone ENC28J60 Ethernet controller. The integrated controller is connected to the left Ethernet jack (closest to the
LCD), and the standalone part is connected to the right one. By default the stack is configured to use the integrated controller, so the left port should be connected to the network cable. No other configuration of the board is necessary.
The User's Guide that shipped with this development board may refer to an older version of the TCP/IP Stack. This document updates much of that documentation for version 5.42.04.
70
6.1 Hardware Setup Microchip TCP/IP Stack Help PICDEM.net 2
Using the Fast Ethernet PICtail
By default, this board will use the ENC28J60 or the PIC18F97J60 for Ethernet communication. However, by connecting the
Fast Ethernet PICtail to the PICtail connector on the board, you can use it to test the ENC624J600. To use the Fast Ethernet
PICtail, insert it as shown in the picture, with header J4 on the PICtail inserted into connector J5 on the demo board.
The Fast Ethernet PICtail is designed to use the SPI communication bus when connected through a PICtail header, so the jumper settings are unused in this configuration, with one exception: the JP2 jumper on the PICtail, labeled ISENSE, should be shorted. The pre-compiled and pre-configured versions of the demo that correspond to this setup are already written to
configuration page.
Using the Microchip MRF24WB0MA / MRF24WG0MA 802.11b/g WiFi PICtail
The PICDEM.net 2 can be used to debug wireless functionality by connecting the PICtail as show in the picture, with header
J1 on the PICtail inserted into connector J5 on the demo board.
Note if jumper JP3 exists, it must be shorted between pins 2 and 3 when used on this development platform.
71
6.1 Hardware Setup Microchip TCP/IP Stack Help PIC18 Explorer
application.
6.1.3
PIC18 Explorer
Visit the Microchip web site to view the PIC18 Explorer Product Page .
The PIC18 Explorer is for evaluation of high pin-count PIC18 microcontrollers. By connecting a TCP/IP daughter board to it, you can test and debug Ethernet functionality with a variety of PIC18s. The PIC18F97J60 family includes a built-in Ethernet
recommended development board for this part.
When using the PIC18 Explorer, ensure that jumpers JP2 and JP3 are shorted to enable the LCD and EEPROM, and switch
S4 is configured to properly select the on-board PIC or the ICE setting, as your application requires.
Using the Ethernet PICtail
Unlike the PICDEM.net 2, the PIC18 Explorer does not include an ENC28J60 on the board. To enable testing and
header J2 into connector J3 on the demo board).
When using this configuration, short pins 2 and 3 on jumper J9, to indicate that the PIC18 Explorer is providing a 5V power
72
6.1 Hardware Setup Microchip TCP/IP Stack Help Explorer 16 and PIC32 Starter Kit supply. The pre-compiled and pre-configured versions of the demo that correspond to this setup are already written to
page.
Using the Fast Ethernet PICtail
By connecting the Fast Ethernet PICtail to the PICtail connector on the board, you can use it to test the ENC624J600. To use the Fast Ethernet PICtail, insert it as shown in the picture, with header J4 on the PICtail inserted into connector J3 on the demo board.
The Fast Ethernet PICtail is designed to use the SPI communication bus when connected through a PICtail header, so the jumper settings are unused in this configuration, with one exception: the JP2 jumper on the PICtail, labeled ISENSE, should be shorted. The pre-compiled and pre-configured versions of the demo that correspond to this setup are already written to
configuration page.
Using the Microchip MRF24WB0MA / MRF24WG0MA 802.11b/g WiFi PICtail
The PIC18 Explorer can be used to debug wireless functionality by connecting the PICtail as show in the picture, with header
J1 on the PICtail inserted into connector J3 on the demo board.
Note if jumper JP3 exists, it must be shorted between pins 2 and 3 when used on this development platform.
application.
6.1.4
Explorer 16 and PIC32 Starter Kit
Visit the Microchip web site to view the Explorer 16 Product Page and the PIC32 Starter Kit Product Page .
The Explorer 16 board is an all-purpose demonstration and development board for 16-bit and 32-bit parts. It can be expanded for TCP/IP support using the Ethernet PICtail Plus, Fast 100Mbps Ethernet PICtail Plus, or 802.11b WiFi PICtail
Plus daughter board.
Before using the Explorer 16, check that:
73
6.1 Hardware Setup Microchip TCP/IP Stack Help Explorer 16 and PIC32 Starter Kit
1. Switch S2 selects PIM
2. Jumper J7 selects PIC24 (even though the label reads PIC24, this jumper setting selects the programming signals to any
PIC on the Explorer 16).
The PIC32 Starter Kit performs a similar function for 32-bit PIC32 parts. By using the PIC32 I/O Expansion Board you can
connect ( see page 176) the same PICtail Plus board that connect ( see page 176) to the Explorer 16.
Using the Ethernet PICtail Plus
Plus, as shown in the picture (insert header J2 into the upper card-edge connector J5 (Explorer 16) or J4 (I/O Expansion
Board)). Note that for some demos, the Ethernet PICtail Plus will need to be inserted into the center card-edge connector of
74
6.1 Hardware Setup Microchip TCP/IP Stack Help Explorer 16 and PIC32 Starter Kit
The pre-compiled and pre-configured versions of the demo that correspond to this setup are already written to enable
Using the Fast Ethernet PICtail Plus
By connecting the Fast 10/100 Ethernet PICtail Plus to the PICtail Plus connector on your board, you can use it to test the
ENC624J600. The Fast Ethernet PICtail Plus can be used with these boards in either serial (SPI) or parallel communication
Expansion Board), as seen in the pictures. When operating in serial mode, the jumpers on the Fast Ethernet PICtail are unused, with one exception: the JP2 jumper on the PICtail, labeled ISENSE, should be shorted.
To use the Fast Ethernet PICtail Plus board in parallel mode, insert header J1 into connector J5 of the Explorer 16 or J4 of the I/O Expansion Board, as seen in the pictures. In this configuration, the jumpers must be shorted or opened corresponding to the parallel communication mode being used. A matrix outlining which jumper connections must be made for the jumpers labeled
PSPCFG3
,
PSPCFG2
,
PSPCFG1&4
,
PMA to AD
, and
PMA to A
is printed on the back side of the daughter board.
The pre-compiled and pre-configured versions of the demo that correspond to this setup are already written to enable
Using the Microchip MRF24WB0MA / MRF24WG0MA 802.11b/g WiFi PICtail
The Explorer 16 and PIC32 Starter Kit can be used to debug wireless functionality by connecting the PICtail as show in the pictures, with header J2 on the PICtail inserted into the top slot of connector J5 (Explorer 16) or J4 (I/O Expansion Board) on the demo boards.
75
6.2 Programming and First Run Microchip TCP/IP Stack Help
Note if jumper JP3 exists, it must be shorted between pins 1 and 2 when used on this development platform.
application.
6.1.5
PIC24FJ256DA210 Dev Board
Visit the Microchip web site to view the PIC24FJ256DA210 Development Kit Product Page .
The PIC24FJ256DA210 Development Kit is a low cost and efficient development kit to evaluate the features and performance of the PIC24FJ256DA210 with integrated graphics, mTouch™ and USB.
You can add network connectivity to this demo board by inserting an Ethernet PICtail Plus, Fast Ethernet PICtail Plus, or
Microchip MRF24WB0MA / MRF24WG0MA 802.11b/g WiFi PICtail into the PICtail Plus connector on the demo board. The
6.2
Programming and First Run
Project Setup
Open a session of the MPLAB IDE.
1. From the "File" menu, select "Import." Browse to the Precompiled Hex subdirectory in your demo project directory and select the *.hex file that matches your hardware setup. The hex file names describe the hardware that the file has been compiled for. For example, the file " Microchip Solutions v2011-06-02\TCPIP\Demo App\Precompiled
Hex\C18-PICDN2_ETH97 18F97J60.hex"
corresponds to the generic TCP/IP Demo application for the PIC18F97J60 on the PICDEM.net 2, using the PIC's internal Ethernet module. A document enumerating the abbreviations used in the hex file and project file names is available in the Microchip Solutions v20xx-xx-xx/Help directory.
2. Verify that the MPLAB IDE processor target selection and linker script (if one is present) match the part on your demonstration board (ex: PIC18F97J60).
Note that the projects and source code used to build each hex file are present in the project directory. The hardware and firmware configuration files used to build each project are included in the Configs subdirectory.
Programming
Select your device programmer from the Programmer menu in MPLAB, and then use the Program shortcut button or the
Program menu option to program the code you imported to your board.
Clearing the EEPROM
The TCP/IP Stack stores network configuration settings (such as the host name, MAC address, default static IP addresses,
76
6.3 Configure your WiFi Access Point Microchip TCP/IP Stack Help
SNMP strings, WiFi network name (SSID), etc) in external EEPROM on the board. The demo project will detect if the default values have been changed in the EEPROM, and if so, use the new values. If not, the demo will use the default values configured in TCPIPConfig.h and WF_Config.h. Checksums stored in the EEPROM are used to determine if the structures stored in EEPROM are valid. Manually clearing the EEPROM will allow the demo to resume using the default settings.
Use the following procedure to clear the EEPROM:
1. Make sure the development board is programmed and not in debug mode
2. Disconnect the MPLAB® ICD 2/3 or MPLAB REAL ICE
TM
from the board
3. Press and hold BUTTON0 (RD13/S4 on Explorer 16 or RB3/S5 on PICDEM.net
TM
2)
4. Press and release the MCLR button
5. Continue holding BUTTON0 until several LEDs flash indicating that EEPROM has been cleared. This takes about 4 seconds.
6. Release BUTTON0
7. Press and release MCLR again to reset the software
Once you see LED0 (right-most LED) blinking, the software is running and ready for use.
6.3
Configure your WiFi Access Point
To run the Wi-Fi demos with the MRF24WB0M / MRF24WG0M PICtail, you'll also need to setup a wireless access point. As an example, this guide will walk through the setup of a Linksys WRT54G2 access point.
Access Point Browser GUI
The Linksys, along with many other popular router brands, uses a built-in webserver on the router to administer the network
(both wired and wireless). Please consult the documentation that came with your router for more information on configuration
access to this web page, you'll need to point your browser to http://192.168.1.1. By default, the username field is left blank, and the password is admin.
77
6.4 Connecting to the Network Microchip TCP/IP Stack Help
Wireless Setup
Along the top of the webpage, there should be many tabs for all the different features of the access point. One of the tabs should read "Wireless". After clicking the tab, you will be presented with the Wi-Fi protected setup page. You'll need to click the manual tab to be able to enter your own wireless settings to match the demo.
The out of box demo is looking for an AP with the following parameters (note that the SSID is case sensitive):
SSID
Security
Channel
MicrochipDemoAP
None
Either 1, 6, or 11
You should have settings similar to the following:
Once the network is setup, you can connect your device to the network ( see page 78).
6.4
Connecting to the Network
78
6.5 Uploading Web Pages Microchip TCP/IP Stack Help
Protocol) allows this assignment to take place automatically (for more address information and configuration options, see the
Addresses ( see page 152) topic).
the board can be connected directly using any standard straight-through Ethernet cable. Under this configuration, the board will attempt to obtain an IP address from your network's DHCP server.
PC's Ethernet port. Using this configuration, the board will act as its own DHCP server and will assign a single IP address to the computer. (The Fast 100Mbps Ethernet PICtail Plus and some newer PCs do not require a special crossover cable, so any Ethernet cable can be used.)
Connect the development board to the network and wait for the link LED on the Ethernet jack to light up. The board is now on the network and capable of communicating with other devices.
If the link LED on the Ethernet jack does not light, your board cannot link to the network. Ensure that you have selected the proper cable, and try switching from a straight-through to a crossover cable, or vice versa.
Now that the board is online, you can Upload the Demo Web Pages ( see page 79).
6.5
Uploading Web Pages
example, the EEPROM chip ( 25LC256 ) on your demo board will be programmed with a pre-built MPFS2 BIN image. This location can be changed via a compile-time option in TCPIPConfig.h.
The target application on the development board must be running for this procedure to work. Make sure the right most status
LED is blinking.
Each hex file is configured to provide a Host Name for your development board. This will be the name by which your board is accessed. In the default hex files, the host name is mchpboard , so your board can be accessed at http://mchpboard. This
accessible from the Internet. Note that this service is not supported by all operating systems. If you have difficulty accessing your board, try using the IP address shown on the LCD screen instead (e.g. access the board at http://192.168.1.101). You
can also determine the IP address by using the Microchip TCP/IP Discoverer ( see page 67).
Open a web browser and access the board at http://mchpboard/mpfsupload
. This form will allow web pages stored on the device to be updated. If you mistype this URL, the board will provide a default HTTP 404 error page with a link to the
MPFS Upload page. This default 404 page will not appear if you've configured your browser to override custom error pages
(e.g. by checking "Show friendly HTTP error messages" in Internet Explorer 7's internet options menu). Select the file
MPFSImg2.bin
from the
TCPIP\Demo App
folder as shown below.
This update method is only available when using external storage.
79
6.6 Accessing the Demo Application Microchip TCP/IP Stack Help
When the Upload button is clicked, the MPFS image is sent to the board and programmed into the EEPROM. As this happens, the activity LED on the Ethernet jack will blink. Once the browser reports that the upload has completed, click the link provided within the status message to access the board's web pages.
You can now Access the Demo Application ( see page 80).
6.6
Accessing the Demo Application
The board is now accessible at the mchpboard
host name or at the board's IP address. When accessed in a web browser, a real-time update of the board's controls is displayed. The demo application will show off several features, and will explain how to modify the web pages and application to suit various needs.
If you attempt to access the Network Configuration or SNMP Configuration web pages from the red menu on the left, you will be prompted for a username and password. The default username is "admin" and the default password is "microchip". More
80
6.7 Configuring WiFi Security Microchip TCP/IP Stack Help
Some features of the default demo application may not be available on certain hardware platforms. For more information,
more about the stack and start developing your own application.
6.7
Configuring WiFi Security
enabled. Both MRF24WB0M / MRF24WG0M supports WEP (40-bit and 104-bit), as well as WPA (TKIP) and WPA2
(TKIP/AES). In addition, MRF24WG0M supports Wi-Fi Protected Setup (WPS) both Push Button Configuration (WPS-PBC) and Personal Information Number (WPS-PIN). MRF24WG0M also supports WPA2 Enterprise (EAP-PEAP/ EAP-TTLS), requiring special approval from Microchip.
Device Security Modes
Security settings for the MRF24WB0M / MRF24WG0M are located in the file
WF_Config.h
. To enable security features the
#define preprocessor definition for MY_DEFAULT_WIFI_SECURITY_MODE must be defined as one of the following options:
WF_SECURITY_WEP_40
WF_SECURITY_WEP_104 104-bit WEP security. This equates to 13 ASCII characters or 26 hex digits.
MY_DEFAULT_WEP_KEYS_104
contains up to four keys that can be programmed (default is key 0).
WF_SECURITY_WPA_WITH_KEY
WF_SECURITY_WPA2_WITH_KEY
WF_SECURITY_WPA_AUTO_WITH_KEY
Uses the 32 bytes in
MY_DEFAULT_PSK
as the key to join the network.
These values are generated from a hash of the SSID name and WPA passphrase. For the purpose of the demo, the 32-bytes in
MY_DEFAULT_PSK
in
WF_Config.h
correspond to an SSID of
"MicrochipDemoAP" and passphrase "Microchip 802.11 Secret PSK
Password".
WF_SECURITY_WPA_WITH_PASS_PHRASE
WF_SECURITY_WPA2_WITH_PASS_PHRASE
WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE
Instructs the MRF24WB0M / MRF24WG0M to generate the 32 byte
PSK using the SSID and passphrase. The default in
WF_Config.h
corresponds to an SSID of "MicrochipDemoAP" and passphrase
"Microchip 802.11 Secret PSK Password". Note that it takes approximately 30 seconds for the MRF24WB0M / MRF24WG0M to calculate this value
[1]
.
WF_SECURITY_WPS_PUSH_BUTTON
WF_SECURITY_WPS_PIN
Supported by MRF24WG0M only.
For WPS-PBC, define the MY_DEFAULT_SSID_NAME as “”.
For WPS-PIN, define the MY_DEFAULT_WPS_PIN to be the same as the AP/router PIN, for example, 12390212 and define the
MY_DEFAULT_SSID_NAME to be the same as the AP or router’s
SSID.
WF_SECURITY_WPA2_ENTERPRISE
40-bit WEP security. This equates to 5 ASCII characters or 10 hex digits. MY_DEFAULT_WEP_KEYS_40 contains up to four keys that can be programmed (default is key 0).
Supported by MRF24WG0M only. Requires MLA v5.42.06 March 2013 release and future releases.
EAP-PEAP/MSCHAPv2 and EAP-TTLS/MSCHAPv2.
Special approval needs to be submitted to marketing.
81
6.7 Configuring WiFi Security Microchip TCP/IP Stack Help
Note: Some routers try to increase the random nature of the WEP key by adding an additional layer that will convert an
ASCII passphrase into a hexadecimal key. The MRF24WB0M / MRF24WG0M PICtail will require a hexadecimal key, no matter which way it is generated.
Access Point Security Settings
The access point will also need to be changed to match the same security settings. Wireless security settings can be found in the "Wireless Security" tab under the main "Wireless" tab (example shows a Linksys WRT5G2). The drop-down box for security has all the different security options. Note that for WPA/WPA2, the MRF24WB0M / MRF24WG0M only supports personal security levels (as opposed to enterprise, which is not supported).
[1]: Once the 32-byte PSK is calculated, it can be retrieved by the host from the MRF24WB0M / MRF24WG0M. The host can then save this key to external non-volatile memory. On future connection attempts, the host can program the MRF24WB0M /
MRF24WG0M with the WF_SECURITY_WPA/WPA2/WPA_AUTO_WITH_KEY options, provide the saved key, and not have to wait 30 seconds to reconnect to the network.
Pre-generated PSK
You also have the option to pre-generate the PSK and use the 32-byte PSK directly in the source code. One handy tool to generate the PSK can be found online at the Wireshark Foundation http://www.wireshark.org/tools/wpa-psk.html
. The
Wireshark website can generate the expected 32-byte PSK key with the SSID name and the passphrase. You can then use these values in the variable MY_DEFAULT_PSK in TCPIPConfig.h.
Wi-Fi Protected Setup (WPS)
WiFi Protected Setup (WPS) allows users to set up and expand the WiFi networks with security enabled, even if they are not familiar with the underlying technologies or processes involved. For example, users no longer have to know that SSID refers to the network name or WPA2 refers to the security mechanism. WPS will configure the network name SSID and security key for the AP and WPS client devices on a network. It supports the WEP / WPA / WPA2 security methods.
AP/routers from 2007 onwards will have this WPS feature.
82
6.7 Configuring WiFi Security Microchip TCP/IP Stack Help
83
Microchip TCP/IP Stack Help 7.1 Demo Compatibility Table
7
Demo Information
This section describes Microchip's TCP/IP Demo projects, including information about demo-hardware compatibility. For information about how to load and configure the demos, please consult the Getting Started section.
7.1
Demo Compatibility Table
Each stack demonstration project comes with several predefined, tested configurations. Pre-built hex files for each demo are available in the Precompiled Hex subdirectory in that demo's project folder (i.e. the files for
Demo App
are located in
<install directory>\Microchip Solutions v20xx-xx-xx\TCPIP\Demo App\Precompiled Hex
). This section will specify the combinations of demo boards, processors, MAC/PHY layers, and communication buses that are set up to work by default.
Demo Board
PIC18 Explorer
PIC18 Explorer
PIC18 Explorer
PIC18 Explorer
PIC18 Explorer
PIC18 Explorer
PIC18 Explorer
PIC18 Explorer
PIC18 Explorer
PICDEM.net 2
PICDEM.net 2
PICDEM.net 2
PICDEM.net 2
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Processor
18F87J11
18F87J11
18F87J11
18F87J50
18F87J50
18F87J50
18F8722
18F8722
18F8722
18F97J60
18F97J60
18F97J60
18F97J60
24FJ128GA010
24FJ128GA010
24FJ128GA010
24FJ128GA010
24FJ256GA110
24FJ256GA110
24FJ256GA110
24FJ256GA110
MAC/PHY Layer
ENC28J60
ENCX24J600 SPI
MRF24WB0M MRF24WG0M SPI
ENC28J60
ENCX24J600
SPI
SPI
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENCX24J600 SPI
MRF24WB0M MRF24WG0M SPI
ETH97J60 -
Comm. Bus Notes
SPI Requires silicon revision
A4 later.
or
ENC28J60
ENCX24J600
SPI
SPI
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENCX24J600 SPI
MRF24WB0M MRF24WG0M SPI
ENCX24J600 PSP
Indirect
ENC28J60
ENCX24J600
SPI2
SPI2
ENCX24J600 PSP
Indirect
MRF24WB0M MRF24WG0M SPI2
5
5
84
7.1 Demo Compatibility Table
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
24FJ256GB210
33FJ256GP710
33FJ256GP710
33FJ256GP710
33FJ256GP710
32MX360F512L
33EP512MU810
24EP512GU810
32MX360F512L
32MX360F512L
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
32MX360F512L
32MX360F512L
32MX460F512L
32MX460F512L
32MX460F512L
32MX795F512L
32MX795F512L
32MX795F512L
PIC24FJ256DA210 Development
Board
24FJ256DA210
PIC24FJ256DA210 Development
Board
24FJ256DA210
PIC24FJ256DA210 Development
Board
24FJ256DA210
PIC24FJ256DA210 Development
Board
24FJ256DA210
PIC32 General Purpose Starter Kit
(DM320001)
32MX360F512L
PIC32 General Purpose Starter Kit
(DM320001)
32MX360F512L
PIC32 General Purpose Starter Kit
(DM320001)
32MX360F512L
PIC32 General Purpose Starter Kit
(DM320001)
32MX360F512L
Microchip TCP/IP Stack Help
24FJ256GB110
24FJ256GB110
24FJ256GB110
24FJ256GB110
24FJ256GB210
24FJ256GB210
24FJ256GB210
ENC28J60
ENCX24J600
ENCX24J600
SPI
SPI
PSP
Indirect
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENCX24J600
ENCX24J600
SPI
PSP
Indirect
Bitbang
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENCX24J600 SPI
ENCX24J600 PSP
Indirect
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENC28J60
ENC28J60
ENCX24J600
ENCX24J600
SPI2
SPI2
SPI
PSP
Indirect
ENCX24J600 PSP 9
MRF24WB0M MRF24WG0M SPI
ENC28J60
ENCX24J600
SPI
SPI
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENCX24J600 SPI
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
5
5
5
5
ENCX24J600 SPI
ENCX24J600 PSP
Indirect
Bitbang
MRF24WB0M MRF24WG0M SPI
5
ENC28J60 SPI
ENCX24J600 SPI
ENCX24J600 PSP
Indirect
MRF24WB0M MRF24WG0M SPI
5
85
7.1 Demo Compatibility Table
PIC32 USB
(DM320003_2)
Starter
PIC32 USB (DM320003_2)
PIC32 USB (DM320003_2)
PIC32 USB (DM320003_2)
PIC32 USB (DM320003_2)
PIC32 Ethernet Starter Kit dsPIC33E USB Starter Kit dsPIC33E USB Starter Kit dsPIC33E USB Starter Kit dsPIC33E USB Starter Kit
PIC24E USB Starter Kit
PIC24E USB Starter Kit
PIC24E USB Starter Kit
Kit 32MX795F512L
32MX795F512L
32MX795F512L
32MX795F512L
32MX795F512L
32MX795F512L
33EP512MU810
33EP512MU810
33EP512MU810
33EP512MU810
24EP512GU810
24EP512GU810
24EP512GU810
PIC24E USB Starter Kit 24EP512GU810
Demo Board Processor
PICDEM.net 2
PICDEM.net 2
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
Explorer 16
TCPIP WiFi EasyConfig Demo App ( see page 138)
18F97J60
18F97J60
24FJ128GA010
24FJ128GA010
24FJ128GA010
33FJ256GP710
33FJ256GP710
33FJ256GP710
32MX360F512L
32MX360F512L
32MX360F512L
32MX460F512L
32MX460F512L
32MX460F512L
32MX795F512L
32MX795F512L
32MX795F512L
Microchip TCP/IP Stack Help
ENC28J60 SPI2
ENCX24J600
ENCX24J600
SPI2
PSP
Indirect
ENCX24J600 PSP 9
MRF24WB0M MRF24WG0M SPI2
Internal MAC, National
DP83848C PHY
-
ENCX24J600
ENCX24J600
ENCX24J600
SPI2
PSP 5
PSP
Indirect
MRF24WB0M MRF24WG0M SPI2
ENCX24J600 SPI2
ENCX24J600
ENCX24J600
PSP5
PSP
Indirect
MRF24WB0M MRF24WG0M SPI2
5
5
5
MAC/PHY Layer
ENC28J60
ETH97J60
ENC28J60
ENCX24J600
SPI
SPI
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENCX24J600
ENC28J60
ENCX24J600
ENC28J60
ENCX24J600
Comm.
Bus
-
SPI
SPI
MRF24WB0M MRF24WG0M SPI
SPI
SPI
MRF24WB0M MRF24WG0M SPI
ENC28J60 SPI
ENCX24J600 SPI
MRF24WB0M MRF24WG0M SPI
SPI
SPI
MRF24WB0M MRF24WG0M SPI
Notes
86
7.1 Demo Compatibility Table
Demo Board Processor
Explorer 16
Explorer 16
24FJ128GA010
33FJ256GP710
Explorer 16
Explorer 16
32MX360F512L
32MX460F512L
Explorer 16 32MX795F512L
PIC24FJ256DA210 Development
Board
PIC24FJ256DA210
TCPIP WiFi Console Demo App ( see page 131)
Demo Board Processor
Microchip TCP/IP Stack Help
MAC/PHY Layer
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
PICDEM.net 2
Explorer 16
Explorer 16
Explorer 16
Explorer 16
18F97J60
24FJ128GA010
33FJ256GP710
32MX360F512L
32MX460F512L
Explorer 16 32MX795F512L
PIC24FJ256DA210 Development
Board
PIC24FJ256DA210
TCPIP Internet Radio App ( see page 130)
Demo Board
Internet Radio Board
Processor
18F67J60
TCPIP Internet Bootloader ( see page 124)
Processor MAC/PHY Layer
N/A
N/A
N/A
N/A
N/A
N/A
N/A
N/A
N/A
Demo
Board
N/A
N/A
N/A
N/A
N/A
N/A
18F66J60
18F66J60
18F66J65
18F66J65
18F67J60
18F67J60
18F86J60
18F86J60
18F86J65
18F86J65
18F87J60
18F87J60
18F96J60
18F96J60
18F96J65
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
ETH97J60
MAC/PHY Layer
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MRF24WB0M MRF24WG0M
MAC/PHY Layer
ENC28J60
-
-
-
-
-
-
-
-
-
-
-
-
SPI
SPI
SPI
SPI
Comm.
Bus
Notes
SPI
SPI
Comm.
Bus
Notes
SPI
SPI
SPI
SPI
SPI
SPI
SPI
Comm. Bus
SPI
-
-
-
Comm.
Bus
Notes
Extended Instruction Mode
Extended Instruction Mode
Extended Instruction Mode
Extended Instruction Mode
Extended Instruction Mode
Extended Instruction Mode
Extended Instruction Mode
Notes
87
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
N/A
N/A
N/A
18F96J65
18F97J60
18F97J60
ETH97J60
ETH97J60
ETH97J60
-
-
-
Extended Instruction Mode
Extended Instruction Mode
TCPIP MDD Demo App ( see page 140)
Demo Board
Explorer 16
Explorer 16
Processor MAC/PHY
Layer
PIC24FJ256GB110 ENC28J60
PIC24FJ128GA010 ENC28J60
Comm.
Bus
Notes
SPI
SPI
Uses USB Thumb Drive as a storage medium for web pages.
Uses SD Card as a storage medium for web pages.
Google Map
For information on the Google Map demo compatibility, see the file "Getting Started - Running the Graphics Google Map
Demo" in the Combo Demos/Google Map directory in your Microchip Applications Library installation directory.
7.2
Available Demos
The TCP/IP Stack comes with several example applications. These applications are described in the following sections.
7.2.1
Demo App
The TCPIP\Demo App project folder contains the main demo application for the Microchip TCP/IP Stack. Besides showing example applications using the web server, e-mail client, SNMP server, and more, this application also includes examples for implementing custom application layers. Details about these applications are provided here.
Unspecified hardware configurations may also be useable with the Demo App, but some additional configuration may be necessary.
Some demo features are disabled in certain Demo App projects to support the associated hardware platform and TCP/IP controller. Please consult the following table to determine which features are available on which configurations:
7.2.1.1
TCPIP Demo App Features by Hardware Platform
Some hardware platforms cannot support all of the features implemented in the TCP/IP Demo Application. The following table outlines which features are available for each combination of demo board and MAC/PHY layer supported natively by the TCP/IP Demo App. Note that this table will not appear in the PDF version of the help file; see the "TCPIP Demo App
Features.htm" file in the TCPIP documentation folder in the Microchip Application Library help folder.
NVM Storage
A board with Non-Volatile Memory can modify and save its configuration variables at runtime. In the TCP/IP Demo App, this
parameters via a web page interface. The data will be written to SPI Flash or EEPROM and then used to reinitialize the board if it is reset. A board without this feature will always use the default settings after power-up.
Buttons and LEDs
88
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
The TCP/IP Stack-compatible demo boards have a variable number of buttons and LEDs. By default, the TCP/IP Demo App
buttons and LEDs used depend on what is available on the board.
7.2.1.2
Demo Modules
Modules
Name
E-mail (SMTP) Demo ( see page 100)
Description
Provides an example for building a custom HTTP application using the HTTP2 server and allows several other demo features to be accessed and controlled via web interface.
Demonstrates how to use an e-mail client to send messages when events occur. This is a standalone demo; for the web page "Send Email" demo, see
the Forms using POST ( see page 92) topic.
Generic TCP Client ( see page 101)
Demonstrates how to build a TCP Client application through an HTTP client example.
Demonstrates how to build a TCP server application
Generic TCP Server ( see page 104)
Ping (ICMP) Demo ( see page 105)
Demonstrates how to build a Ping client.
SNMP Server (Agent) ( see page 107)
Describes the Simple Network Management Protocol Demo.
Description
Several custom modules are used in this demo. This section will describe the components and functionality of these modules.
For Microchip 802.11b/g WiFi PICtail MRF24W, the following network types are supported.
• CFG_WF_INFRASTRUCTURE
• CFG_WF_ADHOC
• CFG_WF_P2P (supported by MRF24WG0M only)
For Microchip 802.11b/g WiFi PICtail MRF24W, the new security modes are supported.
• WF_SECURITY_WPS_PUSH_BUTTON (supported by MRF24WG0M only)
• WF_SECURITY_WPS_PIN (supported by MRF24WG0M only)
7.2.1.2.1
Web Page Demos
Functions
Name Description
This is function HTTPPostImage.
Processes the configuration form on config/index.htm
This is function HTTPPostSNMPCommunity.
Parsing and collecting http data received from http form.
HTTPPostDDNSConfig ( see page 96)
Processes the e-mail form on email/index.htm
Processes the LCD form on forms.htm
Processes the file upload form on upload.htm
89
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
Variables
Name
Description
This is variable Flag_ImageUpdate_running.
ImageUpdate_Addr ( see page 98)
Processes the file upload form on upload_Image.htm
RAM allocated for DDNS parameters
This is variable ImageUpdate_Checksum.
ImageUpdate_Checksum ( see page 99)
ImageUpdate_Size ( see page 99)
This is variable ImageUpdate_Size.
Stick status message variable. See lastSuccess ( see page 100) for details.
previous POST operation was successful. The application uses these to store status messages when a POST operation redirects. This lets the application provide status messages after a redirect, when connection instance data has already been lost.
Description
The CustomHTTPApp.c file demonstrates how to build a custom HTTP application on top of the HTTP2 server. All the
dynamic variables.
7.2.1.2.1.1
Dynamic Variables
Module
Description
Overview
This section describes how to view dynamic variables in the TCP/IP Demo App HTTP2 demo. For information about how to
implement dynamic variables in your own page, see the HTTP2 dynamic variables topic ( see page 236).
Instructions
1. Program your board with the demo code and upload the demo app web page. Open your web browser and navigate to the board's web page (http://mchpboard by default).
2. Observe the LED output, button state, and potentiometer reading in the box in the upper right of the web page. The button and potentiometer values will be updated dynamically based on the status of the buttons on your board. In addition, if you click the LEDs to toggle them, their status will be dynamically updated on the page. Note that some LEDs or buttons may
( see page 88) topic for more information.
3. Observe the current Stack Version and Build Date in the top center of the Overview Page.
4. Navigate to the Dynamic Variables page using the navigation panel on the left of the page.
5. Observe the Build Date and Time, LED state, stack version, and current IP address- these variables are output to this page dynamically when it's downloaded by the browser.
Exercises
90
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
variable demo page.
1. Start by opening dynvars.htm
in your "TCPIP Demo App\WebPages2" folder.
2. Locate the dynamic variables in the page and replace the question mark with a dynamic variable to display the value of
LED 0. You can use the other LED variables as a template, but specify 0 as the LED to open.
3. In your MPLAB project, open
CustomHTTPApp.c
and ensure that the
HTTPPrint_led
function (if you used
~led(0)~ as your dynamic variable) if written to output data when 0 is passed in as a parameter.
4. Rebuild your web page with the MPFS2 Utility.
5. Rebuilt your project, and reprogram your board. Navigate to the dynamic variable page and verify that the LED0 field reflects the status of the LED on your board. Since the LED on your board is blinking, you may need to refresh the web page to view its current status.
The second exercise on this page simply demonstrates how to dynamically insert a file into a web page.
1. Start by opening dynvars.htm
in your "TCPIP Demo App\WebPages2" folder.
2. Locate the dynamic variables that include header.inc
and footer.inc
. Observe the difference between the declaration of these variables and the other variables on the page.
7.2.1.2.1.2
Authentication
Module
Description
Overview
This section describes how to use the authentication demo in the TCP/IP Demo App HTTP2 demo. For information about
Instructions
1. Program your board with the demo code and upload the demo app web page. Open your web browser and navigate to the board's web page (http://mchpboard by default).
2. Navigate to the Authentication page using the navigation panel on the left of the page.
3. Note the authentication user name ("admin") and password ("microchip").
4. Click on the "Access Restricted Page" link on the Authentication page.
5. Enter an incorrect combination of usernames and passwords. The browser will not advance to the Access Restricted
Page. After 3 incorrect username/password combinations, the browser will be redirected to an "Unauthorized" screen.
6. Click the back button in your browser. Click on the "Access Restricted Page" link and enter the correct username and password.
7. You will advance to the "Login Successful" page. Your browser will store this username/password combination until it is closed and reopened.
Exercise
You can optionally complete the exercise described on the "Login Successful" page. In this exercise, you will change the username and password that you use to log in to this page.
1. Open
CustomHTTPApp.c
in your TCP/IP Demo App MPLAB project.
2. Locate the HTTPCheckAuth ( see page 247) function.
3. Change the values being compared to the function inputs to a username and password of you choosing.
91
7.2 Available Demos Microchip TCP/IP Stack Help
4. Rebuild your project and program your board.
Demo App
7.2.1.2.1.3
Forms using GET
Module
Description
Overview
This section describes how to use web forms in the TCP/IP Demo App HTTP2 demo. For information about how to
implement forms in your own page, see the HTTP2 form processing topic ( see page 238).
Instructions
1. Program your board with the demo code and upload the demo app web page. Open your web browser and navigate to the board's web page (http://mchpboard by default).
2. Observe the LED state on the board. Click on an LED indicator in the box on the top right of the Overview page. Verify that the LED state changes on the board. Note that some LEDs or buttons may not be implemented, depending on your
information.
3. Navigate to the Form Processing page using the navigation panel on the left of the page.
4. Select new LED states in the pull-down boxes. Click "Save" and observe that the LED states of your board changed to match the settings you selected.
Exercise
You can optionally complete the exercise described on the "Form Processing" page. In this exercise, you will change the
example to support LED5. You may want to read the HTTP2 form processing topic ( see page 238) first.
1. Start by opening forms.htm
in your "TCPIP Demo App\WebPages2" folder.
2. Locate the GET method implementation the will display the LEDs. You should see select
forms for the four LEDs that are already implemented. Each of these has two options: the On option will send a '1' to the server when submitted and the Off option will send a '0' when submitted. Each of the declarations of these options also use the ledSelected dynamic variable to determine which option will be selected by default, based on the current status of the corresponding
LED on the board. This dynamic variable accepts two arguments: the first defines which LED is being checked, and the second describes the state being checked for. So, for example, the
~ledSelected(4,TRUE)~
variable will be replaced by the word "SELECTED" if LED4 is on when this variable callback function is called. In this case,
~ledSelected(4,FALSE)~ would be replaced by nothing. This would result in the 'On' option being selected by default in the page.
3. Create a new select
input for LED5.
4. Open
CustomHTTPApp.c
in the TCP/IP Demo App MPLAB project.
5. Verify that the HTTPPrint_ledSelected dynamic variable callback function has been implemented for LED5.
HTTPExecuteGet ( see page 247)
function. Locate the section of code the processes GET arguments for the forms.htm
file.
7. Add implementation to search for the "led5" argument string in the GET data buffer and then set LED5_IO based on the associated value.
7.2.1.2.1.4
Forms using POST
Module
Description
Overview
92
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
This section describes how to use web forms in the TCP/IP Demo App HTTP2 demo. For information about how to
implement forms in your own page, see the HTTP2 form processing topic ( see page 238).
Instructions
1. Program your board with the demo code and upload the demo app web page. Open your web browser and navigate to the board's web page (http://mchpboard by default).
2. Navigate to the Form Processing page using the navigation panel on the left of the page.
3. Enter a text string into the "LCD" text box and click on "Save." Verify that this string was written to the LCD display on your demo board.
4. Navigate to the File Uploads page using the navigation panel on the left of the page.
5. Browser for a file on your computer and click "Get MD5." The application will read your file using a series of POST transfers and calculate and display and MD5 hash of the contents.
6. Navigate to the Send E-mail page using the navigation panel on the left of the page.
7. Fill in the form fields with the appropriate information.
1. No SSL - You will need a local SMTP server that does not require a secure connection. Enter the address in the SMTP
Server field, set the port to 25, and enter your user name and password for the server. Set the "To:" field to the email recipient and press "Send Message."
2. SSL - Enter the address of a public SMTP server (e.g. smtp.gmail.com). Set the port number to 465 or 587. Enter your email account information (e.g. [email protected] and your Gmail password). Set the "To:" field to the email recipient and press "Send Message." Note that some corporate subnets may block outgoing secure traffic on the
your board to a network that's not blocked by this type of firewall. You must have installed the Microchip Data
more information.
8. Verify that the e-mail was received on the recipient e-mail address.
7.2.1.2.1.5
Cookies
Module
Description
Overview
This section describes how to use the cookie demo in the TCP/IP Demo App HTTP2 demo. For information about how to
93
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
implement cookies in your own page, see the HTTP2 Cookies topic ( see page 243).
Instructions
1. Program your board with the demo code and upload the demo app web page. Open your web browser and navigate to the board's web page (http://mchpboard by default).
2. Navigate to the Cookies page using the navigation panel on the left of the page.
3. Type your first name into the "First Name" text box and click "Set Cookies." Verify that the name was read successfully and displayed in the "Name" output field.
Exercise
You can optionally complete the exercise described on the "Cookies" page. In this exercise, you will create a cookie called
236), GET ( see page 238), and cookie ( see page 243) topics first.
1. Start by opening cookies.htm
in your "TCPIP Demo App\WebPages2" folder.
"not implemented" string with a dynamic variable to output the data from the cookie.
3. Locate the code for the select box form input for the favorite architecture. Note the value of the name
field of the select form.
4. Open
CustomHTTPApp.c
in the TCP/IP Demo App MPLAB project. Locate the
function and find the code that handles GET method inputs from cookies.htm
.
5. Set the value of curHTTP.hasArgs to indicate that two form arguments are present in the data buffer.
6. In
CustomHTTPApp.c
, create a function to output data for the dynamic variable you created in step 2. The name of the function will depend on the name of the variable. For a variable named
~cookiefavorite~
you would implement a function called HTTPPrint_cookiefavorite . This function should search through the curHTTP.data
data buffer to try and find a name/value pair with the name equal to the name of your select form from step 3. If it finds it, it should write the value for that pair to the TCP buffer; otherwise, it should write "not set." See the implementation of
HTTPPrint_cookiename
for an example.
void
HTTPPrint_cookiename(
void
)
{
BYTE *ptr;
ptr = HTTPGetROMArg(curHTTP.data, (ROM BYTE*)"name");
if
(ptr)
TCPPutString(sktHTTP, ptr);
else
TCPPutROMString(sktHTTP, (ROM BYTE*)"not set");
return
;
}
7. Compile your web page using the MPFS2 Utility and upload it to your board. You may receive a warning that your dynamic variables have changed in your page.
8. Rebuild your project and program your board.
9. Verify that both cookies can be set.
94
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
7.2.1.2.1.6
Functions
Functions
Name Description
This is function HTTPPostImage.
Processes the configuration form on config/index.htm
This is function HTTPPostSNMPCommunity.
HTTPPostDDNSConfig ( see page 96)
Parsing and collecting http data received from http form.
Processes the e-mail form on email/index.htm
Processes the LCD form on forms.htm
Processes the file upload form on upload.htm
Module
7.2.1.2.1.6.1
HTTPPostImage Function
File
CustomHTTPApp.c
C static
HTTP_IO_RESULT HTTPPostImage();
Description
This is function HTTPPostImage.
7.2.1.2.1.6.2
HTTPPostConfig Function
File
CustomHTTPApp.c
C static
HTTP_IO_RESULT HTTPPostConfig();
Description
Accepts configuration parameters from the form, saves them to a temporary location in RAM, then eventually saves the data to EEPROM or external Flash.
When complete, this function redirects to config/reboot.htm, which will display information on reconnecting to the board.
This function creates a shadow copy of the AppConfig structure in RAM and then overwrites incoming data there as it arrives. For each name/value pair, the name is first read to curHTTP.data[0:5]. Next, the value is read to newAppConfig.
Once all data has been read, the new AppConfig is saved back to EEPROM and the browser is redirected to reboot.htm.
That file includes an AJAX call to reboot.cgi, which performs the actual reboot of the machine.
If an IP address cannot be parsed, too much data is POSTed, or any other parsing error occurs, the browser reloads config.htm and displays an error message at the top.
Preconditions
None
95
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_NEED_DATA
Description
all parameters have been processed data needed by this function has not yet arrived
7.2.1.2.1.6.3
HTTPPostSNMPCommunity Function
File
CustomHTTPApp.c
C static
HTTP_IO_RESULT HTTPPostSNMPCommunity();
Description
This is function HTTPPostSNMPCommunity.
7.2.1.2.1.6.4
HTTPPostDDNSConfig Function
File
CustomHTTPApp.c
C static
HTTP_IO_RESULT HTTPPostDDNSConfig();
Description
This routine will be excuted every time the Dynamic DNS Client configuration form is submitted. The http data is received as a string of the variables seperated by '&' characters in the TCP RX buffer. This data is parsed to read the required
purpose. As the data is read, DDNSPointers is also populated so that the dynamic DNS client can execute with the new parameters.
Preconditions
curHTTP ( see page 245) is loaded.
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_NEED_DATA
HTTP_IO_WAITING
Description
Finished with procedure
More data needed to continue, call again later
Waiting for asynchronous process to complete, call again later
7.2.1.2.1.6.5
HTTPPostEmail Function
File
CustomHTTPApp.c
C static
HTTP_IO_RESULT HTTPPostEmail();
Description
This function sends an e-mail message using the SMTP client and optionally encrypts the connection to the SMTP server using SSL. It demonstrates the use of the SMTP client, waiting for asynchronous processes in an HTTP callback, and how to send e-mail attachments using the stack.
Messages with attachments are sent using multipart/mixed MIME encoding, which has three sections. The first has no headers, and is only to be displayed by old clients that cannot interpret the MIME format. (The overwhelming majority of these clients have been obseleted, but the so-called "ignored" section is still used.) The second has a few headers to indicate that it is the main body of the message in plain- text encoding. The third section has headers indicating an attached
96
7.2 Available Demos Microchip TCP/IP Stack Help Demo App file, along with its name and type. All sections are separated by a boundary string, which cannot appear anywhere else in the message.
Preconditions
None
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_WAITING
HTTP_IO_NEED_DATA
Description
the message has been sent the function is waiting for the SMTP process to complete data needed by this function has not yet arrived
7.2.1.2.1.6.6
HTTPPostLCD Function
File
CustomHTTPApp.c
C static
Description
Locates the 'lcd' parameter and uses it to update the text displayed on the board's LCD display.
This function has four states. The first reads a name from the data string returned as part of the POST request. If a name cannot be found, it returns, asking for more data. Otherwise, if the name is expected, it reads the associated value and writes it to the LCD. If the name is not expected, the value is discarded and the next name parameter is read.
In the case where the expected string is never found, this function will eventually return HTTP_IO_NEED_DATA when no data is left. In that case, the HTTP2 server will automatically trap the error and issue an Internal Server Error to the browser.
Preconditions
None
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_WAITING
HTTP_IO_NEED_DATA
Section
Function Prototypes and Memory Globalizers
Description
the parameter has been found and saved the function is pausing to continue later data needed by this function has not yet arrived
7.2.1.2.1.6.7
HTTPPostMD5 Function
File
CustomHTTPApp.c
C static
Description
This function demonstrates the processing of file uploads. First, the function locates the file data, skipping over any headers that arrive. Second, it reads the file 64 bytes at a time and hashes that data. Once all data has been received, the function calculates the MD5 sum and stores it in curHTTP.data.
After the headers, the first line from the form will be the MIME separator. Following that is more headers about the file, which we discard. After another CRLFCRLF, the file data begins, and we read it 16 bytes at a time and add that to the MD5 calculation. The reading terminates when the separator string is encountered again on its own line. Notice that the actual file
97
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
that the data buffer is used as an arbitrary storage array for the result. The ~uploadedmd5~ callback reads this data later to send back to the client.
Preconditions
None
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_WAITING
HTTP_IO_NEED_DATA
Description
all parameters have been processed the function is pausing to continue later data needed by this function has not yet arrived
7.2.1.2.1.7
Variables
Module
Variables
Name
Description
This is variable Flag_ImageUpdate_running.
ImageUpdate_Addr ( see page 98)
Processes the file upload form on upload_Image.htm
RAM allocated for DDNS parameters
ImageUpdate_Checksum ( see page 99)
This is variable ImageUpdate_Checksum.
ImageUpdate_Size ( see page 99) lastFailure ( see page 99)
This is variable ImageUpdate_Size.
Stick status message variable. See lastSuccess ( see page 100) for details.
previous POST operation was successful. The application uses these to store status messages when a POST operation redirects. This lets the application provide status messages after a redirect, when connection instance data has already been lost.
7.2.1.2.1.7.1
Flag_ImageUpdate_running Variable
File
CustomHTTPApp.c
C
UINT8 Flag_ImageUpdate_running = 0;
Description
This is variable Flag_ImageUpdate_running.
7.2.1.2.1.7.2
ImageUpdate_Addr Variable
File
CustomHTTPApp.c
C
UINT32 ImageUpdate_Addr = 0;
Description
This function demonstrates the processing of file uploads. First, the function locates the file data, skipping over any headers
98
7.2 Available Demos Microchip TCP/IP Stack Help Demo App that arrive. Second, it reads the file 64 bytes at a time and hashes that data. Once all data has been received, the function calculates the MD5 sum and stores it in curHTTP.data.
After the headers, the first line from the form will be the MIME separator. Following that is more headers about the file, which we discard. After another CRLFCRLF, the file data begins, and we read it 16 bytes at a time and add that to the update. The reading terminates when the separator string is encountered again on its own line. Notice that the actual file data is trashed
buffer is used as an arbitrary storage array for the result. The ~uploadeImage~ callback reads this data later to send back to the client.
Preconditions
None
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_WAITING
HTTP_IO_NEED_DATA
Description
all parameters have been processed the function is pausing to continue later data needed by this function has not yet arrived
7.2.1.2.1.7.3
DDNSData Variable
File
CustomHTTPApp.c
C
BYTE DDNSData[100];
Description
RAM allocated for DDNS parameters
7.2.1.2.1.7.4
ImageUpdate_Checksum Variable
File
CustomHTTPApp.c
C
UINT32 ImageUpdate_Checksum = 0;
Description
This is variable ImageUpdate_Checksum.
7.2.1.2.1.7.5
ImageUpdate_Size Variable
File
CustomHTTPApp.c
C
UINT32 ImageUpdate_Size = 0;
Description
This is variable ImageUpdate_Size.
7.2.1.2.1.7.6
lastFailure Variable
File
CustomHTTPApp.c
99
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
C
BOOL lastFailure = FALSE;
Description
Stick status message variable. See lastSuccess ( see page 100) for details.
7.2.1.2.1.7.7
lastSuccess Variable
File
CustomHTTPApp.c
C
BOOL lastSuccess = FALSE;
Description
Sticky status message variable. This is used to indicated whether or not the previous POST operation was successful. The application uses these to store status messages when a POST operation redirects. This lets the application provide status messages after a redirect, when connection instance data has already been lost.
7.2.1.2.2
E-mail (SMTP) Demo
Functions
Name
Description
Demonstrates use of the e-mail (SMTP) client.
Description
Overview
This file provides two examples for using the SMTP client module to send e-mail messages. The first transmits short alert messages whose entire bodies can be stored in RAM at once. The second example demonstrates how to generate messages on-the-fly when the entire body cannot be allocated in RAM. (This second example is commented. You must comment the first example and uncomment this one to use it.)
messages with attachments, as well as how to dynamically configure the recipient and e-mail server at run-time.
Instructions (Short Message Demo)
1. Open your project in MPLAB and open SMTPDemo.c. Scroll down to the MAIL_BEGIN case in the switch statement in
the SMTPDemo ( see page 101)() function.
1. Replace ( see page 226) the initializer of the RAMStringTo[] array with the target email address.
mail server. Note that this demo does not include security features, so you will need a mail server that does not require
SSL. To test this functionality with a mail server that does support SSL (including most public mail servers), please use
the HTTPPostEmail ( see page 96) SMTP demo.
2. Compile the code, program your board, and run the demo.
3. Press buttons 2 and 3 on your board to transmit an email message. LED1 on your board will indicate that the message is being transmitted; LED2 will indicate that is was sent successfully. Check the BUTTON2_IO, BUTTON3_IO, LED1_IO, and LED2_IO macros in the copy of HardwareProfile.h that corresponds to your project to determine which buttons and
LEDs are used for your hardware setup.
4. Verify that the message was received by the email account you specified in the RAMStringTo[] array.
Description
powered on, the state machine is initialized to the SM_HOME state, in which it waits for buttons 2 and 3 to be pressed. Once
100
7.2 Available Demos Microchip TCP/IP Stack Help Demo App they are pressed, the task will enter the MAIL_BEGIN state.
In the MAIL_BEGIN state, the task will attempt to requisition the SMTP module. Once it's able to do this, it will populate the
MAIL_SMTP_FINISHING state.
when the module is finished. It will then give up control of the SMTP module and toggle LEDs based on the successful operation of the SMTP module. The state machine will then enter the MAIL_DONE state, which will wait at least 1 second before transitioning back to MAIL_HOME, allowing another email to be sent.
7.2.1.2.2.1
SMTPDemo Function
File
MainDemo.h
C void
SMTPDemo();
Module
E-mail (SMTP) Demo ( see page 100)
Returns
None
Description
This function demonstrates the use of the SMTP client. The function is called periodically by the stack, and checks if
BUTTON2 and BUTTON3 are pressed simultaneously. If they are, it attempts to send an e-mail message using parameters hard coded in the function below.
While the client is executing, LED1 will be used as a busy indicator. LED2 will light when the transmission has been completed successfully. If both LEDs extinguish, an error occurred.
For an example of sending a longer message (one that does not exist in RAM all at once), see the commented secondary implementation of this function in this file (SMTPDemo.c) below. For an example of sending a message using parameters
CustomHTTPApp.c.
Preconditions
The SMTP client is initialized.
7.2.1.2.3
Generic TCP Client
Functions
Name
GenericTCPClient ( see page 102)
Description
Implements a simple HTTP client (over TCP).
Variables
Name
Description
Defines the URL to be requested by this HTTP client
Defines the server to be accessed for this application
ServerPort ( see page 103) Note that if HTTPS is used, the ServerName ( see page 103) and URL must
change to an SSL enabled server.
101
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
Description
Overview
The Generic TCP Client provides an example of how to build an HTTP client (or any other TCP client) using the Microchip
TCP/IP Stack. It will print out the results from a search engine query to the PIC's UART module. The result data can be viewed on a PC terminal.
Instructions
1. Connect the programmed demo board to a router that is connected to the Internet.
2. Connect your PC to your demo board with an RS-232 cable. Open a terminal program like HyperTerminal, and configure it to the following settings: 19200 bps, 8 data bits, No parity, 1 stop bit, No flow control.
3. Press Button 1 on your demo board (check the BUTTON1_IO macro in the copy of HardwareProfile.h that corresponds to your project to determine which button is Button 1).
4. Observe the search results for "Microchip" at www.microchip.com on your terminal.
Description
The Generic TCP Client demo implements a task function with five states. When the board is powered on, the initial state will be set to SM_DONE. This state will wait for the user to press Button 1; when a button-press event occurs, the state will
server port will be 80, the port used for HTTP connections. The task will switch the state machine to the
SM_SOCKET_OBTAINED state.
The task will wait in the SM_SOCKET_OBTAINED state until a connection is established with Google or a 5-second timeout elapses. If a timeout occurs, the state will close the socket and change the state back to SM_HOME. Otherwise, it will wait
for the word "Microchip" at the site "microchip.com." Once the GET has been sent, the state will switch to
SM_PROCESS_RESPONSE.
In the SM_PROCESS_RESPONSE state, the task will wait until a response is received or the socket was disconnected. If a response is received, it will print it to the UART. In either case, the task will transition to the SM_DISCONNECT state, where it will close the client socket and return to the SM_DONE state.
7.2.1.2.3.1
GenericTCPClient Function
File
MainDemo.h
C void
GenericTCPClient();
Module
Generic TCP Client ( see page 101)
Returns
None
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.
102
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
Preconditions
TCP is initialized.
7.2.1.2.3.2
Variables
Module
Generic TCP Client ( see page 101)
Variables
Name
Description
Defines the URL to be requested by this HTTP client
Defines the server to be accessed for this application
ServerPort ( see page 103) Note that if HTTPS is used, the ServerName ( see page 103) and URL must
change to an SSL enabled server.
7.2.1.2.3.2.1
RemoteURL Variable
File
GenericTCPClient.c
C
ROM BYTE RemoteURL[] = "/search?as_q=Microchip&as_sitesearch=microchip.com";
Description
Defines the URL to be requested by this HTTP client
7.2.1.2.3.2.2
ServerName Variable
File
GenericTCPClient.c
C
BYTE ServerName[] = "www.google.com";
Description
Defines the server to be accessed for this application
7.2.1.2.3.2.3
ServerPort Variable
File
GenericTCPClient.c
C
Description
103
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
7.2.1.2.4
Generic TCP Server
Functions
Name
GenericTCPServer ( see page 105)
Description
Implements a simple ToUpper TCP Server.
Macros
Name
Description
Defines which port the server will listen ( see page 180) on
Description
Overview
to the demo server, it will echo your keystrokes back to you after converting the characters to UPPER CASE.
Instructions
1. Connect the programmed demo board to a computer either directly or through a router. For Ethernet, a direct connection may require a crossover cable; for WiFi, the board may need to be in AdHoc mode to establish a direct connection.
2. Determine the IP address of the demo board. This can be done several different ways.
1. If you are using a demo setup with an LCD display (e.g. Explorer 16 or PICDEM.net 2), the IP address should be displayed on the second line of the display.
2. Open the Microchip TCP/IP Discoverer from the start menu. Press the "Discover Devices" button to see the addresses
to configure your computer's firewall to prevent it from blocking UDP port 30303 for this solution.
3. If your board is connected directly with your computer with a crossover cable:
1. Open a command/DOS prompt and type 'ipconfig'. Find the network adaptor that is connected to the board. The IP address of the board is located in the 'Default Gateway' field
2. Open up the network status for the network adaptor that connects the two devices. This can be done by right clicking on the network connection icon in the network settings folder and select 'status' from the menu. Find the
'Default Gateway' field.
3. Open a command/DOS prompt. Type "telnet ip_address 9760" where ip_address is the IP address that you got from step
2 and 9760 is the TCP port chosen for the Generic TCP Server implementation.
4. As you type characters, they will be echoed back in your command prompt window in UPPER CASE.
5. Press Escape to end the demo.
Description
task will attempt to open a TCP server
This socket will use a
Once the socket has been successfully opened, the task function will enter the SM_LISTENING state. In this state, the task will always return unless a client has connected to it (by establishing a telnet connection on port 9760). Once a client has connected to the server, the server will read received data from the TCP socket's RX buffer, convert it to upper case, and write it to the TCP socket's TX buffer.
If an Escape character is received, the server will enter the SM_CLOSING state. In this state, it will close the server socket to break the current connection. The server will then re-enter the SM_HOME state, where it will reopen the
TCP_PURPOSE_GENERIC_TCP_SERVER socket to listen ( see page 180) for new connections.
104
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
7.2.1.2.4.1
GenericTCPServer Function
File
MainDemo.h
C void
GenericTCPServer();
Module
Generic TCP Server ( see page 104)
Returns
None
Description
for incoming connections. When a connection is made, the server reads all incoming data, transforms it to uppercase, and echos it back.
This example can be used as a model for many TCP server applications.
Preconditions
TCP is initialized.
7.2.1.2.4.2
Macros
Macros
Name
Module
Generic TCP Server ( see page 104)
Description
Defines which port the server will listen ( see page 180) on
7.2.1.2.4.2.1
SERVER_PORT Macro
File
GenericTCPServer.c
C
#define
SERVER_PORT 9760
Description
Defines which port the server will listen ( see page 180) on
7.2.1.2.5
Ping (ICMP) Demo
Functions
Name Description
Demonstrates use of the ICMP (Ping) client.
Macros
Name
Description
Address ( see page 152) that ICMP client will ping. If the DNS client module is
not available in the stack, then this hostname is ignored and the local gateway
IP address will be pinged instead.
105
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
Description
Overview
The Ping Demo explains how to use the ICMP client to check if a remote node is reachable. If the project with this demo includes the DNS module, the PIC will ping "ww1.microchip.com." Otherwise, it will ping the local gateway. This demo is only available on hardware setups with LCD displays (e.g. Explorer 16 or PICDEM.net 2).
Instructions
1. Press Button 0 on your demo board. Button 0 is usually the rightmost or topmost button on the board (check the
BUTTON0_IO macro in the copy of HardwareProfile.h that corresponds to your project to determine exactly which button is Button 0).
2. When the device receives an echo response from the remote node or when the ping times out, the LCD will be updated with the appropriate information.
Description
state until the user presses button 0. Once the button is pressed, the task will attempt to obtain ownership of the ICMP
transition to the SM_GET_ICMP_RESPONSE state.
action depending on the return value:
Value Action
-2 Remain in this state and keep waiting for a response.
-1
-3
Write a message to the LCD indicating that the ping timed out. Change state to SM_HOME.
Write a message to the LCD indicating that the DNS module couldn't resolve the target address. Change state to
SM_HOME.
Other Convert the response time to a text string and print it to the LCD. Change state to SM_HOME.
7.2.1.2.5.1
PingDemo Function
File
MainDemo.h
C void
PingDemo();
Module
Ping (ICMP) Demo ( see page 105)
Returns
None
Description
This function implements a simple ICMP client. The function is called periodically by the stack, and it checks if BUTTON0 has been pressed. If the button is pressed, the function sends an ICMP Echo Request (Ping) to a Microchip web server. The round trip time is displayed on the UART when the response is received.
This function can be used as a model for applications requiring Ping capabilities to check if a host is reachable.
Preconditions
TCP is initialized.
106
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
7.2.1.2.5.2
Macros
Macros
Name
Description
Address ( see page 152) that ICMP client will ping. If the DNS client module is
not available in the stack, then this hostname is ignored and the local gateway
IP address will be pinged instead.
Module
Ping (ICMP) Demo ( see page 105)
7.2.1.2.5.2.1
HOST_TO_PING Macro
File
PingDemo.c
C
#define
HOST_TO_PING "ww1.microchip.com"
// Address that ICMP client will ping. If the
DNS client module is not available in the stack, then this hostname is ignored and the local gateway IP address will be pinged instead.
Description
hostname is ignored and the local gateway IP address will be pinged instead.
7.2.1.2.6
SNMP Server (Agent)
Functions
Name
SNMPGetTimeStamp ( see page 120)
Description
Prepare, validate remote node which will receive trap and send trap pdu.
Obtains the current Tick value for the SNMP time stamp.
Macros
Name Description
MAX_TRY_TO_SEND_TRAP ( see page 121)
Update the Non record id OID value which is part of CustomSnmpDemo.c file
STACK_USE_SMIV2 ( see page 122)
Default STACK_USE_SMIV2 is enabled . For Stack V5.31,
STACK_USE_SMIV2 should be disabled.
Variables
Name
gSendTrapSMstate ( see page 120)
gSnmpNonMibRecInfo ( see page 121) gSnmpv3UserSecurityName
Description
This is variable gSendTrapSMstate.
OLD snmp.mib file with SMIv1 standard
This is variable gSnmpv3UserSecurityName.
Description
The Microchip SNMP server is a multilingual implementation which supports SNMPv1, V2c and V3 server features simultaneously. SNMP server is implemented to address the requirements of embedded applications. The SNMPv3 support
107
7.2 Available Demos Microchip TCP/IP Stack Help Demo App is added with TCPIP Stack Version 5.31. SNMPv1 and V2c are enabled with single macro
#define
STACK_USE_SNMP_SERVER . The SNMPv3 server could be selectively enabled with independent macro #define
STACK_USE_SNMPV3_SERVER
. As SNMPv3 stacks are required to support SNMPv1 and SNMPv2c, enabling the SNMPv3
Server will automatically enable SNMPv1 and SNMPv2c servers in the Microchip TCPIP Stack SNMP agent. These macros are defined in the
TCPIP (MAC/PHY).h
file located at
<Installation Path>:\Microchip Solutions
MAIN\TCPIP\Demo App\Configs\ .
This series of topics will address the application- and demo-specific implementation of an SNMP server included with the
TCP/IP Demo applications. For information describing the SNMP module in general, please see the SNMP API topic.
V2c is implemented with support for the configuration of multiple community names, which are stored in selected non-volatile memory (SPI EEPROM or SPI Flash). The community names can be configured through the TCP/IP Configuration Wizard or through the HTTP/MPFS2 web interface. An access-restricted web page is provided with the demo application to allow dynamic configuration of SNMP communities.
SNMPv3 RFC specifies different types of access mechanism, user security model (USM), authentication and privacy protocols. Microchip SNMPv3 server is implemented with support for USM, AES 128 CFB 128 privacy protocol, and MD5 and SHA1 message authentication protocols. The demo implementation of the server is configured with 3 different types of user names with respective authentication and privacy credentials and authentication types. These credentials and other user information are stored in the global array. The user of the SNMPv3 stack can decide on the number of user names in the User’s data base to be stored with the Server. According to the SNMPv3 recommendation, SNMPv3 server should not be configured with the authentication and privacy passwords. Instead could be configured with the respective localized keys of the password. Microchip SNMPv3 agent is provided with the password information in the database for the “Getting
Started” and for understanding purpose only. It is recommended that the SNMPv3 stack should be modified to restrict access to the password OIDs declared in the user data base.
Note that even though SNMPv3 also requires SNMPv1 and SNMPv2c, a layer in the SNMP stack will prevent access to the variables that should be secured by SNMPv3. SNMP variables are structures in a tree in the Management Information Base
(MIB). Access to parts of this tree are determined by version. For example, SYSTEM-type variables can be accessed regardless of SNMP version, SNMPv2c requests can access part of the tree, and authenticated SNMPv3 requests can access the complete tree.
Note: For existing Microchip SNMP V1 and V2c users.
• SNMP V1/V2c users wanting to upgrade the Microchip TCP/IP Stack from older versions to the latest version and continue to use SNMP V1/V2c can get the SNMP V1/V2c services from this agent, provided they do not modify the default settings of the SNMP module in v5.25 onward.
• The implementation framework for V1 and V2c remains the same, except for a few new features and functions. The names and parameters of some of the functions have been changed. V1/V2c users may have to make changes to their application-specific code. There should not be any change in the SNMP stack code unless users have incorporated application code in the SNMP stack.
• Users should build a new MPFS image using the MPFS File System Generator utility and upload it to the selected
EEPROM or Flash memory, as the AppConfig structure is updated to accommodate community names in V2c and SNMP engine ID for SNMPv3.
7.2.1.2.6.1
MIB Files
Module
SNMP Server (Agent) ( see page 107)
Description
SNMP describes the hierarchal storage of management objects (referred to with object IDs or OIDs) with Management
Information Base (MIB) files. The Microchip SNMP server demo includes two MIB files:
• mchip.mib - This is an Abstract Syntax Notation One (ASN.1) formatted MIB file containing information about the variables used in the demo.
• snmp.mib - This is a custom-formatted file that can be parsed to create webpage and header resources that can be
108
7.2 Available Demos Microchip TCP/IP Stack Help Demo App accessed with a PIC microcontroller.
The TCP/IP stack includes the mib2bib utility, which will compile the custom Microchip MIB script (snmp.mib) to generate two files called snmp.bib and mib.h. The snmp.bib file is a compressed record of management objects that will be stored with web pages and the mib.h file contains C defines for each OID. These files are included in the appropriate directories for the
TCP/IP Demo Apps, but for a custom application you must copy snmp.bib to your web page directory, copy mib.h to your application directory and include it in your project, rebuild your project, and then rebuild and re-upload your web page. This will bundle the BIB file into your web page image, which will allow the SNMP agent to search for the required variable information with the MPFS file system.
7.2.1.2.6.2
MIB Browsers
Module
SNMP Server (Agent) ( see page 107)
Description
Several SNMP MIB browsers are available. Users can also install a customized MIB browser specific to their application.
This help file describes using the iReasoning MIB browser to run the demo app. The iReasoning MIB browser can be obtained from: http://www.ireasoning.com/downloadmibbrowserlicense.shtml
. The MIB script upload, the MIB tree structure display, and the SNMP query mechanism procedures vary from browser to browser.
Note that the use of a MIB browser or other third-party tools may require that users review and agree to the terms of a license. Microchip's reference to the iReasoning MIB browser is for the users' convenience. It is the user's responsibility to obtain information about, and comply with the terms of, any applicable licenses.
Once your browser installation has been completed, perform the following steps:
1. Copy the mchip.mib
file to the MIB file directory of your browser (e.g. "C:\Program Files\ireasoning\mibbrowser\mibs").
2. Open the iReasoning browser, select File->Load MIBs , and select the mchip.mib, RFC1213.mib and
SNMP-FRAMEWORK-MIB.mib
(If SNMPv3 server is enabled) file.
The Microchip MIB directory will be displayed in the
SNMP MIB
pane.
The minimum set of RFC 1213 MIB2 variables that are required to identify the Microchip node as an SNMP node to the network are implemented. These variables can be accessed by any SNMP browser with a "public" type community name.
Refer to AN870 - "SNMP V2c Agent for Microchip TCP/IP Stack" for more details on the MIB scripts, community names, and demo SNMP MIB variable tree structure. The following figure shows the variables implemented in the Microchip SNMP
Agent.
109
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
The ASN.1 format mchip.mib
file is defined with a private variable tree structure for the MIB variables. Also the mchp.mib is added with number of OIDs which could be accessed only with SNMPv3 request. The browser can access every variable in the MIB database provided the community name matches. The access to the MIB variables is restricted to the type of the request. The RFC1213 mib variables could be accessed with SNMPv2c/v3 request. But the SNMP-FRAMEWORK-MIB.mib
variables could only be accessed with SNMPv3 reqeust if the credentials are matched and the message is authenticated. To modify these MIB variables, corresponding changes must be made to both MIB scripts ( snmp.mib
and mchip.mib
). The following figure shows the Microchip private MIB variable tree structure in the browser.
Configuring the Browser
To configure the iReasoning MIB browser:
1. Select the "Advanced" tab in the browser.
The following configuration window will be displayed:
2. If V2C services are required, select SNMP version V2c, configure the Read and Write community to the browser.
• The V2c agent will respond only to the queries from SNMP MIB browsers using the same community. That is, the V2c agent and the browser should be members of the same community.
• If the community fields are left blank, the manager sends the SNMP request with the community name as "public."
• The V2c agent is configured by default with 3 Read communities ("public", "read", "") and 3 Write communities
("private","write","public").
• The default maximum community length is 8 characters.
• As the default communities also contain the "public" community name, the agent will respond to all of the browsers
110
7.2 Available Demos Microchip TCP/IP Stack Help Demo App requesting the "public" community.
run time, the community names can be dynamically configured using the HTTP interface for SNMP community name configuration.
The V2c agent's multiple community support feature enables the user application to provide limited access to the requesting browser based on the community name used by the browser to access the MIB database variables of the agent.
3. If SNMPv3 services are required, select the SNMP Version as 'V3' in the 'Advanced' tab of the SNMP MIB Browser. The following configuration window will be displayed:
4. If SNMPv3 services are required, SNMPv3 browser is required to be configured with the user name, authentication and privacy password, message authentication hash type, privacy protocol type. The SNMP server would respond only if one of the user credentials and user security parameters in the below table is configured at the manager. The below table is stored in the global structure with the SNMPv3 server stack. The SNMPv3 server would only respond if the request credentials of the MIB browser matches to that of the stored user data base of the SNMP server.
USM User
Security Level
USER 1
microchip auth, priv
USER 2
SnmpAdmin auth, no priv
USER 3
root no auth, no priv
Auth Algorithm
Auth password
Privacy Algorithm
Privacy password
MD5 auth12345
AES priv12345
SHA1
ChandlerUS
5. The Microchip SNMPv3 stack does support only one Context Engine ID with the server. Leave the "Context Name" option in the "Advanced" tab empty. It is ignored on the server.
6. According to the user and the auth and privacy protocols configured with the SNMP browser, the UDP authenticated and encrypted message would be exchanged between server and the client.
• If the USER 1 values, as in above table, are configured in the MIB browser, the data exchange between client and server is encrypted and authenticated. The PDU could be captured in the Ethernet packet sniffer like WireShark and examined.
As the data is encrypted and authenticated, the data integrity and the privacy is achieved.
111
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
• If USER 2 values, as in above table, are configured in the MIB browser, the data exchange between client and server is authenticated. The data integrity would be checked once the data is received at either end. The message authentication mechanism protects from the possible data sniffing and modification threat, and alos guarantees that the data is received from the authenticated and guaranteed source.
• if USER3 values, as in above table, are configured in the MIB browser, the data exchange between client and server is neither authenticated nor encrypted.
• Considering the above three USER configurations, if the SNMP server is to be accessed over WAN, in the internet cloud, tha data should be encrypted and authenticated to have the highest level of data privacy and integrity.
7. Configure the IP address of the SNMP agent to the "Address ( see page 152) field.
7. Select the variable to be accessed from the agent MIB database from the
SNMP MIBs
pane. The selected variable's OID can be seen in the OID tab in the following figure.
8. Select the SNMP Get operation from the operations tab.
9. The SNMPv3 server demo MIB is included with RFC1213 SNMPv2 MIB variables, private mib variables and the
SNMP-FRAMEWORK-MIB variables. If the SNMPv2C request with validated community name is generated from the MIB
Browser, only set of few variables is accessed. The access to the MIB variables is restricted to the type of SNMP version request received. If the SNMPv3 request with correct credentials is generated from the MIB Browser, the complete MIB access is provided.
10. The user would require to decide on which part of the MIB should be required to be restricted depending upon the
SNMP version type. The MIB design is the one of the important step in deciding the MIB tree structure and the variable to be placed accordingly.
11. The SNMP server demo MIB is added with a static variable OID named as "snmpv3PvtObject" with OID value as
43.6.1.4.1.17095.6.1. This variable is placed in the private branch of the MIB by creating an independent branch. All the other variables in the private branch are accessible by SNMPv2c request. The access to this static variable is restricted by the SNMP version type. Only the SNMPv3 request with correct credentials could access this variable.
Exploring the Demo
After the MIB script is uploaded to the SNMP browser, the MIB tree structure will be displayed in the browser. Any of the variables in this tree can be accessed (using SNMP operations) from the agent if the agent supports these variables. The browser and agent should be members of the same community. To learn more about SNMP operations, PDU types, and terminology, refer to AN870 - "SNMP V2C Agent for Microchip TCP/IP Stack."
7.2.1.2.6.3
SNMP Operations
Module
SNMP Server (Agent) ( see page 107)
Description
Get
112
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
1. Select the "Advanced" tab and configure the SNMP version to '1' and the Read community to "public".
2. Select "Get" from the operations menu.
3. Select the sysDescr
variable from the MIB Tree.
The Result Table displays the sysDescr
variable information. Repeat this procedure for any MIB variable. For SNMP V2c, repeat the same procedure, substituting '2' in place of '1' in the version configuration.
As explained earlier, the V2c agent is configured with three Read and Write community defaults. Configure the browser to use any of these communities and try accessing the MIB variables. You should be able to access some of the MIB variables even with the Read Community configured as any of the 'write' community defaults. For GET operations, if the Read or Write community matches, the agent processes the request. For SET operations, the received community names must match any of the 'write' community names.
For SNMP V3, substitute '3' in place of '1' in the version configuration in the "Advanced" tab. Configure the other user based auth and priv credentials as explained in the "MIB Browsers" section.
With appropriate credentials, all the MIB variables are accessible. Select any of the MIB variables in the MIB tree and do a
GET operation.
Get_Next
1. Repeat the process for GET. Select the sysDescr
variable from the MIB tree. Select "Get Next" from the operations menu. The result table will display the sysObjectID
variable information.
2. Repeat for additional MIB variables to get the information for the corresponding next variable.
3. Set the SNMP MIB Browser version to v1/v2c. Try to access the private MIB variable "snmpv3PvtObject" with OID value as 43.6.1.4.1.17095.6.1. The access should be restricted. Set the verison to V3, configre the credentails, again try a
Get_Next operation for the sae variable. The access should be granted.
Get_Bulk
This operation is supported in SNMP V2c and SNMP V3. Get_Bulk enables the collection of bulk information from the agent with a single request from the manager.
1. Configure the SNMP version to '2' or '3' in the SNMP browser.
2. If version is configured to '2', set the Read Community to 'public' or 'read.'
3. If version is configured to '3', configure the appropriate V3 credentials.
4. Select the sysDescr
variable from the MIB tree.
5. Select the Get Bulk operation from the Operations menu.
The result table will display information for 10 MIB variables in a single request (if the Max-Repetitions=10 and
Non-Repeaters=0 is configured). These variables are the lexicographical successors of the sysDescr
variable. The number of variables that the agent will respond with can be configured in the browser through the menus:
"Tools->Options->Non-Repeaters" and "Tools->Options->Max-Repetitions." The Non-Repeaters and Max-Repetitions
113
7.2 Available Demos Microchip TCP/IP Stack Help Demo App numbers are extracted by the SNMP agent from the received Get_Bulk request and the number of variables that will be included in the response PDU is calculated. for more information on calculating the number of variables, Non-Repeaters, and Max-Repetitions, refer to RFC 3416.
Set
The Set command updates the variable information of the MIB database in the agent. The Set command can be performed only on those variables which are declared as 'READWRITE' in the MIB scripts, and only if the community name matches any one of the 'write' community names configured with the agent.
1. Select the ledD5
variable from the MIB tree.
2. Configure the SNMP version to '1' or '2.' Configure the Write Community to 'public', 'write', or 'private'.
3. If version is configured to '3', configure the appropriate V3 credentials.
4. Select 'Set' from the Operations menu.
The SNMP SET window will pop up. Enter the value for the browser in the OID field.
A success message will appear.
A 'Get' operation for the same variable should now return the new 'Set' value for this variable. LED5 on the demo board should now be ON. Repeat the procedure to set LED5 to OFF. LED6 can also be set ON or OFF.
7.2.1.2.6.4
SNMP Traps
Module
SNMP Server (Agent) ( see page 107)
114
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
Description
The SNMP agent in version 5.25 and later of Microchip's TCP/IP Stack supports SNMP V1 and V2c formatted traps. Traps are notifications from the agent to the manager that are used when a predefined event occurs at the agent.
Several preprocessor macro in the
TCPIPConfig.h
variant header file can be used to enable or disable traps in the agent.
Commenting and un-commenting these macros in the file will have different effects. The SNMP_TRAP_DISABLED macro will disable traps entirely if it is not commented:
#define
SNMP_TRAP_DISABLED
The user must configure the expected trap format at the SNMP Manager. SNMPv2 entities acting as an agent should be able to generate and transmit SNMP V2 trap PDUs when the manager is configured to received and process SNMP V2 trap
PDUs. To configure the trap format, comment or uncomment the following macro in the TCPIPConfig.h header file:
#defiine SNMP_STACK_USE_V2_TRAP
If the macro has been commented out, the SNMP agent will send V1 formatted trap PDUs; otherwise, it will send V2 formatted trap PDUs. By default, the SNMP agent is configured to send V2 formatted traps. Note that the SNMP V2c agent should only send V2 formatted traps.
To enable traps in SNMPv3, the
#define SNMP_V1_V2_TRAP_WITH_SNMPv3
macro must be uncommented.
The following table illustrates how to enable/disable traps for different versions of SNMP:
TRAP v1
(Enabled by default)
SNMPv1
• Comment out the
#define
SNMP_TRAP_DISABLED macro
SNMPv2c
• Comment out the
#define
SNMP_TRAP_DISABLED macro
SNMPv3
• Comment out the macro
#define
SNMP_TRAP_DISABLED macro
• Uncomment the
#define
SNMP_V1_V2_TRAP_WITH_SNMPV3
TRAP v2
(Disabled by default)
(Not supported)
• Comment out the macro
#define
SNMP_TRAP_DISABLED
• Uncomment the
#define
SNMP_STACK_USE_V2_TRAP macro
• Comment out the #define
SNMP_TRAP_DISABLED
macro
• Uncomment the
#define
SNMP_V1_V2_TRAP_WITH_SNMPV3 macro
• Uncomment the #define
SNMP_STACK_USE_V2_TRAP
macro
Demos
Two trap demos are included with the TCP/IP Stack. The task functions for these demos are called in the main application function:
•
SNMPTrapDemo()
- This API demonstrates V1 or V2 trap formats (depending of the status of the
SNMP_STACK_USE_V2_TRAP macro). The trap PDU will only have one demo variable binding on the varbind list.
•
SNMPV2TrapDemo()
- This API provides V2 format notifications with multiple (3) variable bindings. The user should modify or use this routine as a reference for sending V2 trap format notifications with multiple bindings on the varbind list.
The user should only enable one SNMP demo API at a time. By default, the
SNMPTrapDemo()
API is enabled and
SNMPV2TrapDemo() is commented out.
V1/V2 Formatted Traps with a Single Variable Binding
In the TCPIPConfig.h header file:
• Uncomment
#define SNMP_TRAP_DISABLED
• Comment
//#define SNMP_STACK_USE_V2_TRAP
For the Trap demonstration, two events are defined within the V2c agent:
• If the Analog Potentiometer value is greater than 512, the agent will send a Trap every 5 seconds to the configured
115
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
'trapReceiverIPAddress.'
• If Button 3 on the demo board is pressed, an organization-specific PUSH_BUTTON trap will be sent.
• If a request is received to modify (Set) a private MIB variable, or
• If the value of the variable is requested (get) by a browser with the wrong community name.
Procedure:
1. Open the "Advanced" configuration menu, configure the SNMP version to '2,' and configure the Write Community to
"public', 'write', or 'private'.
2. Select the 'trapEnabled.0' variable from the MIB tree.
3. Select 'Set' from the Operations menu.
4. Enter '1' in the value field of the SNMP SET window.
5. Select 'trapReceiverIPAddress.0' from the MIB tree.
6. Set the value to the IP address of the PC on which the SNMP browser is installed and running.
7. Select 'trapCommunity.0' from the MIB tree.
8. Set the community name of the SNMP browser (the default community, if not set, is 'public'). The 'trapCommunity' name will work as a filter for the SNMP browsers on a trap-monitoring server.
9. Open the "Trap Receiver' utility that was installed with the iReasoning MIB browser (Start->Programs->iReasoning->MIB
Browser->Trap Receiver).
To test the analog potentiometer trap, adjust the potentiometer on the demo board so the value is greater than 512 (turn it clockwise). This is an enterprise-specific trap. The SNMP Manager will receive the source IP address, the OID (as the name of the variable), the value, the timestamp, etc. for each event. The browser will interpret the data as AnalogPot variable information based on the OID name.
To test the push button trap, press the appropriate button on the development board (RB0 on the PICDEM.net 2 or S3 on the Explorer 16 board).
name that is not supported by the agent (the default supported names are 'public' and 'read'). For example:
1. Configure 'mchp' as the Read Community name in the browser.
116
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
2. Select the private MIB variable
LED5
from the MIB tree and issue a 'Get' operation from the browser.
This is an intimation from the agent to the SNMP Manager that there was an unauthorized attempt to access the private MIB variable in the database.
V2 Formatted Traps with a Multiple Variable Bindings
In the TCPIPConfig.h header file:
• Uncomment
#define SNMP_TRAP_DISABLED
• Uncomment
#define SNMP_STACK_USE_V2_TRAP
The SNMP V2 Trap PDU structure is:
Version (2) | community | SNMP-PDU pdu-type (TRAP=0xA7) | request-id | error-status | err-index | varbind List
The first two variable varbinds in the variable binding list of an SNMPv2-TRAP-PDU are sysUpTime.0 and snmpTrapOID.0, respectively. If any additional variables are to be included, then each of these varbind structures must be copied to the variable binding list.
For the SNMPv2 multiple TRAP variable varbind demonstration, ANALOG_POT0 is used to generate an event and transmit an SNMP v2 Trap PDU. Adjust the analog potentiometer to a value greater than 512 (turn it clockwise) on the demo board.
In addition to the sysUpTime.0 and snmpTrapOID.0 varbinds, the additional varbinds that are included with the trap PDU are:
• PUSH-BUTTON
• LED0_IO
• ANALOG_POT0
The following figure shows a V2 formatted trap with ANALOG_POT0 as the variable binding to be notified.
117
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
The next figure shows a multiple-variable varbind for an SNMP V2 Trap PDU, with the three additional variable bindings:
7.2.1.2.6.5
HTTP Configuration
Module
SNMP Server (Agent) ( see page 107)
Description
If an HTTP2 server is used with the Microchip TCP/IP Stack, it is possible to dynamically configure the Read and Write community names through the SNMP Configuration web page. Follow the steps in the Getting Started section to upload the web pages to non-volatile memory, then access the SNMP Configuration web page through the navigation bar. Use "admin" for the username and "microchip" for the password.
118
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
7.2.1.2.6.6
Functions
Functions
Name
SNMPGetTimeStamp ( see page 120)
Description
Prepare, validate remote node which will receive trap and send trap pdu.
Obtains the current Tick value for the SNMP time stamp.
Module
SNMP Server (Agent) ( see page 107)
7.2.1.2.6.6.1
SendNotification Function
File
CustomSNMPApp.c
C static
BOOL SendNotification(
BYTE receiverIndex,
UINT8 targetIndex
);
Description
This routine prepares the trap notification pdu, sends ARP and get remote device MAC address to which notification to sent, sends the notification. Notofication state machine is getting updated if there is any ARP resolution failure for a perticular trap destination address.
Remarks
None.
Preconditions
SNMPTrapDemo() is called.
Parameters
Parameters
receiverIndex var
Description
The index to array where remote ip address is stored.
SNMP var ID that is to be used in notification
119
7.2 Available Demos Microchip TCP/IP Stack Help Demo App val targetIndex
Return Values
Return Values
TRUE
FALSE
Value of var. Only value of BYTE, WORD or DWORD can be sent.
snmpv3 target index
Description
If notification send is successful.
If send notification failed.
7.2.1.2.6.6.2
SNMPGetTimeStamp Function
File
CustomSNMPApp.c
C static
DWORD SNMPGetTimeStamp();
Description
TickGetDiv64K ( see page 610) to collect all 48bits of the internal Tick Timer.
Remarks
None.
Preconditions
None
Return Values
Return Values
timeStamp
Description
DWORD timevalue
7.2.1.2.6.7
Variables
Module
SNMP Server (Agent) ( see page 107)
Variables
Name
gSendTrapSMstate ( see page 120)
gSnmpNonMibRecInfo ( see page 121) gSnmpv3UserSecurityName
Description
This is variable gSendTrapSMstate.
OLD snmp.mib file with SMIv1 standard
This is variable gSnmpv3UserSecurityName.
7.2.1.2.6.7.1
gSendTrapSMstate Variable
File
CustomSNMPApp.c
C
UINT8 gSendTrapSMstate = 0;
Description
This is variable gSendTrapSMstate.
120
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
7.2.1.2.6.7.2
gSnmpNonMibRecInfo Variable
File
CustomSNMPApp.c
C
SNMPNONMIBRECDINFO gSnmpNonMibRecInfo[SNMP_MAX_NON_REC_ID_OID] = {
{{43,6,1,4,1,0x81,0x85,0x47,6},SNMP_V3}, {{43,6,1,2,1,1},SNMP_V2C},
{{43,6,1,4,1,0x81,0x85,0x47,0x1},SNMP_V2C}, };
Description
OLD snmp.mib file with SMIv1 standard
7.2.1.2.6.7.3
gSnmpv3UserSecurityName Variable
File
CustomSNMPApp.c
C
BYTE gSnmpv3UserSecurityName[SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE];
Description
This is variable gSnmpv3UserSecurityName.
7.2.1.2.6.8
Macros
Macros
Name Description
MAX_TRY_TO_SEND_TRAP ( see page 121)
Update the Non record id OID value which is part of CustomSnmpDemo.c file
STACK_USE_SMIV2 ( see page 122)
Default STACK_USE_SMIV2 is enabled . For Stack V5.31,
STACK_USE_SMIV2 should be disabled.
Module
SNMP Server (Agent) ( see page 107)
7.2.1.2.6.8.1
MAX_TRY_TO_SEND_TRAP Macro
File
CustomSNMPApp.c
C
#define
MAX_TRY_TO_SEND_TRAP (10)
Section
Global Variables
************************************************************************
This Macro is used to provide maximum try for a failure Trap server address
121
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
7.2.1.2.6.8.2
SNMP_MAX_NON_REC_ID_OID Macro
File
CustomSNMPApp.c
C
#define
SNMP_MAX_NON_REC_ID_OID 3
Description
Update the Non record id OID value which is part of CustomSnmpDemo.c file
7.2.1.2.6.8.3
STACK_USE_SMIV2 Macro
File
CustomSNMPApp.c
C
#define
STACK_USE_SMIV2
Description
Default STACK_USE_SMIV2 is enabled . For Stack V5.31, STACK_USE_SMIV2 should be disabled.
7.2.1.2.7
UART-to-TCP Bridge
Overview
The UART-to-TCP bridge feature of the TCP/IP Demo App transmits all incoming TCP bytes on a socket out of the PIC's
UART module and all incoming UART bytes out of a TCP socket.
Instructions
1. Compile your MPLAB project and program the demo board.
2. Connect the RS-232 port on your demo board to an RS-232 port on your computer. On a newer computer you may need an RS-232 to USB converter cable. On your computer, open a terminal program (such as HyperTerminal). Set it to use the COM port you connected your board to, at 19200 baud, with 8 data bits, no parity, 1 stop bit, and no flow control.
3. Connect the programmed demo board to a computer either directly or through a router. For Ethernet, a direct connection may require a crossover cable; for WiFi, the board may need to be in AdHoc mode to establish a direct connection.
4. Determine the IP address of the demo board. This can be done several different ways.
1. If you are using a demo setup with an LCD display (e.g. Explorer 16 or PICDEM.net 2), the IP address should be displayed on the second line of the display.
2. Open the Microchip Ethernet Device Discoverer from the start menu. Press the "Discover Devices" button to see the
may have to configure your computer's firewall to prevent it from blocking UDP port 30303 for this solution.
3. If your board is connected directly with your computer with a crossover cable:
1. Open a command/DOS prompt and type 'ipconfig'. Find the network adaptor that is connected to the board. The IP address of the board is located in the 'Default Gateway' field
2. Open up the network status for the network adaptor that connects the two devices. This can be done by right clicking on the network connection icon in the network settings folder and select 'status' from the menu. Find the
'Default Gateway' field.
5. Open a command/DOS prompt. Type "telnet ip_address 9761" where ip_address is the IP address that you got from step
4.
122
7.2 Available Demos Microchip TCP/IP Stack Help Demo App
PIC, and then transmitted out of the PIC's UART to appear on your terminal program. As you type characters in the terminal program, they will be transmitted to the PIC through the UART module, and then retransmitted over the TCP
connection to appear in the command prompt Telnet ( see page 577) session.
7.2.1.2.8
Zero Configuration (ZeroConf)
Zero configuration (Zeroconf), provides a mechanism to ease the configuration of a device on a network. It also provides for a more human-like naming convention, instead of relying on IP addresses alone. Zeroconf also goes by the names Bonjour
(Apple) and Avahi (Linux), and is an IETF standard.
Enabling
Zeroconf can be enabled by setting the following two defines in TCPIPConfig.h:
•
STACK_USE_ZEROCONF_LINK_LOCAL
•
STACK_USE_ZEROCONF_MDNS_SD
Currently, the use of Zeroconf is limited to the WiFi demo applications (and the MRF24WB0M / MRF24WG0M module).
Future versions of the stack should enable Zeroconf support across all Ethernet solutions.
Link Local
The first component of Zeroconf is the ability to self-assign an IP address to each member of a network. Normally, a DHCP server would handle such situations. However, in cases where no DHCP server exists, Zeroconf enabled devices negotiate unique IP addresses amongst themselves.
mDNS
The second component of Zeroconf is the ability to self-assign human-readable hostnames for themselves. Multicast DNS provides a local network the ability to have the features of a DNS server. Users can use easily remembered hostnames to accesses the devices on the network. In the event that devices elect to use the same hostname, as in the IP address resolution, each of the devices will auto-negotiate new names for themselves (usually by appending a number to the end of the name).
Service Discovery
The last component of Zeroconf is service discovery. All Zeroconf devices can broadcast what services they provide. For instance, a printer can broadcast that it has printing services available. A thermostat can broadcast that it has an HVAC control service. Other interested parties on the network who are looking for certain services can then see a list of devices
to know whether something exists on a network (and what it's IP or hostname is). As an end-user, all you would need to do
is query the network if a certain service exists, and easily connect ( see page 176) to it.
Demo
The demo, when enabled, shows all three items above working together. Each development kit in the network assumes the hostname of MCHPBOARD-x.local, where x is an incrementing number from 1 (only in the case where multiple kits are programmed for the network). Each board will broadcast it's service, which is the DemoWebServer.
Zeroconf Enabled Environments
All Apple products have Zeroconf enabled by default. On Windows, you'll need to download the Safari web browser, and
123
7.2 Available Demos Microchip TCP/IP Stack Help Internet Bootloader during the install, enable support for Bonjour. Note that in the Safari browser, you can browse and see a list of all Bonjour enabled devices, and click through to them automatically.
7.2.2
Internet Bootloader
The Internet Bootloader is a stand alone application allowing new application firmware to be uploaded directly into the Flash memory of a PIC18F microcontroller over an Ethernet network or the Internet. For other PIC and dsPIC architectures, third-party TCP/IP bootloaders can be obtained from http://www.brushelectronics.com/ . This Internet Bootloader application implements its own private UDP/IP stack as well as a Trivial File Transfer Protocol (TFTP) server. The bootloader operates independently of the main application and cannot update itself. Safeguards are implemented internally to minimize the risk of non-recoverable failed upgrades.
Important attributes of the Internet bootloader include:
• Self contained TFTP, UDP, IP, ARP, and Ethernet protocol handling
• Executes on Power-on Reset instead of during main application
• Waits approximately 4 seconds before starting main application
• Requires 8KB of program Flash
• Requires 0B of RAM (all used RAM is overlaid with main application)
• Requires no CPU time while executing main application
• Requires minimal or no changes to main application code and linker script
• Does not interfere with application interrupt vector locations or add interrupt latency
• Can reprogram configuration words
• Can reuse MAC and IP address provided by main application
• Client update software is already available on most computers
7.2.2.1
Bootloader Design
Bootloader Entry
The bootloader is a TFTP server which starts automatically on Power-on Reset (POR). It can be located anywhere within program memory. To cause the automatic startup, the bootloader transparently performs a replacement of the instruction(s) at program memory locations
000000h
-
000003h
. The .hex file to be programmed to the chip by the bootloader will normally contain a GOTO instruction at address 000000h which branches to the main application. Instead of writing the original instruction at address zero, the bootloader creates a new
GOTO
instruction which always branches to the start address of the bootloader code. The original application instruction at address zero is moved to a jump table, which is later called to exit the bootloader. The jump table also contains a
GOTO 000004h
instruction to ensure normal application operation if the first instruction was not a GOTO .
If the device is programmed with only the bootloader (no application), address
000000h
through the start address of the bootloader code will be in an unprogrammed state (
FFFFh
). These are
NOP
instructions which will quickly execute until the program counter reaches the start of the bootloader. This ensures entry into the bootloader for both programmed and unprogrammed parts.
Bootloader Re-entry
If the running application wants to reenter the bootloader, it should clear the
RCON<NOT_POR>
bit and then execute a
RESET instruction. When the bootloader returns control to the main application, the
NOT_POR
bit will be in the set state. If an application needs to reset quickly without waiting for the bootloader timeout, it should leave this bit in the set state. This will cause the bootloader to skip its normal operation and return immediately to the application.
Prior to executing the
RESET
instruction to reenter the bootloader, the main application can specify the MAC and IP address
124
7.2 Available Demos Microchip TCP/IP Stack Help Internet Bootloader for the bootloader to use. To do this:
1. Select a random memory location where 12 bytes can be written
2. Copy the MAC address to the chosen memory location at offset 0
3. Copy the IP address to the chosen memory location at offset 6
4. Compute an IP checksum of the MAC and IP address stored at the memory locations 0 through 9
5. Write the IP checksum at the chosen memory location at offset 10
6. Store the address of the chosen memory location into the
PRODH:PRODL
registers
7. Clear the
RCON<NOT_POR>
bit and execute a
RESET
instruction to enter the bootloader
Upon entry, the bootloader will detect that the
RCON<NOT_RI>
bit is clear, indicating the bootloader was entered from the main application instead of a genuine POR event. In this case, the bootloader will dereference the PRODH:PRODL pointer, validate the checksum, and if valid, use the MAC and IP address specified. If the checksum is invalid, the bootloader will use it's default compiled MAC and IP address.
obtained automatically via DHCP) can be used as the TFTP bootloader target. If the IP address used by the main application is Internet routable, then the bootloader itself will be accessible via the Internet.
Memory Map
The entire program memory map when using the bootloader is shown below.
*: GOTO instruction is automatically generated by bootloader when writing. Application instruction at address
000000h
is moved to Bootloader Jump Table.
125
7.2 Available Demos Microchip TCP/IP Stack Help Internet Bootloader
**: Some configuration options are not supported and will automatically be changed by the bootloader before flashing. The bootloader requires HS or HS+PLL oscillator mode and does not support 1:1 and 1:2 Watchdog Timer Postscale modes.
Switching between Extended and non-Extended mode is not supported either. (The bootloader must be recompiled to change modes.)
The bootloader uses a block of 8256 bytes of program memory. To prevent the application from inadvertently using this block, you should modify the linker script in your application prior to compiling. For example, for the MPLAB
®
C18 C compiler, the linker script will contain a
CODEPAGE
line describing the available Flash memory in the device. For the
PIC18F97J60 product with 128kB of program memory, the linker script (
18f97j60i.lkr
) will contain a line such as:
CODEPAGE NAME=page START=0x2A END=0x1FFF7
This line indicates that the linker can place application constants and code anywhere between
00002Ah
and
01FFF7h
. This line must be split into two
CODEPAGE
lines to describe the gap in available program memory occupied by the bootloader. Ex:
CODEPAGE NAME=page START=0x2A END=0x1DBBF
CODEPAGE NAME=page2 START=0x1FC00 END=0x1FFF7
The above example removes the Jump Table and Bootloader Code blocks for the PIC18F97J60 with 128kB of Flash memory. Other devices with less Flash memory will need to use different start and end values according to the Jump Table start address and Bootloader Code end address described in the memory map figure above.
Erase Operations
The TFTP server performs a "bulk erase" before starting any TFTP put (write) operation. The erase is not a true bulk erase because the bootloader and configuration words remain intact. However, all other locations are reverted to their unprogrammed state. The erase procedure starts with the Flash page containing the Jump Table and continues backwards in memory towards address
000000h
. After address
000000h
is erased, the last program memory page containing the device configuration words is erased. For example, assuming a PIC18F97J60 with 128kB of Flash, the erase procedure will follow these steps:
1. Erase 01D800h-01DBFFh
2. Erase 01D400h-01D7FFh
3. Erase 01D000h-01D3FFh
4. ...
5. Erase 000400h-0007FFh
6. Erase 000000h-0003FFh
7. Erase 01FC00h-01FFFFh
After the last page containing the configuration words are erased, the configuration words are immediately reprogrammed to their previous value. This algorithm provides very robust operation with an extremely low likelihood of destroying access to the bootloader due to an unexpected event (ex: power or network connectivity is lost while bootloading). Unexpected events will leave the first
GOTO
instruction at address
000000h
intact, ensuring that the bootloader will start up again. Because the configuration words are erased last, there will not be any means of circumventing the internal code protect feature while application code still remains in the device.
Program Operations
Program operations are performed sequentially starting at address
000000h
and growing upwards, as presented in the .hex
file to be programmed. The device configuration words are typically the last values encountered in the .hex file. Because the erase procedure involves clearing the configuration words and then immediately reprogramming them, the configuration words will already be programmed by the time the configuration words are encountered in the
.hex
file. Therefore, if the
.hex file contains different configuration words from what are already stored in the Flash memory, the bootloader will have to perform a new erase operation on the last page prior to programming the new configuration words. This extra erase/write cycle will reduce overall Flash endurance on the last page as compared to the rest of the device. However, the bootloader will not perform this erase/write if the configuration words have not changed. This feature preserves endurance for most application firmware upgrades, which typically do not require different configuration options to be programmed.
126
7.2 Available Demos Microchip TCP/IP Stack Help Internet Bootloader
Read Operations
To save code space, the bootloader currently only supports reading through the TFTP server as binary data. Instead of getting a .hex file from a TFTP get operation, the bootloader will send back a binary file sized to the amount of internal Flash memory available (128kB for PIC18F97J60, 64kB for PIC18F66J60, etc.). The bootloader verifies code immediately after programming devices, so the read feature is primarily for debugging only.
Read operations are disabled if the currently programmed application has the PIC
®
microcontroller Code Protect feature turned on.
7.2.2.2
Using the Bootloader
Operation
After the bootloader has started, the code will enable the Ethernet module and begin running a private UDP/IP stack. It will use the following default addresses out of Power-on Reset:
• IP Address ( see page 152): 192.168.97.60
• MAC Address ( see page 152): 00-04-A3-00-00-00
These default addresses are statically defined and can only be changed by recompiling the bootloader itself. However, if the
use the application assigned IP and MAC addresses (if provided).
The only services that are available during bootloader operation are TFTP and ARP. ICMP (ping) and other services are not implemented.
Configuring Your PC (Power-on Reset entry)
To access the bootloader, the bootloader's IP address must be on the same subnet as your computer. For the default
192.168.97.60 IP address, you must temporarily change the settings on your PC. If the bootloader's IP address was application specified and already on the same subnet as your PC, then this section should be skipped.
The following instructions assume you are using Microsoft
®
Windows
®
XP and will vary for other operating systems.
1. Open Network Connections.
2. Right click on the network adapter that you are using to communicate with the bootloader and choose Properties.
127
7.2 Available Demos Microchip TCP/IP Stack Help Internet Bootloader
3. Select Internet Protocol (TCP/IP) and click Properties.
4. Select Use the following IP address and then enter the IP address 192.168.97.61.
5. Click OK and then Close on the previous dialog to close them and set the new address.
TFTP Operation (Power-on Reset entry)
Most operating systems come with a TFTP client built in. In Microsoft Windows, this utility is named tftp.exe
. This utility is
128
7.2 Available Demos Microchip TCP/IP Stack Help Internet Radio a very simple console application which can be used to upload your application .hex file over the network to the bootloader.
To perform a Flash upgrade using the tftp.exe
client, follow these procedures:
1. At a console, type the following command, but do not execute it. Make appropriate path changes to the .hex file. tftp
192.168.97.60 put "C:\Microchip Solutions\TCPIP Demo App\TCPIP Demo App-C18.hex"
2. Power cycle the target board or if the device has a MCLR reset button, press it.
3. Quickly press enter to execute the tftp
command. If firmware is already in the device, the bootloader will automatically terminate after approximately 4 seconds, so you must execute the tftp command within the 4 second window.
4. If successful, the TFTP client will indicate how long the transfer took. Actual programming time will vary based on numerous factors, including need to erase the Flash first, .hex file size, .hex file complexity, and internal programming time. The reported transfer rate is therefore not a good metric of network performance in embedded applications.
The bootloader does data read back verification shortly after writing and does not need a second step to read back the Flash contents. If a verification error occurs, the error will be immediately reported to the TFTP client.
The most likely cause of a verification failure is not a Flash endurance problem, but rather, an invalid .hex file given as input. As shown in the bootloader memory map, .hex files cannot contain any data within the 8KB area of Flash were the bootloader is stored. The bootloader internally masks off this region of Flash and treats it as read only to prevent bootloader corruption. As a result, if the .hex file contains data in the read-only region, the write will fail and verification will show a mismatch.
5. After a successful write, the bootloader will time out after approximately 4 seconds and begin executing the main application that was just loaded.
After completing the TFTP upload process, restore your PC's IP address settings to allow normal network activity and access to the application you bootloaded.
TFTP Operation (Application entry)
a time-sensitive power cycling process. Instead, you can execute a TFTP operation directly on the device without any interactive steps.
1. At a console, type the following command and execute it. Make appropriate IP adddress/hostname and path changes.
tftp mchpboard put "C:\Microchip Solutions\TCPIP Demo App\TCPIP Demo App-C18.hex"
If the bootload process is interrupted due to a network failure or user cancellation, you can simply retry the tftp command.
The bootloader will not attempt to run a partially bootloaded application. The application specified MAC and IP address will be retained indefinitely until the device is power cycled or otherwise reset.
If the bootload operation is interrupted due to a power failure, the bootloader will start back up using the Power-on Reset default MAC and IP addresses. In this case, you must follow the Power-on Reset entry directions to recover.
7.2.3
WebVend
The TCPIP WebVend App is a sample web-enabled vending machine application. It is used by the TCP/IP Webinar series:
1. TCP/IP Networking Part 1: Web-Based Status Monitoring ( view )
2. TCP/IP Networking Part 2: Web-Based Control ( view )
3. TCP/IP Networking Part 3: Advanced Web-Based Control ( view )
129
7.2 Available Demos Microchip TCP/IP Stack Help WiFi Console
7.2.4
Internet Radio
IMPORTANT: Because of changes to the SHOUTcast protocol, the Internet Radio demo app is no longer able to perform its intended function. This demo now exists only as an TCP/IP Stack code example.
The Internet Radio app demonstrates the use of the TCP/IP Stack for a stand-alone embedded application. This application is capable of contacting various SHOUTcast servers and playing back the audio stream to a pair of stereo speakers. The demo requires the Internet Radio Demonstration board. A PIC18F67J60 is used for the processing of Ethernet interface, while an external MP3 decoder handles the audio playback. Application note AN1128 "TCP/IP Networking: Internet Radio
Using OLED Display and MP3 Audio Decoder (DS01128)" describes the Internet Radio application in detail.
automatically until a genre is selected. Follow the OLED display’s on screen menu to change genre, station, and volume.
the IP address shown on the board’s OLED display. Shown below is a screen shot of the webpage. To start, first select a genre from the drop down list box, and click 'Select'. To change station, click 'Prev' or 'Next'. To adjust volume, click 'Down' or 'Up'. If a station does not play, it could be that the port is blocked, try a different station.
Each Internet Radio board also has a sticker containing a unique MAC address. This unique MAC address can be saved to the board by using the web interface’s configurations section.
130
7.2 Available Demos Microchip TCP/IP Stack Help WiFi Console
7.2.5
WiFi Console
The TCPIP WiFi Console Demo App (previously the TCPIP WiFi Iperf Demo App) is a command line interface (CLI) to the
MRF24WB0M / MRF24WG0M. It allows for command line debugging and setup of network information for the wireless LAN.
It also has iperf built in for doing WLAN bandwidth testing. This application is meant more as a development debug tool, and should be disabled in end user applications.
The following network types are supported
• CFG_WF_INFRASTRUCTURE (as a client in infrastructure network)
• CFG_WF_ADHOC
• CFG_WF_P2P (Wi-Fi Direct) (as a group client in Wi-Fi Direct network)
CFG_WF_P2P is only available for MRF24WG0MA/B.
New security modes are supported.
• WF_SECURITY_WPS_PUSH_BUTTON (supported by MRF24WG0M only)
• WF_SECURITY_WPS_PIN (supported by MRF24WG0M only)
Wireless configurations are set up in WF_Config.h
New demo feature: Cloud Networking Application
From MLA v5.42.06 March 2013 and future releases, a new demo is added to showcase cloud networking. The relevant source file is CloudTCPClient.c. Reference web server is http://www.openwificloud.com
This cloud demo supports the functions
• Temperature reading
• Potentiometer reading
• LEDs ON/OFF toggling
7.2.5.1
Standalone Commands
These command line interface (CLI) commands are not related to the wireless or networking interface directly.
help
Lists all the available CLI commands for the MRF24WB0M / MRF24WG0M.
getwfver
Lists the WiFi firmware and host driver version numbers.
reset
Issues a host reset.
cls
Resets the prompt.
131
7.2 Available Demos iperf kill iperf ping
Microchip TCP/IP Stack Help WiFi Console
Initiates an iperf session. See the section on iperf ( see page 136) for more information.
Stops a running iperf session. See the section on iperf ( see page 136) for more information.
Initiates a ping session. This will verify IP-level connectivity to another TCP/IP terminal by sending
Internet Control Message Protocol (ICMP) Echo Request messages. The receipt of corresponding
Echo Reply messages are displayed, along with round-trip times.
killping wpscred
Stops a running ping session.
Display WPS credentials.
7.2.5.2
iwconfig Commands
Note that most of these items should not be changed while the device is in a connected state to a network.
iwconfig commands take the following structure:
132
7.2 Available Demos Microchip TCP/IP Stack Help iwconfig [ ssid <name> ]
[ mode <idle|managed|adhoc> ]
[ channel <channel list|all> ]
[ power <reenable|disable|unicast|all> ]
[ domain <name> ]
[ rts <length> ]
[ scan ]
[ hibernate ]
[ wakeup ]
Note: iwconfig with no options will display wireless status. ssid name 1-32 ASCII characters.
Currently doesn't accept ( see page 174) spaces in the SSID name.
mode idle managed adhoc
WiFi Console
Forces the MRF24WB0M / MRF24WG0M to disconnect from any currently connected network
(adhoc or infrastructure).
The MRF24WB0M / MRF24WG0M will connect ( see page 176) to the SSID in infrastructure
mode. Note that all the network parameters must be correct before this command is called.
The MRF24WB0M / MRF24WG0M will connect ( see page 176) to the SSID in adhoc mode.
Note that all the network parameters must be correct before this command is called.
channel channel list all power reenable / all disable unicast
A comma separated list of all the channels to scan.
Sets the MRF24WB0M / MRF24WG0M to scan all channels in the given regulatory domain.
Enables all power saving features (PS_POLL) of the MRF24WB0M / MRF24WG0M.
MRF24WB0M / MRF24WG0M will wake up to check for all types of traffic (unicast, multicast, and broadcast).
Disables any power savings features. The MRF24WB0M / MRF24WG0M will always be in an active power state.
The MRF24WB0M / MRF24WG0M will be in it's deepest sleep state, only waking up at periodic intervals to check for unicast data. The MRF24WB0M / MRF24WG0M will not wake up on the
DTIM period for broadcast or multicast traffic.
domain fcc ic etsi spain france japan japana japanb
United States channels 1-11.
Canada channels 1-11. Applicable for MRF24WB0M only.
European channels 1-13.
Spanish channels 10-11. Applicable for MRF24WB0M only.
French channels 10-13. Applicable for MRF24WB0M only.
Japanese channel 1-14. Applicable for MRF24WG0M only.
Japanese channel 14. Applicable for MRF24WB0M only.
Japanese channels 1-11. Applicable for MRF24WB0M only.
133
7.2 Available Demos Microchip TCP/IP Stack Help WiFi Console rts length Set the requested number of bytes to send. Default max is 2347.
scan
Instructs the MRF24WB0M / MRF24WG0M to perform an active site scan. Scan results will be displayed to the output terminal.
hibernate
Turns off LDO of the MRF24W module, which is equivalent to removing power to the
MRF24WB0M / MRF24WG0M. Has the same effect of resetting MRF24WB0M / MRF24WG0M.
MRF24W state is not maintained when transitioning to hibernate mode.
wakeup
Restores power to the MRF24WB0M / MRF24WG0M and reconnects.
Note: scan is only supported by the WiFi EZConfig demo.
7.2.5.3
ifconfig Commands
Note that these items should not be changed while the device is in a connected state to a network.
ifconfig commands take the following structure: ifconfig [ <IP address> ]
[ <MAC address> ]
[ netmask <IP address> ]
[ gateway <IP address> ]
[ auto-dhcp <start|drop> ]
Note ifconfig by itself will give network status.
IP address
Use a static IP address. IP address must be in dot-decimal notation.
Note that this command will return an invalid parameter if the DHCP client is enabled. First disable the DHCP attempts ( ifconfig auto-dhcp drop
) before running this command.
MAC address
Redefine the device MAC address. MAC address must be specified in hexadecimal colon notation.
This command can only be issued when the MRF24WB0M / MRF24WG0M is in idle mode. Doing so at other times can have unexpected results.
netmask
IP address
Use the specified IP address for the netmask. The netmask value is specified in dot-decimal notation.
gateway
IP address
Configure the gateway address. The gateway value is specified in dot-decimal notation.
134
7.2 Available Demos auto-dhcp start drop
Microchip TCP/IP Stack Help WiFi Console
Starts the DHCP client.
Only valid if the DHCP module has been compiled in. DHCP client is started by default.
Stops the DHCP client. A static IP address will need to be assigned to the device.
Only valid if the DHCP module has been compiled in.
7.2.5.4
iwpriv Commands
Note that these items should not be changed while the device is in a connected state to a network.
iwpriv commands take the following structure: iwpriv [ enc <none|wep|wpa-psk|wpa-phrase> ]
[ key <[1]|[2]|[3]|[4]> <value> ]
[ psk <value> ]
[ phrase <value> ]
Note iwpriv by itself will display network security settings. enc none wep wpa-psk wpa-phrase
The MRF24WB0M / MRF24WG0M will not use any encryption to connect ( see page 176) to the
specified network.
The MRF24WB0M / MRF24WG0M will use either WEP-40 (short) or WEP-104 (long) encryption
to connect ( see page 176) to the specified network.
The MRF24WB0M / MRF24WG0M will use the specified 32-byte PSK to connect ( see page
The MRF24WB0M / MRF24WG0M will take the given 1-32 ASCII character passphrase, along with the SSID, and compute the required 32-byte PSK for the network.
Note that doing so takes approximately 30 seconds to complete the calculation.
key
[1] [2]
[3] [4] value
Instructs the MRF24WB0M / MRF24WG0M to use this key for connecting to the WEP encrypted network.
Note that only key 1 is considered safe to use among different AP vendors. Keys 2-4 can have implementation specific entries that may not be compatible from AP to AP.
If value is specified, this will instruct the MRF24WB0M / MRF24WG0M to use the specified key number and also program the device with this key value. For WEP-40 networks, this implies the key is either 5 ASCII characters of 10 hex characters in length. For WEP-104 networks, this implies the key is either 13 ASCII characters or 26 hex characters in length.
The console only accepts hex WEP keys. Therefore, the user must do the ASCII to hex conversion for their ASCII keys.
135
7.2 Available Demos psk value
Microchip TCP/IP Stack Help WiFi Console
32-byte hex value for the PSK.
This value can be calculated from the following website hosted on the Wireshark website .
phrase value An 8-63 ASCII character phrase (delimited with quotes if using spaces). This phrase will be used along with the SSID to generate the 32-byte PSK value for the network.
7.2.5.5
iperf Example
iperf is a networking tool that helps to measure networking bandwidth and performance. The console demo application has a built-in iperf application, that can act as both a client and server for testing. iperf has the ability to test both UDP and TCP. In the case of UDP, you can specify the size of the UDP datagrams. For TCP, iperf measures the throughput of the payload.
In order to run iperf, you'll need a PC that has an iperf application on it as well. There is an open source version that is maintained, as well as many other variants across the internet. iperf is meant to be run at the command line. However, if a
GUI is desired, a variant called jperf can be used.
In the case of the demo application, iperf measures performance data in a unidirectional format. Therefore, the side that the server is running on is considered the receiver, and provides the most accurate performance values.
Command Synopsis
iperf [ -s|-c <IP addr> ]
[ -u ]
[ -i <sec> ]
[ -b <bandwidth> ]
[ -t <time> ]
-s
-c <IP addr>
-u
-i <sec>
-b <bandwidth>
-t <time>
Runs the iperf server. No IP address needs to be specified.
Runs the iperf client. The IP address is the IP address of the server.
Server side only. Sends UDP datagrams.
Specified the time interval, in seconds, that the display will be updated.
Specifies the amount of data to try and send. This option is only valid with UDP datagrams.
Amount of time, in seconds, to run the test.
Running the Demo
After powering on the development board and associating with your wireless network, you'll need to start the server side iperf application first. if you start iperf as a server on the development board in the console, then this implies that you are trying to measure the MRF24WB0M / MRF24WG0M receiver performance. If you start the iperf server on a PC, then you will be measuring MRF24WB0M / MRF24WG0M transmit performance. Below are two images that show receiver and transmitter performance, respectively.
136
7.2 Available Demos Microchip TCP/IP Stack Help WiFi EZConfig
137
7.2 Available Demos Microchip TCP/IP Stack Help WiFi EZConfig
7.2.6
WiFi EZConfig
Overview
WLAN networks provide a unique challenge for configuring embedded wireless without a natural user interface. Unlike wired networks, wireless networks require unique items such as the SSID and network type and keys, which have to be sent to the device in some form or another. Traditionally, this means a user would enter this information using a keyboard and display.
EasyConfig is a mechanism to allow for configuration of an embedded device on a wireless network. It utilizes the web server of the TCP/IP stack, as well as a wireless adhoc (IBSS) network to allow the user to input the desired network
The EasyConfig demo works in roughly the following manner:
1. Upon power up the device, it broadcasts an adhoc network with SSID "EasyConfig".
3. Upon connecting, the user can then use a standard web browser to go to the IP address of the demo (http://169.254.1.1).
4. The user will then be presented with some web pages from the web server. The index.htm web page has some additional information on EasyConfig, and also shows the continually updating status of the LEDs, buttons, and potentiometer on
a network of their choosing.
5. The device will then reset itself, using the parameters for the new network. In order to continue using the demo, the client device will now need to reconnect to the same network that the development board is on.
demo to startup in adhoc mode again, then button S3 on the Explorer 16 development board needs to be held down for 4 seconds.
The following network types are supported
• CFG_WF_ADHOC
• CFG_WF_SOFT_AP
Wireless configurations are set up in WF_Config.h
Adhoc Networks
one is not found. Adhoc networks are peer-to-peer networks, with no centralized coordinator for the network. All the devices in the network share the responsibilities of keeping the network going.
One downfall of adhoc networks is that typically security is not employed on them. The MRF24WB0M / MRF24WG0M module can secure the network with WEP (40-bit/104-bit) security, as can most laptops and adhoc devices. Almost no devices in the market can secure an adhoc network with WPA level security due to the tremendous overhead in doing so.
The demo starts an adhoc network with no security. This means that all the network information that is being configured on the device is going over-the-air in the open. For most applications, unless somebody is specifically attempting to eavesdrop on this network, there should be little to no impact on security. However, for applications that do require some baseline level of security, then WEP can be employed on the network. SSL can also be used to encrypt the traffic between the web server and client browser. Additionally, some other form of data-level security can be employed to obfuscate the ASCII network information being sent to the device.
SoftAP Networks
This is only available for MRF24WG0MA/B. Upon starting the demo, the MRF24WG0MA/B will start up a network as a
138
7.2 Available Demos Microchip TCP/IP Stack Help WiFi EZConfig
to the softAP. Routing is not supported. The demo can start a softAP network with no or WEP security.
Network Parameters
Below is some information on the parameters that are being sent via HTTP POST from the client browser to the device. All this information is being parsed and handled in the function HTTPPostWifiConfig() in CustomHTTPApp.c
.
WLAN Type
SSID
Security Type
Either adhoc or infrastructure
Name of network (1-32 ASCII characters)
• None
• WEP-40 (5 ASCII characters or 10 hex numbers)
• WEP-104 (13 ASCII characters or 26 hex numbers)
• WPA/WPA2 passphrase (8-63 ASCII characters)
Configured vs Un-configured State
When the demo is running in an unconfigured state (i.e, serving the default EasyConfig SSID in adhoc mode), then the heartbeat LED (LED0) will blink twice per second to indicate that it hasn't been configured yet. Once the network has been configured, then the heartbeat LED will change to blink once per second, in a similar fashion to the other TCP/IP demo applications.
EasyConfig Demo Additional Features
There are four defines that enable EasyConfig as well as extend it with natural features.
STACK_USE_EZ_CONFIG
EZ_CONFIG_SCAN
EZ_CONFIG_STORE
EZ_CONFIG_STALL
The top level define to enable EasyConfig features.
Adds additional ability to instruct the MRF24WB0M / MRF24WG0M module to scan for available networks nearby. This can be done when you are already connected to a network.
Store the configuration information for the new network to non-volatile memory. In the event that WPA/WPA2 level security is used, the 32-byte PSK will be saved to
NVM.
Before switching networks, forces the configuration state machine to pause. This gives the client device additional time to request resources from the development
platform before it attempts to connect ( see page 176) to a new network.
EZ_CONFIG_SCAN
The MRF24WB0M / MRF24WG0M has the ability to scan for nearby networks. This is similar to a laptop that can show available wireless networks that can be connected to. The scan results are stored on the MRF24WB0M / MRF24WG0M module, and can be retrieved one at a time from the device. This helps to reduce the impact of storing all the scan results on the host itself.
The scan can be performed when idle, or when connected to either an adhoc or infrastructure network.
139
7.2 Available Demos Microchip TCP/IP Stack Help Google PowerMeter
EZ_CONFIG_STORE
The new network parameters can also be stored to non-volatile memory. For the Explorer 16 development board, this information is stored to the 32kB EEPROM on the board.
One extremely useful feature of storing the information surfaces when connecting to a network with WPA/WPA2 security.
The computation of the 32-byte PSK is computationally heavy, and can take the MRF24WB0M / MRF24WG0M up to 30 seconds to calculate the key. In a normal application, it would be unacceptable to have to wait 30 seconds every time the device started up before connection to the network was established.
EZ_CONFIG_STORE
helps to alleviate doing the calculation each time by storing the 32-byte PSK to NVM. In doing so, there is only one 30-second hit the very first time the key is calculated only. Successive connections to the network will be significantly faster.
EZ_CONFIG_STALL
The configuration state machine that controls the network connections within EasyConfig can employ a wait state between switching networks. From an end user experience, this becomes vital. If the switch between different networks was instantaneous, a client browser would never get an indication that the HTTP session was closed after the POST information was sent. The end user would see this as a browser that was continually waiting, which would eventually timeout.
To make the switch more natural and complete,
EZ_CONFIG_STALL
adds additional time to allow the client to get the remaining web page information. For the demo, this includes a HTTP redirect to a page that highlights the new network information.
Current Incompatibilities
The javascript being used in EasyConfig is not compatible with Internet Explorer 7. EasyConfig does work with many other flavors of browser on different architectures, not limited to Internet Explorer 8, Mozilla Firefox, Apple Safari and Google
Chrome. The incompatibility is something that is being investigated, and should be fixed in a future stack release.
New demo feature: Mobile Application
From MLA v5.42.06 March 2013 and future releases, a new mobile application demo is added to Explorer16+PIC32 configuration. The relevant source file is MobileTCPServer.c. Supported devices run on Android (version 4.0 or later) and iOS6 or later. On Goggle Play store and Apple Apps Store, search for the app "OpenWifiFog".
The functions supported
• Temperature reading
• Potentiometer reading
• LEDs ON/OFF toggling
7.2.7
Demo App MDD
The TCPIP MDD Demo App is a variant of TCPIP Demo App that uses an SD card or USB Thumb Drive to store web pages.
For more information, see the TCPIP MDD Demo App Getting Started guide, installed in the stack's documentation folder.
140
7.2 Available Demos Microchip TCP/IP Stack Help Energy Monitoring
7.2.8
Google PowerMeter
Google, Inc. has deprecated Google PowerMeter and expressed its intent to remove access to it on September 16, 2011.
Because of this development, Microchip Technology has removed the Google PowerMeter demo projects from the Microchip
Application Libraries distribution. To obtain Microchip's Google PowerMeter reference implementation, please download the archived Microchip Application Libraries installation from June, 2011 from www.microchip.com/mla .
7.2.9
Energy Monitoring
This demo implements a power monitoring application that uploads data to Google PowerMeter. In this application, actual power consumption data is obtained from a PIC18F87J72 Energy Monitoring PICtail Plus Daughter Board.
Google, Inc. has deprecated Google PowerMeter and expressed its intent to remove access to it on September 16, 2011.
Because of this development, Microchip Technology has removed the Google PowerMeter demo projects from the Microchip
Application Libraries distribution. To obtain Microchip's Google PowerMeter reference implementation, please download the archived Microchip Application Libraries installation from June, 2011 from www.microchip.com/mla.
This Energy Monitoring demo has been modified to remove its Google PowerMeter upload features. However, the energy measurements made by the PICtail can still be viewed on the demo board-hosted web page.
The PC GUI for the Energy Monitoring PICtail can be obtained http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1406&dDocName=en550456
from:
141
Required Files Microchip TCP/IP Stack Help 8.2 How the Stack Works
8
Using the Stack
This section describes how to use Microchip's TCP/IP Stack.
8.1
Stack Architecture
The TCP/IP stack is modular in design and written in the 'C' programming language. It follows the TCP/IP (Internet) protocol suite. The stack currently supports the TCP and UDP transport layer modules, the IPv4 (and part of the ICMP) Internet Layer modules, the ARP link layer modules, and a variety of application layer modules. Most of the Media Access Control link layer
functionality is provided by the hardware MAC/PHY chips ( see page 63) used with the stack.
8.2
How the Stack Works
This topic contains information about how the stack works, what is required to use the stack, and how your code can be structured to work cohesively with the TCP/IP stack.
8.2.1
Required Files
There are several base files that must be included in every project using Microchip’s TCP/IP stack. They are:
• A main file ( see page 143)- this is the file with your application code in it..
• ARP.c
and ARP.h
- These files are used by the stack to discover the MAC address associated with a given IP address.
•
Delay.c
and
Delay.h
– These files are used to provide delays for some stack functions. Note that it would be best to not use these delays in your own code, as they do create blocking conditions.
• Physical layer files – These files are used to enable a specified physical layer. More information on which files to include
can be found in the Hardware Configuration ( see page 147) section.
•
Helpers.c
and
Helpers.h
– These files contain helper functions used for miscellaneous stack tasks.
•
IP.c
and
IP.h
– These files provide internet layer functionality for the stack.
•
StackTsk.c
and
StackTsk.h
– These files contain the code to initialize the stack and perform the callbacks that keep the stack going.
•
Tick.c
and
Tick.h
– These files implement a tick timer that is used to implement some timing functionality within the stack.
•
HardwareProfile.h
– This configuration file is used to set up hardware options.
142
8.2 How the Stack Works Microchip TCP/IP Stack Help Main File
•
TCPIPConfig.h
– This configuration file is used to set up firmware options.
•
MAC.h
– This header file provides macros and structures relating to the hardware MAC layer.
•
TCPIP.h
– This is the primary include file for the stack. Your main file should include
TCPIP.h
.
You may choose to include additional files to support additional protocols and features. The list of protocols and their
8.2.2
APP_CONFIG Structure
your application and initialize it with the default values defined in
TCPIPConfig.h
. For example, you would set the bytes of the
MyIPAddr
field to the values of the
MY_DEFAULT_IP_ADDR_BYTEn
macros in
TCPIPConfig.h
. The
InitAppConfig function in the file MainDemo.c
of the TCPIP Demo App project demonstrates how to populate this structure completely.
The full list of parameters in the APP_CONFIG structure is defined in the file
StackTsk.h
.
At the beginning of most stack demonstration applications, the code will check an EEPROM to determine if it contains a valid image of an APP_CONFIG structure. If so, it will read the image and use it to populate the AppConfig instance in the demo project. Otherwise, it will load the application variables from your statically defined values and/or configure them based on application protocols (DHCP/AutoIP). This allows a board to retain its configured settings even if the application loses power.
8.2.3
Main File
Because there is a huge variety of ways in which you could write your application, this section will provide an outline of what your main file should contain. It also provides some description of the stack operation, and of best-practice programming techniques to prevent stack problems.
8.2.3.1
Initialization
You should start by initializing your hardware. This includes PPS pins, oscillators, LEDs, LCDs, any SPI or PMP modules you're using to control your hardware MAC/PHY chip, etc.
the tick timer that manages your stack timing. Then call any additional initialization functions that require hardware
memory storage ( see page 147) device to store web pages, so it should be called now.
Once your hardware is initialized, you can begin configuring your stack. Most of the stack-related application variables are
default values, or provide another means of initializing the AppConfig structure.
Finally, you can initialize the stack by calling the StackInit() function. This function will automatically call the initialization
application-specific firmware initialization functions.
8.2.3.2
Main Loop
Once your program has been initialized, you should enter an infinite loop which will handle your application tasks. Within this
143
8.2 How the Stack Works Microchip TCP/IP Stack Help Cooperative Multitasking loop, there are two functions that you must call regularly:
StackTask
and
StackApplications
.
The
StackTask
function will perform any timed operations that the stack requires, and will handle transmission and reception of data packets. This function will also route any packets that have been received to the appropriate application protocol-level function to handle it.
The
StackApplications
function will call loaded application modules. For example, if an application is using an HTTP2 server, StackApplications
will automatically call the HTTPServer ( see page 256)
function to process any
HTTP2 tasks that are queued.
Most sub-tasks within StackTask and StackApplications are implemented as state-machine controlled cooperative multitasking functions. Since these sub-tasks consists of multiple steps (which may occur at varying times) this call-back system ensures that no single task will monopolize control of the processor.
Within this main loop, you may also want to poll for any I/O changes in your application and call any application specific tasks that you've implemented. To avoid causing buffer overflows in your hardware or protocol timing violations you should try to implement your own application tasks in callback functions with timing-based triggers. A method to do this is described in the next topic.
You must make one call to StackTask for each call of StackApplications but you aren't required to call these functions with any specific frequency. Calling
StackTask
too infrequently could limit your throughput, though, as each call of
StackTask
can retrieve one packet (at most) from the packet buffer. Similarly, application tasks that are time-dependant
(like an ICMP ping response) may produce undesirable results if
StackApplications
is not called frequently enough.
The amount of time that the main loop takes to complete one iteration depends on several factors. If data is ready to be transmitted, or if a packet of received data was received, the
StackTask
function will take more time than it would otherwise. Each additional protocol included in your application will cause the main loop to take additional time as well, with the amount of time for each varying from the length of the shortest state machine state in the task to the longest.
Once your application is complete, you can set up a test case to determine the min/average/approximate maximum time that your loop will take to run. You can set your code up to use an internal timer to measure the duration of each iteration of the main loop, or you can set the code up to trigger an output pin each time the main loop completes, and use an oscilloscope to capture the network execution time. You can then provide application inputs or additional network traffic with a PC program
(or other PICs) to simulate real-world operating conditions.
8.2.4
Cooperative Multitasking
If you implement the TCP/IP stack using a cooperative multitasking approach, you must make periodic calls to task functions to transmit/receive packets and to maintain protocol functionality. To prevent conflicts with the stack, you should write your own custom tasks in a way that will allow them to give up the processor if it's not needed. If you create a protocol or application task with multiple steps, it may be beneficial to divide them up between states. You can then use a global or static variable to track your state, and call that task function periodically to move through the state machine.
The following example contains a sample application for transferring data from a machine of some type to an external target.
It includes a task function called
ApplicationTask
that has states to wait for button inputs, update the display, and transfer data from the machine. The functions in the example are used to represent other actions:
ButtonPressDetected represents the code needed to check for an input from the user,
LCDDisplay
represents the code needed to update a display on the machine,
SampleData
gets data from the machine,
DataBufferIsFull
indicates that the buffer used to hold data samples needs to be sent, and
TransferData
is a function that writes the data to an open TCP or UDP socket.
In between each of these states, the
ApplicationTask
function returns to the main loop, and the
StackTask
and
StackApplications functions are called. This flow will allow the StackApplications function to maintain any module tasks. The
StackTask
function will periodically transmit the data from the socket buffers to its destination, which will prevent the transmit buffers from overflowing.
unsigned char
gAppState;
// State tracking variable
int
main (
void
)
{
144
8.2 How the Stack Works Microchip TCP/IP Stack Help Cooperative Multitasking
// Pseudo-initialization function
InitializeCode();
// Setup application state
gAppState = STATE_DISPLAY_MENU;
// Main Loop
while
(1)
{
StackTask();
StackApplications();
ApplicationTask();
}
}
void
ApplicationTask (
void
)
{
switch
(gAppState)
{
case
STATE_DISPLAY_MENU:
LCDDisplay (stringMainMenu);
gAppState = STATE_MAIN_MENU;
break
;
case
STATE_MAIN_MENU:
if
(ButtonPressDetected (BUTTON_1) )
// Check an input
gAppState = STATE_MONITOR_MACHINERY;
break
;
case
STATE_MONITOR_MACHINERY:
LCDDisplay (stringTransferringData);
// Generate or send data
if
(DataBufferIsFull())
{
TransferData();
}
else
{
SampleData();
}
if
(ButtonPressDetected (BACK_BUTTON) )
gAppState = STATE_DISPLAY_MENU;
break
;
}
}
Some of the states in your application may be time based. Suppose, for example, that our sample application needs to send data for 5 seconds every time an input is detected. Stack problems could occur if the application used a delay loop to wait for
5 seconds until it was time to stop, so this functionality should be implemented using the stack's built-in tick timer. When the
request to send data is received, the code will get the current tick time using the
function, add enough ticks to make up 5 seconds, save it in a static variable called tickCounter
, and then switch to a transmit state.
Every time the
ApplicationTask
function gets called, it will enter this state in the state machine, call
again, and then compare it to the value stored in that static variable. If the current time is later than the initial time plus the delay, the code will restore the display and re-enter the main menu state. void ApplicationTask (void)
{
static DWORD tickCounter;
switch (gAppState)
{
case STATE_DISPLAY_MENU:
LCDDisplay (stringMainMenu);
gAppState = STATE_MAIN_MENU;
break;
case STATE_MAIN_MENU:
if (ButtonPressDetected (BUTTON_1) ) // Check an input
gAppState = STATE_MONITOR_MACHINERY;
break;
case STATE_MONITOR_MACHINERY:
LCDDisplay (stringTransferringData);
// Save the current time, and add 5 seconds to it
tickCounter = TickGet() + (5 * TICK_SECOND);
145
8.2 How the Stack Works Microchip TCP/IP Stack Help RTOS
gAppState = STATE_CONTINUE_MONITORING;
break;
case STATE_CONTINUE_MONITORING:
if ((long)(TickGet() - tickCounter) > 0)
gAppState = STATE_DISPLAY_MENU;
else
{
// Generate or send data
if (DataBufferIsFull())
{
TransferData();
}
else
{
SampleData();
}
}
break;
}
}
block critical functions for too long.
8.2.5
RTOS
As an alternative to implementing your stack application in a cooperative multitasking format, you can integrate the stack into a Real-Time Operating System. For more information, see Application Note 1264 on the Microchip web site.
146
External Storage Microchip TCP/IP Stack Help 9.1 Hardware Configuration
9
Configuring the Stack
There is a wide range of configuration options available for Microchip's TCP/IP Stack. This topic will discuss the functionality of these options, and how to implement them.
9.1
Hardware Configuration
Most hardware configuration is performed by commenting, uncommenting, or defining a series of macros in the one of the variants of the header file
HardwareProfile.h
. You can see sample versions of how to set these options in the copies of
HardwareProfile.h that are included with the stack's demo projects ( see page 84).
In most cases, the macro to enable a device is the same macro used to define the device's chip select pin. In the default copies of HardwareProfile.h included with the demonstration projects, there are example sections defined for most demo boards, delimited by preprocessor statements. For example, the section for the Explorer 16 begins with the macro "
#elif defined (EXPLORER_16) " and continues until the next demo board preprocessor statement. If you use one of these files as a base for your project, make sure you are modifying the macros in the correct section.
9.1.1
Clock Frequency
Many TCP/IP operations are time-dependant. By specifying the oscillator frequency that you're using in your application for the stack, you can enable automatic handling of these operations. To set hte clock value, substitute your oscillator frequency
(in Hertz) for the value in the following macro in
HardwareProfile.h
:
#define
GetSystemClock() xxxxxxxxxxxxxxx
There are also two other clock macros.
GetInstructionClock()
and
GetPeripheralClock()
provide frequency values for the instruction clock and peripheral clock in your microcontroller. These values will usually be set as a fraction of the system clock (i.e.
GetInstructionClock()
would be defines as
(GetSystemClock() / 2)
for PIC24F processors).
9.1.2
External Storage
There are several features in the TCP/IP stack that use external storage to maintain structures or web pages. Support for a few storage devices is included with the stack; the support files can be used as a template to write drivers for other devices as well. The
HardwareProfile.h
pin definitions are roughly equivalent for each storage device, except for the first word of the macro, which indicates which type of storage device it applies to (e.g. EEPROM_CS_IO vs SPIFLASH_CS_IO). There are three different storage media.
EEPROM
to the stack that it should use a EEPROM to store MPFS2 images, define the macro MPFS_USE_EEPROM in the
TCPIPConfig.h
header file. By default, the stack includes a driver for Microchip’s 25LC256 EEPROM family (to use the 1
Mbit EEPROM, you must also define the macro
USE_EEPROM_25LC1024
in
TCPIPConfig.h
). The macros to control communication with the EEPROM will be prepended with the string
EEPROM_
in this case. To enable communication, define
EEPROM_CS_TRIS and include the files
SPIEEPROM.c
and
XEEPROM.h
in your application. These files may requires
147
9.1 Hardware Configuration Microchip TCP/IP Stack Help ENC28J60 Config some changes to support additional EEPROM devices.
Serial Flash
Storage for MPFS images and custom structures is also available on serial flash devices (tested with SST 25VF016B and
Spansion 25FL040A). To indicate that the stack should use serial flash to store web pages, define
MPFS_USE_SPI_FLASH in
TCPIPConfig.h
. The communicaiton macros will be prepended with the string SPIFLASH_ in this case. To enable communication functionality, define
SPIFLASH_CS_TRIS
and include the files
SPIFlash.c
and
SPIFlash.h
in your application. These files may require some changes to support additional flash devices. There are several macros included within “SPIFlash.h” that must also be defined, including macros to define the sector and page sizes, and macros to describe whether the SST or Spansion flash device is being used.
SRAM
Semiconductor’s N256S0830HDA). The macros will be prepended with the string SPIRAM_ in this case. To use this functionality, define EEPROM_CS_TRIS and include the files “SPIRAM.c” and “SPIRAM.h” in your application. These files may require some changes to support additional RAM devices.
Macro
xxxxxx_CS_IO
Purpose Sample Value
Defines the LAT (or PORT, where applicable) register bit that corresponds to the chip select pin. Defining this macro will indicate that the stack should use the specified type of external storage.
LATDbits.LATD12
xxxxxx_CS_TRIS xxxxxx_SDI_TRIS
Defines the TRIS bit that corresponds to the chip select pin on the device.
xxxxxx_SCK_TRIS Defines the TRIS bit that corresponds to the clock pin of the SPI module connected to the device.
TRISGbits.TRISG6
Defines the TRIS bit that corresponds to the data-in pin of the SPI module connected to the device.
TRISDbits.TRISD12
TRISGbits.TRISG7
xxxxxx_SDO_TRIS Defines the TRIS bit that corresponds to the data-out pin of the SPI module connected to the device.
TRISGbits.TRISG8
xxxxxx_SPI_IF xxxxxx_SSPBUF
Points to the interrupt flag for the SPI module connected to the device.
Points to the SPI buffer register for the SPI module connected to the device.
IFS2bits.SPI2IF
SPI2BUF xxxxxx_SPICON1 Points to the SPI control register for the SPI module connected to the device.
SPI2CON1 xxxxxx_SPICON1bits Provides bitwise access to the SPI control register for the SPI module connected to the device. The ____bits registers are typically defined in the processor’s header files.
SPI2CON1bits xxxxxx_SPICON2 Points to the second SPI control register for the SPI module connected to the device. If your device doesn’t have an SPICON2 register (e.g. PIC32) just omit this definition.
SPI2CON2 xxxxxx_SPISTAT Points to the SPI status register for the SPI module connected to the device.
SPI2STAT xxxxxx_SPISTATbits Provides bitwise access to the SPI status register for the SPI module connected to the device.
SPI2STATbits xxxxxx_SPIBRG Points to the SPI Baud Rate Generator register for the SPI module connected to the device. If your device doesn’t have a BRG-based SPI module, just omit this definition.
SPI2BRG
9.1.3
ENC28J60 Config
To use the ENC28J60 in your project, include the files ‘ENC28J60.c” and “ENC28J60.h” in your project and uncomment the following macro in
HardwareProfile.h
:
148
9.1 Hardware Configuration Microchip TCP/IP Stack Help ENCX24J600 Config
#define ENC_CS_TRIS xxxxxxxxxxxxxxx
Several macros need to be mapped to registers or register bits when using the ENC28J60. They include:
Macro
ENC_CS_IO
Purpose Sample Value
Defines the LAT (or PORT, where applicable) register bit that corresponds to the chip select pin. Defining this macro will also indicate that the stack should use the ENC28J60.
LATDbits.LATD14
Defines the TRIS bit that corresponds to the chip select pin.
TRISDbits.TRISD14
ENC_CS_TRIS
ENC_RST_IO Defines the LAT (or PORT, where applicable) register bit that corresponds to the reset pin. If you leave the reset pin unconnected in your design, comment this macro out.
LATDbits.LATD15
ENC_RST_TRIS Defines the TRIS bit that corresponds to the reset pin.
TRISDbits.TRISD15
ENC_SPI_IF
ENC_SSPBUF
Points to the interrupt flag for the SPI module connected to the chip.
Points to the SPI buffer register for the SPI module connected to the chip.
IFS0bits.SPI1IF
SPI1BUF
ENC_SPISTAT Points to the SPI status register for the SPI module connected to the chip.
SPI1STAT
ENC_SPISTATbits Provides bitwise access to the SPI status register for the SPI module connected to the chip. The ____bits registers are typically defined in the processor’s header files.
SPI1STATbits
ENC_SPICON1 Points to the SPI control register for the SPI module connected to the chip.
SPI1CON1
ENC_SPICON1bits Provides bitwise access to the SPI control register for the SPI module connected to the chip (see ENC_SPISTATbits entry).
SPI1CON1bits
ENC_SPICON2 Points to the second SPI control register for the SPI module connected to the chip. If your device doesn’t have an SPICON2 register (e.g. PIC32) just omit this definition.
SPI1CON2
ENC_SPIBRG Points to the SPI Baud Rate Generator register for the SPI module connected to the chip. If your device doesn’t have a BRG-based SPI module, just omit this definition.
SPI1BRG
9.1.4
ENCX24J600 Config
To use the ENC624J600 or -424J600 in your project, include “ENCX24J600.c” and “ENCX24J600.h” and uncomment the following macro in
HardwareProfile.h
:
#define
ENC100_INTERFACE_MODE 0
The parameter ‘0’ indicates that you’ll be using the device in SPI mode. Potential usable parameters include:
5
6
9
10
3
4
1
2
Parameter Functionality
0 SPI mode using CS, SCK, SI, and SO pins
8-bit demultiplexed PSP Mode 1 with RD and WR pins
8-bit demultiplexed PSP Mode 2 with R/~W and EN pins
16-bit demultiplexed PSP Mode 3 with Rd, WRL, and WRH pins
16-bit demultiplexed PSP Mode 4 with R/~W, B0SEL, and B1SEL pins
8-bit multiplexed PSP Mode 5 with RD and WR pins
8-bit multiplexed PSP Mode 6 with R/~W and EN pins
16-bit multiplexed PSP Mode 9 with AL, RD, WRL, and WRH pins
16-bit multiplexed PSP Mode 10 with AL, R/~W, B0SEL, and B1SEL pins
More information on the functionality of each mode is available in the ENC624J600 family datasheet. Note, however, that the
149
9.1 Hardware Configuration Microchip TCP/IP Stack Help ENCX24J600 Config
44-pin ENC424J600 only supports communication using the SPI mode and PSP Modes 5 and 6. Also, because of board conflicts, PSP Modes 2, 4, 6, and 10 shouldn’t be used with the Explorer 16 (and PSP Mode 3 may cause bus contention with the 25LC256 EEPROM).
Several macros need to be mapped to registers or register bits when using the ENCX24J600 as well. In addition, some features can be enabled/disabled for this device by defining certain macros. Macros include:
Macro
ENC100_INTERFACE_MODE
ENC100_PSP_USE_INDIRECT_-
RAM_ADDRESSING
ENC100_TRANSLATE_TO_PIN-
_ADDR(a)
ENC100_MDIX_IO
ENC100_MDIX_TRIS
ENC100_INT_IO
ENC100_INT_TRIS
ENC100_CS_IO
Purpose Sample Value
Indicates which communication mode the stack should use to interface to the chip. This macro will also indicate that the stack should use the ENCX24J600.
0
Un-commenting this macro will allow the stack to indirectly address the RAM of the ENCX24J600 (to save some address wires). For SPI mode or PSP Modes 9 and 10, this option will be ignored.
N/A
This macro will actually remap the addresses passed into the parallel interface to fit the configuration of the pins (if you are using indirect addressing).
((((a)&0x100)<<6) |
((a&0x00FF))
If you design an Auto-crossover (Auto-MDIX) circuit into your board, this macro will define the pin to use for it. See the
Fast 100Mbps Ethernet PICtail/PICtail Plus board schematic for an example circuit.
LATBbits.LATB3
Defines the TRIS bit to use for the Auto-crossover circuit.
TRISBbits.TRISB3
Defines an I/O pin to use for the chip’s interrupt signal pin.
This feature is currently unused by the stack.
PORTAbits.RA13
Defines a TRIS bit to use for the chip’s interrupt signal pin.
TRISAbits.TRISA13
Defines a port bit for use with the chip select pin. Optional in
PSP modes.
LATAbits.LATA5
ENC100_CS_TRIS
ENC100_POR_IO
ENC100_SCK_AL_IO
Defines a TRIS bit to use for the chip select pin.
TRISAbits.TRISA5
Defines the port bit to use with a power disconnect circuit. If your application doesn’t have this feature implemented, comment out this bit.
LATCbits.LATC1
Defines the TRIS bit to use with a power disconnect circuit.
TRISCbits.TRISC1
ENC100_POR_TRIS
ENC100_SO_WR_B0SEL_EN_IO
ENC100_SO_WR_B0SEL_EN_TRIS Defines the TRIS bit to use with the
ENC100_SO_WR_B0SEL_EN_IO pin.
TRISDbits.TRISD4
ENC100_SI_RD_RW_IO Defines a pin used for communication. The functionality of this pin depends on which communication mode in selected.
It can be equivalent to the ENCX24J600 serial in pin, the parallel mode RD strobe, or the R/~W pin.
LATDbits.LATD5
ENC100_SI_RD_RW_TRIS
Defines a pin used for communication. The functionality of this pin depends on which communication mode in selected.
It can be equivalent to the ENCX24J600 serial out pin, the parallel mode WR strobe, the B0SEL pin, or the EN pin.
LATDbits.LATD4
Defines the TRIS bit to use with the ENC100_SI_RD_RW_IO pin.
TRISDbits.TRISD5
Defines a pin used for communication. The functionality of this pin depends on which communication mode in selected.
It can be equivalent to the ENCX24J600 serial clock pin or the parallel mode address latch strobe.
LATDbits.LATDB15
ENC100_SCK_AL_TRIS
ENC100_ISR_ENABLE
Defines the TRIS bit to use with the ENC100_SCK_AL_IO pin.
TRISDbits.TRISD15
Points to the bit to enable the interrupt for the I/O based
ENCX24J600-triggered interrupt. This feature is not currently implemented.
IEC1bits.INT2IE
150
9.1 Hardware Configuration
ENC100_ISR_FLAG
ENC100_ISR_POLARITY
ENC100_ISR_PRIORITY
ENC100_SPI_ENABLE
ENC100_SPI_IF
ENC100_SSPBUF
ENC100_SPISTAT
ENC100_SPISTATbits
ENC100_SPICON1
ENC100_SPICON1bits
ENC100_SPICON2
ENC100_SPIBRG
Microchip TCP/IP Stack Help PIC32MX7XX Config
Points to the interrupt flag bit for the I/O based
ENCX24J600-triggered interrupt. This feature is not currently implemented.
IFS1bits.INT2IF
Points to the interrupt polarity bit for the I/O based
ENCX24J600-triggered interrupt. This feature is not currently implemented.
INTCON2bits.INT2EP
Points to the interrupt priority bit for the I/O based
ENCX24J600-triggered interrupt. This feature is not currently implemented.
IPC7bits.INT2IP
Points to the SPI module enable bit if SPI mode is used.
SPI1STATbits.SPIEN
Points to the interrupt flag for the SPI module if SPI mode is used.
IFS0bits.SPI1IF
Points to the SPI buffer register for the SPI module if SPI mode is used.
SPI1BUF
Points to the SPI status register for the SPI module if SPI mode is used.
SPI1STAT
Provides bitwise access to the SPI status register for the SPI if SPI mode is used. The ____bits registers are typically defined in the processor’s header files.
SPI1STATbits
Points to the SPI control register for the SPI module if SPI mode is used.
SPI1CON1
Provides bitwise access to the SPI control register for the
SPI module if SPI mode is used (see ENC_SPISTATbits entry).
SPI1CON1bits
Points to the second SPI control register for the SPI module if SPI mode is used. If your device doesn’t have an
SPICON2 register (e.g. PIC32) just omit this definition.
SPI1CON2
Points to the SPI Baud Rate Generator register for the SPI module if SPI mode is used. If your device doesn’t have a
BRG-based SPI module, just omit this definition.
SPI1BRG
9.1.5
PIC18F97J60 Config
The 18F97J60 can be used in your application by selecting it as the processor in MPLAB, ensuring that the ENC_CS_TRIS macro is commented out, and including the files “ETH97J60.c” and “ETH97J60.h.” There are no additional macros to define for the 97J60; since it uses its own internal MAC and PHY for communication all of the register names and bit names are fixed.
9.1.6
PIC32MX7XX Config
To use the PIC32MX795 in your project, include the files ETHPIC32IntMac.c and ETHPIC32ExtPhy.c
in your project.
You’ll also have to add a specific PHY implementation file (by default
ETHPIC32ExtPhyDP83848.c
is provided) depending on your actual external PHY selection.
Update the following definitions in
HardwareProfile.h
:
151
9.2 Address Microchip TCP/IP Stack Help MAC Address
Macro
PHY_RMII
Purpose
Define this macro if the external PHY runs in RMII mode. Comment it out if you’re using an MII PHY.
-
Sample
Value
PHY_CONFIG_ALTERNATE Define this symbol if the PIC32MX7XX uses the alternate configuration pins to
connect ( see page 176) to the PHY. Comment it out for the default configuration
pins.
-
PHY_ADDRESS Update with the MIIM address of the external PHY you are using (the address on which the PHY responds to MIIM transactions. See the PHY datasheet).
0x1
Update the following definitions in
TCPIPConfig.h
:
Macro
ETH_CFG_LINK
ETH_CFG_AUTO
ETH_CFG_10
ETH_CFG_100
Purpose
Set to 0 to use the default connection characteristics (depends on the selected PHY).
Set to 1 to configure the Ethernet link to the following specific parameters.
Auto-negotiation will always be enabled if supported by the PHY.
0
Sample
Value
Set to 1 to use auto negotiation. Strongly recommended.
Use/advertise 10 Mbps capability.
Use/advertise 100 Mbps capability.
1
1
1
ETH_CFG_HDUPLEX
ETH_CFG_FDUPLEX
Use/advertise half duplex capability.
Use/advertise full duplex capability.
ETH_CFG_AUTO_MDIX Use/advertise auto MDIX capability (effective only when ETH_CFG_AUTO is enabled). 1
ETH_CFG_SWAP_MDIX Use swapped MDIX if defined. Otherwise, use normal MDIX.
1
1
1
9.2
Address
A TCP/IP application will need to have both a Media Access Control (MAC) address and an Internet Protocol (IP) address.
There are multiple methods for obtaining or setting these addresses.
9.2.1
MAC Address
The 6-byte MAC address provides addressing for the Media Access Control protocol layer of the TCP/IP stack. MAC addresses are permanent addresses tied to hardware. Blocks of MAC addresses are sold to organizations and individuals by the IEEE; if you aren't using a Microchip device with a built-in MAC address, you will need to purchase one of these blocks to assign MAC addresses to your products.
The MAC address is defined in the firmware configuration header "TCPIPConfig.h." There are six macros that must be defined in this file to set the MAC address. They are:
Macro
MY_DEFAULT_MAC_BYTE1
MY_DEFAULT_MAC_BYTE2
MY_DEFAULT_MAC_BYTE3
MY_DEFAULT_MAC_BYTE4
Sample Value
(0x00)
(0x04)
(0xA3)
(0x00)
152
9.2 Address Microchip TCP/IP Stack Help IP Address
MY_DEFAULT_MAC_BYTE5
MY_DEFAULT_MAC_BYTE6
(0x00)
(0x00)
Each of these macros represents a byte of the MAC address (note that 00:04:A3:xx:xx:xx is the block of MAC addresses reserved for Microchip products). Once you obtain your block of addresses, you will need to specify a unique address for every device you produce. The "TCP/IP Demo App" demonstration project describes a method for using Microchip's MPLAB
PM3 programmer to serially program a range of MAC addresses into multiple parts without recompiling your project.
The ENCX24J600, MRF24WB0M, MRF24WG0M and PIC32MX7XX/6XX feature a pre-programmed MAC address (from
Microchip's address block). If you are using either of these part families in your project, you can define your MAC address as
"00:04:A3:00:00:00" and the stack will automatically use the part's pre-programmed address for your application.
Microchip also provides a family of EEPROMs that include a unique, pre-programmed EUI-48 (MAC) or EUI-64 address.
device's MAC address from one of these EEPROMs instead of the default MAC address macros.
9.2.2
IP Address
The IP address is used to address nodes on an Internet Protocol network. You will need to configure your application with an
IP address, or enable a method to obtain one. You may also want to define a few other parameters that describe how your device will try to fit into its network, by default.
The macros that you will need to define include:
Macro
MY_DEFAULT_IP_ADDR_BYTE1
MY_DEFAULT_IP_ADDR_BYTE2
MY_DEFAULT_IP_ADDR_BYTE3
MY_DEFAULT_IP_ADDR_BYTE4
MY_DEFAULT_MASK_BYTE1
MY_DEFAULT_MASK_BYTE2
MY_DEFAULT_MASK_BYTE3
MY_DEFAULT_MASK_BYTE4
MY_DEFAULT_GATE_BYTE1
MY_DEFAULT_GATE_BYTE1
MY_DEFAULT_GATE_BYTE1
MY_DEFAULT_GATE_BYTE1
Property
Default IP address byte 1
Default IP address byte 2
Default IP address byte 3
Default IP address byte 4
Default subnet mask byte 1
Default subnet mask byte 2
Default subnet mask byte 3
Default subnet mask byte 4
Default gateway byte 1
Default gateway byte 2
Default gateway byte 3
Default gateway byte 4
255ul
255ul
0ul
192ul
168ul
1ul
1ul
Sample
Value
192ul
168ul
1ul
100ul
255ul
The subnet address is a bit mask that defines the scope of the network. If your IP address is 192.168.5.100, and you specify a subnet mask of 255.255.255.0, the stack will assume that addresses in the range 192.168.5.x are on the same subnet that you are, and that packets sent to any of those addresses won't have to be routed anywhere else.
The default gateway is the IP address of the node on the network that your application will send packets to if it doesn't know how to route them to the address it wants to send them to. If your application is on the 192.268.5.x subnet, if it wants to send a packet to 198.175.253.160 and it doesn't know exactly how to get there, it will send it to the default gateway.
itself) may modify any of the APP_CONFIG fields that represent these parameters.
153
9.3 Protocol Configuration Microchip TCP/IP Stack Help Protocol Macros and Files
There are three methods that you can use to set or obtain an IP address: static, DHCP, or AutoIP.
Static IP Addressing
Using a static address will allow you to specify a set IP address. This can either be done at compile time, by setting the default IP address to the value you'd like to use and using the demo code (which populated your AppConfig structure automatically), or during run-time, by programming your application to set the IP address in your AppConfig structure based on some input. If you'd like to include the code for DCHP and AutoIP address acquisition if your project but still use static addressing, you can call the DHCP and AutoIP functions that disable those modules to prevent them from overwriting your
IP address. Use of static addresses will usually only work if the server is configured to support that address.
DHCP
The DHCP client module will allow your application to dynamically obtain an IP address from a DHCP server on the same network. Doing this will reset the IP address, subnet mask, gateway address, and some other configuration parameters in your AppConfig structure. To use DHCP, include the files
DHCP.c
,
DHCPs.c
, and
DHCP.h
in your project, and add or uncomment the definition "
#define STACK_USE_DHCP_CLIENT
" to
TCPIPConfig.h
. The TCP/IP stack also includes a simple DHCP server that can supply an IP address to one DHCP client. To enable this functionality, add the macro
"
#define STACK_USE_DHCP_SERVER
" to
TCPIPConfig.h
.
AutoIP
The AutoIP module will allow your application to choose an IP address and claim it for itself. These addresses are link-local, meaning they cannot be routed, and will only work on your local link. This functionality is based on the specification for allocating dynamic link-local addresses, but is modified to take the form used by Microsoft's APIPA link-local address allocation scheme. To enable this feature, include the files
AutoIP.c
and
AutoIP.h
and add the macro "
#define
STACK_USE_AUTO_IP
" to
TCPIPConfig.h
.
IP Address ( see page 152) Module Interaction
It is possible to configure a default static address and enable DHCP and AutoIP at the same time. If you don't disable one or the other, the AutoIP module will immediately choose an address in the specified address range and begin attempting to claim it. DHCP will also begin sending messages to attempt to lease a DHCP IP address from a DHCP server. In most cases the DHCP module will complete all of its transactions before AutoIP finishes claiming its address. In this case, the DHCP address will be copied to the AppConfig structure and the AutoIP module will stop trying to claim its address. Since a routable DHCP address is always preferred to a link-local AutoIP address, the stack will also immediately start using a
DHCP address if it becomes available, even if an AutoIP address was already in use (i.e. if you enable DHCP after AutoIP has already claimed an address). This may cause existing open sockets to lose communication; they should be re-opened with the new address. In this situation, you can also use a static address if you disable DHCP and AutoIP and set the static address in the AppConfig structure.
If AutoIP is used in conjunction with the DHCP Server module, the AutoIP module will generate an address in the
169.254.x.x subnet and then serve another address in the same subnet to the DHCP client connected to the board.
9.3
Protocol Configuration
There are a few steps that you must take to include each protocol in your application. Most of this configuration is performed by setting options in one of the variants of the
TCPIPConfig.h
header file. Nearly all protocols will require you to enable them by defining one or more macros in
TCPIPConfig.h
. You will also need to include the files needed by your protocols in your project. Some protocols will require you to define sockets for them to use in
TCPIPConfig.h
, and allocate memory to them.
The TCP/IP Configuration Wizard, included with the stack, will allow you to select the features that you want while handling most complex firmware configuration automatically. Because of this, it is the easiest (and safest) way to set up your application protocols.
The Module APIs topic has a description of each of the modules.
154
9.3 Protocol Configuration Microchip TCP/IP Stack Help Protocol Macros and Files
9.3.1
Protocol Macros and Files
You will need to define some macros in TCPIPConfig.h and include some files in your project to enable each protocol. These include:
Module Macro
STACK_USE_ICMP_SERVER
Function
Provides the ability to query and respond to pings.
Required Files
ICMP.c
,
ICMP.h
STACK_USE_ICMP_CLIENT Provides the ability to transmit pings.
ICMP.c
,
ICMP.h
STACK_USE_HTTP2_SERVER
FTP
STACK_USE_SSL_SERVER
STACK_USE_SSL_CLIENT
STACK_USE_FTP_SERVER
STACK_USE_SMTP_CLIENT
STACK_USE_SNMP_SERVER
STACK_USE_TFTP_CLIENT
STACK_USE_TELNET_SERVER
STACK_USE_ANNOUNCE
Provides HTTP server functionality with
dynamic variables, POST, Cookies ( see
page 93), Authentication ( see page 91),
and other features
HTTP2.c
,
HTTP2.h
,
TCP.c, TCP.h,
CustomHTTPApp.c
and
HTTPPrint.h
(see HTTP2 ( see page 235) section for
information on these files)
Provides support for SSL server sockets.
Provides support for SSL client sockets.
SSL.c,
ARCFOUR.c,
Random.h,
RSA.h
SSL.h,
ARCFOUR.h, BigInt.c,
BigInt.h, Random.c,
RSA.c,
SSL.c,
ARCFOUR.c,
SSL.h,
ARCFOUR.h, BigInt.c,
BigInt.h,
Random.h,
RSA.h
Random.c,
RSA.c,
Provides ability to remotely upload MPFS2 images to HTTP2 servers via FTP
FTP.c, FTP.h, TCP.c,
TCP.h
Provides the ability to send email SMTP.c,
TCP.c,
SMTP.h,
TCP.h,
Helpers.c, Helpers.h
Provides a network-based machine control/monitoring protocol
UDP.c,
UDP.h
Provides unreliable file upload/download services
TFTPc.c,
TCP.c, TCP.h
TFTPc.h,
Provides telnet services.
Provides device hostname and IP address discovery on a local Ethernet subnet
Telnet.c,
TCP.c, TCP.h
Announce.c,
Announce.h
Telnet.h,
155
9.3 Protocol Configuration Microchip TCP/IP Stack Help Additional Features
STACK_USE_DNS
STACK_USE_NBNS
Provides the ability to resolve hostnames to
IP addresses
Provides the ability to resolve hostnames to
IP addresses on the same subnet.
DNS.c, DNS.h, UDP.c,
UDP.h
NBNS.c,
UDP.c, UDP.h
NBNS.h,
STACK_USE_SNTP_CLIENT Provides the ability to get the date/time from the internet
SNTP.c,
UDP.c, UDP.h
SNTP.h,
STACK_USE_DYNAMICDNS_CLIENT Provides the ability to resolve hostnames to
IP addresses that change frequently.
DynDNS.c, DynDNS.h,
TCP.c, TCP.h
STACK_USE_MPFS2
STACK_USE_TCP
STACK_USE_UDP
Provides MPFS2 services for custom applications. This functionality will be enabled/required automatically by stack-based protocols that require MPFS2.
MPFS2.c, MPFS2.h
Provides TCP transport layer services for custom protocols. This functionality is automatically enabled/required by stack-based protocols that require TCP sockets.
TCP.c, TCP.h
Provides UDP transport layer services for custom protocols. This functionality is automatically enabled/required by stack-based protocols that require UDP sockets.
UDP.c, UDP.h
9.3.2
Additional Features
The TCP/IP stack includes some additional functionality that can be enabled in
TCPIPConfig.h
.
Feature
UART Demo
UART-to-TCP
Bridge
IP Gleaning
Macro
STACK_USE_UART
STACK_USE_UART2TCP_BRIDGE
STACK_USE_IP_GLEANING
STACK_USE_REBOOT_SERVER
Description Required Files
Application demo using
UART for IP address display and stack configuration.
UART.c, UART.h
UART to TCP Bridge application example
UART2TCPBridge.c,
UART2TCPBridge.h
Allows assignment of an IP address via reception of an
ICMP packet with a valid IP during configuration mode
-
Allows the PIC to be reset remotely bootloaders).
(useful for
Reboot.c, Reboot.h
STACK_USE_UDP_PERFORMANCE_TEST UDP performance test.
Monitor a local area network for UDP packets with a packet sniffer. This test will transmit 1024 packets. Use the timestamps of the first and last packets to calculate throughput.
UDPPerformanceTest.c,
UDPPerformanceTest.h
156
9.3 Protocol Configuration Microchip TCP/IP Stack Help Sockets
STACK_USE_TCP_PERFORMACE_TEST TCP performance test.
Connect a demo board to a
PC via UART, execute the code, and monitor the throughput on the PC terminal.
TCPPerformanceTest.c,
TCPPerformanceTest.h
STACK_USE_BERKELEY_API
API abstraction layer.
BerkeleyAPI.c,
BerkeleyAPI.h
9.3.3
Sockets
Most of your application protocols will require you to allocate memory for each connection (socket) that you have open. Like the other firmware configuration options, this is controlled by the definition of macros in
TCPIPConfig.h
. For TCP sockets, you will have to specify four initialization parameters for each socket, including the purpose of that socket, the type of memory the socket should be stored in, the size of the transmit FIFO, and the size of the receive FIFO. The stack will then initialize the sockets with this information, and create a TCP Control Block (TCB) for each to control its operations. This topic will outline the socket configuration functionality in the sample version of
TCPIPConfig.h
that is included with the TCP/IP
Demo App project.
9.3.3.1
Memory Allocation
#define TCP_ETH_RAM_SIZE (3900ul)
#define TCP_PIC_RAM_SIZE (0ul)
#define TCP_SPI_RAM_SIZE (0ul)
#define TCP_SPI_RAM_BASE_ADDRESS (0ul)
The first four macros in the socket section are used to describe the total amount of memory used to contain sockets. When data is sent from a TCP socket, it will first be copied into the socket's transmit FIFO, and then to the MAC/PHY transmit buffer. Similarly, received data will be read from the MAC/PHY chip into the receive FIFO. These FIFOs, as well as the TCB, can be stored in 3 places.
TCP_ETH_RAM_SIZE
is used to define the RAM available for sockets on the actual TCP/IP MAC/PHY chip. This will not be the same as the total RAM on the chip; some memory must be reserved for packets being transmitted and received. By default ~1518 bytes (the maximum single-packet transmission size) will be reserved for TX packets on Microchip parts. The amount reserved for the receive packet buffer will equal the amount remaining after allocating the memory for the TX buffer and the memory for the sockets. You may receive a compile-time warning if the RX buffer is unreasonably small.
TCP_PIC_RAM_SIZE
is used to define the RAM available for sockets on the PIC microcontroller that's driving your application.
TCP_SPI_RAM_SIZE
defines the RAM available for sockets on an external SPI RAM (see External Storage ( see page
147)). You can specify the base address in this RAM chip to use with the
TCP_SPI_RAM_BASE_ADDRESS
macro.
9.3.3.2
Socket Types
When creating an initialization list for your sockets, you will have to specify a socket type. This parameter will define which protocol can use the socket. You can create and delete socket types as you require. In the sample version of
TCPIPConfig.h
, the following types are defined:
#define TCP_SOCKET_TYPES
#define TCP_PURPOSE_GENERIC_TCP_CLIENT 0
#define TCP_PURPOSE_GENERIC_TCP_SERVER 1
#define TCP_PURPOSE_TELNET 2
157
9.3 Protocol Configuration Microchip TCP/IP Stack Help Sockets
#define TCP_PURPOSE_FTP_COMMAND 3
#define TCP_PURPOSE_FTP_DATA 4
#define TCP_PURPOSE_TCP_PERFORMANCE_TX 5
#define TCP_PURPOSE_TCP_PERFORMANCE_RX 6
#define TCP_PURPOSE_UART_2_TCP_BRIDGE 7
#define TCP_PURPOSE_HTTP_SERVER 8
#define TCP_PURPOSE_DEFAULT 9
#define TCP_PURPOSE_BERKELEY_SERVER 10
#define TCP_PURPOSE_BERKELEY_CLIENT 11
#define END_OF_TCP_SOCKET_TYPES
The
TCP_PURPOSE_GENERIC_TCP_CLIENT
and
TCP_PURPOSE_GENERIC_TCP_SERVER
socket types are used by the generic TCP client and server examples (see GenericTCPClient.c
and GenericTCPServer.c
). These files are used as an example of how to create a new, custom TCP client or server application.
If you are trying to open a Telnet ( see page 577) connection, the stack will try to use a
TCP_PURPOSE_TELNET socket.
The
TCP_PURPOSE_FTP_COMMAND
and
TCP_PURPOSE_FTP_DATA
socket types are used to receive FTP commands and data.
The two
TCP_PERFORMANCE_x
socket types are used solely to conduct TCP performance testing.
The
TCP_PURPOSE_UART_2_TCP_BRIDGE
socket type is used for the UART-to-TCP bridge example.
The
TCP_PURPOSE_HTTP_SERVER
socket type is used for sockets on HTTP servers that listen ( see page 180) for web
page view requests.
The
TCP_PURPOSE_DEFAULT
socket type can be used for miscellaneous applications, or for applications that only need sockets temporairly. Dynamic DNS connections and SMTP connections use default sockets, and the legacy wrapper
implementation for the TCPListen ( see page 546)
and
functions try to open them.
The TCP_PURPOSE_BERKELEY_SERVER and TCP_PURPOSE_BERKELEY_CLIENT socket types indicate that a socket is
9.3.3.3
Initialization Structure
In the
TCPIPConfig.h
header file, you must also define an array of structures to declare and initialize any sockets that you need. The sample structure is:
#define TCP_CONFIGURATION ROM struct {
BYTE vSocketPurpose, BYTE vMemoryMedium, WORD wTXBufferSize, WORD wRXBufferSize }
TCPSocketInitializer[] =
{
{TCP_PURPOSE_GENERIC_TCP_CLIENT, TCP_ETH_RAM, 125, 100},
{TCP_PURPOSE_GENERIC_TCP_SERVER, TCP_ETH_RAM, 20, 20},
{TCP_PURPOSE_TELNET, TCP_ETH_RAM, 200, 150},
//{TCP_PURPOSE_TELNET, TCP_ETH_RAM, 200, 150},
//{TCP_PURPOSE_TELNET, TCP_ETH_RAM, 200, 150},
//{TCP_PURPOSE_FTP_COMMAND, TCP_ETH_RAM, 100, 40},
//{TCP_PURPOSE_FTP_DATA, TCP_ETH_RAM, 0, 128},
{TCP_PURPOSE_TCP_PERFORMANCE_TX, TCP_ETH_RAM, 200, 1},
//{TCP_PURPOSE_TCP_PERFORMANCE_RX, TCP_ETH_RAM, 40, 1500},
{TCP_PURPOSE_UART_2_TCP_BRIDGE, TCP_ETH_RAM, 256, 256},
{TCP_PURPOSE_HTTP_SERVER, TCP_ETH_RAM, 200, 200},
{TCP_PURPOSE_HTTP_SERVER, TCP_ETH_RAM, 200, 200},
{TCP_PURPOSE_DEFAULT, TCP_ETH_RAM, 200, 200},
{TCP_PURPOSE_BERKELEY_SERVER, TCP_ETH_RAM, 25, 20},
//{TCP_PURPOSE_BERKELEY_SERVER, TCP_ETH_RAM, 25, 20},
//{TCP_PURPOSE_BERKELEY_SERVER, TCP_ETH_RAM, 25, 20},
//{TCP_PURPOSE_BERKELEY_CLIENT, TCP_ETH_RAM, 125, 100},
};
#define END_OF_TCP_CONFIGURATION
As you can see from the structure parameters, the four parameters you'll need to include in each of your socket declarations are:
158
9.3 Protocol Configuration Microchip TCP/IP Stack Help Sockets
• Socket purpose/type
• RAM storage location
• TX FIFO buffer size
• RX FIFO buffer size
TCP_ETH_RAM
(the MAC/PHY chip RAM). Other options are
TCP_PIC_RAM
(the PIC's own RAM) and
TCP_SPI_RAM
(an external SPI RAM device). Finally, the TX and RX
FIFOs are declared. Each RX buffer must contain at least one byte, to handle the SYN and FIN messages required by TCP.
Each socket you declare will require up to 48 bytes of PIC RAM, and 40 + (TX FIFO size) + (RX FIFO size) bytes of RAM on the storage medium that you select.
9.3.3.4
UDP Sockets
UDP sockets are somewhat easier to declare than TCP sockets. Since UDP transmissions don't have to be processed in a particular order and responses aren't required by the sender, you don't have to declare separate buffers for these sockets.
There are two options to define when using UDP:
#define MAX_UDP_SOCKETS (10u)
//#define UDP_USE_TX_CHECKSUM
The
MAX_UDP_SOCKETS
definition defines the size of an array of
UDP_SOCKET_INFO ( see page 631)
structures.
These structures contain two sixteen-bit identifiers for the remote node's and local node's UDP port numbers, and a 10-byte structure used to hold the remote node's MAC address and IP address (these structures use the packed attribute, so the
UDP_SOCKET_INFO ( see page 631)
structure may very slightly depending on the PIC architecture you use).
The
UDP_USE_TX_CHECKSUM
definition will cause the stack to generate checksums for transmitted data, and include them with transmitted packets. This can provide some data integrity verification, but it will also decrease TX performance by nearly
50% unless the ENCX24J600 is used (the ENCX24J600 chips include hardware checksum calculators).
9.3.3.5
BSD Sockets
uses one TCP or UDP socket, defined by the TCPSocketInitializer[] array ( see page 158) and the
sum of the number of UDP sockets you declare and the number of TCP Berkeley-type sockets you declare. The
TCPIPConfig.h
macro to define the number of Berkeley sockets is:
#define BSD_SOCKET_COUNT (5u)
159
Microchip TCP/IP Stack Help Announce Stack Members 10.1 Announce
10
Stack API
Modules
Name
Description
Provides a UDP MAC address announcement feature.
Provides Address ( see page 152) Resolution Protocol support.
Berkeley (BSD) Sockets ( see page 172) Provides a BSD socket wrapper to the Microchip TCP/IP Stack.
Dynamic DNS Client ( see page 198)
Provides Domain Name Service resolution.
Updates an external IP address to a Dynamic DNS service.
Calculates MD5 and SHA-1 hash sums.
Provides several helper function for stack operation.
Provides an advanced embedded web server.
Provides Ping functionality.
Provides a light-weight file system.
Performance Tests ( see page 298)
Describes the NetBIOS Name Service protocol.
Tests TCP and UDP performance of an application.
Sends e-mail messages across the internet.
Provides a service to remotely reboot the PIC.
Provides an Simple Network Management Protocol agent.
Obtains absolute time stamps from a pool of network time servers.
Implements SSL encryption for TCP connections.
Implements the TCP transport layer protocol.
Describes the operation of the Telnet module.
Describes the TFTP module.
Provides accurate time-keeping capabilities.
Implements the UDP transport layer protocol.
Description
The Microchip TCP/IP Stack is implemented as a suite of modules. Each module exists on its own layer in the TCP/IP layer model, and has its own set of APIs. These APIs are described in this section
10.1
Announce
This module will facilitate device discovery on DHCP enabled networks by broadcasting a UDP message on port 30303 whenever the local IP address changes. You can change the port used by the announce module by changing the following macro definition in Announce.c
.
#define ANNOUNCE_PORT 30303
The Announce protocol is designed to be used with the TCP/IP Discoverer ( see page 67) PC program.
160
10.1 Announce Microchip TCP/IP Stack Help Announce Stack Members
10.1.1
Announce Stack Members
Functions
Name
Module
Description
Transmits an Announce ( see page 160) packet.
Announce ( see page 160) callback task.
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.1.1.1
AnnounceIP Function
File
Announce.h
C void
AnnounceIP();
Side Effects
None
Returns
None
Description
AnnounceIP opens a UDP socket and transmits a broadcast packet to port 30303. If a computer is on the same subnet and a utility is looking for packets on the UDP port, it will receive the broadcast. For this application, it is used to announce the change of this board's IP address. The messages can be viewed with the TCP/IP Discoverer software tool.
Remarks
A UDP socket must be available before this function is called. It is freed at the end of the function. MAX_UDP_SOCKETS may need to be increased if other modules use UDP sockets.
Preconditions
Stack is initialized()
10.1.1.2
DiscoveryTask Function
File
Announce.h
C void
DiscoveryTask();
161
10.2 ARP Microchip TCP/IP Stack Help ARP Public Members
Side Effects
None
Returns
None
Description
messages can be sent using the Microchip Device Discoverer tool. If one is received, this function will transmit a reply.
Remarks
A UDP socket must be available before this function is called. It is freed at the end of the function. MAX_UDP_SOCKETS may need to be increased if other modules use UDP sockets.
Preconditions
Stack is initialized()
10.2
ARP
Types
Name
Description
ARP packet structure
Description
physical MAC addresses, or locates a gateway through which a machine may be located.
Responses to incoming ARP requests are processed automatically. Resolution of ARP requests follows a simple state machine, as indicated in the following diagram.
10.2.1
ARP Public Members
Functions
Name
Description
Transmits an ARP request to resolve an IP address.
Determines if an ARP request has been resolved yet.
162
10.2 ARP Microchip TCP/IP Stack Help ARP Public Members
ARPDeRegisterCallbacks ( see page 164)
ARPRegisterCallbacks ( see page 165)
De-Registering callbacks with ARP module that are registered previously.
Registering callback with ARP module to get notified about certian events.
Transmits an ARP request/Reply initated by Application or external module.
Macros
Name Description
Operation code indicating an ARP Request
ARP_RESP ( see page 166) Operation code indicating an ARP Response
MAX num allowed registrations of Modules/Apps
Module
Structures
Name
arp_app_callbacks ( see page 166)
Description
This is record arp_app_callbacks.
Description
The following functions and variables are available to the stack application.
10.2.1.1
ARPResolve Function
File
ARP.h
C void
ARPResolve(
IP_ADDR* IPAddr
);
Returns
None
Description
This function transmits and ARP request to determine the hardware address of a given IP address.
Remarks
This function is only required when the stack is a client, and therefore is only enabled when STACK_CLIENT_MODE is enabled.
To retrieve the ARP query result, call the ARPIsResolved ( see page 164)() function.
Preconditions
None
Parameters
Parameters
IPAddr
Description
The IP address to be resolved. The address must be specified in network byte order (big endian).
163
10.2 ARP Microchip TCP/IP Stack Help ARP Public Members
10.2.1.2
ARPIsResolved Function
File
ARP.h
C
BOOL ARPIsResolved(
IP_ADDR* IPAddr,
MAC_ADDR* MACAddr
);
Description
This function checks if an ARP request has been resolved yet, and if so, stores the resolved MAC address in the pointer provided.
Remarks
This function is only required when the stack is a client, and therefore is only enabled when STACK_CLIENT_MODE is enabled.
Preconditions
ARP packet is ready in the MAC buffer.
Parameters
Parameters
IPAddr
Description
The IP address to be resolved. This must match the IP address provided to the
ARPResolve ( see page 163)() function call.
A buffer to store the corresponding MAC address retrieved from the ARP query.
MACAddr
Return Values
Return Values
TRUE
FALSE
Description
The IP address has been resolved and MACAddr MAC address field indicates the response.
The IP address is not yet resolved. Try calling ARPIsResolved() again at a later time. If you don't get a response after a application specific timeout period, you
may want to call ARPResolve ( see page 163)() again to transmit another
ARP query (in case if the original query or response was lost on the network). If you never receive an ARP response, this may indicate that the IP address isn't in use.
10.2.1.3
ARPDeRegisterCallbacks Function
File
ARP.h
C
BOOL ARPDeRegisterCallbacks(
CHAR id
);
Returns
TRUE - On success FALSE - Failure to indicate invalid reg_id
Description
This function allows end user-application to de-register with callbacks, which were registered previously. This is called by user-application, when its no longer interested in notifications from ARP-Module. This allows the other application to get registered with ARP-module.
164
10.2 ARP
Preconditions
None
Parameters
Parameters
reg_id
Microchip TCP/IP Stack Help ARP Public Members
Description
Registration-id returned in ARPRegisterCallbacks ( see page 165) call
10.2.1.4
ARPRegisterCallbacks Function
File
ARP.h
C
CHAR ARPRegisterCallbacks(
struct
);
Returns
id > 0 - Returns non-negative value that represents the id of registration The same id needs to be used in de-registration -1 -
Description
This function allows end user application to register with callbacks, which will be called by ARP module to give notification to user-application about events occurred at ARP layer. For ex: when a ARP-packet is received, which is conflicting with our
implementation (ZeroconfLL.c)
Preconditions
None
Parameters
Parameters
app
Description
ARP-Application callbacks structure supplied by user-application
10.2.1.5
ARPSendPkt Function
File
ARP.h
C
BOOL ARPSendPkt(
DWORD SrcIPAddr,
DWORD DestIPAddr,
BYTE op_req
);
Returns
TRUE - The ARP packet was generated properly FALSE - Not possible return value
Description
Remarks
This API is to give control over AR-packet to external modules.
165
10.2 ARP Microchip TCP/IP Stack Help ARP Public Members
Preconditions
ARP packet is ready in the MAC buffer.
Parameters
Parameters
SrcIPAddr
DestIPAddr op_req
Description
The Source IP-address
The Destination IP-Address ( see page 152)
Operation Request (ARP_REQ ( see page 166)/ARP_RESP ( see page
10.2.1.6
arp_app_callbacks Structure
File
ARP.h
C struct
arp_app_callbacks {
BOOL used;
void
(* ARPPkt_notify)(DWORD SenderIPAddr, DWORD TargetIPAddr, MAC_ADDR* SenderMACAddr,
MAC_ADDR* TargetMACAddr, BYTE op_req);
};
Description
This is record arp_app_callbacks.
10.2.1.7
ARP_REQ Macro
File
ARP.h
C
#define
ARP_REQ 0x0001u
// Operation code indicating an ARP Request
Description
Operation code indicating an ARP Request
10.2.1.8
ARP_RESP Macro
File
ARP.h
C
#define
ARP_RESP 0x0002u
// Operation code indicating an ARP Response
Description
Operation code indicating an ARP Response
10.2.1.9
MAX_REG_APPS Macro
File
ARP.c
166
10.2 ARP Microchip TCP/IP Stack Help ARP Stack Members
C
#define
MAX_REG_APPS 2
// MAX num allowed registrations of Modules/Apps
Description
MAX num allowed registrations of Modules/Apps
10.2.2
ARP Stack Members
Functions
Name
Module
Description
Initializes the ARP module.
Processes an incoming ARP packet.
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.2.2.1
ARPInit Function
File
ARP.h
C void
ARPInit();
Returns
None
Description
Initializes the ARP module. Call this function once at boot to invalidate the cached lookup.
Remarks
This function is only required when the stack is a client, and therefore is only enabled when STACK_CLIENT_MODE is enabled.
Preconditions
None
10.2.2.2
ARPProcess Function
File
ARP.h
C
BOOL ARPProcess();
167
10.2 ARP Microchip TCP/IP Stack Help ARP Internal Members
Description
Retrieves an ARP packet from the MAC buffer and determines if it is a response to our request (in which case the ARP is resolved) or if it is a request requiring our response (in which case we transmit one.)
Preconditions
ARP packet is ready in the MAC buffer.
Return Values
Return Values
TRUE
FALSE
Description
All processing of this ARP packet is complete. Do not call again until a new
ARP packet is waiting in the RX buffer.
This function must be called again. More time is needed to send an ARP response.
10.2.3
ARP Internal Members
Functions
Name
Description
Writes an ARP packet to the MAC.
Swaps endian-ness of header information in an ARP packet.
Macros
Module
Variables
Name
ARP_OPERATION_REQ ( see page 170)
Description
Operation code indicating an ARP Request
ARP_OPERATION_RESP ( see page 170)
Operation code indicating an ARP Response
ARP Hardware type as defined by IEEE 802.3
ARP IP packet type as defined by IEEE 802.3
Name
Description
Cache for one ARP response
Call-Backs storage for MAX of two Modules/Apps
// ARP packet structure typedef struct __attribute__((aligned(2), packed)) {
WORD HardwareType; WORD Protocol; BYTE MACAddrLen; BYTE
ProtocolLen; WORD Operation; MAC_ADDR SenderMACAddr; IP_ADDR
SenderIPAddr; MAC_ADDR TargetMACAddr; IP_ADDR TargetIPAddr; }
Description
The following functions and variables are designated as internal to the ARP module.
168
10.2 ARP Microchip TCP/IP Stack Help ARP Internal Members
10.2.3.1
ARPPut Function
File
ARP.c
C static
BOOL ARPPut(
);
Description
Writes an ARP packet to the MAC.
Preconditions
None
Parameters
Parameters
packet
Description
A pointer to an ARP_PACKET ( see page 171) structure with correct
operation and target preconfigured.
Return Values
Return Values
TRUE
FALSE
Section
Helper Function Prototypes
Description
The ARP packet was generated properly
Not a possible return value
10.2.3.2
SwapARPPacket Function
File
ARP.h
C void
SwapARPPacket(
);
Returns
None
Description
Swaps endian-ness of header information in an ARP packet.
Preconditions
None
Parameters
Parameters
p
Description
The ARP packet to be swapped
169
10.2 ARP Microchip TCP/IP Stack Help ARP Internal Members
10.2.3.3
ARP_OPERATION_REQ Macro
File
ARP.h
C
#define
ARP_OPERATION_REQ 0x0001u
// Operation code indicating an ARP Request
Description
Operation code indicating an ARP Request
10.2.3.4
ARP_OPERATION_RESP Macro
File
ARP.h
C
#define
ARP_OPERATION_RESP 0x0002u
// Operation code indicating an ARP Response
Description
Operation code indicating an ARP Response
10.2.3.5
HW_ETHERNET Macro
File
ARP.c
C
#define
HW_ETHERNET (0x0001u)
// ARP Hardware type as defined by IEEE 802.3
Description
ARP Hardware type as defined by IEEE 802.3
10.2.3.6
ARP_IP Macro
File
ARP.c
C
#define
ARP_IP (0x0800u)
// ARP IP packet type as defined by IEEE 802.3
Description
ARP IP packet type as defined by IEEE 802.3
10.2.3.7
Cache Variable
File
ARP.c
170
10.2 ARP
C
NODE_INFO Cache;
Description
Cache for one ARP response
Microchip TCP/IP Stack Help Types
10.2.3.8
reg_apps Variable
File
ARP.c
C struct
arp_app_callbacks reg_apps[MAX_REG_APPS];
Description
Call-Backs storage for MAX of two Modules/Apps
// ARP packet structure typedef struct __attribute__((aligned(2), packed)) { WORD HardwareType; WORD Protocol; BYTE
MACAddrLen; BYTE ProtocolLen; WORD Operation; MAC_ADDR SenderMACAddr; IP_ADDR SenderIPAddr; MAC_ADDR
TargetMACAddr; IP_ADDR TargetIPAddr; } ARP_PACKET ( see page 171);
10.2.4
Types
Module
Structures
Name
Description
ARP packet structure
10.2.4.1
ARP_PACKET Structure
File
ARP.h
C typedef struct
{
WORD HardwareType;
WORD Protocol;
BYTE MACAddrLen;
BYTE ProtocolLen;
WORD Operation;
MAC_ADDR SenderMACAddr;
IP_ADDR SenderIPAddr;
MAC_ADDR TargetMACAddr;
IP_ADDR TargetIPAddr;
} ARP_PACKET;
Members
Members
WORD HardwareType;
WORD Protocol;
Description
Link-layer protocol type (Ethernet is 1).
The upper-layer protocol issuing an ARP request (0x0800 for IPv4)..
171
10.3 Berkeley (BSD) Sockets
BYTE MACAddrLen;
BYTE ProtocolLen;
WORD Operation;
MAC_ADDR SenderMACAddr;
IP_ADDR SenderIPAddr;
MAC_ADDR TargetMACAddr;
IP_ADDR TargetIPAddr;
Description
ARP packet structure
Microchip TCP/IP Stack Help BSD Wrapper Public Members
MAC address length (6).
Length of addresses used in the upper-layer protocol (4).
The operation the sender is performing (ARP_REQ ( see page 166) or
The sender's hardware (MAC) address.
The sender's IP address.
The target node's hardware (MAC) address.
The target node's IP address.
10.3
Berkeley (BSD) Sockets
The Berkeley Socket Distribution (BSD) APIs provide a BSD wrapper to the native Microchip TCP/IP Stack APIs. Using this interface, programmers familiar with BSD sockets can quickly develop applications using Microchip's TCP/IP Stack.
The illustration below shows a typical interaction for a TCP server or client using the Berkeley socket APIs.
172
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Public Members
10.3.1
BSD Wrapper Public Members
Functions
Name
Description
This function accepts connection requests queued for a listening socket.
This function assigns a name to the socket descriptor.
closesocket ( see page 176) The closesocket function closes an existing socket.
listen ( see page 180) recv ( see page 180)
This function connects to the peer communications end point.
Returns the standard host name for the system.
The listen function sets the specified socket in a listen mode
The recv() function is used to receive incoming data that has been queued for a socket.
The recvfrom() function is used to receive incoming data that has been queued for a socket.
The send function is used to send outgoing data on an already connected socket.
This function used to send the data for both connection oriented and connection-less sockets.
This function creates a new Berkeley socket.
Macros
Name
Description
Internet Address ( see page 152) Family - UDP, TCP, etc.
IP address for server binding.
INVALID_TCP_PORT ( see page 179)
Invalide TCP port
IP Address ( see page 152) for server binding
Indicates IP pseudo-protocol.
IPPROTO_TCP ( see page 179) Indicates TCP for the internet address family.
IPPROTO_UDP ( see page 179) Indicates UDP for the internet address family.
SOCK_DGRAM ( see page 183) Connectionless datagram socket. Use UDP for the internet address family.
Connection based byte streams. Use TCP for the internet address family.
Socket connection state.
SOCKET_DISCONNECTED ( see page 186)
Socket disconnected
Socket error
Module
Berkeley (BSD) Sockets ( see page 172)
173
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help
Structures
Name Description
BSDSocket ( see page 175) Berkeley Socket structure
in_addr structure
generic address structure for all address families
sockaddr_in ( see page 184) In the Internet address family
Types
Name
Description
generic address structure for all address families
In the Internet address family
Socket descriptor
Description
The following functions and variables are available to the stack application.
BSD Wrapper Public Members
10.3.1.1
accept Function
File
BerkeleyAPI.h
C
struct
int
* addrlen
);
Returns
If the accept function succeeds, it returns a non-negative integer that is a descriptor for the accepted socket. Otherwise, the
value INVALID_SOCKET ( see page 533) is returned.
Description
The accept function is used to accept connection requests queued for a listening socket. If a connection request is pending, accept removes the request from the queue, and a new socket is created for the connection. The original listening socket
type socket.
Remarks
None.
Preconditions
listen ( see page 180) function should be called.
Parameters
Parameters
s addr addrlen
Description
Socket descriptor returned from a previous call to socket. must be bound to a local name and in listening mode.
Optional pointer to a buffer that receives the address of the connecting entity.
Optional pointer to an integer that contains the length of the address addr
174
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Public Members
10.3.1.2
AF_INET Macro
File
BerkeleyAPI.h
C
#define
AF_INET 2
// Internet Address Family - UDP, TCP, etc.
Description
Internet Address ( see page 152) Family - UDP, TCP, etc.
10.3.1.3
bind Function
File
BerkeleyAPI.h
C int
bind(
const struct
int
namelen
);
Returns
Description
The bind function assigns a name to an unnamed socket. The name represents the local address of the communication
connect ( see page 176) or accept ( see page 174) function is executed.
Remarks
None.
Preconditions
socket function should be called.
Parameters
Parameters
s name namelen
Description
Socket descriptor returned from a previous call to socket.
pointer to the sockaddr ( see page 183) structure containing the local address
of the socket.
length of the sockaddr ( see page 183) structure.
10.3.1.4
BSDSocket Structure
File
BerkeleyAPI.h
C struct
BSDSocket {
int
SocketType;
WORD localPort;
175
10.3 Berkeley (BSD) Sockets
WORD remotePort;
DWORD remoteIP;
int
backlog;
BOOL isServer;
};
Members
Members
int SocketType;
BSD_SCK_STATE bsdState;
WORD localPort;
WORD remotePort;
DWORD remoteIP; int backlog;
BOOL isServer;
TCP_SOCKET SocketID;
Description
Berkeley Socket structure
Microchip TCP/IP Stack Help
Description
Socket type
Socket state local port remote port remote IP maximum number or client connection server/client check
Socket ID
BSD Wrapper Public Members
10.3.1.5
closesocket Function
File
BerkeleyAPI.h
C int
closesocket(
);
Returns
error.
Description
The closesocket function closes an existing socket. This function releases the socket descriptor s. Any data buffered at the socket is discarded. If the socket s is no longer needed, closesocket() must be called in order to release all resources associated with s.
Remarks
None.
Preconditions
None.
Parameters
Parameters
s
Description
Socket descriptor returned from a previous call to socket
10.3.1.6
connect Function
File
BerkeleyAPI.h
176
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Public Members
C int
connect(
struct
int
namelen
);
Returns
indicate an error condition. For stream based socket, if the connection is not established yet, connect returns
SOCKET_CNXN_IN_PROGRESS ( see page 185).
Description
The connect function assigns the address of the peer communications endpoint. For stream sockets, connection is established between the endpoints. For datagram sockets, an address filter is established between the endpoints until changed with another connect() function.
Remarks
None.
Preconditions
socket function should be called.
Parameters
Parameters
s name namelen
Description
Socket descriptor returned from a previous call to socket.
pointer to the sockaddr ( see page 183) structure containing the peer address
and port number.
length of the sockaddr ( see page 183) structure.
10.3.1.7
gethostname Function
File
BerkeleyAPI.h
C int
gethostname(
char
* name,
int
namelen
);
Returns
Description
This function returns the standard host name of the system which is calling this function. The returned name is null-terminated.
Remarks
None.
Preconditions
None.
177
10.3 Berkeley (BSD) Sockets
Parameters
Parameters
name namelen
Microchip TCP/IP Stack Help BSD Wrapper Public Members
Description
Pointer to a buffer that receives the local host name.
size of the name array.
10.3.1.8
in_addr Structure
File
BerkeleyAPI.h
C struct
in_addr {
union
{
struct
{
BYTE s_b1, s_b2, s_b3, s_b4;
} S_un_b;
struct
{
WORD s_w1, s_w2;
} S_un_w;
DWORD S_addr;
} S_un;
};
Members
Description
union of IP address
Members
union { struct {
BYTE s_b1, s_b2, s_b3, s_b4;
} S_un_b; struct {
WORD s_w1, s_w2;
} S_un_w;
DWORD S_addr;
} S_un; struct {
BYTE s_b1, s_b2, s_b3, s_b4;
} S_un_b; struct {
WORD s_w1, s_w2;
} S_un_w;
DWORD S_addr;
Description
in_addr structure
IP address in Byte
IP address in Word
IP address
10.3.1.9
INADDR_ANY Macro
File
BerkeleyAPI.h
C
#define
INADDR_ANY 0x00000000u
// IP address for server binding.
Description
IP address for server binding.
178
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Public Members
10.3.1.10
INVALID_TCP_PORT Macro
File
BerkeleyAPI.h
C
#define
INVALID_TCP_PORT (0L)
//Invalide TCP port
Description
Invalide TCP port
10.3.1.11
IP_ADDR_ANY Macro
File
BerkeleyAPI.h
C
#define
IP_ADDR_ANY 0u
// IP Address for server binding
Description
IP Address ( see page 152) for server binding
10.3.1.12
IPPROTO_IP Macro
File
BerkeleyAPI.h
C
#define
IPPROTO_IP 0
// Indicates IP pseudo-protocol.
Description
Indicates IP pseudo-protocol.
10.3.1.13
IPPROTO_TCP Macro
File
BerkeleyAPI.h
C
#define
IPPROTO_TCP 6
// Indicates TCP for the internet address family.
Description
Indicates TCP for the internet address family.
10.3.1.14
IPPROTO_UDP Macro
File
BerkeleyAPI.h
179
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Public Members
C
#define
IPPROTO_UDP 17
// Indicates UDP for the internet address family.
Description
Indicates UDP for the internet address family.
10.3.1.15
listen Function
File
BerkeleyAPI.h
C int
listen(
int
backlog
);
Returns
Returns 0 on success, else return SOCKET_ERROR ( see page 186).
Description
This function sets the specified socket in a listen mode. Calling the listen function indicates that the application is ready to
see page 174) connection requests arriving at a socket of type SOCK_STREAM ( see page 183). The
defines the maximum number of pending connections that may be queued.
Remarks
None
Preconditions
bind() must have been called on the s socket first.
Parameters
Parameters
s backlog
Description
Socket identifier returned from a prior socket() call.
Maximum number of connection requests that can be queued. Note that each backlog requires a TCP_PURPOSE_BERKELEY_SERVER type TCP socket to be allocated in the TCPSocketInitializer[] in TCPIPConfig.h. Also, ensure that
BSD_SOCKET_COUNT (also in TCPIPConfig.h) is greater than the backlog by at least 1 (more if you have other BSD sockets in use).
10.3.1.16
recv Function
File
BerkeleyAPI.h
C int
recv(
char
* buf,
int
len,
int
flags
);
Returns
If recv is successful, the number of bytes copied to application buffer buf is returned. A value of zero indicates no data
180
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Public Members
SOCKET_DISCONNECTED ( see page 186) indicates the connection no longer exists.
Description
The recv() function is used to receive incoming data that has been queued for a socket. This function can be used with both datagram and stream socket. If the available data is too large to fit in the supplied application buffer buf, excess bytes are
Remarks
None.
Preconditions
function should be called.
Parameters
Parameters
s buf len flags
Description
Socket descriptor returned from a previous call to socket.
application data receive buffer.
buffer length in bytes.
no significance in this implementation
10.3.1.17
recvfrom Function
File
BerkeleyAPI.h
C int
recvfrom(
char
* buf,
int
len,
int
flags,
struct
int
* fromlen
);
Returns
If recvfrom is successful, the number of bytes copied to application buffer buf is returned. A value of zero indicates no data
available. A return value of SOCKET_ERROR ( see page 186) (-1) indicates an error condition.
Description
The recvfrom() function is used to receive incoming data that has been queued for a socket. This function can be used with both datagram and stream type sockets. If the available data is too large to fit in the supplied application buffer buf, excess
types, the data is buffered internally so the application can retreive all data by multiple calls of recvfrom.
Remarks
None.
Preconditions
socket function should be called.
Parameters
Parameters
s
Description
Socket descriptor returned from a previous call to socket.
181
10.3 Berkeley (BSD) Sockets buf len flags from fromlen
Microchip TCP/IP Stack Help BSD Wrapper Public Members application data receive buffer.
buffer length in bytes.
message flags. Currently this is not supported.
pointer to the sockaddr ( see page 183) structure that will be filled in with the
destination address.
size of buffer pointed by from.
10.3.1.18
send Function
File
BerkeleyAPI.h
C int
send(
const char
* buf,
int
len,
int
flags
);
Returns
indicates no data send.
Description
The send function is used to send outgoing data on an already connected socket. This function is used to send a reliable,
Remarks
None.
Preconditions
function should be called.
Parameters
Parameters
s buf len flags
Description
Socket descriptor returned from a previous call to socket.
application data buffer containing data to transmit.
length of data in bytes.
message flags. Currently this field is not supported.
10.3.1.19
sendto Function
File
BerkeleyAPI.h
C int
sendto(
const char
* buf,
int
len,
int
flags,
const struct
int
tolen
182
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Public Members
);
Returns
Description
The sendto function is used to send outgoing data on a socket. The destination address is given by to and tolen. Both
Datagram and stream sockets are supported.
Remarks
None.
Preconditions
socket function should be called.
Parameters
Parameters
s buf len flags to tolen
Description
Socket descriptor returned from a previous call to socket.
application data buffer containing data to transmit.
length of data in bytes.
message flags. Currently this field is not supported.
Optional pointer to the the sockaddr ( see page 183) structure containing the
destination address. If NULL, the currently bound remote port and IP address are used as the destination.
length of the sockaddr ( see page 183) structure.
10.3.1.20
SOCK_DGRAM Macro
File
BerkeleyAPI.h
C
#define
SOCK_DGRAM 110
//Connectionless datagram socket. Use UDP for the internet address family.
Description
Connectionless datagram socket. Use UDP for the internet address family.
10.3.1.21
SOCK_STREAM Macro
File
BerkeleyAPI.h
C
#define
SOCK_STREAM 100
//Connection based byte streams. Use TCP for the internet address family.
Description
Connection based byte streams. Use TCP for the internet address family.
10.3.1.22
sockaddr Structure
File
BerkeleyAPI.h
183
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help
C struct
sockaddr {
unsigned short
sa_family;
char
sa_data[14];
};
Members
Members
unsigned short sa_family; char sa_data[14];
Description
address family up to 14 bytes of direct address
Description
generic address structure for all address families
BSD Wrapper Public Members
10.3.1.23
SOCKADDR Type
File
BerkeleyAPI.h
C typedef struct
Description
generic address structure for all address families
10.3.1.24
sockaddr_in Structure
File
BerkeleyAPI.h
C struct
sockaddr_in {
short
sin_family;
WORD sin_port;
struct
char
sin_zero[8];
};
Members
Members
short sin_family;
WORD sin_port; struct in_addr sin_addr; char sin_zero[8];
Description
In the Internet address family
Description
Address ( see page 152) family; must be AF_INET ( see page 175).
Internet Protocol (IP) port.
IP address in network byte order.
Padding to make structure the same size as SOCKADDR ( see page 184).
10.3.1.25
SOCKADDR_IN Type
File
BerkeleyAPI.h
184
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help
C typedef struct
Description
In the Internet address family
BSD Wrapper Public Members
10.3.1.26
socket Function
File
BerkeleyAPI.h
C
int
af,
int
type,
int
protocol
);
Returns
New socket descriptor. INVALID_SOCKET ( see page 533) in case of error.
Description
This function creates a new BSD socket for the microchip TCPIP stack. The return socket descriptor is used for the subsequent BSD operations.
Remarks
None.
Preconditions
BerkeleySocketInit ( see page 186) function should be called.
Parameters
Parameters
af type protocol
Description
address family - AF_INET ( see page 175).
socket type SOCK_DGRAM ( see page 183) or SOCK_STREAM ( see page
IP protocol IPPROTO_UDP ( see page 179) or IPPROTO_TCP ( see page
10.3.1.27
SOCKET Type
File
BerkeleyAPI.h
C typedef
BYTE SOCKET;
Description
Socket descriptor
10.3.1.28
SOCKET_CNXN_IN_PROGRESS Macro
File
BerkeleyAPI.h
185
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help
C
#define
SOCKET_CNXN_IN_PROGRESS (-2)
//Socket connection state.
Description
Socket connection state.
10.3.1.29
SOCKET_DISCONNECTED Macro
File
BerkeleyAPI.h
C
#define
SOCKET_DISCONNECTED (-3)
//Socket disconnected
Description
Socket disconnected
10.3.1.30
SOCKET_ERROR Macro
File
BerkeleyAPI.h
C
#define
SOCKET_ERROR (-1)
//Socket error
Description
Socket error
BSD Wrapper Stack Members
10.3.2
BSD Wrapper Stack Members
Functions
Name
BerkeleySocketInit ( see page 186)
Module
Berkeley (BSD) Sockets ( see page 172)
Description
Initializes the Berkeley socket structure array.
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.3.2.1
BerkeleySocketInit Function
File
BerkeleyAPI.h
C void
BerkeleySocketInit();
186
10.3 Berkeley (BSD) Sockets Microchip TCP/IP Stack Help BSD Wrapper Internal Members
Returns
None
Description
This function initializes the Berkeley socket array. This function should be called before any BSD socket call.
Remarks
None.
Preconditions
None.
10.3.3
BSD Wrapper Internal Members
Enumerations
Name
Description
Berkeley Socket (BSD) states
Functions
Name Description
HandlePossibleTCPDisconnection
Internal function that checks for asynchronous TCP connection state changes and resynchs the BSD socket descriptor state to match.
Module
Berkeley (BSD) Sockets ( see page 172)
Variables
Name
BSDSocketArray ( see page 188) gAutoPortNumber ( see page 188)
Description
Array of BSDSocket ( see page 175) elements; used to track all socket state
and connection information.
Contains the next local port number to associate with a socket.
Description
The following functions and variables are designated as internal to the module.
10.3.3.1
BSD_SCK_STATE Enumeration
File
BerkeleyAPI.h
C typedef enum
{
SKT_CLOSED,
SKT_CREATED,
SKT_BOUND,
SKT_BSD_LISTEN,
SKT_LISTEN,
SKT_IN_PROGRESS,
SKT_EST,
SKT_DISCONNECTED
} BSD_SCK_STATE;
187
10.3 Berkeley (BSD) Sockets
Members
Members
SKT_CLOSED
SKT_CREATED
SKT_BOUND
SKT_BSD_LISTEN
SKT_LISTEN
SKT_IN_PROGRESS
SKT_EST
SKT_DISCONNECTED
Description
Berkeley Socket (BSD) states
Microchip TCP/IP Stack Help BSD Wrapper Internal Members
Description
Socket closed state indicating a free descriptor
Socket created state for TCP and UDP sockets
Socket bound state for TCP and UDP sockets
Listening state for TCP BSD listener handle "socket
TCP server listen ( see page 180) state
TCP client connection in progress state
TCP client or server established state
TCP client or server no longer connected to the remote host (but was historically)
10.3.3.2
BSDSocketArray Variable
File
BerkeleyAPI.c
C struct
BSDSocket BSDSocketArray[BSD_SOCKET_COUNT];
Description
10.3.3.3
gAutoPortNumber Variable
File
BerkeleyAPI.c
C
WORD gAutoPortNumber = 1024;
Description
Contains the next local port number to associate with a socket.
10.3.3.4
HandlePossibleTCPDisconnection Function
File
BerkeleyAPI.c
C static
BOOL HandlePossibleTCPDisconnection(
);
Returns
TRUE - Socket is disconnected FALSE - Socket is
Description
Internal function that checks for asynchronous TCP connection state changes and resynchs the BSD socket descriptor state
188
Microchip TCP/IP Stack Help DNS Public Members 10.4 DNS Client to match.
Preconditions
None
Parameters
Parameters
s
Description
TCP type socket descriptor returned from a previous call to socket. This socket must be in the SKT_LISTEN, SKT_IN_PROGRESS, SKT_EST, or
SKT_DISCONNECTED states.
10.4
DNS Client
The Domain Name Service associates host names (such as www.microchip.com) with IP addresses (such as 10.0.54.2).
The DNS Client module provides DNS resolution capabilities to the stack.
unknown.
DNS resolution operations follow a simple state machine, as indicated in the diagram below.
10.4.1
DNS Public Members
Functions
Name
Description
Claims access to the DNS module.
Releases control of the DNS module.
Begins resolution of an address.
Begins resolution of an address.
Determines if the DNS resolution is complete and provides the IP.
Macros
Name
Description
Constant for record type in DNSResolve ( see page 191). Indicates an A
(standard address) record.
189
10.4 DNS Client Microchip TCP/IP Stack Help DNS Public Members
Constant for record type in DNSResolve ( see page 191). Indicates an MX
(mail exchanger) record.
Module
Description
The following functions and variables are available to the stack application.
10.4.1.1
DNSBeginUsage Function
File
DNS.h
C
BOOL DNSBeginUsage();
Description
This function acts as a semaphore to obtain usage of the DNS module. Call this function and ensure that it returns TRUE
module so that other applications may make use of it.
Remarks
module. If this is not done, the stack will hang for all future applications requiring DNS access.
Preconditions
Stack is initialized.
Return Values
Return Values
TRUE
FALSE
Description
No other DNS resolutions are in progress and the calling application has sucessfully taken ownership of the DNS module
The DNS module is currently in use. Yield to the stack and attempt this call again later.
10.4.1.2
DNSEndUsage Function
File
DNS.h
C
BOOL DNSEndUsage();
Description
This function acts as a semaphore to obtain usage of the DNS module. Call this function when this application no longer needs the DNS module so that other applications may make use of it.
Remarks
Ensure that DNSEndUsage is always called once your application has obtained control of the DNS module. If this is not done, the stack will hang for all future applications requiring DNS access.
Preconditions
DNSBeginUsage ( see page 190) returned TRUE on a previous call.
190
10.4 DNS Client
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help
Description
The address to the host name was successfully resolved.
The DNS failed or the address does not exist.
DNS Public Members
10.4.1.3
DNSResolve Function
File
DNS.h
C void
DNSResolve(
BYTE* HostName,
BYTE Type
);
Returns
None
Description
This function attempts to resolve a host name to an IP address. When called, it starts the DNS state machine. Call
DNSIsResolved ( see page 192) repeatedly to determine if the resolution is complete.
Only one DNS resoultion may be executed at a time. The Hostname must not be modified in memory until the resolution is complete.
Remarks
This function requires access to one UDP socket. If none are available, MAX_UDP_SOCKETS may need to be increased.
Preconditions
DNSBeginUsage ( see page 190) returned TRUE on a previous call.
Parameters
Parameters
Hostname
Description
A pointer to the null terminated string specifiying the host for which to resolve an IP.
DNS_TYPE_A ( see page 192) or DNS_TYPE_MX ( see page 193)
depending on what type of record resolution is desired.
10.4.1.4
DNSResolveROM Function
File
DNS.h
C void
DNSResolveROM(
ROM BYTE* Hostname,
BYTE Type
);
Returns
None
Description
This function attempts to resolve a host name to an IP address. When called, it starts the DNS state machine. Call
DNSIsResolved ( see page 192) repeatedly to determine if the resolution is complete.
191
10.4 DNS Client Microchip TCP/IP Stack Help DNS Public Members
Only one DNS resoultion may be executed at a time. The Hostname must not be modified in memory until the resolution is complete.
Remarks
This function requires access to one UDP socket. If none are available, MAX_UDP_SOCKETS may need to be increased.
This function is aliased to DNSResolve ( see page 191) on non-PIC18 platforms.
Preconditions
DNSBeginUsage ( see page 190) returned TRUE on a previous call.
Parameters
Parameters
Hostname
Description
A pointer to the null terminated string specifiying the host for which to resolve an IP.
DNS_TYPE_A ( see page 192) or DNS_TYPE_MX ( see page 193)
depending on what type of record resolution is desired.
10.4.1.5
DNSIsResolved Function
File
DNS.h
C
BOOL DNSIsResolved(
IP_ADDR* HostIP
);
Description
Call this function to determine if the DNS resolution of an address has been completed. If so, the resolved address will be provided in HostIP.
Preconditions
DNSResolve ( see page 191) or DNSResolveROM ( see page 191) has been called.
Parameters
Parameters
HostIP
Description
A pointer to an IP_ADDR structure in which to store the resolved IP address once resolution is complete.
Return Values
Return Values
TRUE
FALSE
Description
The DNS client has obtained an IP, or the DNS process has encountered an error. HostIP will be 0.0.0.0 on error. Possible errors include server timeout (i.e.
DNS server not available), hostname not in the DNS, or DNS server errors.
The resolution process is still in progress.
10.4.1.6
DNS_TYPE_A Macro
File
DNS.h
C
#define
DNS_TYPE_A (1u)
// Constant for record type in DNSResolve. Indicates an A
(standard address) record.
192
10.4 DNS Client Microchip TCP/IP Stack Help
Description
Constant for record type in DNSResolve ( see page 191). Indicates an A (standard address) record.
DNS Internal Members
10.4.1.7
DNS_TYPE_MX Macro
File
DNS.h
C
#define
DNS_TYPE_MX (15u)
// Constant for record type in DNSResolve. Indicates an
MX (mail exchanger) record.
Description
Constant for record type in DNSResolve ( see page 191). Indicates an MX (mail exchanger) record.
10.4.2
DNS Internal Members
Functions
Name
DNSPutROMString ( see page 194)
DNSDiscardName ( see page 197)
Description
Writes a string to the DNS socket.
Writes a ROM string to the DNS socket.
Reads a name string or string pointer from the DNS socket and discards it.
Macros
Name
Description
Default port for DNS resolutions
Elapsed time after which a DNS resolution is considered to have timed out
Module
Structures
Name
Description
Structure for the DNS header
Variables
Name
DNSHostNameROM ( see page 195)
Description
Host name in RAM to look up
Host name in ROM to look up
Stores various flags for the UDP module
Record type being queried
193
10.4 DNS Client Microchip TCP/IP Stack Help
Node information about the resolved node
State machine for a DNS query
Description
The following functions and variables are designated as internal to the DNS module.
10.4.2.1
DNSPutString Function
File
DNS.c
C static void
DNSPutString(
BYTE* String
);
Returns
None
Description
This function writes a string to the DNS socket, ensuring that it is properly formatted.
Preconditions
UDP socket is obtained and ready for writing.
Parameters
Parameters
String
Section
Function Prototypes
Description
the string to write to the UDP socket.
10.4.2.2
DNSPutROMString Function
File
DNS.c
C static void
DNSPutROMString(
ROM BYTE* String
);
Returns
None
Description
This function writes a string to the DNS socket, ensuring that it is properly formatted.
Remarks
This function is aliased to DNSPutString ( see page 194) on non-PIC18 platforms.
Preconditions
UDP socket is obtained and ready for writing.
DNS Internal Members
194
10.4 DNS Client
Parameters
Parameters
String
Microchip TCP/IP Stack Help
Description
the string to write to the UDP socket.
10.4.2.3
DNS_PORT Macro
File
DNS.c
C
#define
DNS_PORT 53u
// Default port for DNS resolutions
Description
Default port for DNS resolutions
DNS Internal Members
10.4.2.4
DNS_TIMEOUT Macro
File
DNS.c
C
#define
// Elapsed time after which a DNS resolution is considered to have timed out
Description
Elapsed time after which a DNS resolution is considered to have timed out
10.4.2.5
DNSHostName Variable
File
DNS.c
C
BYTE * DNSHostName;
Description
Host name in RAM to look up
10.4.2.6
DNSHostNameROM Variable
File
DNS.c
C
ROM BYTE * DNSHostNameROM;
Description
Host name in ROM to look up
195
10.4 DNS Client Microchip TCP/IP Stack Help
10.4.2.7
Flags Variable
File
UDP.c
C struct
{
unsigned char
bFirstRead : 1;
unsigned char
bWasDiscarded : 1;
} Flags;
Members
Members
unsigned char bFirstRead : 1; unsigned char bWasDiscarded : 1;
Description
Stores various flags for the UDP module
Description
No data has been read from this segment yet
The data in this segment has been discarded
10.4.2.8
RecordType Variable
File
DNS.c
C
BYTE RecordType;
Description
Record type being queried
10.4.2.9
ResolvedInfo Variable
File
DNS.c
C
NODE_INFO ResolvedInfo;
Description
Node information about the resolved node
10.4.2.10
smDNS Variable
File
DNS.c
C enum
{
DNS_START = 0,
DNS_ARP_START_RESOLVE,
DNS_ARP_RESOLVE,
DNS_OPEN_SOCKET,
DNS_QUERY,
DNS Internal Members
196
10.5 Dynamic DNS Client
DNS_GET_RESULT,
DNS_FAIL,
DNS_DONE
} smDNS;
Members
Members
DNS_START = 0
DNS_ARP_START_RESOLVE
DNS_ARP_RESOLVE
DNS_OPEN_SOCKET
DNS_QUERY
DNS_GET_RESULT
DNS_FAIL
DNS_DONE
Description
State machine for a DNS query
Microchip TCP/IP Stack Help
Description
Initial state to reset client state variables
Send ARP resolution of DNS server or gateway MAC address
Wait for response to ARP request
Open UDP socket
Send DNS query to DNS server
Wait for response from DNS server
ARP or DNS server not responding
DNS query is finished
10.4.2.11
DNS_HEADER Structure
File
DNS.c
C typedef struct
{
WORD_VAL TransactionID;
WORD_VAL Flags;
WORD_VAL Questions;
WORD_VAL Answers;
WORD_VAL AuthoritativeRecords;
WORD_VAL AdditionalRecords;
} DNS_HEADER;
Description
Structure for the DNS header
10.4.2.12
DNSDiscardName Function
File
DNS.c
C static void
DNSDiscardName();
Returns
None
Description
This function reads a name string from the DNS socket. Each string consists of a series of labels. Each label consists of a length prefix byte, followed by the label bytes. At the end of the string, a zero length label is found as termination. If name compression is used, this function will automatically detect the pointer and discard it.
Preconditions
UDP socket is obtained and ready for reading a DNS name
197
10.5 Dynamic DNS Client Microchip TCP/IP Stack Help Dynamic DNS Public Members
10.5
Dynamic DNS Client
The Dynamic DNS Client module provides a method for updating a dynamic IP address to a public DDNS service. These services can be used to provide DNS hostname mapping to devices that behind routers, firewalls, and/or on networks that dynamically assign IP addresses.
Note that this only solves one of the two problems for communicating to devices on local subnets from the Internet. While
Dynamic DNS can help to locate the device, the router or firewall it sits behind must still properly forward the incoming connection request. This generally requires port forwarding to be configured for the router behind which the device is located.
The Dynamic DNS client supports the popular interface used by DynDNS.org
, No-IP.com
, and DNS-O-Matic.com
.
IMPORTANT: The dynamic DNS services stipulate that updates should be made no more frequently than 10 minutes, and only when the IP address has changed. Updates made more often than that are considered abusive, and may eventually cause your account to be disabled. Production devices that get rebooted frequently may need to store the last known IP in non-volatile memory. You also should not enable this module while testing the rest of your application.
10.5.1
Dynamic DNS Public Members
Enumerations
Name
Description
Dynamic DNS Services. Must support the DynDNS ( see page 198) API
Status message for DynDNS ( see page 198) client. GOOD and NOCHG are
ok, but ABUSE through 911 are fatal. UNCHANGED through INVALID are locally defined.
Functions
Name
DDNSForceUpdate ( see page 201)
Description
Forces an immediate DDNS update
Returns the last known external IP address of the device.
DDNSGetLastStatus ( see page 202)
DDNSSetService ( see page 202)
Returns the status of the most recent update.
Selects a pre-configured Dynamic DNS service
Module
Dynamic DNS Client ( see page 198)
Structures
Name
Variables
Description
Configuration parameters for the Dynamic DNS Client
Name Description
DDNSClient ( see page 201) Configuration parameters for the module
198
10.5 Dynamic DNS Client Microchip TCP/IP Stack Help
Description
These functions and variables are meant to be called by your stack application.
Dynamic DNS Public Members
10.5.1.1
DDNS_POINTERS Structure
File
DynDNS.h
C typedef struct
{
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} CheckIPServer;
WORD CheckIPPort;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} UpdateServer;
WORD UpdatePort;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Username;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Password;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Host;
struct
{
unsigned char
CheckIPServer : 1;
unsigned char
UpdateServer : 1;
unsigned char
Username : 1;
unsigned char
Password : 1;
unsigned char
Host : 1;
} ROMPointers;
} DDNS_POINTERS;
Description
This structure of pointers configures the Dynamic DNS Client. Initially, all pointers will be null and the client will be disabled.
Set DDNSClient ( see page 201).[field name].szRAM
to use a string stored in RAM, or
DDNSClient ( see page 201).[field name].szROM
to use a string stored in ROM. (Where [field name] is one of the parameters below.)
If a ROM string is specified, DDNSClient.ROMPointers.[field name] must also be set to 1 to indicate that this field should be retrieved from ROM instead of RAM.
Parameters
Parameters
CheckIPServer
CheckIPPort
UpdateServer
UpdatePort
Username
Password
Host
ROMPointers
Description
The server used to determine the external IP address
Port on the above server to connect ( see page 176) to
The server where updates should be posted
Port on the above server to connect ( see page 176) to
The user name for the dynamic DNS server
The password to supply when making updates
The host name you wish to update
Indicates which parameters to read from ROM instead of RAM.
199
10.5 Dynamic DNS Client Microchip TCP/IP Stack Help Dynamic DNS Public Members
10.5.1.2
DDNS_SERVICES Enumeration
File
DynDNS.h
C typedef enum
{
DYNDNS_ORG = 0u,
NO_IP_COM,
DNSOMATIC_COM
} DDNS_SERVICES;
Members
Members
DYNDNS_ORG = 0u
NO_IP_COM
DNSOMATIC_COM
Description
www.dyndns.org
www.no-ip.com
www.dnsomatic.com
Description
10.5.1.3
DDNS_STATUS Enumeration
File
DynDNS.h
C typedef enum
{
DDNS_STATUS_GOOD = 0u,
DDNS_STATUS_NOCHG,
DDNS_STATUS_ABUSE,
DDNS_STATUS_BADSYS,
DDNS_STATUS_BADAGENT,
DDNS_STATUS_BADAUTH,
DDNS_STATUS_NOT_DONATOR,
DDNS_STATUS_NOT_FQDN,
DDNS_STATUS_NOHOST,
DDNS_STATUS_NOT_YOURS,
DDNS_STATUS_NUMHOST,
DDNS_STATUS_DNSERR,
DDNS_STATUS_911,
DDNS_STATUS_UPDATE_ERROR,
DDNS_STATUS_UNCHANGED,
DDNS_STATUS_CHECKIP_ERROR,
DDNS_STATUS_INVALID,
DDNS_STATUS_UNKNOWN
} DDNS_STATUS;
Members
Members
DDNS_STATUS_GOOD = 0u
DDNS_STATUS_NOCHG
DDNS_STATUS_ABUSE
DDNS_STATUS_BADSYS
DDNS_STATUS_BADAGENT
Description
Update successful, hostname is now updated
Update changed no setting and is considered abusive. Additional 'nochg' updates will cause hostname to be blocked.
The hostname specified is blocked for update abuse.
System parameter not valid. Should be dyndns, statdns or custom.
The user agent was blocked or not sent.
200
10.5 Dynamic DNS Client Microchip TCP/IP Stack Help Dynamic DNS Public Members
DDNS_STATUS_BADAUTH
DDNS_STATUS_NOT_DONATOR
DDNS_STATUS_NOT_FQDN
DDNS_STATUS_NOHOST
DDNS_STATUS_NOT_YOURS
DDNS_STATUS_NUMHOST
DDNS_STATUS_DNSERR
DDNS_STATUS_911
DDNS_STATUS_UPDATE_ERROR
DDNS_STATUS_UNCHANGED
DDNS_STATUS_CHECKIP_ERROR
DDNS_STATUS_INVALID
DDNS_STATUS_UNKNOWN
The username and password pair do not match a real user.
An option available only to credited users (such as offline URL) was specified, but the user is not a credited user. If multiple hosts were specified, only a single
!donator will be returned.
The hostname specified is not a fully-qualified domain name (not in the form hostname.dyndns.org or domain.com).
The hostname specified does not exist in this user account (or is not in the service specified in the system parameter).
The hostname specified does not belong to this user account.
Too many hosts specified in an update.
Unspecified DNS error encountered by the DDNS service.
There is a problem or scheduled maintenance with the DDNS service.
Error communicating with Update service.
The IP Check indicated that no update was necessary.
Error communicating with CheckIP service.
DDNS Client data is not valid.
DDNS client has not yet been executed with this configuration.
Description
UNCHANGED through INVALID are locally defined.
10.5.1.4
DDNSClient Variable
File
DynDNS.c
C
Description
Configuration parameters for the module
10.5.1.5
DDNSForceUpdate Function
File
DynDNS.h
C void
DDNSForceUpdate();
Returns
None
Description
This function forces the DDNS Client to execute a full update immediately. Any error message is cleared, and the update will
parameters have been modified.
Preconditions
DDNSInit ( see page 203) must have been called.
201
10.5 Dynamic DNS Client Microchip TCP/IP Stack Help Dynamic DNS Public Members
10.5.1.6
DDNSGetLastIP Function
File
DynDNS.h
C
IP_ADDR DDNSGetLastIP();
Returns
The last known external IP address of the device.
Description
This function returns the last known external IP address of the device.
Preconditions
None
10.5.1.7
DDNSGetLastStatus Function
File
DynDNS.h
C
DDNS_STATUS DDNSGetLastStatus();
Returns
DDNS_STATUS ( see page 200) indicating the status code for the most recent update.
Description
possible codes.
Preconditions
None
10.5.1.8
DDNSSetService Function
File
DynDNS.h
C void
DDNSSetService(
);
Returns
None
Description
Preconditions
None
202
10.5 Dynamic DNS Client
Parameters
Parameters
svc
Microchip TCP/IP Stack Help Dynamic DNS Stack Members
Description
one of the DDNS_SERVICES ( see page 200) elements to indicate the
selected service
10.5.2
Dynamic DNS Stack Members
Functions
Name Description
Initializes the Dynamic DNS module.
DDNSTask ( see page 203) Dynamic DNS client task/state machine.
Module
Dynamic DNS Client ( see page 198)
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.5.2.1
DDNSInit Function
File
DynDNS.h
C void
DDNSInit();
Returns
None
Description
module to attempt the first update after 15 seconds have elapsed (so as to allow the DHCP configuration to stabalize).
Remarks
This function is called only one during lifetime of the application.
Preconditions
None
10.5.2.2
DDNSTask Function
File
DynDNS.h
C void
DDNSTask();
Returns
None
203
10.5 Dynamic DNS Client Microchip TCP/IP Stack Help Dynamic DNS Internal Members
Description
This function performs the background tasks of the Dynamic DNS Client. Once the DDNSPointers structure is configured, this task attempt to update the Dynamic DNS hostname on a periodic schedule.
The task first accesses the CheckIP server to determine the device's current external IP address. If the IP address has changed, it issues an update command to the dynamic DNS service to propagate the change. This sequence executes
Remarks
This function acts as a task (similar to one in an RTOS). It performs its task in a co-operative manner, and the main application must call this function periodically to ensure that its tasks get executed in a timely fashion.
Preconditions
DDNSInit ( see page 203)() has been called.
Section
Function Prototypes
10.5.3
Dynamic DNS Internal Members
Macros
Name
DDNS_DEFAULT_PORT ( see page 207)
Description
Default CheckIP server for determining current IP address
Default port for CheckIP server
Module
Dynamic DNS Client ( see page 198)
Variables
Name
205) ddnsServiceHosts ( see page 205) ddnsServicePorts ( see page 205) dwUpdateAt ( see page
Description
Indicates that the update should be done regardless of whether or not the IP changed. Use this flag when the user/pass/hostname have changed.
Host names for various Dynamic DNS services
Port numbers for various Dynamic DNS services
Indicates when the next CheckIP should be done
Last known IP address of this device
Status response from last update
_checkIpSrvrResponse ( see page 206)
Delimiter to locate IP address from CheckIP server
_updateIpSrvrResponse ( see page 206)
Response codes from DynDNS ( see page 198) Update Server
Description
The following functions and variables are designated as internal to the Dynamic DNS module.
204
10.5 Dynamic DNS Client Microchip TCP/IP Stack Help Dynamic DNS Internal Members
10.5.3.1
bForceUpdate Variable
File
DynDNS.c
C
BOOL bForceUpdate;
Description
Indicates that the update should be done regardless of whether or not the IP changed. Use this flag when the user/pass/hostname have changed.
10.5.3.2
ddnsServiceHosts Variable
File
CustomHTTPApp.c
C
ROM
char
* ROM ddnsServiceHosts[];
Description
Host names for various Dynamic DNS services
10.5.3.3
ddnsServicePorts Variable
File
DynDNS.c
C
ROM WORD ddnsServicePorts[] = { 80, 80, 80, };
Description
Port numbers for various Dynamic DNS services
10.5.3.4
dwUpdateAt Variable
File
DynDNS.c
C
DWORD dwUpdateAt;
Description
Indicates when the next CheckIP should be done
10.5.3.5
lastKnownIP Variable
File
DynDNS.c
205
10.5 Dynamic DNS Client
C
IP_ADDR lastKnownIP;
Description
Last known IP address of this device
Microchip TCP/IP Stack Help
10.5.3.6
lastStatus Variable
File
DynDNS.c
C
Description
Status response from last update
10.5.3.7
_checkIpSrvrResponse Variable
File
DynDNS.c
C
ROM BYTE _checkIpSrvrResponse[] = "Address:";
Description
Delimiter to locate IP address from CheckIP server
Dynamic DNS Internal Members
10.5.3.8
_updateIpSrvrResponse Variable
File
DynDNS.c
C
ROM
char
* _updateIpSrvrResponse[] = { "good", "nochg", "abuse", "badsys", "badagent",
"badauth", "!donator", "notfqdn", "nohost", "!yours", "numhost", "dnserr", "911", };
Description
Response codes from DynDNS ( see page 198) Update Server
10.5.3.9
DDNS_CHECKIP_SERVER Macro
File
DynDNS.h
C
#define
DDNS_CHECKIP_SERVER (ROM BYTE*)"checkip.dyndns.com"
// Default CheckIP server for determining current IP address
Description
Default CheckIP server for determining current IP address
206
10.6 Hashes Microchip TCP/IP Stack Help Hashes Public Members
10.5.3.10
DDNS_DEFAULT_PORT Macro
File
DynDNS.h
C
#define
DDNS_DEFAULT_PORT (80u)
// Default port for CheckIP server
Description
Default port for CheckIP server
10.6
Hashes
The Hashes module calculates MD5 and/or SHA-1 hash sums of data. Hash sums are one-way digest functions, meaning that the original message cannot be derived from the hash of the message. Collisions, while exceedingly rare, do exist.
However, they are extremely difficult to create.
Hash functions are generally used for message integrity and authentication purposes. They are used extensively by encryption protocols such as SSL to verify that a message has not been tampered with during transit.
The following flow diagram demonstrates how to use this module.
MD5Initialize ( see page 210) or SHA1Initialize (
see page 210). Then, call HashAddData ( see page 208) or
calculation, continue adding data and repeating this process as many times as necessary.
10.6.1
Hashes Public Members
Functions
Name
HashAddROMData ( see page 208)
Description
Adds data to the hash sum.
Adds data to the hash sum.
207
10.6 Hashes Microchip TCP/IP Stack Help
Calculates an MD5 hash
Initializes a new MD5 hash.
Calculates a SHA-1 hash
Initializes a new SHA-1 hash.
Module
Structures
Name
Description
Context storage for a hash operation
Description
The following functions and variables are available to the stack application.
10.6.1.1
HashAddData Function
File
Hashes.h
C void
HashAddData(
BYTE* data,
WORD len
);
Returns
None
Description
Adds data to the hash sum.
Remarks
This function calls the appropriate hashing function based on the hash typed defined in theSum.
Preconditions
The hash sum has already been initialized
Parameters
Parameters
theSum data len
Description
hash context state the data to be added to the hash sum length of data
10.6.1.2
HashAddROMData Function
File
Hashes.h
Hashes Public Members
208
10.6 Hashes Microchip TCP/IP Stack Help
C void
HashAddROMData(
ROM BYTE* data,
WORD len
);
Returns
None
Description
Adds data to the hash sum.
Remarks
This function calls the appropriate hashing function based on the hash typed defined in theSum.
This function is aliased to HashAddData ( see page 208) on non-PIC18 platforms.
Preconditions
The hash sum has already been initialized
Parameters
Parameters
theSum data len
Description
hash context state the data to be added to the hash sum length of data
Hashes Public Members
10.6.1.3
MD5Calculate Function
File
Hashes.h
C void
MD5Calculate(
BYTE* result
);
Returns
None
Description
This function calculates the hash sum of all input data so far. It is non-destructive to the hash context, so more data may be added after this function is called.
Preconditions
The hash context has been properly initialized.
Parameters
Parameters
theSum result
Description
the current hash context
16 byte array in which to store the resulting hash
209
10.6 Hashes Microchip TCP/IP Stack Help Hashes Public Members
10.6.1.4
MD5Initialize Function
File
Hashes.h
C void
MD5Initialize(
);
Returns
None
Description
Initializes a new MD5 hash.
Preconditions
None
Parameters
Parameters
theSum
Description
pointer to the allocated HASH_SUM ( see page 211) object to initialize as MD5
10.6.1.5
SHA1Calculate Function
File
Hashes.h
C void
SHA1Calculate(
BYTE* result
);
Returns
None
Description
This function calculates the hash sum of all input data so far. It is non-destructive to the hash context, so more data may be added after this function is called.
Preconditions
The hash context has been properly initialized.
Parameters
Parameters
theSum result
Description
the current hash context
20 byte array in which to store the resulting hash
10.6.1.6
SHA1Initialize Function
File
Hashes.h
210
10.6 Hashes
C void
SHA1Initialize(
);
Returns
None
Description
Initializes a new SHA-1 hash.
Preconditions
None
Parameters
Parameters
theSum
Section
Function Prototypes
Microchip TCP/IP Stack Help Hashes Stack Members
Description
pointer to the allocated HASH_SUM ( see page 211) object to initialize as
SHA-1
10.6.1.7
HASH_SUM Structure
File
Hashes.h
C typedef struct
{
DWORD h0;
DWORD h1;
DWORD h2;
DWORD h3;
DWORD h4;
DWORD bytesSoFar;
BYTE partialBlock[64];
} HASH_SUM;
Members
Members
DWORD h0;
DWORD h1;
DWORD h2;
DWORD h3;
DWORD h4;
DWORD bytesSoFar;
BYTE partialBlock[64];
HASH_TYPE hashType;
Description
Context storage for a hash operation
Description
Hash state h0
Hash state h1
Hash state h2
Hash state h3
Hash state h4
Total number of bytes hashed so far
Beginning of next 64 byte block
Type of hash being calculated
211
10.6 Hashes Microchip TCP/IP Stack Help Hashes Stack Members
10.6.2
Hashes Stack Members
Functions
Name
SHA1AddROMData ( see page 213)
Module
Description
Adds data to an MD5 hash calculation.
Adds data to a SHA-1 hash calculation.
Adds data to a SHA-1 hash calculation.
Adds data to an MD5 hash calculation.
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.6.2.1
MD5AddROMData Function
File
Hashes.h
C void
MD5AddROMData(
ROM BYTE* data,
WORD len
);
Returns
None
Description
Adds data to an MD5 hash calculation.
Remarks
This function is aliased to MD5AddData ( see page 214) on non-PIC18 platforms.
Preconditions
The hash context has already been initialized.
Parameters
Parameters
theSum data len
Description
a pointer to the hash context structure the data to add to the hash the length of the data to add
212
10.6 Hashes Microchip TCP/IP Stack Help
10.6.2.2
SHA1AddROMData Function
File
Hashes.h
C void
SHA1AddROMData(
ROM BYTE* data,
WORD len
);
Returns
None
Description
Adds data to a SHA-1 hash calculation.
Remarks
This function is aliased to SHA1AddData ( see page 213) on non-PIC18 platforms.
Preconditions
The hash context has already been initialized.
Parameters
Parameters
theSum data len
Description
a pointer to the hash context structure the data to add to the hash the length of the data to add
10.6.2.3
SHA1AddData Function
File
Hashes.h
C void
SHA1AddData(
BYTE* data,
WORD len
);
Returns
None
Description
Adds data to a SHA-1 hash calculation.
Preconditions
The hash context has already been initialized.
Parameters
Parameters
theSum data
Description
a pointer to the hash context structure the data to add to the hash
Hashes Stack Members
213
10.6 Hashes len
Microchip TCP/IP Stack Help the length of the data to add
10.6.2.4
MD5AddData Function
File
Hashes.h
C void
MD5AddData(
BYTE* data,
WORD len
);
Returns
None
Description
Adds data to an MD5 hash calculation.
Preconditions
The hash context has already been initialized.
Parameters
Parameters
theSum data len
Description
a pointer to the hash context structure the data to add to the hash the length of the data to add
10.6.3
Hashes Internal Members
Enumerations
Name
Description
Type of hash being calculated
Functions
Name Description
Calculates the SHA-1 hash sum of a block.
Calculates the MD5 hash sum of a block.
Module
Variables
Name
_MD5_r ( see page 215) lastBlock ( see page 215)
Description
Array of pre-defined K values for MD5
Array of pre-defined R vales for MD5
Stores a copy of the last block with the required padding
Hashes Internal Members
214
10.6 Hashes Microchip TCP/IP Stack Help Hashes Internal Members
Description
10.6.3.1
_MD5_k Variable
File
Hashes.c
C
ROM DWORD _MD5_k[64] = { 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE, 0xF57C0FAF,
0x4787C62A, 0xA8304613, 0xFD469501, 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE,
0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821, 0xF61E2562, 0xC040B340, 0x265E5A51,
0xE9B6C7AA, 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8, 0x21E1CDE6, 0xC33707D6,
0xF4D50D87, 0x455A14ED, 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A, 0xFFFA3942,
0x8771F681, 0x6D9D6122, 0xFDE5380C, 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70,
0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05, 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8,
0xC4AC5665, 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039, 0x655B59C3, 0x8F0CCC92,
0xFFEFF47D, 0x85845DD1, 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1, 0xF7537E82,
0xBD3AF235, 0x2AD7D2BB, 0xEB86D391 };
Description
Array of pre-defined K values for MD5
10.6.3.2
_MD5_r Variable
File
Hashes.c
C
ROM BYTE _MD5_r[64] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9,
14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16,
23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};
Description
Array of pre-defined R vales for MD5
10.6.3.3
lastBlock Variable
File
Hashes.c
C
BYTE lastBlock[64];
Description
Stores a copy of the last block with the required padding
10.6.3.4
HASH_TYPE Enumeration
File
Hashes.h
215
10.6 Hashes
C typedef enum
{
HASH_MD5 = 0u,
HASH_SHA1
} HASH_TYPE;
Members
Members
HASH_MD5 = 0u
HASH_SHA1
Description
Type of hash being calculated
Microchip TCP/IP Stack Help
Description
MD5 is being calculated
SHA-1 is being calculated
Hashes Internal Members
10.6.3.5
SHA1HashBlock Function
File
Hashes.c
C static void
SHA1HashBlock(
BYTE* data,
DWORD* h0,
DWORD* h1,
DWORD* h2,
DWORD* h3,
DWORD* h4
);
Returns
None
Description
This function calculates the SHA-1 hash sum over a block and updates the values of h0-h3 with the next context.
Preconditions
The data pointer must be WORD aligned on 16-bit parts and DWORD aligned on 32-bit PICs. If alignment is not correct, a memory alignment exception will occur.
Parameters
h2 h3 h4
Parameters
data h0 h1
Section
Functions and variables required for SHA-1
Description
The block of 64 bytes to hash the current hash context h0 value the current hash context h1 value the current hash context h2 value the current hash context h3 value the current hash context h4 value
10.6.3.6
MD5HashBlock Function
File
Hashes.c
216
10.7 Helpers Microchip TCP/IP Stack Help Helpers Public Members
C static void
MD5HashBlock(
BYTE* data,
DWORD* h0,
DWORD* h1,
DWORD* h2,
DWORD* h3
);
Returns
None
Description
This function calculates the MD5 hash sum over a block and updates the values of h0-h3 with the next context.
Preconditions
The data pointer must be WORD aligned on 16-bit parts and DWORD aligned on 32-bit PICs. If alignment is not correct, a memory alignment exception will occur.
Parameters
Parameters
data h0 h1 h2 h3
Description
The block of 64 bytes to hash the current hash context h0 value the current hash context h1 value the current hash context h2 value the current hash context h3 value
10.7
Helpers
Functions
Name Description
(0x0000 to 0xFFFF).
Copies multiple strings to a destination
Variables
Name
dwLFSRRandSeed ( see page 235)
Description
Default Random Number Generator seed. 0x41FE9F9E corresponds to calling
LFSRSeedRand ( see page 233)(1)
Description
This module contains several helper functions used throughout the TCP/IP Stack. Some of these duplicate functionality already implemented in the compiler's default libraries. In those cases, the compiler's version is used and the stack's version is omitted.
217
10.7 Helpers Microchip TCP/IP Stack Help Helpers Public Members
10.7.1
Helpers Public Members
Functions
Name
Description
Decodes a Base-64 array to its literal representation.
Encodes a binary array to Base-64.
Converts the upper nibble of a binary value to a hexadecimal ASCII byte.
Converts the lower nibble of a binary value to a hexadecimal ASCII byte.
CalcIPChecksum ( see page 221)
ExtractURLFields ( see page 221)
Calculates an IP checksum value.
Extracts all parameters from an URL string (ex:
"http://admin:[email protected]:8080/myfile.gif" is split into
{PROTOCOL_HTTP, "admin", "passwd", "www.microchip.com", 8080,
"/myfile.gif"}.
Formats a string to a valid NetBIOS name.
FormatNetBIOSName ( see page 224)
Generates a random DWORD.
Converts a hex string to a single byte.
Left-rotates a DWORD.
leftRotateDWORD ( see page 226)
ROMStringToIPAddress ( see page 227)
stricmppgm2ram ( see page 228)
Replaces all instances of a particular substring with a new string
Converts a string to an IP address
Case-insensitive comparison of a string in RAM to a string in ROM.
StringToIPAddress ( see page 229) strupr ( see page 229)
Converts a string to an IP address
swaps ( see page 231) uitoa ( see page 231)
Converts a string to uppercase.
Searches a string up to a specified number of characters for a specific character.
Swaps the endian-ness of a DWORD.
Swaps the endian-ness of a WORD.
Converts an unsigned integer to a decimal string.
Converts an unsigned integer to a decimal string.
Decodes a URL-encoded string.
Macros
Name
leftRotateDWORD ( see page 226)
ROMStringToIPAddress ( see page 228)
Module
Description
Rotations are more efficient in C30 and C32
Non-ROM variant for C30 and C32
218
10.7 Helpers Microchip TCP/IP Stack Help
Description
The following functions and variables are available to the stack application.
Helpers Public Members
10.7.1.1
Base64Decode Function
File
Helpers.h
C
WORD Base64Decode(
BYTE* cSourceData,
WORD wSourceLen,
BYTE* cDestData,
WORD wDestLen
);
Returns
Number of decoded bytes written to cDestData.
Description
Decodes a Base-64 array to its literal representation.
Remarks
This function is binary safe and will ignore invalid characters (CR, LF, etc). If cSourceData is equal to cDestData, the data will be converted in-place. If cSourceData is not equal to cDestData, but the regions overlap, the behavior is undefined.
Decoded data is always at least 1/4 smaller than the source data.
Preconditions
None
Parameters
Parameters
cSourceData wSourceLen cDestData
Description
Pointer to a string of Base-64 encoded data
Length of the Base-64 source data Maximum length that can be written to cDestData
Pointer to write the decoded data
10.7.1.2
Base64Encode Function
File
Helpers.h
C
WORD Base64Encode(
BYTE* cSourceData,
WORD wSourceLen,
BYTE* cDestData,
WORD wDestLen
);
Returns
Number of encoded bytes written to cDestData. This will always be a multiple of 4.
Description
Encodes a binary array to Base-64.
219
10.7 Helpers Microchip TCP/IP Stack Help Helpers Public Members
Remarks
Encoding cannot be performed in-place. If cSourceData overlaps with cDestData, the behavior is undefined.
Encoded data is always at least 1/3 larger than the source data. It may be 1 or 2 bytes larger than that.
Preconditions
None
Parameters
Parameters
cSourceData wSourceLen cDestData
Description
Pointer to a string of binary data
Length of the binary source data Maximum length that can be written to cDestData
Pointer to write the Base-64 encoded data
10.7.1.3
btohexa_high Function
File
Helpers.h
C
BYTE btohexa_high(
BYTE b
);
Returns
The upper hexadecimal ASCII byte '0'-'9' or 'A'-'F'.
Description
Converts the upper nibble of a binary value to a hexadecimal ASCII byte. For example, btohexa_high(0xAE) will return 'A'.
Preconditions
None
Parameters
Parameters
b
Description
the byte to convert
10.7.1.4
btohexa_low Function
File
Helpers.h
C
BYTE btohexa_low(
BYTE b
);
Returns
The lower hexadecimal ASCII byte '0'-'9' or 'A'-'F'.
Description
220
10.7 Helpers
Preconditions
None
Parameters
Parameters
b
Microchip TCP/IP Stack Help Helpers Public Members
Description
the byte to convert
10.7.1.5
CalcIPChecksum Function
File
Helpers.h
C
WORD CalcIPChecksum(
BYTE* buffer,
WORD len
);
Returns
The calculated checksum.
Description
This function calculates an IP checksum over an array of input data. The checksum is the 16-bit one's complement of one's complement sum of all words in the data (with zero-padding if an odd number of bytes are summed). This checksum is defined in RFC 793.
Internal
This function could be improved to do 32-bit sums on PIC32 platforms.
Preconditions
buffer is WORD aligned (even memory address) on 16- and 32-bit PICs.
Parameters
Parameters
buffer count
Description
pointer to the data to be checksummed number of bytes to be checksummed
10.7.1.6
ExtractURLFields Function
File
Helpers.h
C
BYTE ExtractURLFields(
BYTE * vURL,
PROTOCOLS * protocol,
BYTE * vUsername,
WORD * wUsernameLen,
BYTE * vPassword,
WORD * wPasswordLen,
BYTE * vHostname,
WORD * wHostnameLen,
WORD * wPort,
BYTE * vFilePath,
WORD * wFilePathLen
);
221
10.7 Helpers Microchip TCP/IP Stack Help Helpers Public Members
Returns
Zero on success. Nonzero indicates an error code. If a nonzero error code is returned, none of the returned buffers or pointer values should be treated as valid, but some of them may have been written to. The following are all possible return values.
0 No error
1 Protocol unknown (additional code needs to be added to ExtractURLFields() and the PROTOCOLS enum needs to be updated if you want to decode URLs of this protocol type.
2 URL malformed. Illegal or unknown URL format encountered.
3 Buffer too small. One of the input buffer sizes is too small to contain the URL parameter.
Description
Extracts all parameters from an URL string (ex: "http://admin:[email protected]:8080/myfile.gif" is split into
{PROTOCOL_HTTP, "admin", "passwd", "www.microchip.com", 8080, "/myfile.gif"}.
The URL string can be null terminated, or alternatively could be terminated by a carriage return or line feed.
If the protocol is unrecognized or the protocol is recognized but the URL is malformed, than an error is safely returned. For more information on URL/URI interpretation see RFC 2396.
Preconditions
This function is commented out by default to save code space because it is not used by any current stack features.
However, if you want to use it, go ahead and uncomment it. It has been tested, so it (should) work correctly.
Parameters
Parameters
vURL protocol
Description
Pointer to null terminated URL to decode and extract from. This parameter is required and needs to have the minimum RFC 1738 components in it (protocol and hostname).
Optional pointer to a PROTOCOLS enum to retrieve the decoded protocol type.
If this parameter is unneeded, specify a NULL pointer. The protocol is a required part of the URL, so it must always be present. The protocol also determines what scheme all other parameters are decoded using, so the function will fail if an unrecognized protocol is provided. The PROTOCOLS enum members show all of the currently supported protocols for this function.
vUsername
For the example URL provided in the function description, PROTOCOL_HTTP would be returned for this field.
Optional pointer to a buffer to write the decoded username portion of the URL.
If the URL does not contain a username or a NULL pointer is supplied, then this field is ignored.
For the example URL provided in the function description, "admin" would be returned for this field.
222
10.7 Helpers wUsernameLen vPassword wPasswordLen vHostname
Microchip TCP/IP Stack Help Helpers Public Members
On call: Optional pointer to a WORD specifying the maximum length of the vUsername buffer, including the null terminator character.
Upon return: If wUsernameLen and vUsername are non-NULL, the
*wUsernameLen WORD is updated with the actual number of characters written to the vUsername buffer, including the null terminator character. If vUsername is NULL but wUsernameLen is non-NULL, then no characters are copied, but *wUsernameLen will return the number of characters required to fit the full username string. If wUsernameLen is NULL, then the username field in the URL, if present, is ignored and the vUsername pointer is not used.
If zero characters were written, this indicates that the URL did not contain a username field. If one character was written, this indicates that a username field was present, but was a zero character string (ex: "").
For the example URL provided in the function description, 6 (0x0006) would be returned for this field.
Optional pointer to a buffer to write the decoded password portion of the URL. If the URL does not contain a password or a NULL pointer is supplied, then this field is ignored.
For the example URL provided in the function description, "passwd" would be returned for this field.
On call: Optional pointer to a WORD specifying the maximum length of the vPassword buffer, including the null terminator character.
Upon return: If wPasswordLen and vPassword are non-NULL, the
*wPasswordLen WORD is updated with the actual number of characters written to the vPassword buffer, including the null terminator character. If vPassword is
NULL but wPasswordLen is non-NULL, then no characters are copied, but
*wPasswordLen will return the number of characters required to fit the full password string. If wPasswordLen is NULL, then the password field in the URL, if present, is ignored and the vPassword pointer is not used.
If zero characters were written, this indicates that the URL did not contain a password field. If one character was written, this indicates that a password field was present, but was a zero character string (ex: "").
For the example URL provided in the function description, 7 (0x0007) would be returned for this field.
Optional pointer to a buffer to write the decoded hostname portion of the URL.
All Internet URLs must contain a hostname or IP address, however, if a NULL pointer is supplied, then this field is ignored.
For the example URL provided in the function description,
"www.microchip.com" would be returned for this field. If the URL was
"http://192.168.0.1", then this field would be returned as "192.168.0.1". The IP
223
10.7 Helpers wHostnameLen wPort vFilePath wFilePathLen
Microchip TCP/IP Stack Help Helpers Public Members
On call: Optional pointer to a WORD specifying the maximum length of the vHostname buffer, including the null terminator character.
Upon return: If wHostnameLen and vHostname are non-NULL, the
*wHostnameLen WORD is updated with the actual number of characters written to the vHostname buffer, including the null terminator character. If vHostname is NULL but wHostnameLen is non-NULL, then no characters are copied, but
*wHostnameLen will return the number of characters required to fit the full hostname string. If wHostnameLen is NULL, then the hostname field in the
URL, is ignored and the vHostname pointer is not used.
For the example URL provided in the function description, 18 (0x0012) would be returned for this field. If the URL was "http://192.168.0.1", then this field would be returned as 12 (0x000C).
Optional pointer to a WORD specifying the TCP or UDP port that the server is listening on. If the port field is absent from the URL, then this parameter will specify the default port for the protocol. For example,
"http://www.microchip.com" would result in 80 being return as the specified port.
If the wPort pointer is NULL, then the port field in the URL is ignored, if present.
Optional pointer to a buffer to write the decoded file path portion of the URL. If a
NULL pointer is supplied, then this field is ignored. If a file path is not present in the URL, then "/" will be returned in this field.
For the example URL provided in the function description, "/myfile.gif" would be returned for this field.
On call: Optional pointer to a WORD specifying the maximum length of the vFilePath buffer, including the null terminator character.
Upon return: If wFilePathLen and vFilePath are non-NULL, the *wFilePathLen
WORD is updated with the actual number of characters written to the vFilePath buffer, including the null terminator character. If vFilePath is NULL but wFilePathLen is non-NULL, then no characters are copied, but *wFilePathLen will return the number of characters required to fit the full file path string. If wFilePathLen is NULL, then the file path field in the URL, if present, is ignored and the vFilePath pointer is not used.
This function always returns "/" if no file path is present, so *wFilePathLen will also be at least 2 characters ('/' and null terminator) if the pointer is non-NULL.
For the example URL provided in the function description, 12 (0x000C) would be returned for this field.
10.7.1.7
FormatNetBIOSName Function
File
Helpers.h
C void
FormatNetBIOSName(
BYTE Name[16]
);
Returns
None
Description
This function formats a string to a valid NetBIOS name. Names will be exactly 16 characters, as defined by the NetBIOS spec. The 16th character will be a 0x00 byte, while the other 15 will be the provided string, padded with spaces as necessary.
224
10.7 Helpers
Preconditions
None
Parameters
Parameters
Name
Microchip TCP/IP Stack Help Helpers Public Members
Description
the string to format as a NetBIOS name. This parameter must have at least 16 bytes allocated.
10.7.1.8
GenerateRandomDWORD Function
File
Helpers.h
C
DWORD GenerateRandomDWORD();
Side Effects
This function uses the A/D converter (and so you must disable interrupts if you use the A/D converted in your ISR). The
used. TMR#H:TMR#L will have a new value. Note that this is the same timer used by the Tick module.
Returns
Random 32-bit number.
Description
This function generates a random 32-bit integer. It collects randomness by comparing the A/D converter's internal R/C
randomness tests.
Remarks
This function times out after 1 second of attempting to generate the random DWORD. In such a case, the output may not be truly random. Typically, this function executes in around 500,000 instruction cycles.
The intent of this function is to produce statistically random and cryptographically secure random number. Whether or not this is true on all (or any) devices/voltages/temperatures is not tested.
Preconditions
None
10.7.1.9
hexatob Function
File
Helpers.h
C
BYTE hexatob(
WORD_VAL AsciiChars
);
Returns
Resulting packed byte 0x00 - 0xFF.
Description
Converts a two-character ASCII hex string to a single packed byte.
225
10.7 Helpers
Preconditions
None
Parameters
Parameters
AsciiChars
Microchip TCP/IP Stack Help Helpers Public Members
Description
WORD_VAL where .v[0] is the ASCII value for the lower nibble and .v[1] is the
ASCII value for the upper nibble. Each must range from '0'-'9', 'A'-'F', or 'a'-'f'.
10.7.1.10
leftRotateDWORD Function
File
Helpers.h
C
DWORD leftRotateDWORD(
DWORD val,
BYTE bits
);
Returns
Rotated DWORD value.
Description
This function rotates the bits in a 32-bit DWORD left by a specific number of bits.
Remarks
This function is only implemented on 8-bit platforms for now. The 8-bit compilers generate excessive code for this function, while C30 and C32 already generate compact code. Those compilers are served by a macro defined in Helpers.h.
Preconditions
None
Parameters
Parameters
val bits
Description
the DWORD to be rotated the number of bits by which to shift
10.7.1.11
leftRotateDWORD Macro
File
Helpers.h
C
#define
leftRotateDWORD(x, n) (((x) << (n)) | ((x) >> (32-(n))))
Description
Rotations are more efficient in C30 and C32
10.7.1.12
Replace Function
File
Helpers.h
226
10.7 Helpers Microchip TCP/IP Stack Help Helpers Public Members
C
SHORT Replace(
BYTE * vExpression,
ROM BYTE * vFind,
ROM BYTE * vReplacement,
WORD wMaxLen,
BOOL bSearchCaseInsensitive
);
Returns
If zero or greater, indicates the count of how many replacements were made. If less than zero (negative result), indicates that wMaxLen was too small to make the necessary replacements. In this case, no replacements were made.
Description
Searches a string (vExpression) and replaces all instances of a particular substring (vFind) with a new string
(vReplacement). The start offset to being searching and a maximum number of replacements can be specified. The search can be performed in a case sensitive or case insensitive manner.
Remarks
If the replacement string length is shorter than or equal to the search string length and the search string occurs in multiple overlapping locations (ex: expression is "aaa", find is "aa", and replacement is "bb") then the first find match occuring when searching from left to right will be replaced. (ex: output expression will be "bba").
However, if the replacement string length is longer than the search string length, the search will occur starting from the end of the string and proceed to the beginning (right to left searching). In this case if the expression was "aaa", find was "aa", and replacement was "bbb", then the final output expression will be "abbb".
Preconditions
This function is commented out by default to save code space because it is not used by any current stack features.
However, if you want to use it, go ahead and uncomment it. It has been tested, so it (should) work correctly.
Parameters
Parameters
vExpression vFind vReplacement wMaxLen bSearchCaseInsensitive
Description
Null terminated string to search and make replacements within.
Null terminated string to search for.
Null terminated string to replace all instances of vFind with.
Maximum length of the output vExpression string if string expansion is going to occur (replacement length is longer than find length). If the replacements will cause this maximum string length to be exceeded, then no replacements will be made and a negative result will be returned, indicating failure. If the replacement length is shorter or equal to the search length, then this parameter is ignored.
Boolean indicating if the search should be performed in a case insensitive manner. Specify TRUE for case insensitive searches (slower) or FALSE for case sensitive searching (faster).
10.7.1.13
ROMStringToIPAddress Function
File
Helpers.h
C
BOOL ROMStringToIPAddress(
ROM BYTE* str,
IP_ADDR* IPAddress
);
227
10.7 Helpers Microchip TCP/IP Stack Help Helpers Public Members
Description
This function parses a dotted-quad decimal IP address string into an IP_ADDR struct. The output result is big-endian.
Remarks
This function is aliased to StringToIPAddress ( see page 229) on non-PIC18 platforms.
Preconditions
None
Parameters
Parameters
str
IPAddress
Return Values
Return Values
TRUE
FALSE
Description
Pointer to a dotted-quad IP address string
Pointer to IP_ADDR in which to store the result
Description
an IP address was successfully decoded no IP address could be found, or the format was incorrect
10.7.1.14
ROMStringToIPAddress Macro
File
Helpers.h
C
#define
ROMStringToIPAddress(a,b) StringToIPAddress((BYTE*)a,b)
Description
Non-ROM variant for C30 and C32
10.7.1.15
stricmppgm2ram Function
File
Helpers.h
C signed char
stricmppgm2ram(
BYTE* a,
ROM BYTE* b
);
Description
Performs a case-insensitive comparison of a string in RAM to a string in ROM. This function performs identically to strcmppgm2ram, except that the comparison is not case-sensitive.
Preconditions
None
Parameters
Parameters
a b
Description
Pinter to tring in RAM
Pointer to string in ROM
228
10.7 Helpers
Return Values
Return Values
-1
0
1
Microchip TCP/IP Stack Help
Description
a < b a = b a > b
Helpers Public Members
10.7.1.16
StringToIPAddress Function
File
Helpers.h
C
BOOL StringToIPAddress(
BYTE* str,
IP_ADDR* IPAddress
);
Description
This function parses a dotted-quad decimal IP address string into an IP_ADDR struct. The output result is big-endian.
Preconditions
None
Parameters
Parameters
str
IPAddress
Return Values
Return Values
TRUE
FALSE
Description
Pointer to a dotted-quad IP address string
Pointer to IP_ADDR in which to store the result
Description
an IP address was successfully decoded no IP address could be found, or the format was incorrect
10.7.1.17
strupr Function
File
Helpers.h
C char
* strupr(
char
* s
);
Returns
Pointer to the initial string.
Description
This function converts strings to uppercase on platforms that do not already have this function defined. All lower-case characters are converted, an characters not included in 'a'-'z' are left as-is.
Preconditions
None
229
10.7 Helpers
Parameters
Parameters
s
Microchip TCP/IP Stack Help
Description
the null-terminated string to be converted.
Helpers Public Members
10.7.1.18
strnchr Function
File
Helpers.h
C char
* strnchr(
const char
* searchString,
size_t count,
char
c
);
Returns
Pointer to the first occurance of the character c in the string searchString. If the character is not found or the maximum count is reached, a NULL pointer is returned.
Description
Searches a string up to a specified number of characters for a specific character. The string is searched forward and the first occurance location is returned. If the search character is not present in the string, or if the maximum character count is reached first, then a NULL pointer is returned.
Preconditions
None
Parameters
Parameters
searchString count c
Description
Pointer to a null terminated string to search. If count is less than the string size, then the string need not be null terminated.
Maximum number of characters to search before aborting.
Character to search for
10.7.1.19
swapl Function
File
Helpers.h
C
DWORD swapl(
DWORD v
);
Returns
The swapped version of v.
Description
Swaps the endian-ness of a DWORD.
Preconditions
None
230
10.7 Helpers
Parameters
Parameters
v
Microchip TCP/IP Stack Help
Description
the DWORD to swap
10.7.1.20
swaps Function
File
Helpers.h
C
WORD swaps(
WORD v
);
Returns
The swapped version of v.
Description
Swaps the endian-ness of a WORD.
Preconditions
None
Parameters
Parameters
v
Description
the WORD to swap
10.7.1.21
uitoa Function
File
Helpers.h
C void
uitoa(
WORD Value,
BYTE* Buffer
);
Returns
None
Description
Converts a 16-bit unsigned integer to a null-terminated decimal string.
Preconditions
None
Parameters
Parameters
Value
Buffer
Description
The number to be converted
Pointer in which to store the converted string
Helpers Public Members
231
10.7 Helpers Microchip TCP/IP Stack Help Functions
10.7.1.22
ultoa Function
File
Helpers.h
C void
ultoa(
DWORD Value,
BYTE* Buffer
);
Returns
None
************************************************************************
HI-TECH PICC-18 PRO 9.63, C30 v3.25, and C32 v1.12 already have a ultoa() library function C18 already has a ultoa() function that more-or-less matches this one C32 < 1.12 and C30 < v3.25 need this function
Description
C32 < 1.12 and C30 < v3.25 need this 2 parameter stack implemented function
Converts a 32-bit unsigned integer to a null-terminated decimal string.
Preconditions
None
Parameters
Parameters
Value
Buffer
Description
The number to be converted
Pointer in which to store the converted string
10.7.1.23
UnencodeURL Function
File
Helpers.h
C void
UnencodeURL(
BYTE* URL
);
Returns
None
Description
This function is deprecated except for use with HTTP Classic. It attempts to decode a URL encoded string, converting all hex escape sequences into a literal byte. However, it is inefficient over long strings and does not handle URL-encoded data strings ('&' and '=').
Preconditions
None
Parameters
Parameters
URL
Description
the null-terminated string to decode
232
10.7 Helpers Microchip TCP/IP Stack Help Functions
10.7.2
Functions
Functions
Name Description
(0x0000 to 0xFFFF).
Copies multiple strings to a destination
Module
10.7.2.1
LFSRRand Function
File
Helpers.h
C
WORD LFSRRand();
Side Effects
The internal LFSR seed is updated so that the next call to LFSRRand() will return a different random number.
Returns
Random 16-bit unsigned integer.
Description
Returns a pseudo-random 16-bit unsigned integer in the range from 0 to 65535 (0x0000 to 0xFFFF). The random number is generated using a Linear Feedback Shift Register (LFSR) type pseudo-random number generator algorithm. The LFSR can
as a prior string of calls.
The internal LFSR will repeat after 2^32-1 iterations.
Remarks
None
Preconditions
None
10.7.2.2
LFSRSeedRand Function
File
Helpers.h
C
DWORD LFSRSeedRand(
DWORD dwSeed
);
233
10.7 Helpers Microchip TCP/IP Stack Help Functions
Side Effects
None
Returns
The last seed in use. This can be saved and restored by a subsequent call to LFSRSeedRand() if you wish to use
context. For example, if App 1 needs a given sequence of random numbers to perform a test, if you save and restore the seed in App 2, it is possible for App 2 to not disrupt the random number sequence provided to App 1, even if the number of
times App 2 calls LFSRRand ( see page 233)() varies.
Description
returned.
Remarks
Upon initial power up, the internal seed is initialized to 0x1. Using a dwSeed value of 0x0 will return the same sequence of random numbers as using the seed of 0x1.
Preconditions
None
Parameters
Parameters
wSeed
Description
The new 32-bit seed value to assign to the LFSR.
10.7.2.3
strncpy_m Function
File
Helpers.h
C
size_t strncpy_m(
char
* destStr,
size_t destSize,
int
nStrings,
...
);
Returns
Length of the destination string, terminating 0 (if exists) not included
Description
Copies multiple strings to a destination but doesn't copy more than destSize characters. Useful where the destination is actually an array and an extra 0 won't be appended to overflow the buffer
Preconditions
• valid string pointers
• destSize should be > 0
Parameters
Parameters
destStr destSize nStrings
Description
Pointer to a string to be initialized with the multiple strings provided as arguments.
the maximum size of the destStr field, that cannot be exceeded. An 0 won't be appended if the resulting size is > destSize number of string parameters to be copied into destStr
234
10.8 HTTP2 Server
...
Microchip TCP/IP Stack Help variable number of arguments
10.7.3
Variables
Module
Variables
Name
dwLFSRRandSeed ( see page 235)
Description
Default Random Number Generator seed. 0x41FE9F9E corresponds to calling
LFSRSeedRand ( see page 233)(1)
10.7.3.1
dwLFSRRandSeed Variable
File
Helpers.c
C
DWORD dwLFSRRandSeed = 0x41FE9F9E;
Description
10.8
HTTP2 Server
The HTTP2 web server module and its associated MPFS2 file system module allow the board to act as a web server. This facilitates an easy method to view status information and control applications using any standard web browser.
Three main components are necessary to understand how the HTTP2 web server works: the web pages, the MPFS2 Utility, and the source files
CustomHTTPApp.c
and
HTTPPrint.h
. An overview of the entire process is shown below.
Web Pages
This includes all the HTML and associated images, CSS stylesheets, and JavaScript files necessary to display the website.
A sample application including all these components is located in the WebPages2 folder.
MPFS2 Utility
This program, supplied by Microchip, packages the web pages into a format that can be efficiently stored in either external non-volatile storage, or internal flash program memory. This program also indexes dynamic variables found in the web pages and updates
HTTPPrint.h
with these indices.
If external storage is being used, the MPFS2 Utility outputs a BIN file and can upload that file directly to the board. If the data
235
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features is being stored in Flash program memory, the MPFS2 Utility will generate a C source file image to be included in the project.
When dynamic variables are added or removed from your application, the MPFS2 Utility will update
HTTPPrint.h
. When this happens, the project must be recompiled in the MPLAB IDE to ensure that all the new variable indices get added into the application.
CustomHTTPApp.c
described within the demo application's web pages, and is also documented within the
CustomHTTPApp.c
example that is distributed with the stack.
HTTPPrint.h
This file is generated automatically by the MPFS2 Utility. It indexes all the dynamic variables and provides the "glue"
functions defined in
CustomHTTPApp.c
. This file does not require modification by the programmer.
10.8.1
HTTP2 Features
Module
Description
The HTTP2 web server module has many capabilities. The following topics will introduce these features and provide examples.
10.8.1.1
HTTP2 Dynamic Variables
One of the most basic needs is to provide status information back to the user of your web application. The HTTP server provides for this using dynamic variable substitution callbacks. These commands in your HTML code will alert the server to execute a callback function at that point, which the developer creates to write data into the web page. Dynamic Variables should be considered the output of your application.
Basic Use
To create a dynamic variable, simply enclose the name of the variable inside a pair of tilde (~) characters within the web pages' HTML source code. (ex:
~myVariable~
) When you run the MPFS2 Utility to generate the web pages, it will automatically index these variables in
HTTPPrint.h
. This index will instruct your application to invoke the function
HTTPPrint_myVariable
when this string is encountered.
Here is an example of using a dynamic variable to insert the build date of your application into the web pages:
<div
class
="examplebox code">~builddate~</div>
The associated callback will print the value into the web page:
void
HTTPPrint_builddate(
void
)
{
TCPPutROMString(sktHTTP,(ROM
void
*)__DATE__);
}
Passing Parameters
You can also pass parameters to dynamic variables by placing numeric values inside of parenthesis after the variable name.
For example, ~led(2)~ will print the value of the second LED. The numeric values are passed as WORD values to your callback function. You can pass as many parameters as you wish to these functions, and if your C code has constants
236
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features defined, those will be parsed as well. (ex:
~pair(3,TRUE)~
)
The following code inserts the value of the push buttons into the web page, all using the same callback function:
<div
class
="examplebox code">btn(3)~ btn(2)~ btn(1)~ btn(0)~</div>
This associated callback will print the value of the requested button to the web page:
void
HTTPPrint_btn(WORD num)
{
// Determine which button
switch
(num)
{
case
0:
num = BUTTON0_IO;
break
;
case
1:
num = BUTTON1_IO;
break
;
case
2:
num = BUTTON2_IO;
break
;
case
3:
num = BUTTON3_IO;
break
;
default
:
num = 0;
}
// Print the output
if
(num == 1)
TCPPutROMString(sktHTTP, "up");
else
TCPPutROMString(sktHTTP, "down");
}
Longer Outputs
The HTTP protocol operates in a fixed memory buffer for transmission, so not all data can be sent at once. Care must be taken inside of your callback function to avoid overrunning this buffer.
The HTTP2 web server verifies that at least 16 bytes are free in this buffer before invoking a callback. For short outputs (less
callback functions must check how much space is available, write up to that many bytes, then return. The callback will be invoked again when more space is free.
To manage the output state, callbacks should make use of curHTTP.callbackPos
. This DWORD value is set to zero when a callback is first invoked. If a callback is only writing part of its output, it should set this field to a non-zero value to indicate that it should be called again when more space is available. This value will be available to the callback during the next call, which allows the function to resume output where it left off. A common use is to store the number of bytes written, or remaining to be written, in this field. Once the callback is finished writing its output, it must set curHTTP.callbackPos
back to zero in order to indicate completion.
As an example, this code outputs the current value of the LCD display, which is 32 bytes on many Microchip development boards:
<div
class
="examplebox code">~lcdtext~</div>
The following callback function handles the output, and manages its state for multiple calls:
void
HTTPPrint_lcdtext(
void
)
{
WORD len;
// Determine how many bytes we can write
len = TCPIsPutReady(sktHTTP);
// If just starting, set callbackPos
if
(curHTTP.callbackPos == 0)
curHTTP.callbackPos = 32;
237
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features
// Write a byte at a time while we still can
// It may take up to 12 bytes to write a character
// (spaces and newlines are longer)
while
(len > 12 && curHTTP.callbackPos)
{
// After 16 bytes write a newline
if
(curHTTP.callbackPos == 16)
len -= TCPPutROMString(sktHTTP, (ROM BYTE*)"<br />");
if
(LCDText[32-curHTTP.callbackPos] == ' ' || LCDText[32-curHTTP.callbackPos] ==
'\0')
len -= TCPPutROMString(sktHTTP, (ROM BYTE*)" ");
else
len -= TCPPut(sktHTTP, LCDText[32-curHTTP.callbackPos]);
curHTTP.callbackPos--;
}
}
len
to track how much buffer space is left. When buffer space is exhausted, the function exits and waits to be called again. For subsequent calls, the value of curHTTP.callbackPos
is exactly as we left it. The function resumes its output at that point.
Including Files
Often it is useful to include the entire contents of another file in your output. Most web pages have at least some portion that does not change, such as the header, menu of links, and footer. These sections can be abstracted out into separate files which makes them easier to manage and conserves storage space.
To include the entire contents of another file, use a dynamic variable that starts with " inc:
", such as
~inc:header.inc~
.
This sequence will cause the file header.inc
to be read from the file system and inserted at this location.
The following example indicates how to include a standard menu bar section into every page:
<div id="menu">~inc:menu.inc~</div>
At this time, dynamic variables are not recursive, so any variables located inside files included in this manner are not parsed.
10.8.1.2
HTTP2 Form Processing
a web page, then have the device process the values submitted via this form. Web forms are usually submitted using one of two methods (GET and POST), and the HTTP2 web server supports both.
The GET Method
The GET method appends the data to the end of the URI. This data follows the question mark (?) in the browser's address bar. (ex: http://mchpboard/form.htm?led1=0&led2=1&led3=0) Data sent via GET is automatically decoded and stored in the curHTTP.data
array. Since it is to be stored in memory, this data is limited to the size of curHTTP.data
, which by default is 100 bytes. However, it is generally easier to process data received in this manner.
provide an easy method to retrieve submitted values for processing.
The following example demonstrates a form to control several LEDs.
<form method="get" action="leds.htm">
LED 1: <input type="checkbox" name="led1" value="1" /><br />
LED 2: <input type="checkbox" name="led2" value="1" /><br />
LED 3: <input type="checkbox" name="led3" value="1" /><br />
<input type="submit" value="Set LEDs" />
</form>
238
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features
Suppose a user selects the checkboxes for LED 1 and LED3. The following string will be submitted to the server:
GET /leds.htm?led1=1&led3=1 HTTP/1.1
The HTTP2 web server will parse this request and store the following string in curHTTP.data
:
"led1\01\0led3\01\0\0"
be omitted if only one form is provided by the application.) Next, since a checkbox control was used a default state of unchecked must be assumed. Finally, the callback should search for each argument it expects, compare the value, and set the LED pins accordingly. The following example satisfies all these requirements:
HTTP_IO_RESULT HTTPExecuteGet(
void
)
{
BYTE *ptr, filename[20];
// Load the file name (filename[] must be large enough to hold
// the longest file name expected)
MPFSGetFilename(curHTTP.file, filename, 20);
// Verify the file name
if
(!strcmppgm2ram(filename, (ROM
char
*)"leds.htm"))
{
// Assume a default state of off
LED1_IO = 0;
LED2_IO = 0;
LED3_IO = 0;
// Search for each LED parameter and process
ptr = HTTPGetROMArg(curHTTP.data, (ROM BYTE*)"led1");
if
(ptr)
LED1_IO = (*ptr == '1');
ptr = HTTPGetROMArg(curHTTP.data, (ROM BYTE*)"led2");
if
(ptr)
LED2_IO = (*ptr == '1');
ptr = HTTPGetROMArg(curHTTP.data, (ROM BYTE*)"led3");
if
(ptr)
LED3_IO = (*ptr == '1');
}
// Indicate completion
return
HTTP_IO_DONE;
}
The POST Method
The POST method transmits data after all the request headers have been sent. This data is not visible in the browser's address bar, and can only be seen with a packet capture tool. It does however use the same URL encoding method.
The HTTP2 server does not perform any pre-parsing of this data. All POST data is left in the TCP buffer, so the custom
these functions can only be used when at least entire variables are expected to fit in the TCP buffer at once.
Most POST processing functions will be implemented as state machines in order to use these functions. The variable curHTTP.smPost is available to store the current state. This state machine variable is reset to zero with each new request.
Functions should generally implement a state to read a variable name, and another to read an expected value. Additional states may be helpful depending on the application.
The following example form accepts an e-mail address, a subject, and a message body. Since this data will likely total over
100 bytes, it should be submitted via POST.
<form method="post" action="/email.htm">
To: <input type="text" name="to" maxlength="50" /><br />
Subject: <input type="text" name="subject" maxlength="50" /><br />
239
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features
Message:<br />
<textarea name="msg" rows="6"></textarea><br />
<input type="submit" value="Send Message" /></div>
</form>
Suppose a user enters the following data into this form:
Subject: Sent by a PIC
Message: I sent this message using my development board!
to=joe%40picsaregood.com&subject=Sent+by+a+PIC
&msg=I+sent+
this
+message+
using
+my+development+board%21
To use the e-mail module, the application needs to read in the address and the subject, store those in RAM, then send the message. However, since the message is not guaranteed to fit in RAM all at once, it must be read as space is available and
passed to the e-mail module. A state machine, coupled with the HTTPReadPostName ( see page 252) and
HTTPReadPostValue ( see page 253) functions can simplify this greatly.
The following example callback function will properly parse this input. For this example, it is assumed that this is the only form the board accepts, so file name checking is not performed. The address will be stored at curHTTP.data[0:49], and the subject will be stored at curHTTP.data[50:99]. This is not the most optimal solution, but serves as a simple example.
HTTP_IO_RESULT HTTPExecutePost(
void
)
{
BYTE *dest, temp[16];
// Define state machine values
#define
SM_READ_NAME (0u)
#define
SM_READ_VALUE (1u)
#define
SM_START_MESSAGE (2u)
#define
SM_SEND_MESSAGE (3u)
switch
(curHTTP.smPost)
{
case
SM_READ_NAME:
// Read the next variable name. If a complete name is
// not found, request more data. This function will
// automatically truncate invalid data to prevent
// buffer overflows.
if
(HTTPReadPostName(temp,16) == HTTP_READ_INCOMPLETE)
return
HTTP_IO_NEED_DATA;
// Save "to" values to curHTTP.data[0:49]
if
(!strcmppgm2ram((
char
*)temp, (ROM
char
*)"to"))
dest = curHTTP.data;
// Save "subject" values to curHTTP.data[50:99]
else if
(!strcmppgm2ram((
char
*)temp, (ROM
char
*)"subject"))
dest = curHTTP.data + 50;
// When a "msg" is encountered, start sending
else if
(!strcmppgm2ram((
char
*)temp, (ROM
char
*)"msg"))
{
curHTTP.smPost = SM_START_MESSAGE;
break
;
}
// Ignore unexpected values
else
dest = NULL;
// Move to the next state, but do not break yet
curHTTP.smPost = SM_READ_VALUE;
case
SM_READ_VALUE:
// Read the next value. If a complete value is
// not found, request more data. This function will
// automatically truncate invalid data to prevent
// buffer overflows.
240
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features
if
(HTTPReadPostValue(dest,50) == HTTP_READ_INCOMPLETE)
return
HTTP_IO_NEED_DATA;
// Return to read a new name
curHTTP.smPost = SM_READ_NAME;
break
;
case
SM_START_MESSAGE:
// TODO: Perform necessary tasks to start sending the message.
// Move on to sending the message body
curHTTP.smPost = SM_SEND_MESSAGE;
break
;
case
SM_SEND_MESSAGE:
// The message may be longer than the TCP buffer can hold
// at once. To avoid errors, read the data piece by
// piece and send it to the e-mail module. This requires
// using TCP functions directly.
// Send all remaining data
while
(curHTTP.byteCount > 0)
{
// First check if data is ready
if
(TCPIsGetReady(sktHTTP) == 0)
return
HTTP_IO_NEED_DATA;
// TODO: Read data with TCPGetArray and send
// it to the e-mail module.
}
// Process is complete
return
HTTP_IO_DONE;
}
// Assume return for state machine convenience.
// Do not return HTTP_IO_NEED_DATA here by default, because
// doing so when more data will not arrive is cause for
// the HTTP2 server to return an error to the user.
return
HTTP_IO_WAITING;
}
The previous example uses the HTTPReadPostName (
see page 252) and HTTPReadPostValue ( see page 253)
simple example of this.
For more examples, refer to CustomHTTPApp.c in the TCPIP Demo App project.
10.8.1.3
HTTP2 Authentication
The HTTP protocol provides a method for servers to request a user name and password from a client before granting access to a page. The HTTP2 server supports this authentication mechanism, allowing developers to require valid credentials for access to some or all pages.
access. This split between two callback functions is necessitated by the nature of the HTTP protocol and the low-memory architecture of the HTTP2 server. In cases where different credentials or sets of credentials may be accepted for different pages, the two functions communicate with each other through a single byte stored in curHTTP.isAuthorized
.
241
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features
Requiring Authentication
password protection. This function returns a value to instruct the HTTP2 server how to proceed. The most significant bit indicates whether or not access is granted. That is, values
0x80
and higher allow access unconditionally, while values
0x79 and lower will require a user name and password at a later point. The value returned is stored as curHTTP.isAuthorized
so that it can be accessed by future callback functions.
The following example is the simplest case, in which all files require a password for access:
BYTE HTTPNeedsAuth(BYTE* cFile)
{
return
0x00;
}
In some cases, only certain files will need to be protected. The second example requires a password for any file located in the
/treasure
folder:
BYTE HTTPNeedsAuth(BYTE* cFile)
{
// Compare to "/treasure" folder. Don't use strcmp here, because
// cFile has additional path info such as "/treasure/gold.htm"
if
(!memcmppgm2ram((
void
*)cFile, (ROM
void
*)"treasure", 8))
return
0x00;
return
0x80;
}
More complex uses could require an administrative user to access the
/admin
folder, while any authenticated user can access the rest of the site. The third example requires a different set of user name and password combinations for the
/admin
folder versus the rest of the site:
#define
HTTP_AUTH_ADMIN (0x00)
#define
HTTP_AUTH_OTHER (0x01)
BYTE HTTPNeedsAuth(BYTE* cFile)
{
// Return a specific code for admin users
if
(!memcmppgm2ram((
void
*)cFile, (ROM
void
*)"admin", 5))
return
HTTP_AUTH_ADMIN;
return
HTTP_AUTH_OTHER;
}
Validating Credentials
resource. Again, the most significant bit indicates whether or not access is granted. The value returned is also stored as curHTTP.isAuthorized
so that it can be accessed by future callback functions.
The following example is the simplest case, in which one user/password pair is accepted for all pages:
BYTE HTTPCheckAuth(BYTE* cUser, BYTE* cPass)
{
if
(!strcmppgm2ram((
char
*)cUser, (ROM
char
*)"AliBaba") &&
!strcmppgm2ram((
char
*)cPass, (ROM
char
*)"Open Sesame!") )
return
0x80;
return
0x00;
}
In some cases, you may have multiple users with various levels of access. The following example satisfies the needs used in
the third example of HTTPNeedsAuth ( see page 250) above:
BYTE HTTPCheckAuth(BYTE* cUser, BYTE* cPass)
{
// Check for admin users first
if
(curHTTP.isAuthorized == HTTP_AUTH_ADMIN &&
!strcmppgm2ram((
char
*)cUser, (ROM
char
*)"admin") &&
242
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Features
!strcmppgm2ram((
char
*)cPass, (ROM
char
*)"s3cREt") )
return
0x80;
if
(!strcmppgm2ram((
char
*)cUser, (ROM
char
*)"kate") &&
!strcmppgm2ram((
char
*)cPass, (ROM
char
*)"puppies!") )
return
0x80;
return
0x00;
}
More complex uses are certainly feasible. Many applications may choose to store the user names and passwords in
EEPROM or other non-volatile storage so that they may be updated by the end-user. Some applications may wish to return various values above
0x80
in HTTPCheckAuth ( see page 247) so that later callback functions can determine which user
logged in. The flexibility of these functions provides for many more possibilities that are not documented here but can be developed in just a few hours.
10.8.1.4
HTTP2 Cookies
By design, HTTP is a session-less and state-less protocol; every connection is an independent session with no relation to
server to store small bits of text in a user's browser. These values will be returned to the server with every request, allowing
authentication systems.
Best practice is generally to store the bulk of the data on the server, and store only a unique identifier with the browser. This cuts down on data overhead and ensures that the user cannot modify the values stored with the session. However, logic must be implemented in the server to expire old sessions and allocate memory for new ones. If sensitive data is being stored, it is also important that the identifier be random enough so as to prevent stealing or spoofing another user's cookies.
Retrieving Cookies
In the HTTP2 server, cookies are retrieved automatically. They are stored in curHTTP.data
, just as any other GET form
values.
This model consumes some of the limited space available for URL parameters. Ensure that cookies do not consume more
may be submitted via a GET form. If enough space is not available, the cookies will be truncated.
Setting Cookies
cookie, store the name/value pairs in curHTTP.data
as a series of null-terminated strings. Then set, curHTTP.hasArgs
equal to the number of name/value pairs to be set. For example, the following code sets a cookie indicating a user's preference for a type of cookie:
void
HTTPExecuteGet(
void
)
{
...
// Set a cookie
strcpypgm2ram((
char
*)curHTTP.data, (ROM
char
*)"flavor\0oatmeal raisin");
curHTTP.hasArgs = 1;
...
}
After this, all future requests from this browser will include the parameter "flavor" in curHTTP.data
, along with the associated value of "oatmeal raisin".
243
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Public Members
10.8.1.5
HTTP2 Compression
All modern web browsers can receive files encoded with GZIP compression. For static files (those without dynamic variables), this can decrease the amount of data transmitted by as much as 60%.
The MPFS2 Utility will automatically determine which files can benefit from GZIP compression, and will store the compressed file in the MPFS2 image when possible. This generally includes all JavaScript and CSS files. (Images are typically already compressed, so the MPFS2 Utility will generally decide it is better to store them uncompressed.) This HTTP server will then seamlessly return this compressed file to the browser. Less non-volatile storage space will be required for the MPFS2 image, and faster transfers back to the client will result. No special configuration is required for this feature.
To prevent certain extensions from being compressed, use the Advanced Settings dialog in the MPFS2 Utility.
10.8.2
HTTP2 Public Members
Enumerations
Name
HTTP_IO_RESULT ( see page 246)
HTTP_READ_STATUS ( see page 246)
Functions
Description
Result states for execution callbacks
Result states for HTTPPostReadName and HTTPPostReadValue
Name
HTTPExecuteGet ( see page 247)
HTTPExecutePost ( see page 248)
HTTPPrint_varname ( see page 251)
HTTPReadPostName ( see page 252)
HTTPReadPostValue ( see page 253)
Description
Performs validation on a specific user name and password.
Processes GET form field variables and cookies.
Processes POST form variables and data.
Locates a form field value in a given data array.
Locates a form field value in a given data array.
Determines if a given file name requires authentication
Inserts dynamic content into a web page
Reads a name from a URL encoded string in the TCP buffer.
Reads a value from a URL encoded string in the TCP buffer.
Parses a string from URL encoding to plain-text.
Macros
Name
HTTPReadPostPair ( see page 253)
Description
Reads a name and value pair from a URL encoded string in the TCP buffer.
Access the current socket
244
10.8 HTTP2 Server Microchip TCP/IP Stack Help
Module
Structures
Name
Description
Stores extended state data for each connection
Variables
Name
Description
Current HTTP connection state
Description
The following functions and variables are accessible or implemented by the stack application.
10.8.2.1
curHTTP Variable
File
HTTP2.c
C
Description
Current HTTP connection state
10.8.2.2
HTTP_CONN Structure
File
HTTP2.h
C typedef struct
{
DWORD byteCount;
DWORD nextCallback;
DWORD callbackID;
DWORD callbackPos;
BYTE * ptrData;
BYTE * ptrRead;
BYTE hasArgs;
BYTE isAuthorized;
BYTE smPost;
} HTTP_CONN;
Members
Members
DWORD byteCount;
DWORD nextCallback;
DWORD callbackID;
DWORD callbackPos;
BYTE * ptrData;
Description
How many bytes have been read so far
Byte index of the next callback
Callback ID to execute, also used as watchdog timer
Callback position indicator
Points to first free byte in data
HTTP2 Public Members
245
10.8 HTTP2 Server Microchip TCP/IP Stack Help
BYTE * ptrRead;
MPFS_HANDLE file;
MPFS_HANDLE offsets;
BYTE hasArgs;
BYTE isAuthorized;
HTTP_STATUS httpStatus;
HTTP_FILE_TYPE fileType;
BYTE data[HTTP_MAX_DATA_LEN];
BYTE smPost;
Points to current read location
File pointer for the file being served
File pointer for any offset info being used
True if there were get or cookie arguments
0x00-0x79 on fail, 0x80-0xff on pass
Request method/status
File type to return with Content-Type
General purpose data buffer
POST state machine variable
Description
Stores extended state data for each connection
HTTP2 Public Members
10.8.2.3
HTTP_IO_RESULT Enumeration
File
HTTP2.h
C typedef enum
{
HTTP_IO_DONE = 0u,
HTTP_IO_NEED_DATA,
HTTP_IO_WAITING
} HTTP_IO_RESULT;
Members
Members
HTTP_IO_DONE = 0u
HTTP_IO_NEED_DATA
HTTP_IO_WAITING
Description
Result states for execution callbacks
Description
Finished with procedure
More data needed to continue, call again later
Waiting for asynchronous process to complete, call again later
10.8.2.4
HTTP_READ_STATUS Enumeration
File
HTTP2.h
C typedef enum
{
HTTP_READ_OK = 0u,
HTTP_READ_TRUNCATED,
HTTP_READ_INCOMPLETE
} HTTP_READ_STATUS;
Members
Members
HTTP_READ_OK = 0u
HTTP_READ_TRUNCATED
HTTP_READ_INCOMPLETE
Description
Read was successful
Buffer overflow prevented by truncating value
Entire object is not yet in the buffer. Try again later.
Description
Result states for HTTPPostReadName and HTTPPostReadValue
246
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Public Members
10.8.2.5
HTTPCheckAuth Function
File
HTTP2.h
C
BYTE HTTPCheckAuth(
BYTE* cUser,
BYTE* cPass
);
Description
This function is implemented by the application developer in CustomHTTPApp.c. Its function is to determine if the user name and password supplied by the client are acceptable for this resource.
The value of curHTTP.isAuthorized will be set to the previous return value of HTTPRequiresAuthorization. This callback function can check this value to determine if only specific user names or passwords will be accepted for this resource.
Return values 0x80 - 0xff indicate that the credentials were accepted, while values from 0x00 to 0x79 indicate that authorization failed. While most applications will only use a single value to grant access, flexibility is provided to store multiple values in order to indicate which user (or user's group) logged in.
The return value of this function is saved as curHTTP.isAuthorized, and will be available to future callbacks, including any of
callbacks.
Remarks
This function is only called when an Authorization header is encountered.
This function may NOT write to the TCP buffer.
Internal
See documentation in the TCP/IP Stack API or HTTP2.h for details.
Preconditions
None
Parameters
Parameters
cUser cPass
Return Values
Return Values
<= 0x79
>= 0x80
Description
the user name supplied by the client the password supplied by the client
Description
the credentials were rejected access is granted for this connection
10.8.2.6
HTTPExecuteGet Function
File
HTTP2.h
C
HTTP_IO_RESULT HTTPExecuteGet();
247
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Public Members
Description
This function is implemented by the application developer in CustomHTTPApp.c. Its purpose is to parse the data received from URL parameters (GET method forms) and cookies and perform any application-specific tasks in response to these inputs. Any required authentication has already been validated.
When this function is called, curHTTP.data contains sequential name/value pairs of strings representing the data received. In
variables in the input. If data buffer space associated with this connection is required, curHTTP.data may be overwritten here once the application is done with the values. Any data placed there will be available to future callbacks for this connection,
This function may also issue redirections by setting curHTTP.data to the destination file name or URL, and curHTTP.httpStatus to HTTP_REDIRECT.
Finally, this function may set cookies. Set curHTTP.data to a series of name/value string pairs (in the same format in which parameters arrive) and then set curHTTP.hasArgs equal to the number of cookie name/value pairs. The cookies will be transmitted to the browser, and any future requests will have those values available in curHTTP.data.
Remarks
This function is only called if variables are received via URL parameters or Cookie arguments. This function may NOT write to the TCP buffer.
This function may service multiple HTTP requests simultaneously. Exercise caution when using global or static variables inside this routine. Use curHTTP.callbackPos or curHTTP.data for storage associated with individual requests.
Internal
See documentation in the TCP/IP Stack API or HTTP2.h for details.
Preconditions
None
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_NEED_DATA
HTTP_IO_WAITING
Description
application is done processing this value may not be returned because more data will not become available the application is waiting for an asynchronous process to complete, and this function should be called again later
10.8.2.7
HTTPExecutePost Function
File
HTTP2.h
C
HTTP_IO_RESULT HTTPExecutePost();
Description
This function is implemented by the application developer in CustomHTTPApp.c. Its purpose is to parse the data received from POST forms and perform any application-specific tasks in response to these inputs. Any required authentication has already been validated before this function is called.
When this function is called, POST data will be waiting in the TCP buffer. curHTTP.byteCount will indicate the number of bytes remaining to be received before the browser request is complete.
order to retrieve bytes. When this is done, curHTTP.byteCount MUST be updated to reflect how many bytes now remain.
see page 538), TCPFindString, TCPFindROMString, TCPFindArray ( see page 539), and
248
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Public Members
TCPFindROMArray ( see page 541) may be helpful to locate data in the TCP buffer.
be used to decode this information back to a standard string if required. If data buffer space associated with this connection is required, curHTTP.data may be overwritten here once the application is done with the values. Any data placed there will
Whenever a POST form is processed it is recommended to issue a redirect back to the browser, either to a status page or to the same form page that was posted. This prevents accidental duplicate submissions (by clicking refresh or back/forward) and avoids browser warnings about "resubmitting form data". Redirects may be issued to the browser by setting curHTTP.data to the destination file or URL, and curHTTP.httpStatus to HTTP_REDIRECT.
Finally, this function may set cookies. Set curHTTP.data to a series of name/value string pairs (in the same format in which parameters arrive) and then set curHTTP.hasArgs equal to the number of cookie name/value pairs. The cookies will be transmitted to the browser, and any future requests will have those values available in curHTTP.data.
Remarks
This function is only called when the request method is POST, and is only used when HTTP_USE_POST is defined. This method may NOT write to the TCP buffer.
This function may service multiple HTTP requests simultaneously. Exercise caution when using global or static variables inside this routine. Use curHTTP.callbackPos or curHTTP.data for storage associated with individual requests.
Internal
See documentation in the TCP/IP Stack API or HTTP2.h for details.
Preconditions
None
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_NEED_DATA
HTTP_IO_WAITING
Description
application is done processing more data is needed to continue, and this function should be called again later the application is waiting for an asynchronous process to complete, and this function should be called again later
10.8.2.8
HTTPGetArg Function
File
HTTP2.h
C
BYTE* HTTPGetArg(
BYTE* cData,
BYTE* cArg
);
Returns
A pointer to the argument value, or NULL if not found.
Description
Searches through a data array to find the value associated with a given argument. It can be used to find form field values in data received over GET or POST.
The end of data is assumed to be reached when a null name parameter is encountered. This requires the string to have an even number of null-terminated strings, followed by an additional null terminator.
249
10.8 HTTP2 Server Microchip TCP/IP Stack Help
Preconditions
The data array has a valid series of null terminated name/value pairs.
Parameters
Parameters
data arg
Description
the buffer to search the name of the argument to find
HTTP2 Public Members
10.8.2.9
HTTPGetROMArg Function
File
HTTP2.h
C
BYTE* HTTPGetROMArg(
BYTE* cData,
ROM BYTE* cArg
);
Returns
A pointer to the argument value, or NULL if not found.
Description
Searches through a data array to find the value associated with a given argument. It can be used to find form field values in data received over GET or POST.
The end of data is assumed to be reached when a null name parameter is encountered. This requires the string to have an even number of null-terminated strings, followed by an additional null terminator.
Remarks
This function is aliased to HTTPGetArg ( see page 249) on non-PIC18 platforms.
Preconditions
The data array has a valid series of null terminated name/value pairs.
Parameters
Parameters
data arg
Description
the buffer to search the name of the argument to find
10.8.2.10
HTTPNeedsAuth Function
File
HTTP2.h
C
BYTE HTTPNeedsAuth(
BYTE* cFile
);
Description
This function is implemented by the application developer in CustomHTTPApp.c. Its function is to determine if a file being requested requires authentication to view. The user name and password, if supplied, will arrive later with the request headers, and will be processed at that time.
Return values 0x80 - 0xff indicate that authentication is not required, while values from 0x00 to 0x79 indicate that a user
250
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Public Members name and password are required before proceeding. While most applications will only use a single value to grant access and another to require authorization, the range allows multiple "realms" or sets of pages to be protected, with different credential requirements for each.
The return value of this function is saved as curHTTP.isAuthorized, and will be available to future callbacks, including
248), or HTTPPrint_varname ( see page 251) callbacks.
Remarks
This function may NOT write to the TCP buffer.
Internal
See documentation in the TCP/IP Stack API or HTTP2.h for details.
Preconditions
None
Parameters
Parameters
cFile
Return Values
Return Values
<= 0x79
>= 0x80
Description
the name of the file being requested
Description
valid authentication is required access is granted for this connection
10.8.2.11
HTTPPrint_varname Function
File
HTTP2.h
C void
HTTPPrint_varname(
WORD wParam1,
WORD wParam2,
...
);
Returns
None
Description
Functions in this style are implemented by the application developer in CustomHTTPApp.c. These functions generate dynamic content to be inserted into web pages and other files returned by the HTTP2 server.
Functions of this type are called when a dynamic variable is located in a web page. (ie, ~varname~ ) The name between the tilde '~' characters is appended to the base function name. In this example, the callback would be named
HTTPPrint_varname.
The function prototype is located in your project's HTTPPrint.h, which is automatically generated by the MPFS2 Utility. The prototype will have WORD parameters included for each parameter passed in the dynamic variable. For example, the variable "~myArray(2,6)~" will generate the prototype "void HTTPPrint_varname(WORD, WORD);".
( see page 550), and TCPPutROMString ( see page 551).
to 16 bytes) are free in the output buffer. If the function is writing less than this amount, it should simply write the data to the
251
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Public Members socket and return.
In situations where a function needs to write more this amount, it must manage its output state using curHTTP.callbackPos.
This value will be set to zero before the function is called. If the function is managing its output state, it must set this to a non-zero value before returning. Typically this is used to track how many bytes have been written, or how many remain to be written. If curHTTP.callbackPos is non-zero, the function will be called again when more buffer space is available. Once the callback completes, set this value back to zero to resume normal servicing of the request.
Remarks
This function may service multiple HTTP requests simultaneously, especially when managing its output state. Exercise caution when using global or static variables inside this routine. Use curHTTP.callbackPos or curHTTP.data for storage associated with individual requests.
Preconditions
None
Parameters
Parameters
wParam1 wParam2
...
Description
first parameter passed in the dynamic variable (if any) second parameter passed in the dynamic variable (if any) additional parameters as necessary
10.8.2.12
HTTPReadPostName Function
File
HTTP2.h
C
HTTP_READ_STATUS HTTPReadPostName(
BYTE* cData,
WORD wLen
);
Description
forcing the programmer to indicate how many bytes are expected. At least 2 extra bytes are needed in cData over the maximum length of data expected to be read.
This function will read until the next '=' character, which indicates the end of a name parameter. It assumes that the front of the buffer is the beginning of the name paramter to be read.
This function properly updates curHTTP.byteCount by decrementing it by the number of bytes read. It also removes the delimiting '=' from the buffer.
Preconditions
Front of TCP buffer is the beginning of a name parameter, and the rest of the TCP buffer contains a URL-encoded string with a name parameter terminated by a '=' character.
Parameters
Parameters
cData wLen
Return Values
Return Values
HTTP_READ_OK
Description
where to store the name once it is read how many bytes can be written to cData
Description
name was successfully read
252
10.8 HTTP2 Server
HTTP_READ_TRUNCTATED
HTTP_READ_INCOMPLETE
Microchip TCP/IP Stack Help HTTP2 Public Members entire name could not fit in the buffer, so the value was truncated and data has been lost entire name was not yet in the buffer, so call this function again later to retrieve
10.8.2.13
HTTPReadPostPair Macro
File
HTTP2.h
C
#define
HTTPReadPostPair(cData, wLen) HTTPReadPostValue(cData, wLen)
Description
Reads a name and value pair from a URL encoded string in the TCP buffer. This function is meant to be called from an
overflows by forcing the programmer to indicate how many bytes are expected. At least 2 extra bytes are needed in cData over the maximum length of data expected to be read.
This function will read until the next '&' character, which indicates the end of a value parameter. It assumes that the front of the buffer is the beginning of the name paramter to be read.
This function properly updates curHTTP.byteCount by decrementing it by the number of bytes read. It also removes the delimiting '&' from the buffer.
Once complete, two strings will exist in the cData buffer. The first is the parameter name that was read, while the second is the associated value.
Remarks
provided only for completeness.
Preconditions
Front of TCP buffer is the beginning of a name parameter, and the rest of the TCP buffer contains a URL-encoded string with a name parameter terminated by a '=' character and a value parameter terminated by a '&'.
Parameters
Parameters
cData wLen
Return Values
Return Values
HTTP_READ_OK
HTTP_READ_TRUNCTATED
HTTP_READ_INCOMPLETE
Description
where to store the name and value strings once they are read how many bytes can be written to cData
Description
name and value were successfully read entire name and value could not fit in the buffer, so input was truncated and data has been lost entire name and value was not yet in the buffer, so call this function again later to retrieve
10.8.2.14
HTTPReadPostValue Function
File
HTTP2.h
C
HTTP_READ_STATUS HTTPReadPostValue(
253
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Public Members
BYTE* cData,
WORD wLen
);
Description
forcing the programmer to indicate how many bytes are expected. At least 2 extra bytes are needed in cData above the maximum length of data expected to be read.
This function will read until the next '&' character, which indicates the end of a value parameter. It assumes that the front of the buffer is the beginning of the value paramter to be read. If curHTTP.byteCount indicates that all expected bytes are in the buffer, it assumes that all remaining data is the value and acts accordingly.
This function properly updates curHTTP.byteCount by decrementing it by the number of bytes read. The terminating '&' character is also removed from the buffer.
Preconditions
Front of TCP buffer is the beginning of a name parameter, and the rest of the TCP buffer contains a URL-encoded string with a name parameter terminated by a '=' character.
Parameters
Parameters
cData wLen
Return Values
Return Values
HTTP_READ_OK
HTTP_READ_TRUNCTATED
HTTP_READ_INCOMPLETE
Description
where to store the value once it is read how many bytes can be written to cData
Description
value was successfully read entire value could not fit in the buffer, so the value was truncated and data has been lost entire value was not yet in the buffer, so call this function again later to retrieve
10.8.2.15
HTTPURLDecode Function
File
HTTP2.h
C
BYTE* HTTPURLDecode(
BYTE* cData
);
Returns
A pointer to the last null terminator in data, which is also the first free byte for new data.
Description
Parses a string from URL encoding to plain-text. The following conversions are made: ‘=’ to ‘0’, ‘&’ to ‘0’, ‘+’ to ‘ ‘, and “%xx” to a single hex byte.
After completion, the data has been decoded and a null terminator signifies the end of a name or value. A second null terminator (or a null name parameter) indicates the end of all the data.
Remarks
This function is called by the stack to parse GET arguments and cookie data. User applications can use this function to decode POST data, but first need to verify that the string is null-terminated.
254
10.8 HTTP2 Server Microchip TCP/IP Stack Help
Preconditions
The data parameter is null terminated and has at least one extra byte free.
Parameters
Parameters
cData
Description
The string which is to be decoded in place.
HTTP2 Stack Members
10.8.2.16
sktHTTP Macro
File
HTTP2.h
C
#define
sktHTTP httpStubs[curHTTPID].socket
// Access the current socket
Description
Access the current socket
10.8.3
HTTP2 Stack Members
Functions
Name
Module
Description
Initializes the HTTP server module.
Performs periodic tasks for the HTTP2 module.
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.8.3.1
HTTPInit Function
File
HTTP2.h
C void
HTTPInit();
Returns
None
Description
Sets all HTTP sockets to the listening state, and initializes the state machine and file handles for each connection. If SSL is enabled, opens a socket on that port as well.
Remarks
This function is called only one during lifetime of the application.
255
10.8 HTTP2 Server
Preconditions
TCP must already be initialized.
Section
Function Prototypes
Microchip TCP/IP Stack Help HTTP2 Internal Members
10.8.3.2
HTTPServer Function
File
HTTP2.h
C void
HTTPServer();
Returns
None
Description
Browses through each open connection and attempts to process any pending operations.
Remarks
This function acts as a task (similar to one in an RTOS). It performs its task in a co-operative manner, and the main application must call this function repeatedly to ensure that all open or new connections are served in a timely fashion.
Preconditions
HTTPInit ( see page 255)() must already be called.
10.8.4
HTTP2 Internal Members
Enumerations
Name
HTTP_FILE_TYPE ( see page 258)
Description
File type definitions
Supported Commands and Server Response Codes
SM_HTTP2 ( see page 267) Basic HTTP Connection State Machine
Functions
Name
Description
Parses the "Authorization:" header for a request and verifies the credentials.
Parses the "Content-Length:" header for a request.
HTTPHeaderParseCookie ( see page 262)
Parses the "Cookie:" headers for a request and stores them as GET variables.
HTTPHeaderParseLookup ( see page 263)
Calls the appropriate header parser based on the index of the header that was read from the request.
Writes a file byte-for-byte to the currently loaded TCP socket.
HTTPLoadConn ( see page 264) Switches the currently loaded connection for the HTTP2 module.
Saves a file uploaded via POST as the new MPFS image in EEPROM or external Flash.
256
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Internal Members
Performs any pending operations for the currently loaded HTTP connection.
Reads to a buffer until a specified delimiter character.
Serves up the next chunk of curHTTP ( see page 245)'s file, up to a)
available TX FIFO space or b) the next callback index, whichever comes first.
Macros
Name
HTTP_CACHE_LEN ( see page 258)
HTTP_MAX_DATA_LEN ( see page 259)
Description
Max lifetime (sec) of static responses as string
Define the maximum data length for reading cookie and GET/POST arguments (bytes)
HTTP_MAX_HEADER_LEN ( see page 259)
Set to length of longest string above
Define the minimum number of bytes free in the TX FIFO before executing callbacks
HTTP_PORT ( see page 259) Define the listening port for the HTTP server
Max time (sec) to await more data before timing out and disconnecting the socket
Define the listening port for the HTTPS server (if
STACK_USE_SSL_SERVER is enabled)
Access the current state machine
Macro indicating how much RAM to allocate on an ethernet controller to store
HTTP state data.
Module
Structures
Name
Description
HTTP Connection Struct Stores partial state data for each connection Meant for storage in fast access RAM
Variables
Name Description
curHTTPID ( see page 257) ID of the currently loaded HTTP_CONN ( see page 245)
httpContentTypes ( see page 261)
Content-type strings corresponding to HTTP_FILE_TYPE ( see page 258)
httpFileExtensions ( see page 261)
HTTPRequestHeaders ( see page 266)
Header strings for which we'd like to parse
HTTPResponseHeaders ( see page 266)
Initial response strings (Corresponding to HTTP_STATUS ( see page 259))
HTTP stubs with state machine and socket
Description
The following functions and variables are designated as internal to the HTTP2 module.
10.8.4.1
curHTTPID Variable
File
HTTP2.c
257
10.8 HTTP2 Server Microchip TCP/IP Stack Help
C
BYTE curHTTPID;
Description
ID of the currently loaded HTTP_CONN ( see page 245)
HTTP2 Internal Members
10.8.4.2
HTTP_CACHE_LEN Macro
File
HTTP2.h
C
#define
HTTP_CACHE_LEN ("600")
// Max lifetime (sec) of static responses as string
Description
Max lifetime (sec) of static responses as string
10.8.4.3
HTTP_FILE_TYPE Enumeration
File
HTTP2.h
C typedef enum
{
HTTP_TXT = 0u,
HTTP_HTM,
HTTP_HTML,
HTTP_CGI,
HTTP_XML,
HTTP_CSS,
HTTP_GIF,
HTTP_PNG,
HTTP_JPG,
HTTP_JAVA,
HTTP_WAV,
HTTP_UNKNOWN
} HTTP_FILE_TYPE;
Members
Members
HTTP_TXT = 0u
HTTP_HTM
HTTP_HTML
HTTP_CGI
HTTP_XML
HTTP_CSS
HTTP_GIF
HTTP_PNG
HTTP_JPG
HTTP_JAVA
HTTP_WAV
HTTP_UNKNOWN
Description
File type definitions
Description
File is a text document
File is HTML (extension .htm)
File is HTML (extension .html)
File is HTML (extension .cgi)
File is XML (extension .xml)
File is stylesheet (extension .css)
File is GIF image (extension .gif)
File is PNG image (extension .png)
File is JPG image (extension .jpg)
File is java (extension .java)
File is audio (extension .wav)
File type is unknown
258
10.8 HTTP2 Server Microchip TCP/IP Stack Help
10.8.4.4
HTTP_MAX_DATA_LEN Macro
File
TCPIP MRF24W.h
C
#define
HTTP_MAX_DATA_LEN (100u)
Description
Define the maximum data length for reading cookie and GET/POST arguments (bytes)
10.8.4.5
HTTP_MAX_HEADER_LEN Macro
File
HTTP2.c
C
#define
HTTP_MAX_HEADER_LEN (15u)
Description
Set to length of longest string above
10.8.4.6
HTTP_MIN_CALLBACK_FREE Macro
File
TCPIP MRF24W.h
C
#define
HTTP_MIN_CALLBACK_FREE (16u)
Description
Define the minimum number of bytes free in the TX FIFO before executing callbacks
10.8.4.7
HTTP_PORT Macro
File
TCPIP MRF24W.h
C
#define
HTTP_PORT (80u)
Description
Define the listening port for the HTTP server
10.8.4.8
HTTP_STATUS Enumeration
File
HTTP2.h
HTTP2 Internal Members
259
10.8 HTTP2 Server Microchip TCP/IP Stack Help
C typedef enum
{
HTTP_GET = 0u,
HTTP_POST,
HTTP_BAD_REQUEST,
HTTP_UNAUTHORIZED,
HTTP_NOT_FOUND,
HTTP_OVERFLOW,
HTTP_INTERNAL_SERVER_ERROR,
HTTP_NOT_IMPLEMENTED,
HTTP_MPFS_FORM,
HTTP_MPFS_UP,
HTTP_MPFS_OK,
HTTP_MPFS_ERROR,
HTTP_REDIRECT,
HTTP_SSL_REQUIRED
} HTTP_STATUS;
Members
Members
HTTP_GET = 0u
HTTP_POST
HTTP_BAD_REQUEST
HTTP_UNAUTHORIZED
HTTP_NOT_FOUND
HTTP_OVERFLOW
HTTP_INTERNAL_SERVER_ERROR
HTTP_NOT_IMPLEMENTED
HTTP_MPFS_FORM
HTTP_MPFS_UP
HTTP_MPFS_OK
HTTP_MPFS_ERROR
HTTP_REDIRECT
HTTP_SSL_REQUIRED
Description
GET command is being processed
POST command is being processed
400 Bad Request will be returned
401 Unauthorized will be returned
404 Not Found will be returned
414 Request-URI Too Long will be returned
500 Internal Server Error will be returned
501 Not Implemented (not a GET or POST command)
Show the MPFS Upload form
An MPFS Upload is being processed
An MPFS Upload was successful
An MPFS Upload was not a valid image
302 Redirect will be returned
403 Forbidden is returned, indicating SSL is required
Description
Supported Commands and Server Response Codes
HTTP2 Internal Members
10.8.4.9
HTTP_STUB Structure
File
HTTP2.h
C typedef struct
{
} HTTP_STUB;
Members
Members
SM_HTTP2 sm;
TCP_SOCKET socket;
Description
Current connection state
Socket being served
Description
HTTP Connection Struct Stores partial state data for each connection Meant for storage in fast access RAM
260
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Internal Members
10.8.4.10
HTTP_TIMEOUT Macro
File
HTTP2.h
C
#define
HTTP_TIMEOUT (45u)
// Max time (sec) to await more data before timing out and disconnecting the socket
Description
Max time (sec) to await more data before timing out and disconnecting the socket
10.8.4.11
httpContentTypes Variable
File
HTTP2.c
C
ROM
char
* ROM httpContentTypes[HTTP_UNKNOWN+1] = { "text/plain", "text/html", "text/html",
"text/html", "text/xml", "text/css", "image/gif", "image/png", "image/jpeg",
"application/java-vm", "audio/x-wave", "" };
Description
Content-type strings corresponding to HTTP_FILE_TYPE ( see page 258)
10.8.4.12
httpFileExtensions Variable
File
HTTP2.c
C
ROM
char
* ROM httpFileExtensions[HTTP_UNKNOWN+1] = { "txt", "htm", "html", "cgi", "xml",
"css", "gif", "png", "jpg", "cla", "wav", "\0\0\0" };
Section
File and Content Type Settings
************************************************************************
File type extensions corresponding to HTTP_FILE_TYPE
10.8.4.13
HTTPHeaderParseAuthorization Function
File
HTTP2.c
C static void
HTTPHeaderParseAuthorization();
Returns
None
261
10.8 HTTP2 Server Microchip TCP/IP Stack Help HTTP2 Internal Members
Description
Parses the "Authorization:" header for a request. For example, "BASIC YWRtaW46cGFzc3dvcmQ=" is decoded to a user
CustomHTTPApp.c to determine if the credentials are acceptable.
Remarks
This function is ony available when HTTP_USE_AUTHENTICATION is defined.
Preconditions
None
10.8.4.14
HTTPHeaderParseContentLength Function
File
HTTP2.c
C static void
HTTPHeaderParseContentLength();
Returns
None
Description
Parses the "Content-Length:" header to determine how many bytes of POST data to expect after the request. This value is stored in curHTTP.byteCount.
Remarks
This function is ony available when HTTP_USE_POST is defined.
Preconditions
None
10.8.4.15
HTTPHeaderParseCookie Function
File
HTTP2.c
C static void
HTTPHeaderParseCookie();
Returns
None
Description
Parses the "Cookie:" headers for a request. For example, "Cookie: name=Wile+E.+Coyote; order=ROCKET_LAUNCHER" is decoded to "name=Wile+E.+Coyote&order=ROCKET_LAUNCHER&" and stored as any other GET variable in curHTTP.data.
Remarks
This function is ony available when HTTP_USE_COOKIES is defined.
262
10.8 HTTP2 Server
Preconditions
None
Microchip TCP/IP Stack Help HTTP2 Internal Members
10.8.4.16
HTTPHeaderParseLookup Function
File
HTTP2.c
C static void
HTTPHeaderParseLookup(
BYTE i
);
Description
Calls the appropriate header parser based on the index of the header that was read from the request.
Preconditions
None
Parameters
i
Parameters
Return Values
Return Values
TRUE
FALSE
Section
Function Prototypes
Description
the index of the string found in HTTPRequestHeaders ( see page 266)
Description
the end of the file was reached and reading is done more data remains to be read
10.8.4.17
HTTPIncFile Function
File
HTTP2.h
C void
HTTPIncFile(
ROM BYTE* cFile
);
Returns
None
Description
Allows an entire file to be included as a dynamic variable, providing a basic templating system for HTML web pages. This reduces unneeded duplication of visual elements such as headers, menus, etc.
When curHTTP.callbackPos is 0, the file is opened and as many bytes as possible are written. The current position is then saved to curHTTP.callbackPos and the file is closed. On subsequent calls, reading begins at the saved location and continues. Once the end of the input file is reached, curHTTP.callbackPos is set back to 0 to indicate completion.
Remarks
Users should not call this function directly, but should instead add dynamic variables in the form of ~inc:filename.ext~ in their
HTML code to include (for example) the file "filename.ext" at that specified location. The MPFS2 Generator utility will handle
263
10.8 HTTP2 Server the rest.
Preconditions
None
Parameters
Parameters
cFile
Microchip TCP/IP Stack Help
Description
the name of the file to be sent
HTTP2 Internal Members
10.8.4.18
HTTPLoadConn Function
File
HTTP2.c
C static void
HTTPLoadConn(
BYTE hHTTP
);
Returns
None
Description
( see page 245) in local RAM for processing.
Preconditions
None
Parameters
Parameters
hHTTP
Description
the connection ID to load
10.8.4.19
HTTPMPFSUpload Function
File
HTTP2.c
C static
HTTP_IO_RESULT HTTPMPFSUpload();
Description
Allows the MPFS image in EEPROM or external Flash to be updated via a web page by accepting a file upload and storing it to the external memory.
Remarks
This function is only available when MPFS uploads are enabled and the MPFS image is stored in EEPROM.
Internal
After the headers, the first line from the form will be the MIME separator. Following that is more headers about the file, which are discarded. After another CRLFCRLF pair the file data begins, which is read 16 bytes at a time and written to external memory.
Preconditions
MPFSFormat ( see page 279)() has been called.
264
10.8 HTTP2 Server
Return Values
Return Values
HTTP_IO_DONE
HTTP_IO_NEED_DATA
Microchip TCP/IP Stack Help
Description
on success if more data is still expected
10.8.4.20
HTTPProcess Function
File
HTTP2.c
C static void
HTTPProcess();
Returns
None
Description
Performs any pending operations for the currently loaded HTTP connection.
Preconditions
HTTPInit ( see page 255)() and HTTPLoadConn ( see page 264)() have been called.
HTTP2 Internal Members
10.8.4.21
HTTPReadTo Function
File
HTTP2.c
C static
BYTE delim,
BYTE* buf,
WORD len
);
Description
Reads from the TCP buffer to cData until either cDelim is reached, or until wLen - 2 bytes have been read. The value read is
254) later, which requires a null terminator plus one extra free byte.)
The delimiter character is removed from the buffer, but not saved to cData. If all data cannot fit into cData, it will still be removed from the buffer but will not be saved anywhere.
This function properly updates curHTTP.byteCount by decrementing it by the number of bytes read.
Preconditions
None
Parameters
Parameters
cDelim cData wLen
Description
the character at which to stop reading, or NULL to read to the end of the buffer where to store the data being read how many bytes can be written to cData
265
10.8 HTTP2 Server
Return Values
Return Values
HTTP_READ_OK
HTTP_READ_TRUNCTATED
HTTP_READ_INCOMPLETE
Microchip TCP/IP Stack Help HTTP2 Internal Members
Description
data was successfully read entire data could not fit in the buffer, so the data was truncated and data has been lost delimiter character was not found
10.8.4.22
HTTPRequestHeaders Variable
File
HTTP2.c
C
ROM
char
* ROM HTTPRequestHeaders[] = { "Cookie:", "Authorization:", "Content-Length:" };
Description
Header strings for which we'd like to parse
10.8.4.23
HTTPResponseHeaders Variable
File
HTTP2.c
C
ROM
char
* ROM HTTPResponseHeaders[] = { "HTTP/1.1 200 OK\r\nConnection: close\r\n",
"HTTP/1.1 200 OK\r\nConnection: close\r\n", "HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n400 Bad Request: can't handle Content-Length\r\n", "HTTP/1.1 401
Unauthorized\r\nWWW-Authenticate: Basic realm=\"Protected\"\r\nConnection: close\r\n\r\n401
Unauthorized: Password required\r\n", "HTTP/1.1 404 Not found\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n404: File not found<br>Use <a href=\"/"
HTTP_MPFS_UPLOAD "\">MPFS Upload</a> to program web pages\r\n", "HTTP/1.1 404 Not found\r\nConnection: close\r\n\r\n404: File not found\r\n", "HTTP/1.1 414 Request-URI Too
Long\r\nConnection: close\r\n\r\n414 Request-URI Too Long: Buffer overflow detected\r\n",
"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n500 Internal Server Error:
Expected data not present\r\n", "HTTP/1.1 501 Not Implemented\r\nConnection: close\r\n\r\n501 Not Implemented: Only GET and POST supported\r\n", "HTTP/1.1 200
OK\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n<html><body style=\"margin:100px\"><form method=post action=\"/" HTTP_MPFS_UPLOAD "\" enctype=\"multipart/form-data\"><b>MPFS Image Upload</b><p><input type=file name=i size=40>
<input type=submit value=\"Upload\"></form></body></html>", "", "HTTP/1.1 200
OK\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n<html><body style=\"margin:100px\"><b>MPFS Update Successful</b><p><a href=\"/\">Site main page</a></body></html>", "HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n<html><body style=\"margin:100px\"><b>MPFS Image
Corrupt or Wrong Version</b><p><a href=\"/" HTTP_MPFS_UPLOAD "\">Try again?</a></body></html>", "HTTP/1.1 302 Found\r\nConnection: close\r\nLocation: ",
"HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n403 Forbidden: SSL Required - use
HTTPS\r\n" };
Description
Initial response strings (Corresponding to HTTP_STATUS ( see page 259))
10.8.4.24
HTTPS_PORT Macro
File
TCPIP MRF24W.h
266
10.8 HTTP2 Server Microchip TCP/IP Stack Help
C
#define
HTTPS_PORT (443u)
Description
Define the listening port for the HTTPS server (if STACK_USE_SSL_SERVER is enabled)
HTTP2 Internal Members
10.8.4.25
HTTPSendFile Function
File
HTTP2.c
C static
BOOL HTTPSendFile();
Description
index, whichever comes first.
Preconditions
curHTTP.file and curHTTP.offsets have both been opened for reading.
Return Values
Return Values
TRUE
FALSE
Description
the end of the file was reached and reading is done more data remains to be read
10.8.4.26
httpStubs Variable
File
HTTP2.c
C
HTTP_STUB httpStubs[MAX_HTTP_CONNECTIONS];
Description
HTTP stubs with state machine and socket
10.8.4.27
SM_HTTP2 Enumeration
File
HTTP2.h
C typedef enum
{
SM_HTTP_IDLE = 0u,
SM_HTTP_PARSE_REQUEST,
SM_HTTP_PARSE_HEADERS,
SM_HTTP_AUTHENTICATE,
SM_HTTP_PROCESS_GET,
SM_HTTP_PROCESS_POST,
SM_HTTP_PROCESS_REQUEST,
SM_HTTP_SERVE_HEADERS,
SM_HTTP_SERVE_COOKIES,
SM_HTTP_SERVE_BODY,
SM_HTTP_SEND_FROM_CALLBACK,
267
10.9 ICMP
SM_HTTP_DISCONNECT
} SM_HTTP2;
Members
Members
SM_HTTP_IDLE = 0u
SM_HTTP_PARSE_REQUEST
SM_HTTP_PARSE_HEADERS
SM_HTTP_AUTHENTICATE
SM_HTTP_PROCESS_GET
SM_HTTP_PROCESS_POST
SM_HTTP_PROCESS_REQUEST
SM_HTTP_SERVE_HEADERS
SM_HTTP_SERVE_COOKIES
SM_HTTP_SERVE_BODY
SM_HTTP_SEND_FROM_CALLBACK
SM_HTTP_DISCONNECT
Description
Basic HTTP Connection State Machine
Microchip TCP/IP Stack Help
Description
Socket is idle
Parses the first line for a file name and GET args
Reads and parses headers one at a time
Validates the current authorization state
Invokes user callback for GET args or cookies
Invokes user callback for POSTed data
Begins the process of returning data
Sends any required headers for the response
Adds any cookies to the response
Serves the actual content
Invokes a dynamic variable callback
Disconnects the server and closes all files
10.8.4.28
smHTTP Macro
File
HTTP2.c
C
#define
smHTTP httpStubs[curHTTPID].sm
// Access the current state machine
Description
Access the current state machine
10.8.4.29
RESERVED_HTTP_MEMORY Macro
File
HTTP2.h
C
#define
RESERVED_HTTP_MEMORY ((DWORD)MAX_HTTP_CONNECTIONS * (DWORD)
sizeof
Description
Macro indicating how much RAM to allocate on an ethernet controller to store HTTP state data.
10.9
ICMP
The Internet Control Message Protocol is used to send error and status messages and requests. The ICMP module implements the Echo Reply message type (commonly referred to as a ping) which can be used to determine if a specified host is reachable across an IP network from a device running the TCP/IP stack. An ICMP server is also supported to respond to pings from other devices.
268
10.9 ICMP Microchip TCP/IP Stack Help ICMP Public Members
10.9.1
ICMP Public Members
Functions
Name
ICMPBeginUsage ( see page 269)
ICMPSendPingToHost ( see page 270)
Description
Claims ownership of the ICMP module.
None
None
Begins the process of transmitting an ICMP echo request. This normally involves an ARP resolution procedure first.
None
Gives up ownership of the ICMP module.
Macros
Name
Module
Description
This is macro ICMPSendPingToHostROM.
Description
The following functions and variables are accessible or implemented by the stack application.
10.9.1.1
ICMPBeginUsage Function
File
ICMP.h
C
BOOL ICMPBeginUsage();
Side Effects
None
Returns
module. Calling ICMPSendPing ( see page 270)() will corrupt the other application's ping result.
269
10.9 ICMP
Description
Claims ownership of the ICMP module.
Remarks
None
Preconditions
None
Microchip TCP/IP Stack Help ICMP Public Members
10.9.1.2
ICMPSendPing Function
File
ICMP.h
C void
ICMPSendPing(
DWORD dwRemoteIP
);
Side Effects
None
Returns
Begins the process of transmitting an ICMP echo request. This normally involves an ARP resolution procedure first.
Description
None
Remarks
None
Preconditions
ICMPBeginUsage ( see page 269)() returned TRUE
Parameters
Parameters
dwRemoteIP
Description
IP Address ( see page 152) to ping. Must be stored big endian. Ex.
192.168.0.1 should be passed as 0x0100A8C0.
10.9.1.3
ICMPSendPingToHost Function
File
ICMP.h
C void
ICMPSendPingToHost(
BYTE * szRemoteHost
);
Side Effects
None
Returns
Begins the process of transmitting an ICMP echo request. This normally involves an ARP resolution procedure first.
270
10.9 ICMP Microchip TCP/IP Stack Help ICMP Public Members
Description
None
Remarks
None
Preconditions
ICMPBeginUsage ( see page 269)() returned TRUE
Parameters
Parameters
szRemoteHost
Description
Host name to ping. Must be stored in RAM if being called by PIC18. Ex. www.microchip.com
10.9.1.4
ICMPSendPingToHostROM Function
File
ICMP.h
C void
ICMPSendPingToHostROM(
ROM BYTE * szRemoteHost
);
Side Effects
None
Returns
None
Description
Begins the process of transmitting an ICMP echo request. This normally involves an ARP resolution procedure first.
Remarks
None
Preconditions
ICMPBeginUsage ( see page 269)() returned TRUE
Parameters
Parameters
szRemoteHost
Description
Host name to ping. Must be stored in ROM. Should only be called by PIC18.
Ex. www.microchip.com
10.9.1.5
ICMPGetReply Function
File
ICMP.h
C
LONG ICMPGetReply();
Side Effects
None
271
10.9 ICMP Microchip TCP/IP Stack Help ICMP Internal Members
Returns
-3: Could not resolve hostname (DNS timeout or hostname invalid) -2: No response received yet -1: Operation timed out
transmission and reception of a valid echo.
Description
None
Remarks
None
Preconditions
ICMPBeginUsage ( see page 269)() returned TRUE and ICMPSendPing ( see page 270)() was called
10.9.1.6
ICMPEndUsage Function
File
ICMP.h
C void
ICMPEndUsage();
Side Effects
None
Returns
Your ownership of the ICMP module is released. You can no longer use ICMPSendPing ( see page 270)().
Description
Gives up ownership of the ICMP module.
Remarks
None
Preconditions
ICMPBeginUsage ( see page 269)() was called by you and it returned TRUE.
10.9.1.7
ICMPSendPingToHostROM Macro
File
ICMP.h
C
#define
ICMPSendPingToHostROM(a) ICMPSendPingToHost((BYTE*)(a))
Description
This is macro ICMPSendPingToHostROM.
272
10.9 ICMP Microchip TCP/IP Stack Help ICMP Internal Members
10.9.2
ICMP Internal Members
Functions
Name
Macros
Name
Module
Description
None
Description
ICMP Timeout Value
Structures
Name
Description
ICMP Packet Structure
Variables
Name Description
ICMPFlags ( see page 274) ICMP Flag structure
ICMP State Machine Enumeration
ICMPTimer ( see page 275) ICMP tick timer variable
ICMP Static Variables
wICMPSequenceNumber ( see page 276)
ICMP Sequence Number
Description
The following functions and variables are designated as internal to the ICMP module.
10.9.2.1
ICMPProcess Function
File
ICMP.h
C void
ICMPProcess(
NODE_INFO * remote,
WORD len
);
Side Effects
None
Returns
Generates an echo reply, if requested Validates and sets ICMPFlags.bReplyValid if a correct ping response to one of ours is received.
Description
None
273
10.9 ICMP Microchip TCP/IP Stack Help ICMP Internal Members
Remarks
None
Preconditions
MAC buffer contains ICMP type packet.
Parameters
Parameters
*remote len
Description
Pointer to a NODE_INFO structure of the ping requester
Count of how many bytes the ping header and payload are in this IP packet
10.9.2.2
ICMPFlags Variable
File
ICMP.c
C struct
{
unsigned char
bICMPInUse : 1;
unsigned char
bReplyValid : 1;
unsigned char
bRemoteHostIsROM : 1;
} ICMPFlags;
Members
Members
unsigned char bICMPInUse : 1; unsigned char bReplyValid : 1; unsigned char bRemoteHostIsROM : 1;
Description
ICMP Flag structure
Description
Indicates that the ICMP Client is in use
Indicates that a correct Ping response to one of our pings was received
Indicates that a remote host name was passed as a ROM pointer argument
10.9.2.3
ICMP_PACKET Structure
File
ICMP.c
C typedef struct
{
BYTE vType;
BYTE vCode;
WORD wChecksum;
WORD wIdentifier;
WORD wSequenceNumber;
WORD wData;
} ICMP_PACKET;
Description
ICMP Packet Structure
10.9.2.4
ICMPState Variable
File
ICMP.c
274
10.9 ICMP
C enum
{
SM_IDLE = 0,
SM_DNS_SEND_QUERY,
SM_DNS_GET_RESPONSE,
SM_ARP_SEND_QUERY,
SM_ARP_GET_RESPONSE,
SM_ICMP_SEND_ECHO_REQUEST,
SM_ICMP_GET_ECHO_RESPONSE
} ICMPState;
Description
ICMP State Machine Enumeration
Microchip TCP/IP Stack Help
10.9.2.5
ICMP_TIMEOUT Macro
File
ICMP.c
C
#define
ICMP_TIMEOUT (4ul*TICK_SECOND)
Description
ICMP Timeout Value
10.9.2.6
ICMPTimer Variable
File
ICMP.c
C
DWORD ICMPTimer;
Description
ICMP tick timer variable
10.9.2.7
StaticVars Variable
File
ICMP.c
C union
{
union
{
ROM BYTE * szROM;
BYTE * szRAM;
} RemoteHost;
NODE_INFO ICMPRemote;
} StaticVars;
Description
ICMP Static Variables
ICMP Internal Members
275
MPFS2 Public Members 10.10 MPFS2 Microchip TCP/IP Stack Help
10.9.2.8
wICMPSequenceNumber Variable
File
ICMP.c
C
WORD wICMPSequenceNumber;
Description
ICMP Sequence Number
10.10
MPFS2
The MPFS2 file system module provides a light-weight read-only file system that can be stored in external EEPROM, external serial Flash, or internal Flash program memory. This file system serves as the basis for the HTTP2 web server module, but is also used by the SNMP module and is available to other applications that require basic read-only storage capabilities.
The MPFS2 module includes an MPFS2 Utility that runs on your PC. This program builds MPFS2 images in various formats
Using External Storage
For external storage, the MPFS2 file system supports Microchip 25LCxxx EEPROM parts for densities up to 1Mbit. SST
25VFxxxB serial Flash parts are also supported for densities up to 32Mbit.
To use external EEPROM storage, ensure that the configuration macro MPFS_USE_EEPROM is defined in
TCPIPConfig.h
. If you are using a 1Mbit part (25LC1024), also be sure to define USE_EEPROM_25LC1024 to enable the
24-bit device addressing used by that part. For external serial Flash, define MFPS_USE_SPI_FLASH instead of the
EEPROM macros.
Images stored externally are uploaded via HTTP. This can be accomplished using the MPFS2 Utility, or can be accessed
images via HTTP can be accomplished as described in the Getting Started ( see page 79) section.
When storing images externally, space can be reserved for separate application use. The configuration macro
MPFS_RESERVE_BLOCK controls the size of this space. The specified number of bytes will be reserved at the beginning address of the storage device (0x000000). When using serial Flash, this address must be a multiple of the flash sector size
(4096 bytes).
Using Internal Flash Storage
When storing images in internal Flash program memory, new images cannot be uploaded at run time. Instead, the image is compiled in as part of your project in the MPLAB IDE. To select this storage option comment out the configuration macro
MPFS_USE_EEPROM in
TCPIPConfig.h
, then ensure that the image file generated by the MPFS2 Utility is included in the MPLAB project.
Other Considerations
MPFS2 defines a fixed number of files that can be opened simultaneously. The configuration parameter
MAX_MPFS_HANDLES controls how many files can be opened at once. If this resource is depleted, no new files can be
at least two handles for each connection, plus one extra. Additional handles should be allocated if other modules will be accessing the file system as well.
276
10.10 MPFS2 Microchip TCP/IP Stack Help
10.10.1
MPFS2 Public Members
Enumerations
Name
MPFS_SEEK_MODE ( see page 278)
Description
Indicates the method for MPFSSeek ( see page 288)
Functions
Name Description
MPFSClose ( see page 279) Closes a file.
Prepares the MPFS image for writing.
Reads a byte from a file.
Reads a series of bytes from a file.
MPFSGetBytesRem ( see page 281)
Determines how many bytes remain to be read.
Determines the ending address of a file.
MPFSGetEndAddr ( see page 281)
MPFSGetFilename ( see page 282)
Reads the file name of a file that is already open.
Reads a file's flags.
MPFSGetID ( see page 283) Determines the ID in the FAT for a file.
Reads a DWORD or Long value from the MPFS.
MPFSGetMicrotime ( see page 284)
Reads the microtime portion of a file's timestamp.
Determines the current position in the file
MPFSGetPosition ( see page 284)
MPFSGetStartAddr ( see page 285)
Reads the size of a file.
Reads the starting address of a file.
MPFSGetTimestamp ( see page 285)
Reads the timestamp for the specified file.
MPFSOpen ( see page 286) Opens a file in the MPFS2 file system.
Quickly re-opens a file.
Opens a file in the MPFS2 file system.
Writes an array of data to the MPFS image.
MPFSSeek ( see page 288) Moves the current read pointer to a new location.
Finalizes an MPFS writing operation.
Macros
Name
Description
Indicates a position pointer is invalid
MPFS2 Public Members
277
10.10 MPFS2 Microchip TCP/IP Stack Help
Module
Types
Indicates that a handle is not valid
Name Description
MPFS Handles are currently stored as BYTEs
Description
The following functions and variables are accessible by the stack application.
MPFS2 Public Members
10.10.1.1
MPFS_HANDLE Type
File
MPFS2.h
C typedef
BYTE MPFS_HANDLE;
Description
MPFS Handles are currently stored as BYTEs
10.10.1.2
MPFS_INVALID Macro
File
MPFS2.h
C
#define
MPFS_INVALID (0xffffffffu)
// Indicates a position pointer is invalid
Description
Indicates a position pointer is invalid
10.10.1.3
MPFS_INVALID_HANDLE Macro
File
MPFS2.h
C
#define
MPFS_INVALID_HANDLE (0xffu)
// Indicates that a handle is not valid
Description
Indicates that a handle is not valid
10.10.1.4
MPFS_SEEK_MODE Enumeration
File
MPFS2.h
278
10.10 MPFS2 Microchip TCP/IP Stack Help
C typedef enum
{
MPFS_SEEK_START = 0u,
MPFS_SEEK_END,
MPFS_SEEK_FORWARD,
MPFS_SEEK_REWIND
} MPFS_SEEK_MODE;
Members
Members
MPFS_SEEK_START = 0u
MPFS_SEEK_END
MPFS_SEEK_FORWARD
MPFS_SEEK_REWIND
Description
Seek forwards from the front of the file
Seek backwards from the end of the file
Seek forward from the current position
See backwards from the current position
Description
Indicates the method for MPFSSeek ( see page 288)
MPFS2 Public Members
10.10.1.5
MPFSClose Function
File
MPFS2.h
C void
MPFSClose(
);
Returns
None
Description
Closes a file and releases its stub back to the pool of available handles.
Preconditions
None
Parameters
Parameters
Description
the file handle to be closed
10.10.1.6
MPFSFormat Function
File
MPFS2.h
C
Returns
EEPROM failed to initialize for writing.
Description
Prepares the MPFS image for writing and locks the image so that other processes may not access it.
279
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Public Members
Remarks
available when the MPFS is stored in internal Flash program memory.
Preconditions
None
10.10.1.7
MPFSGet Function
File
MPFS2.h
C
BOOL MPFSGet(
BYTE* c
);
Description
Reads a byte from a file.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
c
Return Values
Return Values
TRUE
FALSE
Description
the file handle from which to read
Where to store the byte that was read
Description
The byte was successfully read
No byte was read because either the handle was invalid or the end of the file has been reached.
10.10.1.8
MPFSGetArray Function
File
MPFS2.h
C
WORD MPFSGetArray(
BYTE* cData,
WORD wLen
);
Returns
The number of bytes successfully read. If this is less than wLen, an EOF occurred while attempting to read.
Description
Reads a series of bytes from a file.
Preconditions
The file handle referenced by hMPFS is already open.
280
10.10 MPFS2
Parameters
Parameters
cData wLen
Microchip TCP/IP Stack Help
Description
the file handle from which to read where to store the bytes that were read how many bytes to read
10.10.1.9
MPFSGetBytesRem Function
File
MPFS2.h
C
DWORD MPFSGetBytesRem(
);
Returns
The number of bytes remaining in the file as a DWORD
Description
Determines how many bytes remain to be read.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
10.10.1.10
MPFSGetEndAddr Function
File
MPFS2.h
C
);
Returns
The address just after the file ends (start address of next file)
Description
Determines the ending address of a file.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
MPFS2 Public Members
281
10.10 MPFS2 Microchip TCP/IP Stack Help
10.10.1.11
MPFSGetFilename Function
File
MPFS2.h
C
BOOL MPFSGetFilename(
BYTE* cName,
WORD wLen
);
Description
Reads the file name of a file that is already open.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
cName wLen
Return Values
Return Values
TRUE
FALSE
Description
the file handle from which to determine the file name where to store the name of the file the maximum length of data to store in cName
Description
the file name was successfully located the file handle provided is not currently open
10.10.1.12
MPFSGetFlags Function
File
MPFS2.h
C
WORD MPFSGetFlags(
);
Returns
The flags that were associated with the file
Description
Reads a file's flags.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
MPFS2 Public Members
282
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Public Members
10.10.1.13
MPFSGetID Function
File
MPFS2.h
C
WORD MPFSGetID(
);
Returns
The ID in the FAT for this file
Description
Determines the ID in the FAT for a file.
Remarks
file handle.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
10.10.1.14
MPFSGetLong Function
File
MPFS2.h
C
BOOL MPFSGetLong(
DWORD* ul
);
Returns
TRUE - The byte was successfully read FALSE - No byte was read because either the handle was invalid or the end of the file has been reached.
Description
Reads a DWORD or Long value from the MPFS.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
ul
Description
the file handle from which to read where to store the DWORD or long value that was read
283
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Public Members
10.10.1.15
MPFSGetMicrotime Function
File
MPFS2.h
C
DWORD MPFSGetMicrotime(
);
Returns
The microtime that was read as a DWORD
Description
Reads the microtime portion of a file's timestamp.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
10.10.1.16
MPFSGetPosition Function
File
MPFS2.h
C
DWORD MPFSGetPosition(
);
Returns
The position in the file as a DWORD (or MPFS_PTR ( see page 291))
Description
Determines the current position in the file
Remarks
time. (Where pos is the value returned by this function.)
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle for which to determine position
10.10.1.17
MPFSGetSize Function
File
MPFS2.h
284
10.10 MPFS2 Microchip TCP/IP Stack Help
C
DWORD MPFSGetSize(
);
Returns
The size that was read as a DWORD
Description
Reads the size of a file.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
10.10.1.18
MPFSGetStartAddr Function
File
MPFS2.h
C
);
Returns
The starting address of the file in the MPFS image
Description
Reads the starting address of a file.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
10.10.1.19
MPFSGetTimestamp Function
File
MPFS2.h
C
DWORD MPFSGetTimestamp(
);
Returns
The timestamp that was read as a DWORD
Description
Reads the timestamp for the specified file.
MPFS2 Public Members
285
10.10 MPFS2 Microchip TCP/IP Stack Help
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
Description
the file handle from which to read the metadata
MPFS2 Public Members
10.10.1.20
MPFSOpen Function
File
MPFS2.h
C
BYTE* cFile
);
Returns
could not be found or no free handles exist.
Description
Opens a file in the MPFS2 file system.
Preconditions
MPFSInit ( see page 289) has been called
Parameters
Parameters
cFile
Description
a null terminated file name to open
10.10.1.21
MPFSOpenID Function
File
MPFS2.h
C
WORD hFatID
);
Returns
could not be found or no free handles exist.
Description
re-open a file without tying up a permanent MPFSStub.
Preconditions
None
Parameters
Parameters
hFatID
Description
the ID of a previous opened file in the FAT
286
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Public Members
10.10.1.22
MPFSOpenROM Function
File
MPFS2.h
C
ROM BYTE* cFile
);
Returns
could not be found or no free handles exist.
Description
Opens a file in the MPFS2 file system.
Remarks
This function is aliased to MPFSOpen ( see page 286) on non-PIC18 platforms.
Preconditions
None
Parameters
Parameters
cFile
Description
a null terminated file name to open
10.10.1.23
MPFSPutArray Function
File
MPFS2.h
C
WORD MPFSPutArray(
BYTE* cData,
WORD wLen
);
Returns
The number of bytes successfully written.
Description
Writes an array of data to the MPFS image.
Remarks
For EEPROM, the actual write may not initialize until the internal write page is full. To ensure that previously written data
gets stored, MPFSPutEnd ( see page 288) must be called after the last call to MPFSPutArray.
Preconditions
MPFSFormat ( see page 279) was sucessfully called.
Parameters
Parameters
Description
the file handle for writing
287
10.10 MPFS2 cData wLen
Microchip TCP/IP Stack Help the array of bytes to write how many bytes to write
MPFS2 Stack Members
10.10.1.24
MPFSSeek Function
File
MPFS2.h
C
BOOL MPFSSeek(
DWORD dwOffset,
);
Returns
TRUE - the seek was successful FALSE - either the new location or the handle itself was invalid
Description
Moves the current read pointer to a new location.
Preconditions
The file handle referenced by hMPFS is already open.
Parameters
Parameters
dwOffset tMode
Description
the file handle to seek with offset from the specified position in the specified direction
one of the MPFS_SEEK_MODE ( see page 278) constants
10.10.1.25
MPFSPutEnd Function
File
MPFS2.h
C void
MPFSPutEnd(
BOOL final
);
Returns
None
Description
Finalizes an MPFS writing operation.
Preconditions
MPFSFormat ( see page 279) and MPFSPutArray ( see page 287) were sucessfully called.
Parameters
Parameters
final
Description
TRUE if the application is done writing, FALSE if MPFS2 called this function locally.
288
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Internal Members
10.10.2
MPFS2 Stack Members
Functions
Name Description
Initializes the MPFS module.
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.10.2.1
MPFSInit Function
File
MPFS2.h
C void
MPFSInit();
Returns
None
Description
Sets all MPFS handles to closed, and initializes access to the EEPROM if necessary.
Remarks
This function is called only one during lifetime of the application.
Preconditions
None
Section
Function Definitions
10.10.3
MPFS2 Internal Members
Functions
Name Description
ReadProgramMemory ( see page 293)
Assembly function to read all three bytes of program memory for 16-bit parts
_LoadFATRecord ( see page 293)
Loads the FAT record for a specified handle.
Validates the MPFS Image
289
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Internal Members
Macros
Module
Structures
Name
MAX_FILE_NAME_LEN ( see page 291)
Description
Supports long file names to 64 characters
Defines the size of a page in EEPROM
Indicates a file has an associated index of dynamic variables
MPFS2_FLAG_ISZIPPED ( see page 292)
Indicates a file is compressed with GZIP compression
Alias of MPFSGetPosition ( see page 284)
MPFS_INVALID_FAT ( see page 295)
Indicates an invalid FAT cache
Name
MPFS_FAT_RECORD ( see page 294)
Description
Stores each file handle's information Handles are free when addr =
Stores the data for an MPFS2 FAT record
Types
Name Description
MPFS_PTR ( see page 291) MPFS Pointers are currently DWORDs
Variables
Name
Description
Allows the MPFS to be locked, preventing access during updates
Track the last read address to prevent unnecessary data overhead to switch locations.
MPFSStubs ( see page 292) Track the MPFS File Handles MPFSStubs[0] is reserved for internal use (FAT
access)
FAT record cache
fatCacheID ( see page 295) ID of currently loaded fatCache ( see page 294)
Number of files in this MPFS image
Description
The following functions and variables are designated as internal to the MPFS2 module.
10.10.3.1
isMPFSLocked Variable
File
MPFS2.c
C
BOOL isMPFSLocked;
Description
Allows the MPFS to be locked, preventing access during updates
290
10.10 MPFS2 Microchip TCP/IP Stack Help
10.10.3.2
lastRead Variable
File
MPFS2.c
C
Description
Track the last read address to prevent unnecessary data overhead to switch locations.
10.10.3.3
MAX_FILE_NAME_LEN Macro
File
MPFS2.c
C
#define
MAX_FILE_NAME_LEN (64u)
Description
Supports long file names to 64 characters
10.10.3.4
MPFS_PTR Type
File
MPFS2.h
C typedef
DWORD MPFS_PTR;
Description
MPFS Pointers are currently DWORDs
10.10.3.5
MPFS_STUB Structure
File
MPFS2.h
C typedef struct
{
DWORD bytesRem;
WORD fatID;
} MPFS_STUB;
Members
Members
MPFS_PTR addr;
DWORD bytesRem;
WORD fatID;
Description
Current address in the file system
How many bytes remain in this file
ID of which file in the FAT was accessed
MPFS2 Internal Members
291
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Internal Members
Description
Stores each file handle's information Handles are free when addr = MPFS_INVALID ( see page 278)
10.10.3.6
MPFS_WRITE_PAGE_SIZE Macro
File
MPFS2.h
C
#define
MPFS_WRITE_PAGE_SIZE (64u)
// Defines the size of a page in EEPROM
Description
Defines the size of a page in EEPROM
10.10.3.7
MPFS2_FLAG_HASINDEX Macro
File
MPFS2.h
C
#define
MPFS2_FLAG_HASINDEX ((WORD)0x0002)
// Indicates a file has an associated index of dynamic variables
Description
Indicates a file has an associated index of dynamic variables
10.10.3.8
MPFS2_FLAG_ISZIPPED Macro
File
MPFS2.h
C
#define
MPFS2_FLAG_ISZIPPED ((WORD)0x0001)
// Indicates a file is compressed with GZIP compression
Description
Indicates a file is compressed with GZIP compression
10.10.3.9
MPFSStubs Variable
File
MPFS2.c
C
MPFS_STUB MPFSStubs[MAX_MPFS_HANDLES+1];
Description
Track the MPFS File Handles MPFSStubs[0] is reserved for internal use (FAT access)
292
10.10 MPFS2 Microchip TCP/IP Stack Help
10.10.3.10
MPFSTell Macro
File
MPFS2.h
C
#define
MPFSTell(a) MPFSGetPosition(a)
Description
Alias of MPFSGetPosition ( see page 284)
10.10.3.11
ReadProgramMemory Function
File
MPFS2.h
C
DWORD ReadProgramMemory(
DWORD address
);
Description
Assembly function to read all three bytes of program memory for 16-bit parts
10.10.3.12
_LoadFATRecord Function
File
MPFS2.c
C static void
_LoadFATRecord(
WORD fatID
);
Returns
None
Description
Loads the FAT record for a specified handle.
Remarks
The FAT record will be stored in fatCache ( see page 294).
Preconditions
None
Parameters
Parameters
fatID
Description
the ID of the file whose FAT is to be loaded
MPFS2 Internal Members
293
10.10 MPFS2 Microchip TCP/IP Stack Help MPFS2 Internal Members
10.10.3.13
_Validate Function
File
MPFS2.c
C static void
_Validate();
Returns
None
Description
Verifies that the MPFS image is valid, and reads the number of available files from the image header. This function is called on boot, and again after any image is written.
Preconditions
None
10.10.3.14
MPFS_FAT_RECORD Structure
File
MPFS2.h
C typedef struct
{
DWORD string;
DWORD data;
DWORD len;
DWORD timestamp;
DWORD microtime;
WORD flags;
} MPFS_FAT_RECORD;
Members
Members
DWORD string;
DWORD data;
DWORD len;
DWORD timestamp;
DWORD microtime;
WORD flags;
Description
Stores the data for an MPFS2 FAT record
Description
Pointer to the file name
Address ( see page 152) of the file data
Length of file data
Timestamp of file
Microtime stamp of file
Flags for this file
10.10.3.15
fatCache Variable
File
MPFS2.c
C
294
10.11 NBNS
Description
FAT record cache
Microchip TCP/IP Stack Help
10.10.3.16
fatCacheID Variable
File
MPFS2.c
C
WORD fatCacheID;
Description
ID of currently loaded fatCache ( see page 294)
10.10.3.17
numFiles Variable
File
MPFS2.c
C
WORD numFiles;
Description
Number of files in this MPFS image
10.10.3.18
MPFS_INVALID_FAT Macro
File
MPFS2.h
C
#define
MPFS_INVALID_FAT (0xffffu)
// Indicates an invalid FAT cache
Description
Indicates an invalid FAT cache
NBNS Stack Members
10.11
NBNS
The NetBIOS Name Service protocol associates host names with IP addresses, similarly to DNS, but on the same IP subnet.
Practically, this allows the assignment of human-name hostnames to access boards on the same subnet. For example. in the "TCPIP Demo App" demonstration project, the demo board is programmed with the human name ' mchpboard ' so it can be accessed directly instead of with its IP address.
295
10.11 NBNS Microchip TCP/IP Stack Help NBNS Stack Members
10.11.1
NBNS Stack Members
Functions
Name
Description
Reads the NetBIOS name from a UDP socket and copies it into a user-specified buffer.
Transmits the NetBIOS name across an open UDP socket.
NBNSTask ( see page 297) Sends responses to NetBIOS name requests
Macros
Name
Module
Description
NetBIOS Name Service port
Structures
Name
Description
NBNS Header structure
NBNS Header structure
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.11.1.1
NBNSGetName Function
File
NBNS.c
C static void
NBNSGetName(
BYTE * String
);
Side Effects
None
Returns
None
Description
Reads the NetBIOS name from a UDP socket and copies it into a user-specified buffer.
Remarks
None
Preconditions
None
296
10.11 NBNS
Parameters
Parameters
String
Microchip TCP/IP Stack Help NBNS Stack Members
Description
Pointer to an array into which a received NetBIOS name should be copied.
10.11.1.2
NBNSPutName Function
File
NBNS.c
C static void
NBNSPutName(
BYTE * String
);
Side Effects
None
Returns
None
Description
Transmits the NetBIOS name across an open UDP socket.
Remarks
None
Preconditions
None
Parameters
Parameters
String
Description
The name to transmit
10.11.1.3
NBNSTask Function
File
NBNS.h
C void
NBNSTask();
Side Effects
None
Returns
None
Description
Sends responses to NetBIOS name requests
Remarks
None
Preconditions
None
297
Performance Test Stack Members 10.12 Performance Tests Microchip TCP/IP Stack Help
10.11.1.4
NBNS_HEADER Structure
File
NBNS.c
C typedef struct
_NBNS_HEADER {
WORD_VAL TransactionID;
WORD_VAL Flags;
WORD_VAL Questions;
WORD_VAL Answers;
WORD_VAL AuthoritativeRecords;
WORD_VAL AdditionalRecords;
} NBNS_HEADER;
Description
NBNS Header structure
10.11.1.5
NBNS_PORT Macro
File
NBNS.c
C
#define
NBNS_PORT (137u)
Description
NetBIOS Name Service port
10.12
Performance Tests
The TCP and UDP Performance Test modules provide a method for obtaining metrics about the stack's performance. They can be used to benchmark the stack on various hardware platforms, and are also useful to determine how your custom application has affected stack performance.
The stack automatically calls these modules when they are included, so you never need to call any functions directly.
TCPTXPerformanceTask ( see page 301), and TCPRXPerformanceTask ( see page 300).
10.12.1
Performance Test Stack Members
Functions
Name Description
TCPPerformanceTask ( see page 299)
Tests the performance of the TCP module.
UDPPerformanceTask ( see page 299)
Tests the transmit performance of the UDP module.
298
10.12 Performance Tests Microchip TCP/IP Stack Help Performance Test Internal Members
Module
Performance Tests ( see page 298)
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.12.1.1
TCPPerformanceTask Function
File
TCPPerformanceTest.h
C void
TCPPerformanceTask();
Returns
None
Description
This function calls both TCPTXPerformanceTask (
see page 301) and TCPRXPerformanceTask ( see page 300) to
perform the performance task functions. Refer to the documentation for each of those functions for details.
Preconditions
TCP is initialized.
10.12.1.2
UDPPerformanceTask Function
File
UDPPerformanceTest.h
C void
UDPPerformanceTask();
Returns
None
Description
This function tests the transmit performance of the UDP module. At boot, this module will transmit 1024 large UDP broadcast packets of 1024 bytes each. Using a packet sniffer, one can determine how long this process takes and calculate the transmit rate of the stack. This function tests true UDP performance in that it will open a socket, transmit one packet, and close the socket for each loop. After this initial transmission, the module can be re-enabled by holding button 3.
This function is particularly useful after development to determine the impact of your application code on the stack's performance. A before and after comparison will indicate if your application is unacceptably blocking the processor or taking too long to execute.
Preconditions
UDP is initialized.
299
10.12 Performance Tests Microchip TCP/IP Stack Help Performance Test Internal Members
10.12.2
Performance Test Internal Members
Functions
Name
TCPRXPerformanceTask ( see page 300)
TCPTXPerformanceTask ( see page 301)
Description
Tests the receive performance of the TCP module.
Tests the transmit performance of the TCP module.
Macros
Name
PERFORMANCE_PORT ( see page 301)
Description
Which UDP port to broadcast from for the UDP tests
The TCP port to listen ( see page 180) on for TCP receive tests
The TCP port to listen ( see page 180) on for TCP transmit tests
Module
Performance Tests ( see page 298)
Description
The following functions and variables are designated as internal to the module.
10.12.2.1
TCPRXPerformanceTask Function
File
TCPPerformanceTest.c
C void
TCPRXPerformanceTask();
Returns
None
Description
This function tests the receive performance of the TCP module. To use, open a telnet connection to the device on
device. Each second the board will report back how many bytes were received in the previous second.
TCP performance is affected by many factors, including round-trip time and the TCP buffer size. For faster results, increase the size of the RX buffer size for the TCP_PURPOSE_TCP_PERFORMANCE_RX socket in TCPIPConfig.h. Round-trip time is affected by the distance to the device, so across the desk will be orders of magnitude faster than across the Internet.
This function is particularly useful after development to determine the impact of your application code on the stack's performance. A before and after comparison will indicate if your application is unacceptably blocking the processor or taking too long to execute.
Preconditions
TCP is initialized.
300
10.12 Performance Tests Microchip TCP/IP Stack Help Performance Test Internal Members
10.12.2.2
TCPTXPerformanceTask Function
File
TCPPerformanceTest.c
C void
TCPTXPerformanceTask();
Returns
None
Description
This function tests the transmit performance of the TCP module. To use, open a telnet connection to the device on
performance to the telnet client.
TCP performance is affected by many factors, including round-trip time and the TCP buffer size. For faster results, increase the size of the TX buffer size for the TCP_PURPOSE_TCP_PERFORMANCE_TX socket in TCPIPConfig.h. Round-trip time is affected by the distance to the device, so across the desk will be orders of magnitude faster than across the Internet.
This function is particularly useful after development to determine the impact of your application code on the stack's performance. A before and after comparison will indicate if your application is unacceptably blocking the processor or taking too long to execute.
Preconditions
TCP is initialized.
10.12.2.3
PERFORMANCE_PORT Macro
File
UDPPerformanceTest.c
C
#define
PERFORMANCE_PORT 9
Description
Which UDP port to broadcast from for the UDP tests
10.12.2.4
RX_PERFORMANCE_PORT Macro
File
TCPPerformanceTest.c
C
#define
RX_PERFORMANCE_PORT 9763
Description
The TCP port to listen ( see page 180) on for TCP receive tests
301
SMTP Client Examples 10.13 SMTP Client Microchip TCP/IP Stack Help
10.12.2.5
TX_PERFORMANCE_PORT Macro
File
TCPPerformanceTest.c
C
#define
TX_PERFORMANCE_PORT 9762
Description
The TCP port to listen ( see page 180) on for TCP transmit tests
10.13
SMTP Client
The SMTP client module in the TCP/IP Stack lets applications send e-mails to any recipient worldwide. These message could include status information or important alerts. Using the e-mail to SMS gateways provided by most cell phone carriers, these messages can also be delivered directly to cell phone handsets.
Using the SMTP client requires access to a local mail server (such as mail.yourdomain.com) for reliable operation. Your ISP or network administrator can provide the correct address, but end-user applications will need an interface to provide this data.
10.13.1
SMTP Client Examples
Module
Description
The following two examples demonstrate the use of the SMTP client in different scenarios. The first, and simpler example, sends a short message whose contents are all located in RAM at once.
The second example is more involved and demonstrates generating a message on the fly in the case where the entire message cannot fit into RAM at once. In this case, the message is started by the stack, but the delivery of the contents happens in pieces and is handled by the application.
10.13.1.1
SMTP Client Short Message Example
The SMTP client API is simplified when messages can be buffered entirely in RAM. The
example provided in
MainDemo.c
sends a brief e-mail message indicating the current status of the board's buttons. This document will walk through that example.
Make sure STACK_USE_SMTP_CLIENT is uncommented in
TCPIPConfig.h
before continuing.
The diagram below provides an overview of the process:
302
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Examples
FALSE is returned, the SMTP client is busy and the application must return to the main loop to allow StackTask to execute again.
Next, set the local relay server to use as SMTPClient.Server
. If the local relay server requires a user name and password, set
SMTPClient.Username
and
SMTPClient.Password
to the appropriate credentials.
If server parameters are not set, the stack will attempt to deliver the message directly to its destination host. This will likely fail due to spam prevention measures put in place by most ISPs and network administrators.
Continue on to set the header strings as necessary for the message. This includes the subject line, from address, and any recipients you need to add. Finally, set
SMTPClient.Body
to the message to be sent.
At this point, verify that
SMTPClient.ROMPointers
is correctly configured for any strings that are stored in program
transmission.
The application must now call SMTPIsBusy ( see page 310) until it returns
FALSE
. Each time
TRUE
is returned, return to the main loop and wait for StackTask to execute again. This allows the SMTP server to continue its work in a cooperative multitasking manner. Once FALSE
is returned, call SMTPEndUsage ( see page 309) to release the SMTP client. Check the
return value of this function to determine if the message was successfully sent.
The example in MainDemo.c
needs minor modifications to use your e-mail address. The Server and To fields must be set in
in order for the message to be properly delivered. Once this is done, holding down
BUTTON2 and BUTTON3 simultaneously (the left-most two buttons) will begin sending the message. LED1 will light as the message is being processed, and will extinguish when the SMTP state machine completes. If the transmission was successful LED2 will light, otherwise it will remain dark.
10.13.1.2
SMTP Client Long Message Example
The SMTP client API is capable of sending messages that do not fit entirely in RAM. To do so, the application must manage
its output state and only write as many bytes as are available in the buffer at a time. The second
example provided in
MainDemo.c
sends a message that is a dump of all contents of the PIC's RAM. This example is currently commented out. Comment out the previous Short Message Example and uncomment the Long Message Example.
This document will walk through sending a longer message.
Make sure STACK_USE_SMTP_CLIENT is uncommented in
TCPIPConfig.h
before continuing.
Sending longer messages is divided into three stages. The first stage configures the SMTP client to send the message. The second stage sends the message in small chunks as buffer space is available. The final stage finishes the transmission and determines whether or not the message was successful.
The diagram below illustrates the first stage:
303
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Examples
308) to verify that the SMTP client is available and to begin a new message. If
FALSE
is returned, the SMTP client is busy and the application must return to the main loop to allow StackTask to execute again.
Next, set the local relay server to use as
SMTPClient.Server
. If the local relay server requires a user name and password, set
SMTPClient.Username
and
SMTPClient.Password
to the appropriate credentials.
If server parameters are not set, the stack will attempt to deliver the message directly to its destination host. This will likely fail due to spam prevention measures put in place by most ISPs and network administrators.
Continue on to set the header strings as necessary for the message. This includes the subject line, from address, and any recipients you need to add.
The next portion of the process differs. Ensure that
SMTPClient.Body
remains set to its default (NULL). At this point, call
now ready to proceed to the second stage and send the message body.
The following diagram provides an overview of stage two and three:
how many bytes are available in the TX buffer. If no bytes are available, return to the main loop so that StackTask can transmit the data to the remote node and free up the buffer.
If space is available, any combination of the SMTPPut ( see page 311), SMTPPutArray ( see page 311),
see page 312), SMTPPutString ( see page 313), and SMTPPutROMString ( see page 313)
functions may be called to transmit the message. These functions return the number of bytes successfully written. Use this
304
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Public Members
the socket initializer for TCP_PURPOSE_DEFAULT type sockets in
TCPIPConfig.h
, which defaults to 200 bytes.
If the TX buffer is exhausted before the message is complete, return to the main loop so that StackTask may transmit the data to the remote node and free up the buffer. Upon return, go to the beginning of the second stage to transmit the next portion of the message.
TRUE is returned, return to the main loop and wait for StackTask to execute again. Once
FALSE
is returned, the message
Check the return value of this function to determine if the message was successfully sent.
The example in
MainDemo.c
needs minor modifications to use your e-mail address. Set the
Server
and
To
fields in
, and ensure that these fields are being properly assigned to SMTPClient ( see page
simultaneously (the left-most two buttons) kicking off the state machine. LED1 will light as the message is being processed, and will extinguish when the SMTP state machine completes. If the transmission was successful LED2 will light, otherwise it will remain dark.
10.13.2
SMTP Client Public Members
Functions
Name
SMTPBeginUsage ( see page 308)
Description
Requests control of the SMTP client module.
Releases control of the SMTP client module.
SMTPFlush ( see page 309) Flushes the SMTP socket and forces all data to be sent.
Determines if the SMTP client is busy.
SMTPIsPutReady ( see page 310)
Determines how much data can be written to the SMTP client.
Writes a single byte to the SMTP client.
Writes a series of bytes to the SMTP client.
Indicates that the on-the-fly message is complete.
SMTPPutROMArray ( see page 312)
SMTPPutROMString ( see page 313)
Writes a series of bytes from ROM to the SMTP client.
Writes a string from ROM to the SMTP client.
Writes a string to the SMTP client.
Initializes the message sending process.
Macros
Name
Description
Connection to SMTP server failed
305
10.13 SMTP Client Microchip TCP/IP Stack Help
Module
DNS lookup for SMTP server failed
Message was successfully sent
Structures
Name
Description
Configures the SMTP client to send a message
Variables
Name
Description
Description
The following functions and variables are available to the stack application.
SMTP Client Public Members
10.13.2.1
SMTP_CONNECT_ERROR Macro
File
SMTP.h
C
#define
SMTP_CONNECT_ERROR (0x8001u)
// Connection to SMTP server failed
Description
Connection to SMTP server failed
10.13.2.2
SMTP_POINTERS Structure
File
SMTP.h
C typedef struct
{
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Server;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Username;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Password;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} To;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} CC;
306
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Public Members
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} BCC;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} From;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Subject;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} OtherHeaders;
union
{
BYTE * szRAM;
ROM BYTE * szROM;
} Body;
struct
{
unsigned char
Server : 1;
unsigned char
Username : 1;
unsigned char
Password : 1;
unsigned char
To : 1;
unsigned char
CC : 1;
unsigned char
BCC : 1;
unsigned char
From : 1;
unsigned char
Subject : 1;
unsigned char
OtherHeaders : 1;
unsigned char
Body : 1;
} ROMPointers;
BOOL UseSSL;
} SMTP_POINTERS;
Description
This structure of pointers configures the SMTP Client to send an e-mail message. Initially, all pointers will be null. Set
SMTPClient ( see page 309).[field name].szRAM
to use a string stored in RAM, or
SMTPClient ( see page 309).[field name].szROM
to use a string stored in ROM. (Where
[field name]
is one of the parameters below.)
If a ROM string is specified,
SMTPClient.ROMPointers.[field name]
must also be set to 1 to indicate that this field should be retrieved from ROM instead of RAM.
Remarks
When formatting an e-mail address, the SMTP standard format for associating a printable name may be used. This format places the printable name in quotation marks, with the address following in pointed brackets, such as "John Smith"
Parameters
Parameters
Server
Username
Password
To
CC
BCC
From
Subject
Description
the SMTP server to relay the message through the user name to use when logging into the SMTP server, if any is required the password to supply when logging in, if any is required the destination address for this message. May be a comma-separated list of addresss, and/or formatted.
The CC addresses for this message, if any. May be a comma-separated list of addresss, and/or formatted.
The BCC addresses for this message, if any. May be a comma-separated list of addresss, and/or formatted.
The From address for this message. May be formatted.
The Subject header for this message.
307
10.13 SMTP Client
OtherHeaders
Body
ROMPointers
UseSSL
Microchip TCP/IP Stack Help SMTP Client Public Members
Any additional headers for this message. Each additional header, including the last one, must be terminated with a CRLF pair.
When sending a message from memory, the location of the body of this message in memory. Leave as NULL to build a message on-the-fly.
Indicates which parameters to read from ROM instead of RAM.
When STACK_USE_SSL_CLIENT is enabled, this flag causes the SMTP client to make an SSL connection to the server.
(WORD value) Indicates the port on which to connect ( see page 176) to the
remote SMTP server.
10.13.2.3
SMTP_RESOLVE_ERROR Macro
File
SMTP.h
C
#define
SMTP_RESOLVE_ERROR (0x8000u)
// DNS lookup for SMTP server failed
Description
DNS lookup for SMTP server failed
10.13.2.4
SMTP_SUCCESS Macro
File
SMTP.h
C
#define
SMTP_SUCCESS (0x0000u)
// Message was successfully sent
Description
Message was successfully sent
10.13.2.5
SMTPBeginUsage Function
File
SMTP.h
C
BOOL SMTPBeginUsage();
Description
Call this function before calling any other SMTP Client APIs. This function obtains a lock on the SMTP Client, which can only be used by one stack application at a time. Once the application is finished with the SMTP client, it must call
SMTPEndUsage ( see page 309) to release control of the module to any other waiting applications.
This function initializes all the SMTP state machines and variables back to their default state.
Preconditions
None
Return Values
Return Values
TRUE
Description
The application has successfully obtained control of the module
308
10.13 SMTP Client
FALSE
Section
SMTP Function Prototypes
Microchip TCP/IP Stack Help SMTP Client Public Members
The SMTP module is in use by another application. Call SMTPBeginUsage again later, after returning to the main program loop
10.13.2.6
SMTPClient Variable
File
SMTP.c
C
Section
SMTP Client Public Variables
************************************************************************
The global set of SMTP_POINTERS.
Set these parameters after calling SMTPBeginUsage successfully.
10.13.2.7
SMTPEndUsage Function
File
SMTP.h
C
WORD SMTPEndUsage();
Description
Call this function to release control of the SMTP client module once an application is finished using it. This function releases
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Return Values
Return Values
1-199 and 300-399
Description
A message was successfully sent
The SMTP server could not be resolved
The connection to the SMTP server failed or was prematurely terminated
The last SMTP server response code
10.13.2.8
SMTPFlush Function
File
SMTP.h
309
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Public Members
C void
SMTPFlush();
Returns
None
Description
Flushes the SMTP socket and forces all data to be sent.
Remarks
This function should only be called externally when the SMTP client is generating an on-the-fly message. (That is,
SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
10.13.2.9
SMTPIsBusy Function
File
SMTP.h
C
BOOL SMTPIsBusy();
Description
Call this function to determine if the SMTP client is busy performing background tasks. This function should be called after
see page 314), SMTPPutDone ( see page 312) to determine if the stack has finished
SMTP client has not prematurely disconnected. When this function returns FALSE, the next call should be to
SMTPEndUsage ( see page 309) to release the module and obtain the status code for the operation.
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Return Values
Return Values
TRUE
FALSE
Description
The SMTP Client is busy with internal tasks or sending an on-the-fly message.
The SMTP Client is terminated and is ready to be released.
10.13.2.10
SMTPIsPutReady Function
File
SMTP.h
C
WORD SMTPIsPutReady();
Returns
The number of free bytes the SMTP TX FIFO.
Description
Use this function to determine how much data can be written to the SMTP client when generating an on-the-fly message.
310
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Public Members
Remarks
This function should only be called externally when the SMTP client is generating an on-the-fly message. (That is,
SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
Preconditions
requires that SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.
10.13.2.11
SMTPPut Function
File
SMTP.h
C
BOOL SMTPPut(
BYTE c
);
Description
Writes a single byte to the SMTP client.
Remarks
This function should only be called externally when the SMTP client is generating an on-the-fly message. (That is,
SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Parameters
Parameters
c
Return Values
Return Values
TRUE
FALSE
Description
The byte to be written
Description
The byte was successfully written
The byte was not written, most likely because the buffer was full
10.13.2.12
SMTPPutArray Function
File
SMTP.h
C
WORD SMTPPutArray(
BYTE* Data,
WORD Len
);
Returns
The number of bytes written. If less than Len, then the TX FIFO became full before all bytes could be written.
Description
Writes a series of bytes to the SMTP client.
311
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Public Members
Remarks
This function should only be called externally when the SMTP client is generating an on-the-fly message. (That is,
SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
Internal
replaced by "rn..".
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Parameters
Parameters
Data
Len
Description
The data to be written
How many bytes should be written
10.13.2.13
SMTPPutDone Function
File
SMTP.h
C void
SMTPPutDone();
Returns
None
Description
Indicates that the on-the-fly message is complete.
Preconditions
message. (That is, SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
10.13.2.14
SMTPPutROMArray Function
File
SMTP.h
C
WORD SMTPPutROMArray(
ROM BYTE* Data,
WORD Len
);
Returns
The number of bytes written. If less than Len, then the TX FIFO became full before all bytes could be written.
Description
Writes a series of bytes from ROM to the SMTP client.
Remarks
This function should only be called externally when the SMTP client is generating an on-the-fly message. (That is,
SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
312
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Public Members
This function is aliased to SMTPPutArray ( see page 311) on non-PIC18 platforms.
Internal
replaced by "rn..".
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Parameters
Parameters
Data
Len
Description
The data to be written
How many bytes should be written
10.13.2.15
SMTPPutROMString Function
File
SMTP.h
C
WORD SMTPPutROMString(
ROM BYTE* Data
);
Returns
The number of bytes written. If less than the length of Data, then the TX FIFO became full before all bytes could be written.
Description
Writes a string from ROM to the SMTP client.
Remarks
This function should only be called externally when the SMTP client is generating an on-the-fly message. (That is,
SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
This function is aliased to SMTPPutString ( see page 313) on non-PIC18 platforms.
Internal
replaced by "rn..".
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Parameters
Parameters
Data
Description
The data to be written
10.13.2.16
SMTPPutString Function
File
SMTP.h
C
WORD SMTPPutString(
BYTE* Data
);
313
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Stack Members
Returns
The number of bytes written. If less than the length of Data, then the TX FIFO became full before all bytes could be written.
Description
Writes a string to the SMTP client.
Remarks
This function should only be called externally when the SMTP client is generating an on-the-fly message. (That is,
SMTPSendMail ( see page 314) was called with SMTPClient.Body set to NULL.)
Internal
replaced by "rn..".
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Parameters
Parameters
Data
Description
The data to be written
10.13.2.17
SMTPSendMail Function
File
SMTP.h
C void
SMTPSendMail();
Returns
None
Description
This function starts the state machine that performs the actual transmission of the message. Call this function after all the
fields in SMTPClient ( see page 309) have been set.
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
10.13.3
SMTP Client Stack Members
Functions
Name Description
SMTPTask ( see page 315) Performs any pending SMTP client tasks
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
314
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Internal Members
10.13.3.1
SMTPTask Function
File
SMTP.h
C void
SMTPTask();
Returns
None
Description
This function handles periodic tasks associated with the SMTP client, such as processing initial connections and command sequences.
Remarks
This function acts as a task (similar to one in an RTOS). It performs its task in a co-operative manner, and the main application must call this function repeatedly to ensure that all open or new connections are served in a timely fashion.
Preconditions
None
10.13.4
SMTP Client Internal Members
Functions
Name
FindEmailAddress ( see page 316)
FindROMEmailAddress ( see page 317)
Description
Searches a string for an e-mail address.
Searches a ROM string for an e-mail address.
Macros
Name
Description
Default port to use when unspecified
Module
Variables
How long to wait before assuming the connection has been dropped
(default 8 seconds)
Name Description
Socket currently in use by the SMTP client
State machine for writing the SMTP message headers
PutHeadersState ( see page 317)
Response code from server when an error exists
State machine for parsing incoming responses
315
10.13 SMTP Client Microchip TCP/IP Stack Help SMTP Client Internal Members
SMTPFlags ( see page 319) Internal flags used by the SMTP Client
IP address of the remote SMTP server
SMTPState ( see page 320) Message state machine for the SMTP Client
State of the transport for the SMTP Client
Description
The following functions and variables are designated for internal use by the SMTP Client module.
10.13.4.1
CRPeriod Variable
File
SMTP.c
C union
{
BYTE * Pos;
enum
{
CR_PERIOD_SEEK_CR = 0,
CR_PERIOD_SEEK_LF,
CR_PERIOD_SEEK_PERIOD,
CR_PERIOD_NEED_INSERTION
} State;
} CRPeriod;
Members
Members
CR_PERIOD_SEEK_CR = 0
CR_PERIOD_SEEK_LF
CR_PERIOD_SEEK_PERIOD
CR_PERIOD_NEED_INSERTION
Description
Idle state, waiting for 'r r" has been written, so check next byte for 'n rn" has been written, so check next byte for '.
"rn." has been written, so an additional '.' must be written before the next byte.
Description
"rn.."
10.13.4.2
FindEmailAddress Function
File
SMTP.c
C static
BYTE * FindEmailAddress(
BYTE * str,
WORD * wLen
);
Returns
A pointer to the e-mail address
Description
This function locates an e-mail address in a string. It is used internally by the SMTP client to parse out the actual address from the From and To strings so that the MAIL FROM and RCPT TO commands can be sent to the SMTP server.
316
10.13 SMTP Client Microchip TCP/IP Stack Help
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Parameters
Parameters
str wLen
Section
SMTP Client Internal Function Prototypes
Description
The string in which to search for an e-mail address the length of str
SMTP Client Internal Members
10.13.4.3
FindROMEmailAddress Function
File
SMTP.c
C static
ROM BYTE * FindROMEmailAddress(
ROM BYTE * str,
WORD * wLen
);
Returns
A pointer to the e-mail address
Description
This function locates an e-mail address in a string. It is used internally by the SMTP client to parse out the actual address from the From and To strings so that the MAIL FROM and RCPT TO commands can be sent to the SMTP server.
Preconditions
SMTPBeginUsage ( see page 308) returned TRUE on a previous call.
Parameters
Parameters
str wLen
Description
The ROM string in which to search for an e-mail address the length of str
10.13.4.4
MySocket Variable
File
SMTP.c
C
TCP_SOCKET MySocket = INVALID_SOCKET;
Description
Socket currently in use by the SMTP client
10.13.4.5
PutHeadersState Variable
File
SMTP.c
317
10.13 SMTP Client Microchip TCP/IP Stack Help
C enum
{
PUTHEADERS_FROM_INIT = 0,
PUTHEADERS_FROM,
PUTHEADERS_TO_INIT,
PUTHEADERS_TO,
PUTHEADERS_CC_INIT,
PUTHEADERS_CC,
PUTHEADERS_SUBJECT_INIT,
PUTHEADERS_SUBJECT,
PUTHEADERS_OTHER_INIT,
PUTHEADERS_OTHER,
PUTHEADERS_DONE
} PutHeadersState;
Members
Members
PUTHEADERS_FROM_INIT = 0
PUTHEADERS_FROM
PUTHEADERS_TO_INIT
PUTHEADERS_TO
PUTHEADERS_CC_INIT
PUTHEADERS_CC
PUTHEADERS_SUBJECT_INIT
PUTHEADERS_SUBJECT
PUTHEADERS_OTHER_INIT
PUTHEADERS_OTHER
PUTHEADERS_DONE
Description
Preparing to send From header
Sending From header
Preparing to send To header
Sending To header
Preparing to send CC header
Sending CC header
Preparing to send Subject header
Sending Subject header
Preparing to send additional headers
Sending additional headers
Done writing all headers
Description
State machine for writing the SMTP message headers
10.13.4.6
ResponseCode Variable
File
SMTP.c
C
WORD ResponseCode;
Description
Response code from server when an error exists
10.13.4.7
RXParserState Variable
File
SMTP.c
C enum
{
RX_BYTE_0 = 0,
RX_BYTE_1,
RX_BYTE_2,
RX_BYTE_3,
RX_SEEK_CR,
RX_SEEK_LF
SMTP Client Internal Members
318
10.13 SMTP Client
} RXParserState;
Description
State machine for parsing incoming responses
Microchip TCP/IP Stack Help SMTP Client Internal Members
10.13.4.8
SMTP_PORT Macro
File
SMTP.c
C
#define
SMTP_PORT 25
// Default port to use when unspecified
Description
Default port to use when unspecified
10.13.4.9
SMTP_SERVER_REPLY_TIMEOUT Macro
File
SMTP.c
C
#define
SMTP_SERVER_REPLY_TIMEOUT (TICK_SECOND*8)
// How long to wait before assuming the connection has been dropped (default 8 seconds)
Description
How long to wait before assuming the connection has been dropped (default 8 seconds)
10.13.4.10
SMTPFlags Variable
File
SMTP.c
C union
{
BYTE Val;
struct
{
unsigned char
RXSkipResponse : 1;
unsigned char
SMTPInUse : 1;
unsigned char
SentSuccessfully : 1;
unsigned char
ReadyToStart : 1;
unsigned char
ReadyToFinish : 1;
unsigned char
ConnectedOnce : 1;
unsigned char
filler : 2;
} bits;
} SMTPFlags;
Description
Internal flags used by the SMTP Client
10.13.4.11
SMTPServer Variable
File
SMTP.c
319
10.13 SMTP Client
C
IP_ADDR SMTPServer;
Description
IP address of the remote SMTP server
Microchip TCP/IP Stack Help SMTP Client Internal Members
10.13.4.12
SMTPState Variable
File
SMTP.c
C enum
{
SMTP_HOME = 0,
SMTP_HELO,
SMTP_HELO_ACK,
SMTP_AUTH_LOGIN,
SMTP_AUTH_LOGIN_ACK,
SMTP_AUTH_USERNAME,
SMTP_AUTH_USERNAME_ACK,
SMTP_AUTH_PASSWORD,
SMTP_AUTH_PASSWORD_ACK,
SMTP_MAILFROM,
SMTP_MAILFROM_ACK,
SMTP_RCPTTO_INIT,
SMTP_RCPTTO,
SMTP_RCPTTO_ACK,
SMTP_RCPTTO_ISDONE,
SMTP_RCPTTOCC_INIT,
SMTP_RCPTTOCC,
SMTP_RCPTTOCC_ACK,
SMTP_RCPTTOCC_ISDONE,
SMTP_RCPTTOBCC_INIT,
SMTP_RCPTTOBCC,
SMTP_RCPTTOBCC_ACK,
SMTP_RCPTTOBCC_ISDONE,
SMTP_DATA,
SMTP_DATA_ACK,
SMTP_DATA_HEADER,
SMTP_DATA_BODY_INIT,
SMTP_DATA_BODY,
SMTP_DATA_BODY_ACK,
SMTP_QUIT_INIT,
SMTP_QUIT
} SMTPState;
Members
Members
SMTP_HOME = 0
SMTP_HELO
SMTP_HELO_ACK
SMTP_AUTH_LOGIN
SMTP_AUTH_LOGIN_ACK
SMTP_AUTH_USERNAME
SMTP_AUTH_USERNAME_ACK
SMTP_AUTH_PASSWORD
SMTP_AUTH_PASSWORD_ACK
SMTP_MAILFROM
SMTP_MAILFROM_ACK
SMTP_RCPTTO_INIT
Description
Idle start state for SMTP client (application is preparing message)
HELO is being sent to server
Received an ACK for the HELO
Requesting to log in
Log in request accepted
Sending user name
User name accepted
Sending password
Password was accepted
Sending inital MAIL FROM command
MAIL FROM was accepted
Preparing to send RCPT TO
320
10.14 Reboot Microchip TCP/IP Stack Help
SMTP_RCPTTO
SMTP_RCPTTO_ACK
SMTP_RCPTTO_ISDONE
SMTP_RCPTTOCC_INIT
SMTP_RCPTTOCC
SMTP_RCPTTOCC_ACK
SMTP_RCPTTOCC_ISDONE
SMTP_RCPTTOBCC_INIT
SMTP_RCPTTOBCC
SMTP_RCPTTOBCC_ACK
SMTP_RCPTTOBCC_ISDONE
SMTP_DATA
SMTP_DATA_ACK
SMTP_DATA_HEADER
SMTP_DATA_BODY_INIT
SMTP_DATA_BODY
SMTP_DATA_BODY_ACK
SMTP_QUIT_INIT
SMTP_QUIT
Description
Message state machine for the SMTP Client
Sending RCPT TO command
RCPT TO was accepted
Done sending RCPT TO commands
Preparing to send RCPT TO CC commands
Sending RCPT TO CC commands
RCPT TO CC was accepted
Done sending RCPT TO CC
Preparing to send RCPT TO BCC commands
Sending RCPT TO BCC commands
RCPT TO BCC was accepted
Done sending RCPT TO BCC
Sending DATA command
DATA command accpted
Sending message headers
Preparing for message body
Sending message body
Message body accepted
Sending QUIT command
QUIT accepted, connection closing
10.13.4.13
TransportState Variable
File
SMTP.c
C enum
{
TRANSPORT_HOME = 0,
TRANSPORT_BEGIN,
TRANSPORT_NAME_RESOLVE,
TRANSPORT_OBTAIN_SOCKET,
TRANSPORT_SECURING_SOCKET,
TRANSPORT_SOCKET_OBTAINED,
TRANSPORT_CLOSE
} TransportState;
Members
Members
TRANSPORT_HOME = 0
TRANSPORT_BEGIN
TRANSPORT_NAME_RESOLVE
TRANSPORT_OBTAIN_SOCKET
TRANSPORT_SECURING_SOCKET
TRANSPORT_SOCKET_OBTAINED
TRANSPORT_CLOSE
Description
State of the transport for the SMTP Client
Description
Idle state
Preparing to make connection
Resolving the SMTP server address
Obtaining a socket for the SMTP connection
Securing the socket for the SMTP over SSL connection
SMTP connection successful
STMP socket is closed
321
10.14 Reboot Microchip TCP/IP Stack Help Reboot Stack Members
10.14
Reboot
The Reboot module will allow a user to remotely reboot the PIC microcontroller that is running the TCP/IP stack. This feature is primarily used for bootloader applications, which must reset the microcontroller to enter the bootloader code section. This module will execute a task that listens on a specified UDP port for a packet, and then reboots if it receives one. The port can be configured in
Reboot.c
with the following macro:
For improved security, you can limit reboot capabilities to users on the same subnet by specifying the following macro in
Reboot.c:
#define REBOOT_SAME_SUBNET_ONLY
10.14.1
Reboot Stack Members
Functions
Name Description
Macros
Name Description
REBOOT_PORT ( see page 323) UDP TFTP port
For improved security, you might want to limit reboot capabilities to only users on the same IP subnet. Define REBOOT_SAME_SUBNET_ONLY to enable this access restriction.
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.14.1.1
RebootTask Function
File
Reboot.h
C void
RebootTask();
Side Effects
None
Returns
None
Description
Checks for incomming traffic on port 69. Resets the PIC if a 'R' is received.
322
10.15 SNMP Microchip TCP/IP Stack Help
Remarks
This module is primarily for use with the Ethernet bootloader. By resetting, the Ethernet bootloader can take control for a second and let a firmware upgrade take place.
Preconditions
Stack is initialized()
10.14.1.2
REBOOT_PORT Macro
File
Reboot.c
C
#define
REBOOT_PORT 69
// UDP TFTP port
Description
UDP TFTP port
10.14.1.3
REBOOT_SAME_SUBNET_ONLY Macro
File
Reboot.c
C
#define
REBOOT_SAME_SUBNET_ONLY
Description
For improved security, you might want to limit reboot capabilities to only users on the same IP subnet. Define
REBOOT_SAME_SUBNET_ONLY to enable this access restriction.
10.15
SNMP
Files
Name
Description
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
323
10.15 SNMP
Microchip TCP/IP Stack Help
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
• Simple Network Management Protocol (SNMP) Version 1 Agent
• Simple Network Management Protocol (SNMP) Version 2 community based Agent
• Module for Microchip TCP/IP Stack
• -Provides SNMP API for doing stuff
*
• -Reference: RFC 1157 (for SNMP V1)
• RFC 3416 (for SNMPv2C)
• SNMP Defs for Microchip TCP/IP Stack
*
Functions
Name
_IsSNMPv3ValidStructure ( see page 379)
_Snmpv3IsValidAuthStructure ( see page 379)
_Snmpv3IsValidInt ( see page 380)
FindOIDsFromSnmpV3Request ( see page 381) getSnmpV2GenTrapOid ( see page 381)
IsSnmpV3ASNNull ( see page 382)
IsSnmpv3ValidOID ( see page 382)
IsSNMPv3ValidStructure ( see page 383)
ProcessGetBulkVar ( see page 383)
ProcessGetNextVar ( see page 384)
Description
Decode variable length structure.
Decode variable length structure.
Verifies variable datatype as INT and retrieves its value.
Finds number of varbinds in the varbind list received in a SNMPv3 pdu.
Resolves generic trap code to generic trap OID.
Verifies the value type as ASN_NULL ( see page 349).
Populates OID type, length and oid string from the received pdu.
Decode variable length structure.
This routine process the SNMPv2c Get Bulk Request.
Retrieves next node from the MIB database.
324
10.15 SNMP Microchip TCP/IP Stack Help
ProcessSnmpv3MsgData ( see page 385)
SNMPGetExactIndex ( see page 386)
SNMPIdRecrdValidation ( see page 386)
SNMPIsValidSetLen ( see page 387)
Processes snmp Get request pdu.
This routine processes the snmpv3 request and parallely creates the response pdu.
To search for exact index node in case of a Sequence variable.
Used to Restrict the access dynamic and non dynamic
OID string for A perticular SNMP Version.
Validates the set variable data length to data type.
Snmpv3AESDecryptRxedScopedPdu ( see page
Snmpv3AESEncryptResponseScopedPdu ( see page 388)
Incoming SNMPv3 scoped PDU decryption using AES decryption protocol.
outGoing SNMPv3 scoped PDU Encryption using AES encryption protocol.
Snmpv3AuthenticateRxedPduForDataIntegrity ( see page 389)
Authenticate an incoming SNMPV3 USM PDU using
MD5 or SHA
Snmpv3AuthenticateTxPduForDataIntegrity ( see page 389)
Authenticate to an outgoing SNMPV3 USM PDU using
MD5 or SHA
Snmpv3AuthKeyZeroing2HmacBufLen64 ( see page 390)
Snmpv3BufferPut ( see page 390)
Pad zero to the authentication key localized buffer.
Copies BYTE data to dynamically allocated memory buffer.
Snmpv3CmprTrapSecNameAndSecLvlWithUSMDb
Routine to find the index of the user name in the user data base table.
Snmpv3ComputeHMACIpadOpadForAuthLoclzedKey
Compute HMAC inner and outer pad for authorization localized key.
Snmpv3ComputeHmacMD5Digest ( see page 392)
Compute HMAC - MD5 authentication code
Snmpv3ComputeHmacShaDigest ( see page 393)
Compute HMAC - SHA authentication code
Snmpv3ComputeMd5HmacCode ( see page 393)
Compute HMAC - MD5 authentication code
Snmpv3ComputeShaHmacCode ( see page 394)
Snmpv3FormulateEngineID ( see page 394)
Snmpv3FreeDynAllocMem ( see page 395)
Snmpv3GetAuthEngineTime ( see page 395)
Compute HMAC - SHA authentication code
Formulates the snmpEngineID ( see page 433) for the
SNMPV3 engine.
Allocated dynamic memory freeing is done by this routine.
Updates the snmp engine time variable
'snmpEngineTime ( see page 434)' for the SNMPV3
engine.
Snmpv3GetBufferData ( see page 396)
Snmpv3GetSecurityLevel ( see page 396)
Snmpv3GetTrapSecurityLevel ( see page 397)
Reads BYTE data from dynamically allocated memory buffer.
Get Security level from authentication and Privacy type.
Routine to find the report, auth and privacy flags settings in the TRAP.
Snmpv3InitializeUserDataBase ( see page 398)
Snmpv3IsValidAuthStructure ( see page 398)
Snmpv3IsValidInt ( see page 399)
Snmpv3MsgProcessingModelProcessPDU ( see page 399)
SNMPv3 initialization.
Intialize default SNMPv3 global user database.
Decode variable length structure.
Verifies variable datatype as INT and retrieves its value.
This routine collects or populates the message processing model infomation from the received
SNMPv3 request PDU or to the response PDU respectively.
Creates and Sends SNMPv3 TRAP pdu.
Snmpv3Pswd2LocalizedAuthKeyMD5Hashing ( see page 400)
Convert MD5 Auth password to the localized Key using
SNMPEngineID.
Snmpv3Pswd2LocalizedAuthKeySHAHashing ( see page 401)
Convert SHA Auth password to the localized Key using
SNMPEngineID.
325
10.15 SNMP Microchip TCP/IP Stack Help
Snmpv3ReportPdu ( see page 401)
Snmpv3ScopedPduProcessing ( see page 402)
Snmpv3SetErrorStatus ( see page 402)
Snmpv3TrapScopedpdu ( see page 403)
Snmpv3UserSecurityModelProcessPDU ( see page
Constructs the report pdu infomration for the Report
Pdu.
This routine collects the scoped pdu header information from the received SNMPv3 request PDU or populates to the response PDU respectively.
Set snmpv3 error status in the response pdu.
TRAP PDU scoped pdu header construction.
This routine collects or populates the security model parametrs infomation from the received SNMPv3 request PDU or to the response PDU respectively.
AES Encryption and decryption init vector.(RFC 3826 )
Snmpv3UsmAesEncryptDecryptInitVector ( see page 404)
Snmpv3UsmOutMsgAuthenticationParam ( see page 405)
Snmpv3USMOutMsgPrivParam ( see page 405)
Snmpv3UsmSnmpEngnAuthPrivPswdLocalization ( see page 405)
Snmpv3ValidateEngineId ( see page 406)
Snmpv3ValidateSecNameAndSecLvl ( see page
Snmpv3ValidateSecurityName ( see page 407)
Both MD5 and SHA1 is used for the outgoing message authentication.
SNMP USM out message uses Privacy protocol (RFC
3826 )
Convert Auth and Priv password to the localized Key using SNMPEngineID.
Validate engine ID.
Vaidate security name with Security level.
Validate SNMPV3 user name or security name.
Macros
Name
AUTH_LOCALIZED_PASSWORD_KEY_LEN ( see page 439)
IS_SNMPV3_AUTH_STRUCTURE ( see page 440)
MSG_AUTHORITATIVE_HEADER_LEN ( see page 440)
Description
SNMPv3 Authentication ( see page 91)
Localized passwed key lenegth size
This is macro INVALID_INDEX.
This is macro
IS_SNMPV3_AUTH_STRUCTURE.
Length of SNMPv3 authoratative msg header length = Header length ( 2 + 2
bytes) + engineID ( snmpEngnIDLength
• engine boot( 4 bytes)+ engine time(4 bytes)
+security name
(securityPrimitivesOfIncomingPdu ( see page 432) value) +authentication
parameters
(snmpOutMsgAuthParamLen ( see page 436) value) +privacy parameters
(snmpOutMsgAuthParamLen ( see page 436) value)
326
10.15 SNMP Microchip TCP/IP Stack Help
MSGGLOBAL_HEADER_LEN ( see page 440)
Length of the SNMPv3 msg header(x) =
Header length (2 bytes)
• MSGID size (type(1 byte) + length of value(1 byte)+4 bytes value)
• msgMAXSIZE(type + length of value +4 bytes value)
• msg flag(type + length of value +1 byte value)
• security model type(type + length of value +1 byte value)
PRIV_LOCALIZED_PASSWORD_KEY_LEN ( see page 441)
REPORT_RESPONSE ( see page 441)
SNMP_ENGINE_MAX_MSG_SIZE ( see page 441)
SNMPV3MSG_AUTHENTICATION_SUCCESS ( see page 444)
USER_SECURITY_NAME_LEN ( see page 444)
#define
PRIV_LOCALIZED_PASSWORD_KEY_
LEN
16 SNMPv3 Privacy Pasword key length size
This is macro REPORT_RESPONSE.
SNMP_ENGINE_MAX_MSG_SIZE is determined as the minimum of the max msg size values supported among all of the transports available to and supported by the engine.
SNMP_MAX_MSG_SIZE ( see page 441)
SNMP_MAX_OID_LEN_MEM_USE ( see page 442)
SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE ( see page
SNMP MIN and MAX message 484 bytes in size As per RFC 3411
snmpEngineMaxMessageSize ( see page 433) and RFC 1157 ( section 4-
protocol specification ) and implementation supports more than 484 whenever feasible.
This macro will be used to avoid SNMP
OID memory buffer corruption
This macro will be used to avoid SNMP
OID memory buffer corruption
This is macro SNMP_V3.
SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
SNMPv3 authentication localized Key length for memory validation
SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE ( see page
SNMPV3_USM_MAX_USER ( see page 443)
This is macro SNMPV3_H.
SNMPv3 privacy key length size for memory validation
User security name length for memory validation
User Security Model should have atleast
1 user. Default is 3. User should change as per the requirement.
SNMPV3MSG_AUTHENTICATION_FAIL ( see page 444)
This is macro
SNMPV3MSG_AUTHENTICATION_FAI
L.
This is macro
SNMPV3MSG_AUTHENTICATION_SU
CCESS.
SNMPv3 User Security Name length
327
10.15 SNMP Microchip TCP/IP Stack Help
Structs, Records, Enums
Name
AccessCtrlSubSysIsAccessAllowed ( see page 408)
Description
Applications are the typical clients of the service(s) of the Access
Control Subsystem. The following primitive is provided by the
Access Control Subsystem to check if access is allowed:
statusInformation ( see page 422) = -- success or errorIndication
dispatcherProcessPdu ( see page 409) Process Incoming Request or Notification PDU
Dispatcher provides the following primitive to pass an incoming snmp pdu to an application.
dispatcherStatusInfo ( see page 409)
Generate Outgoing Request or Notification
statusInformation ( see page 422) = -- sendPduHandle if success --
errorIndication if failure
dispathcerReturnResponsePdu ( see page 410)
MsgProcModPrepareDataElements ( see page 411)
MsgProcModPrepareOutgoingMessage
Generate Outgoing Response
The PDU Dispatcher provides the following primitive for an application to return an SNMP Response PDU to the PDU
Dispatcher: result = SUCCESS or FAILURE
Prepare Data Elements from an Incoming SNMP Message
The Message Processing Subsystem provides this service primitive for preparing the abstract data elements from an incoming SNMP message: result = -- SUCCESS or errorIndication
Prepare Outgoing SNMP Request or Notification Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Request or Notification Message
MsgProcModPrepareResponseMessage
Prepare an Outgoing SNMP Response Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Response Message: result = --
SUCCESS or FAILURE
processResponsePdu ( see page 413) Process Incoming Response PDU
The PDU Dispatcher provides the following primitive to pass an incoming SNMP Response PDU to an application: success or errorIndication
registerContextEngineID ( see page
SecuritySysGenerateRequestMsg ( see page 414)
This is record SecuritySysGenerateRequestMsg.
SecuritySysGenerateResponseMsg ( see page 415)
unregisterContextEngineID ( see page
Generate a Response Message
The Security Subsystem provides the following primitive to generate a Response message:
Release State Reference Information
All Subsystems which pass stateReference information also provide a primitive to release the memory that holds the referenced state information
This is record unregisterContextEngineID.
Types
Name
INOUT_SNMP_PDU ( see page 417)
REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS ( see page 417)
SecuritySysProcessIncomingMsg ( see page 418)
SNMP_ENGNID_OCTET_IDENTIFIER_VAL ( see page
SNMPNONMIBRECDINFO ( see page 419)
Description
This is type INOUT_SNMP_PDU.
This is type
REPORT_FLAG_AND_SECURITY_LEVEL_FLAG
S.
This is type SecuritySysProcessIncomingMsg.
The fifth octet indicates how the rest (6th and following octets) are formatted. Refer to RFC3411 section5 Page# 41
This is type SNMPNONMIBRECDINFO.
328
10.15 SNMP Microchip TCP/IP Stack Help
SNMPV3_HMAC_HASH_TYPE ( see page 419)
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT ( see page 420)
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT ( see page 420)
SNMPV3_PRIV_PROT_TYPE ( see page 420)
Type of hash being calculated
This is type
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT.
This is type
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT.
This is type SNMPV3_PRIV_PROT_TYPE.
SNMPV3_REQUEST_WHOLEMSG ( see page 421)
SNMPV3_RESPONSE_WHOLEMSG ( see page 421) snmpV3EngnUserDataBase ( see page 421)
This is type SNMPV3_REQUEST_WHOLEMSG.
This is type SNMPV3_RESPONSE_WHOLEMSG.
This is type snmpV3EngnUserDataBase.
SNMPv3 snmpv3 target configuration with respect to trap.
success or errorIndication
STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL
This is type
STD_BASED_SNMP_MESSAGE_PROCESSING
_MODEL.
Snmp Message Processing Model
STD_BASED_SNMP_SECURITY_MODEL ( see page
STD_BASED_SNMPV3_SECURITY_LEVEL ( see page
USM_SECURITY_LEVEL ( see page 424)
This is type
STD_BASED_SNMPV3_SECURITY_LEVEL.
This is type USM_SECURITY_LEVEL.
Variables
Name
authKey_iPad ( see page 426) authKey_oPad ( see page 426)
Description
This is variable authKey_iPad.
This is variable authKey_oPad.
authoritativeSnmpEngineBoots ( see page 426)
The number of times that the authoritative SNMP engine has
(re-)initialized itself since its snmpEngineID ( see page 433) was
last configured.
The number of seconds since the value of the
authoritativeSnmpEngineBoots ( see page 426) object last changed
This is variable cipher_text.
This is variable deciphered_text.
getZeroInstance ( see page 427)
This variable is used for gext next request for zero instance
gSnmpV3InPduWholeMsgBuf ( see page 427)
Dynamic memory stub and PDU details for Incoming stored PDU
gSnmpV3OUTPduWholeMsgBuf ( see page 428)
Dynamic memory stub details and constructed outgoing stored PDU details
gSNMPv3PduHeaderBuf ( see page
Response PDU construction offset details
gSNMPv3ScopedPduDataPos ( see page 428) gSNMPv3ScopedPduRequestBuf ( see page 428)
gSNMPv3ScopedPduResponseBuf ( see page 429) gSnmpv3TrapConfigData ( see page
429) gSNMPv3TrapMsgHeaderBuf ( see page 429) gSnmpV3TrapOUTPduWholeMsgBuf
Offset to read scoped PDU data bytes for processing from dynamic memory stub
Stored request scoped pdu details
Processed response scoped pdu details
SNMPv3 global configuration database to be used for trap notification
TRAP message PDU header construction offset details
Dynamic memory stub details and constructed trap PDU details
329
10.15 SNMP Microchip TCP/IP Stack Help
gSNMPv3TrapScopedPduResponseBuf
TRAP scoped PDU construction offset details
This is variable gSNMPV3TrapSecurityLevel.
gSNMPV3TrapSecurityLevel ( see page 430) gSnmpv3UserDBIndex ( see page
Index to the particular reference configured in User security model
data base snmpV3UserDataBase ( see page 437).
gUsmStatsEngineID ( see page 430)
Global variable to find out how many times SNMPv3 engine id has been validated
hmacAuthKeyBuf ( see page 430)
This is variable hmacAuthKeyBuf.
HmacSHADigest ( see page 431) incomingPdu ( see page 431) incomingSnmpPDUmsgID ( see page
This is variable HmacMd5Digest.
This is variable HmacSHADigest.
Incoming PDU details
Retrived Incoming Msg ID value from PDU
ivEncrptKeyOut ( see page 431)
This is variable ivEncrptKeyOut.
md5LocalizedAuthKey ( see page 432) This is variable md5LocalizedAuthKey.
msgSecrtyParamLenOffset ( see page
This is variable msgSecrtyParamLenOffset.
Incoming PDU Security primitive details.
securityPrimitivesOfIncomingPdu ( see page 432) session_key ( see page 432)
This is variable session_key.
This is variable sha1LocalizedAuthKey.
sha1LocalizedAuthKey ( see page
433) snmpEngineBoots ( see page 433)
The number of times that the SNMP engine has (re-)initialized itself
since snmpEngineID ( see page 433) was last configured.
Reserving 32 bytes for the snmpEngineID as the octet string length can vary form 5 to 32
The maximum message size the SNMP engine can handle.
snmpEngineMaxMessageSize ( see page 433) snmpEngineMsgProcessModel ( see page 433)
Type of Message processing model used. Value Maximum range
(2^31-1), RFC3411
snmpEngineSecurityModel ( see page
Type of security model used. Value Maximum range (2^31-1),
RFC3411
snmpEngineTime ( see page 434)
The number of seconds since the value of the snmpEngineBoots ( see page 433) object last changed
snmpEngineTimeOffset ( see page
Stores the time value in seconds since SNMP Engine reset
snmpEngnIDLength ( see page 434)
Engine ID length of the SNMP Engine
snmpInMsgAuthParamLen ( see page
Incoming SNMPv3 msg authentication parameters string is 12 bytes long.
snmpInMsgAuthParamStrng ( see page 435)
Reserving 12 bytes for the incoming SNMPv3 msg authentication parameters.
snmpInMsgPrivParamLen ( see page
Incoming SNMPv3 msg privacy parameters string is 8 bytes long.
snmpInMsgPrvParamStrng ( see page
Reserving 8 bytes for the incoming SNMPv3 msg privacy parameters.
snmpMsgBufSeekPos ( see page 435) Offset to read PDU data bytes for processing from dynamic memory
stub
Outgoing SNMPv3 msg authentication parameters string is 12 bytes long.
Reserving 12 bytes for the outgoing SNMPv3 msg authentication parameters.
Outgoing SNMPv3 msg privacy parameters string is 8 bytes long.
330
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
snmpOutMsgPrvParamStrng ( see page 436)
Reserving 8 bytes for the outgoing SNMPv3 msg privacy parameters.
Type of Security for outgoing message in response to the incoming message.
Type of security. noAuthNoPriv(0),AuthNoPriv(1),AuthPriv(3)
128 Bit
128 Bit
This is variable snmpV3UserDataBase.
Description
Simple Network Management Protocol V2c (community) agent implementation of RFC 3416 .
10.15.1
SNMP Public Members
Enumerations
Name
GENERIC_TRAP_NOTIFICATION_TYPE ( see page 333)
Description
This is type GENERIC_TRAP_NOTIFICATION_TYPE.
VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE
This is type
VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE.
This is the list of SNMP action a remote NMS can perform. This inforamtion is passed to application via
callback SNMPValidateCommunity ( see page 341)().
Application should validate the action for given community string.
COMMUNITY_TYPE ( see page 334)
This is type COMMUNITY_TYPE.
Functions
Name
Description
Prepare, validate remote node which will receive trap and send trap pdu.
Creates and Sends TRAP pdu.
SNMPIsNotifyReady ( see page 339)
SNMPNotifyPrepare ( see page 340)
SNMPGetNextIndex ( see page 340)
SNMPValidateCommunity ( see page 341)
This routine Set the mib variable with the requested value.
Used to Get/collect OID variable information.
Resolves given remoteHost IP address into MAC address.
Collects trap notification info and send ARP to remote host.
To search for next index node in case of a Sequence variable.
Validates community name for access control.
331
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
Macros
Module
Structures
Name Description
This is the maximum length for community string. Application must ensure that this length is observed. SNMP module adds one byte extra after
SNMP_COMMUNITY_MAX_LEN for adding '0' NULL character.
OID_MAX_LEN ( see page 342) Change this to match your OID string length.
SNMP_START_OF_VAR ( see page 342)
This is macro SNMP_START_OF_VAR.
SNMP_END_OF_VAR ( see page 343)
This is macro SNMP_END_OF_VAR.
SNMP_INDEX_INVALID ( see page 343)
TRAP_TABLE_SIZE ( see page 343)
This is macro SNMP_INDEX_INVALID.
This is macro TRAP_TABLE_SIZE.
This is macro TRAP_COMMUNITY_MAX_LEN.
NOTIFY_COMMUNITY_LEN ( see page 344)
This is macro NOTIFY_COMMUNITY_LEN.
Name
Description
This is type TRAP_INFO.
Types
Name
Description
This is the SNMP OID variable id. This id is assigned via MIB file. Only dynamic and AgentID variables can contian ID. MIB2BIB utility enforces this rules when
BIB was generated.
This is type SNMP_INDEX.
Unions
Name Description
SNMP_VAL ( see page 334) This is type SNMP_VAL.
Variables
Name
335) gSetTrapSendFlag ( see page 335)
Description
global flag to send Trap
#if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3) //if gSetTrapSendFlag ==
FALSE then the last varbind variable for //multiple varbind variable pdu structure or if there is only varbind variable send. // if gSetTrapSendFlag ==
TRUE, then v2 trap pdu is expecting more varbind variable. BYTE gSetTrapSendFlag = FALSE; #endif
Global flag for Generic trap notification
gGenericTrapNotification ( see page 336) gSpecificTrapNotification ( see page 336)
Vendor specific trap code
Gloabal var to store SNMP ID of var for OID received in SNMP request.
332
10.15 SNMP Microchip TCP/IP Stack Help
Description
The following functions and variables are available to the stack application.
SNMP Public Members
10.15.1.1
GENERIC_TRAP_NOTIFICATION_TYPE Enumeration
File
C typedef enum
{
COLD_START = 0x0,
WARM_START = 0x1,
LINK_DOWN = 0x2,
LINK_UP = 0x3,
AUTH_FAILURE = 0x4,
EGP_NEBOR_LOSS = 0x5,
ENTERPRISE_SPECIFIC = 0x6
} GENERIC_TRAP_NOTIFICATION_TYPE;
Description
This is type GENERIC_TRAP_NOTIFICATION_TYPE.
10.15.1.2
VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE
Enumeration
File
C typedef enum
{
VENDOR_TRAP_DEFAULT = 0x0,
BUTTON_PUSH_EVENT = 0x1,
POT_READING_MORE_512 = 0x2
} VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE;
Description
This is type VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE.
10.15.1.3
SNMP_ACTION Enumeration
File
C typedef enum
{
SNMP_GET = 0xa0,
SNMP_GET_NEXT = 0xa1,
SNMP_GET_RESPONSE = 0xa2,
SNMP_SET = 0xa3,
SNMP_TRAP = 0xa4,
SNMP_V2C_GET_BULK = 0xa5,
SNMP_V2_TRAP = 0xa7,
SNMPV3_ENCRYPTION = 0x04,
SNMP_ACTION_UNKNOWN = 0
} SNMP_ACTION;
333
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
Members
Members
SNMP_GET = 0xa0
SNMP_GET_NEXT = 0xa1
SNMP_GET_RESPONSE = 0xa2
SNMP_SET = 0xa3
SNMP_TRAP = 0xa4
SNMP_V2C_GET_BULK = 0xa5
SNMP_V2_TRAP = 0xa7
SNMP_ACTION_UNKNOWN = 0
Description
Snmp GET identifier
Snmp GET_NEXT identifier
Snmp GET_RESPONSE ( see page 353) identifier
Snmp SET identifier
Snmp TRAP identifier
Snmp GET_BULK identifier
Snmp v2 Trap Identifier
Snmp requested action unknown
Description
This is the list of SNMP action a remote NMS can perform. This inforamtion is passed to application via callback
10.15.1.4
COMMUNITY_TYPE Enumeration
File
C typedef enum
{
READ_COMMUNITY = 1,
WRITE_COMMUNITY = 2,
INVALID_COMMUNITY = 3
} COMMUNITY_TYPE;
Members
Members
READ_COMMUNITY = 1
WRITE_COMMUNITY = 2
INVALID_COMMUNITY = 3
Description
This is type COMMUNITY_TYPE.
Description
Read only community
Read write community
Community invalid
10.15.1.5
SNMP_VAL Union
File
C typedef union
{
DWORD dword;
WORD word;
BYTE byte;
BYTE v[
sizeof
(DWORD)];
} SNMP_VAL;
Members
Members
DWORD dword;
WORD word;
Description
double word value word value
334
10.15 SNMP
BYTE byte;
BYTE v[sizeof(DWORD)];
Description
This is type SNMP_VAL.
Microchip TCP/IP Stack Help byte value byte array
10.15.1.6
TRAP_INFO Structure
File
C typedef struct
{
BYTE Size;
struct
{
BYTE communityLen;
char
community[TRAP_COMMUNITY_MAX_LEN];
IP_ADDR IPAddress;
struct
{
unsigned int
bEnabled : 1;
} Flags;
} TRAP_INFO;
Members
Members Description
BYTE communityLen; Community name length char community[TRAP_COMMUNITY_MAX_LEN];
Community name array
IP_ADDR IPAddress; unsigned int bEnabled : 1;
IP address to which trap to be sent
Trap enabled flag
Description
This is type TRAP_INFO.
10.15.1.7
gSendTrapFlag Variable
File
CustomSNMPApp.c
C
BYTE gSendTrapFlag = FALSE;
Description
global flag to send Trap
10.15.1.8
gSetTrapSendFlag Variable
File
CustomSNMPApp.c
C
BYTE gSetTrapSendFlag = FALSE;
SNMP Public Members
335
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
Description
#if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3) //if gSetTrapSendFlag ==
FALSE then the last varbind variable for //multiple varbind variable pdu structure or if there is only varbind variable send. // if gSetTrapSendFlag == TRUE, then v2 trap pdu is expecting more varbind variable. BYTE gSetTrapSendFlag = FALSE;
#endif
10.15.1.9
gGenericTrapNotification Variable
File
CustomSNMPApp.c
C
BYTE gGenericTrapNotification = ENTERPRISE_SPECIFIC;
Description
Global flag for Generic trap notification
10.15.1.10
gSpecificTrapNotification Variable
File
CustomSNMPApp.c
C
BYTE gSpecificTrapNotification = VENDOR_TRAP_DEFAULT;
Description
Vendor specific trap code
10.15.1.11
gOIDCorrespondingSnmpMibID Variable
File
CustomSNMPApp.c
C
BYTE gOIDCorrespondingSnmpMibID = MICROCHIP;
Description
Gloabal var to store SNMP ID of var for OID received in SNMP request.
10.15.1.12
SNMPSendTrap Function
File
C void
SNMPSendTrap();
Returns
None.
336
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
Description
This function is used to send trap notification to previously configured ip address if trap notification is enabled. There are different trap notification code. The current implementation sends trap for authentication failure (4).
Remarks
This is a callback function called by the application on certain predefined events. This routine only implemented to send a authentication failure Notification-type macro with PUSH_BUTTON oid stored in MPFS. If the ARP is no resolved i.e. if
according to event occured and should update corrsponding OID and notification type to the trap pdu.
Preconditions
If application defined event occurs to send the trap.
10.15.1.13
SNMPNotify Function
File
C
BOOL SNMPNotify(
);
Description
This function creates SNMP trap PDU and sends it to previously specified remoteHost. snmpv1 trap pdu: | PDU-type | enterprise | agent-addr | generic-trap | specific-trap | | time-stamp | varbind-list |
The v1 enterprise is mapped directly to SNMPv2TrapOID.0
For ASCII STR trap VAL(argument) contains the pointer address of the string variable.
Remarks
This would fail if there were not UDP socket to open.
Preconditions
SNMPIsNotifyReady ( see page 339)() is already called and returned TRUE.
Parameters
Parameters
var val index
Description
SNMP var ID that is to be used in notification
Value of var. Only value of BYTE, WORD or DWORD can be sent.
Index of var. If this var is a single,index would be 0, or else if this var Is a sequence, index could be any value from 0 to 127
Return Values
Return Values
TRUE
FALSE
This would fail under following contions
4) Data type of given var is unknown
Description
if SNMP notification was successful sent. This does not guarantee that remoteHost recieved it.
Notification sent failed.
1) Given SNMP_BIB_FILE does not exist in MPFS 2) Given var does not exist.
3) Previously given agentID does not exist only possible if MPFS itself was corrupted.
337
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
10.15.1.14
SNMPSetVar Function
File
C
BOOL SNMPSetVar(
BYTE ref,
);
Description
This is a callback function called by module for the snmp SET request.User application must modify this function for the new variables address.
Remarks
This function may get called more than once depending on number of bytes in a specific set request for given variable. only dynamic read-write variables needs to be handled.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
var ref val
Description
Variable id whose value is to be set
Variable reference used to transfer multi-byte data 0 if first byte is set otherwise nonzero value to indicate corresponding byte being set.
Up to 4 byte data value. If var data type is BYTE, variable value is in val->byte If var data type is WORD, variable value is in val->word If var data type is
DWORD, variable value is in val->dword. If var data type is IP_ADDRESS,
COUNTER32, or GAUGE32, value is in val->dword If var data type is
OCTET_STRING ( see page 357), ASCII_STRING value is in val->byte;
multi-byte transfer will be performed to transfer remaining bytes of data.
Return Values
Return Values
TRUE
FALSE
Description
if it is OK to set more byte(s).
if otherwise.
10.15.1.15
SNMPGetVar Function
File
C
BOOL SNMPGetVar(
BYTE* ref,
);
Description
This is a callback function called by SNMP module. SNMP user must implement this function in user application and provide
338
10.15 SNMP appropriate data when called.
Remarks
None.
Preconditions
None
Parameters
Parameters
var index ref
Microchip TCP/IP Stack Help SNMP Public Members val
Description
Variable id whose value is to be returned
Index of variable that should be transferred
Variable reference used to transfer multi-byte data It is always
SNMP_START_OF_VAR ( see page 342) when very first byte is requested.
Otherwise, use this as a reference to keep track of multi-byte transfers.
Pointer to up to 4 byte buffer. If var data type is BYTE, transfer data in val->byte
If var data type is WORD, transfer data in val->word If var data type is DWORD, transfer data in val->dword If var data type is IP_ADDRESS, transfer data in val->v[] or val->dword If var data type is COUNTER32, TIME_TICKS or
GAUGE32, transfer data in val->dword If var data type is ASCII_STRING or
OCTET_STRING ( see page 357) transfer data in val->byte using multi-byte
transfer mechanism.
Return Values
Return Values
TRUE
FALSE
Description
If a value exists for given variable at given index.
Otherwise.
10.15.1.16
SNMPIsNotifyReady Function
File
C
BOOL SNMPIsNotifyReady(
IP_ADDR* remoteHost
);
Description
This function resolves given remoteHost IP address into MAC address using ARP module. If remoteHost is not aviailable, this function would never return TRUE. Application must implement timeout logic to handle "remoteHost not avialable" situation.
Remarks
This would fail if there were not UDP socket to open.
Preconditions
SNMPNotifyPrepare ( see page 340)() is already called.
Parameters
Parameters
remoteHost
Description
Pointer to remote Host IP address
339
10.15 SNMP
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help SNMP Public Members
Description
If remoteHost IP address is resolved and SNMPNotify ( see page 337) may
be called.
If remoteHost IP address is not resolved.
10.15.1.17
SNMPNotifyPrepare Function
File
C void
SNMPNotifyPrepare(
IP_ADDR* remoteHost,
char
* community,
BYTE communityLen,
BYTE notificationCode,
DWORD timestamp
);
Returns
None
Description
This function prepares SNMP module to send SNMP trap notification to remote host. It sends ARP request to remote host to learn remote host MAC address.
Remarks
This is first of series of functions to complete SNMP notification.
Preconditions
SNMPInit ( see page 376)() is already called.
Parameters
Parameters
remoteHost community communityLen agentIDVar notificaitonCode timestamp
Description
pointer to remote Host IP address
Community string to use to notify
Community string length
System ID to use identify this agent
Notification Code to use
Notification timestamp in 100th of second.
10.15.1.18
SNMPGetNextIndex Function
File
C
BOOL SNMPGetNextIndex(
);
340
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
Description
This is a callback function called by SNMP module. SNMP user must implement this function in user application and provide appropriate data when called. This function will only be called for OID variable of type sequence.
Remarks
Only sequence index needs to be handled in this function.
Preconditions
None
Parameters
Parameters
var index
Return Values
Return Values
TRUE
FALSE
Description
Variable id whose value is to be returned
Next Index of variable that should be transferred
Description
If a next index value exists for given variable at given index and index parameter contains next valid index.
Otherwise.
10.15.1.19
SNMPValidateCommunity Function
File
C
BYTE SNMPValidateCommunity(
BYTE * community
);
Returns
This routine returns the community validation result as READ_COMMUNITY or WRITE_COMMUNITY or
INVALID_COMMUNITY
Description
This function validates the community name for the mib access to NMS. The snmp community name received in the request pdu is validated for read and write community names. The agent gives an access to the mib variables only if the community matches with the predefined values. This routine also sets a gloabal flag to send trap if authentication failure occurs.
Remarks
This is a callback function called by module. User application must implement this function and verify that community matches with predefined value. This validation occurs for each NMS request.
Preconditions
SNMPInit ( see page 376) is already called.
Parameters
Parameters
community
Description
Pointer to community string as sent by NMS.
341
10.15 SNMP Microchip TCP/IP Stack Help SNMP Public Members
10.15.1.20
SNMP_ID Type
File
C typedef int
SNMP_ID;
Description
This is the SNMP OID variable id. This id is assigned via MIB file. Only dynamic and AgentID variables can contian ID.
MIB2BIB utility enforces this rules when BIB was generated.
10.15.1.21
SNMP_INDEX Type
File
C typedef
BYTE SNMP_INDEX;
Description
This is type SNMP_INDEX.
10.15.1.22
SNMP_COMMUNITY_MAX_LEN Macro
File
TCPIP MRF24W.h
C
#define
SNMP_COMMUNITY_MAX_LEN (8u)
Description
This is the maximum length for community string. Application must ensure that this length is observed. SNMP module adds one byte extra after SNMP_COMMUNITY_MAX_LEN for adding '0' NULL character.
10.15.1.23
OID_MAX_LEN Macro
File
C
#define
OID_MAX_LEN (SNMP_MAX_OID_LEN_MEM_USE+1)
Description
Change this to match your OID string length.
10.15.1.24
SNMP_START_OF_VAR Macro
File
342
10.15 SNMP
C
#define
SNMP_START_OF_VAR (0)
Description
This is macro SNMP_START_OF_VAR.
Microchip TCP/IP Stack Help
10.15.1.25
SNMP_END_OF_VAR Macro
File
C
#define
SNMP_END_OF_VAR (0xff)
Description
This is macro SNMP_END_OF_VAR.
10.15.1.26
SNMP_INDEX_INVALID Macro
File
C
#define
SNMP_INDEX_INVALID (0xff)
Description
This is macro SNMP_INDEX_INVALID.
10.15.1.27
TRAP_TABLE_SIZE Macro
File
C
#define
TRAP_TABLE_SIZE (2)
Description
This is macro TRAP_TABLE_SIZE.
10.15.1.28
TRAP_COMMUNITY_MAX_LEN Macro
File
C
#define
TRAP_COMMUNITY_MAX_LEN (SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE+1)
Description
This is macro TRAP_COMMUNITY_MAX_LEN.
SNMP Public Members
343
10.15 SNMP Microchip TCP/IP Stack Help
10.15.1.29
NOTIFY_COMMUNITY_LEN Macro
File
TCPIP MRF24W.h
C
#define
NOTIFY_COMMUNITY_LEN (SNMP_COMMUNITY_MAX_LEN)
Description
This is macro NOTIFY_COMMUNITY_LEN.
SNMP Internal Members
10.15.2
SNMP Internal Members
Enumerations
Name
SNMP_ERR_STATUS ( see page 361)
Functions
Description
Name Description
_SNMPDuplexInit ( see page 347) Prepare for full duplex transfer.
Read byte from snmp udp socket rx buffer.
Copy byte to tx buffer.
Finds number of varbinds in the varbind list received in a pdu.
GetDataTypeInfo ( see page 355) Get ASN data type info.
SetErrorStatus ( see page 360)
Verifies the value type as ASN_NULL ( see page 349).
Set snmp error status in the response pdu.
Retrieves the packet length and actual pdu length.
Searches for the next leaf node in the MIP tree.
Get OID string from MPFS using the node address.
Get complete notification variable OID string from MPFS using var id.
Verifies for the community string datatype and the max community name and length, this agent can process.
Verifies variable datatype as INT and retrieves its value.
Populates OID type, length and oid string from the received pdu.
Verifies for the snmp request type.
IsValidStructure ( see page 371)
Decode variable length structure.
To search and validate whether the requested OID is in the MIB database.
344
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
ProcessGetSetHeader ( see page 372)
Validates the received udp packet Get/Set request header.
Validates the received udp packet Snmp header.
Processes snmp Set request pdu.
ProcessVariables ( see page 374) This routine processes the snmp request and parallely creates the
response pdu.
Get OID string from MPFS using the node address.
To find whether requested OID is only for private access.
Macros
Name
_SNMPGetTxOffset ( see page 348)
_SNMPSetTxOffset ( see page 349)
AGENT_NOTIFY_PORT ( see page 349)
Description
This is macro _SNMPGetTxOffset.
This is macro AGENT_NOTIFY_PORT.
This is macro ASN_INT.
ASN_NULL ( see page 349) This is macro ASN_NULL.
This is macro ASN_OID.
GET_BULK_REQUEST ( see page 352)
GET_NEXT_REQUEST ( see page 352)
IS_GET_REQUEST ( see page 354)
This is macro GET_BULK_REQUEST.
This is macro GET_NEXT_REQUEST.
This is macro GET_RESPONSE.
This is macro IS_AGENT_PDU.
This is macro IS_ASN_INT.
This is macro IS_ASN_NULL.
This is macro IS_GET_NEXT_REQUEST.
This is macro IS_GET_REQUEST.
IS_GET_RESPONSE ( see page 355)
IS_OCTET_STRING ( see page 355)
IS_SET_REQUEST ( see page 356)
This is macro IS_GET_RESPONSE.
This is macro IS_OCTET_STRING.
This is macro IS_OID.
This is macro IS_SET_REQUEST.
This is macro IS_TRAP.
345
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
This is macro OCTET_STRING.
This is macro SET_REQUEST.
SNMP_AGENT_PORT ( see page 360)
SNMP_BIB_FILE_NAME ( see page 360)
SNMP_COUNTER32 ( see page 361)
This is the file that contains SNMP bib file. File name must contain all upper case letter and must match with what was included in MPFS2 image.
This is macro SNMP_COUNTER32.
This is macro SNMP_GAUGE32.
This is macro SNMP_IP_ADDR.
SNMP_NSAP_ADDR ( see page 363)
SNMP_TIME_TICKS ( see page 364)
This is macro SNMP_NMS_PORT.
This is macro SNMP_NSAP_ADDR.
This is macro SNMP_OPAQUE.
This is macro SNMP_TIME_TICKS.
SNMP_V2C ( see page 365) This is macro SNMP_V2C.
This is macro TRAP.
Module
Structures
Name
DATA_TYPE_INFO ( see page 351)
SNMP_NOTIFY_INFO ( see page 363)
Description
Unions
Name
Description
Variables
Name
appendZeroToOID ( see page 349)
Description
global flag to modify OID by appending zero
346
10.15 SNMP Microchip TCP/IP Stack Help
SNMPAgentSocket ( see page 365)
snmpReqVarErrStatus ( see page 366)
ASN format datatype for snmp v1 and v2c
MPFS file handler
Snmp udp socket notify info for trap vars from req list processing err status
Snmp udp buffer rx offset
MIB file access status
Snmp udp buffer tx offset
Initialize trap table with no entries.
Description
The following functions and variables are designated as internal to the SNMP module.
SNMP Internal Members
10.15.2.1
_SNMPDuplexInit Function
File
C void
_SNMPDuplexInit(
);
Returns
None.
Description
As we process SNMP variables, we will prepare response on-the-fly creating full duplex transfer. Current MAC layer does not support full duplex transfer, so SNMP needs to manage its own full duplex connection. Prepare for full duplex transfer.
Set the Tx and Rx offset to start of the buffer.
Remarks
This routine should be called for every new snmp packet received.
Preconditions
SNMPTask ( see page 377)() is called.
Parameters
Parameters
Description
An active udp socket for which tx and rx offset to be set.
10.15.2.2
_SNMPGet Function
File
347
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
C
BYTE _SNMPGet();
Returns
None.
Description
This function reads a single byte from the currently active UDP socket, receive buffer, while incrementing the buffer offset from where the next byte will be read.
Remarks
None.
Preconditions
SNMPTask ( see page 377)() is called. A active udp socket is available to read from.
10.15.2.3
_SNMPGetTxOffset Macro
File
C
#define
Description
This is macro _SNMPGetTxOffset.
10.15.2.4
_SNMPPut Function
File
C void
_SNMPPut(
BYTE v
);
Returns
None.
Description
This function writes a single byte to the currently active UDP socket, transmit buffer, while incrementing the buffer offset for the next write operation.
Remarks
None.
Preconditions
SNMPTask ( see page 377)() is called. A active udp socket is availabe to tx from.
348
10.15 SNMP Microchip TCP/IP Stack Help
10.15.2.5
_SNMPSetTxOffset Macro
File
C
#define
_SNMPSetTxOffset(o) (SNMPTxOffset = o)
Section
SNMP Tx pdu offset settings
10.15.2.6
AGENT_NOTIFY_PORT Macro
File
C
#define
AGENT_NOTIFY_PORT (0xfffe)
Description
This is macro AGENT_NOTIFY_PORT.
10.15.2.7
appendZeroToOID Variable
File
C
BYTE appendZeroToOID = FALSE;
Description
global flag to modify OID by appending zero
10.15.2.8
ASN_INT Macro
File
C
#define
ASN_INT (0x02u)
Description
This is macro ASN_INT.
10.15.2.9
ASN_NULL Macro
File
SNMP Internal Members
349
10.15 SNMP
C
#define
ASN_NULL (0x05u)
Description
This is macro ASN_NULL.
Microchip TCP/IP Stack Help
10.15.2.10
ASN_OID Macro
File
C
#define
ASN_OID (0x06u)
Description
This is macro ASN_OID.
10.15.2.11
DATA_TYPE Enumeration
File
C typedef enum
{
INT8_VAL = 0x00,
INT16_VAL = 0x01,
INT32_VAL = 0x02,
BYTE_ARRAY = 0x03,
ASCII_STRING = 0x04,
IP_ADDRESS = 0x05,
COUNTER32 = 0x06,
TIME_TICKS_VAL = 0x07,
GAUGE32 = 0x08,
OID_VAL = 0x09,
DATA_TYPE_UNKNOWN
} DATA_TYPE;
Members
Members
INT8_VAL = 0x00
INT16_VAL = 0x01
INT32_VAL = 0x02
BYTE_ARRAY = 0x03
ASCII_STRING = 0x04
IP_ADDRESS = 0x05
COUNTER32 = 0x06
TIME_TICKS_VAL = 0x07
GAUGE32 = 0x08
OID_VAL = 0x09
DATA_TYPE_UNKNOWN
Section
Data Structures and Enumerations
Description
8 bit integer value
16 bit integer value
32 bit integer value
Aray of bytes
Ascii string type
IP address variable
32 bit counter variable
Timer vakue counter variable
32 bit guage variable
Object id value var
Unknown data type
SNMP Internal Members
350
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
************************************************************************
SNMP specific data tyes
10.15.2.12
DATA_TYPE_INFO Structure
File
C typedef struct
{
BYTE asnType;
BYTE asnLen;
} DATA_TYPE_INFO;
Members
Members
BYTE asnType;
BYTE asnLen;
Section
ASN data type info
Description
ASN data type
ASN data length
10.15.2.13
DATA_TYPE_TABLE_SIZE Macro
File
C
#define
DATA_TYPE_TABLE_SIZE (
sizeof
sizeof
Section
Macros and Definitions
10.15.2.14
dataTypeTable Variable
File
C
ROM DATA_TYPE_INFO dataTypeTable[] = { { ASN_INT, 1 }, { ASN_INT, 2 }, { ASN_INT, 4 }, {
OCTET_STRING, 0xff }, { OCTET_STRING, 0xff }, { SNMP_IP_ADDR, 4 }, { SNMP_COUNTER32, 4 }, {
SNMP_TIME_TICKS, 4 }, { SNMP_GAUGE32, 4 }, { ASN_OID, 0xff } };
Description
ASN format datatype for snmp v1 and v2c
10.15.2.15
FindOIDsInRequest Function
File
351
10.15 SNMP Microchip TCP/IP Stack Help
C static
BYTE FindOIDsInRequest(
WORD pdulen
);
Description
This routine is used to find the number of OIDs requested in the received snmp pdu.
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
pdulen
Return Values
Return Values
varCount
Description
Length of snmp pdu request received.
Description
Number of OIDs found in a pdu request.
10.15.2.16
GET_BULK_REQUEST Macro
File
C
#define
GET_BULK_REQUEST (0xa5)
Description
This is macro GET_BULK_REQUEST.
10.15.2.17
GET_NEXT_REQUEST Macro
File
C
#define
GET_NEXT_REQUEST (0xa1)
Description
This is macro GET_NEXT_REQUEST.
10.15.2.18
GET_REQUEST Macro
File
C
#define
GET_REQUEST (0xa0)
SNMP Internal Members
352
10.15 SNMP
Section
SNMP v1 and v2c pdu types
Microchip TCP/IP Stack Help
10.15.2.19
GET_RESPONSE Macro
File
C
#define
GET_RESPONSE (0xa2)
Description
This is macro GET_RESPONSE.
10.15.2.20
hMPFS Variable
File
C
Description
MPFS file handler
10.15.2.21
INDEX_INFO Union
File
C typedef union
{
struct
{
unsigned int
bIsOID : 1;
} Flags;
BYTE Val;
} INDEX_INFO;
Members
Members
unsigned int bIsOID : 1;
BYTE Val;
Section
SNMP OID index information
Description
value is OID/index int flag value is OID/index byte flag
10.15.2.22
IS_AGENT_PDU Macro
File
SNMP Internal Members
353
10.15 SNMP Microchip TCP/IP Stack Help
C
#define
IS_AGENT_PDU(a) (a==GET_REQUEST || \
a==SNMP_V2C_GET_BULK)
Description
This is macro IS_AGENT_PDU.
10.15.2.23
IS_ASN_INT Macro
File
C
#define
Description
This is macro IS_ASN_INT.
10.15.2.24
IS_ASN_NULL Macro
File
C
#define
Description
This is macro IS_ASN_NULL.
10.15.2.25
IS_GET_NEXT_REQUEST Macro
File
C
#define
IS_GET_NEXT_REQUEST(a) (a==GET_NEXT_REQUEST)
Description
This is macro IS_GET_NEXT_REQUEST.
10.15.2.26
IS_GET_REQUEST Macro
File
C
#define
IS_GET_REQUEST(a) (a==GET_REQUEST)
Description
This is macro IS_GET_REQUEST.
SNMP Internal Members
354
10.15 SNMP Microchip TCP/IP Stack Help
10.15.2.27
IS_GET_RESPONSE Macro
File
C
#define
IS_GET_RESPONSE(a) (a==GET_RESPONSE)
Description
This is macro IS_GET_RESPONSE.
10.15.2.28
IS_OCTET_STRING Macro
File
C
#define
IS_OCTET_STRING(a) (a==OCTET_STRING)
Description
This is macro IS_OCTET_STRING.
10.15.2.29
IS_OID Macro
File
C
#define
Description
This is macro IS_OID.
10.15.2.30
GetDataTypeInfo Function
File
C
BOOL GetDataTypeInfo(
);
Returns
TRUE - success FALSE - failure
Description
This routine validates the SNMP GEt dtat type and collects ASN data type value to the info.
Remarks
None.
SNMP Internal Members
355
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
Preconditions
ProcessHeader ( see page 373)() is called.
Parameters
Parameters
dataType info
Description
SNMP pdu data type info.
matching data type info w.r.t dataTypeTable ( see page 351)
10.15.2.31
IS_SET_REQUEST Macro
File
C
#define
IS_SET_REQUEST(a) (a==SET_REQUEST)
Description
This is macro IS_SET_REQUEST.
10.15.2.32
IS_STRUCTURE Macro
File
C
#define
IS_STRUCTURE(a) (a==STRUCTURE)
Section
SNMP specific data validation
10.15.2.33
IS_TRAP Macro
File
C
#define
IS_TRAP(a) (a==TRAP)
Description
This is macro IS_TRAP.
10.15.2.34
IsASNNull Function
File
C static
BOOL IsASNNull();
Description
356
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members value field must be NULL and . This routine verifies the data type and value fields in the received requests. The SET
Remarks
None.
Preconditions
None
Parameters
Parameters
TRUE
FALSE
Description
If value type is ASN_NULL ( see page 349) and value is NULL.
If data type and value is other than ASN_NULL ( see page 349) and NULL
resp.
10.15.2.35
MIB_INFO Union
File
C typedef union
{
struct
{
unsigned int
bIsDistantSibling : 1;
unsigned int
bIsConstant : 1;
unsigned int
bIsSequence : 1;
unsigned int
bIsSibling : 1;
unsigned int
bIsParent : 1;
unsigned int
bIsEditable : 1;
unsigned int
bIsAgentID : 1;
unsigned int
bIsIDPresent : 1;
} Flags;
BYTE Val;
} MIB_INFO;
Members
Members
unsigned int bIsDistantSibling : 1; unsigned int bIsConstant : 1; unsigned int bIsSequence : 1; unsigned int bIsSibling : 1; unsigned int bIsParent : 1; unsigned int bIsEditable : 1; unsigned int bIsAgentID : 1; unsigned int bIsIDPresent : 1;
BYTE Val;
Section
SNMP object information
Description
Object have distant sibling node
Object is constant
Object is sequence
Sibling node flag
Node is parent flag
Node is editable flag
Node have agent id flag
Id present flag
MIB Obj info as byte value
10.15.2.36
OCTET_STRING Macro
File
357
10.15 SNMP
C
#define
OCTET_STRING (0x04u)
Description
This is macro OCTET_STRING.
Microchip TCP/IP Stack Help
10.15.2.37
OID_INFO Structure
File
C typedef struct
{
DWORD hNode;
BYTE oid;
WORD_VAL dataLen;
DWORD hData;
DWORD hSibling;
DWORD hChild;
BYTE index;
BYTE indexLen;
} OID_INFO;
Members
Members
DWORD hNode;
BYTE oid;
MIB_INFO nodeInfo;
DATA_TYPE dataType;
SNMP_ID id;
WORD_VAL dataLen;
DWORD hData;
DWORD hSibling;
DWORD hChild;
BYTE index;
BYTE indexLen;
Section
SNMP MIB variable object information
Description
Node location in the mib
Object Id
Node info
Data type
Snmp Id
Data length
Data
Sibling info
Child info
Index of object
Index length
10.15.2.38
PDU_INFO Structure
File
C typedef struct
{
DWORD_VAL requestID;
BYTE nonRepeators;
BYTE maxRepetitions;
BYTE pduType;
BYTE errorStatus;
BYTE erroIndex;
SNMP Internal Members
358
10.15 SNMP
BYTE snmpVersion;
WORD pduLength;
} PDU_INFO;
Members
Members
DWORD_VAL requestID;
BYTE nonRepeators;
BYTE maxRepetitions;
BYTE pduType;
BYTE errorStatus;
BYTE erroIndex;
BYTE snmpVersion;
WORD pduLength;
Section
SNMP pdu information database
Microchip TCP/IP Stack Help
Description
Snmp request id non repeaters in the request max repeaters in the request
Snmp pdu type
Pdu error status
Pdu error Index
Snmp version
Pdu length
10.15.2.39
reqVarErrStatus Structure
File
C typedef struct
{
WORD noSuchObjectErr;
WORD noSuchNameErr;
WORD noSuchInstanceErr;
WORD endOfMibViewErr;
} reqVarErrStatus;
Members
Members
WORD noSuchObjectErr;
WORD noSuchNameErr;
WORD noSuchInstanceErr;
WORD endOfMibViewErr;
Section
SNMP reuested variable list error status information.
Max variable in a request supported 15
Description
Var list no such obj errors flags
Var list no such name error
Var list no such instance error
Var list end of mib view error
10.15.2.40
SET_REQUEST Macro
File
C
#define
SET_REQUEST (0xa3)
Description
This is macro SET_REQUEST.
SNMP Internal Members
359
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
10.15.2.41
SetErrorStatus Function
File
C void
SetErrorStatus(
WORD errorStatusOffset,
WORD errorIndexOffset,
BYTE errorIndex
);
Returns
None.
Description
This routine processes the received snmp Get request pdu for the variable binding in the request and also creates the response pdu.
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
errorStatusOffset errorIndexOffset errorStatus errorIndex
Description
Offset to update error status in Response Tx pdu
Offset to update error index
Snmp process error to be updated in response.
Index of the request varbind in the var bind list for which error status is to be updated.
10.15.2.42
SNMP_AGENT_PORT Macro
File
C
#define
SNMP_AGENT_PORT (161)
Section
SNMP Udp ports
10.15.2.43
SNMP_BIB_FILE_NAME Macro
File
C
#define
SNMP_BIB_FILE_NAME "snmp.bib"
360
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
Description
This is the file that contains SNMP bib file. File name must contain all upper case letter and must match with what was included in MPFS2 image.
10.15.2.44
SNMP_COUNTER32 Macro
File
C
#define
SNMP_COUNTER32 (0x41)
Description
This is macro SNMP_COUNTER32.
10.15.2.45
SNMP_ERR_STATUS Enumeration
File
C typedef enum
{
SNMP_NO_ERR = 0,
SNMP_TOO_BIG,
SNMP_NO_SUCH_NAME,
SNMP_BAD_VALUE,
SNMP_READ_ONLY,
SNMP_GEN_ERR,
SNMP_NO_ACCESS,
SNMP_WRONG_TYPE,
SNMP_WRONG_LENGTH,
SNMP_WRONG_ENCODING,
SNMP_WRONG_VALUE,
SNMP_NO_CREATION,
SNMP_INCONSISTENT_VAL,
SNMP_RESOURCE_UNAVAILABE,
SNMP_COMMIT_FAILED,
SNMP_UNDO_FAILED,
SNMP_AUTH_ERROR,
SNMP_NOT_WRITABLE,
SNMP_INCONSISTENT_NAME,
SNMP_NO_SUCH_OBJ = 128,
SNMP_NO_SUCH_INSTANCE = 129,
SNMP_END_OF_MIB_VIEW = 130
} SNMP_ERR_STATUS;
Members
Members
SNMP_NO_ERR = 0
SNMP_TOO_BIG
SNMP_NO_SUCH_NAME
SNMP_BAD_VALUE
SNMP_READ_ONLY
SNMP_GEN_ERR
SNMP_NO_ACCESS
SNMP_WRONG_TYPE
SNMP_WRONG_LENGTH
Description
Snmp no error
Value too big error
No such name in MIB error
Not assignable value for the var error
Read only variable, write not allowed err
Snmp gen error
Access to modify or read not granted err
Variable data type wrong error
Wrong data length error
361
10.15 SNMP
SNMP_WRONG_ENCODING
SNMP_WRONG_VALUE
SNMP_NO_CREATION
SNMP_INCONSISTENT_VAL
SNMP_RESOURCE_UNAVAILABE
SNMP_COMMIT_FAILED
SNMP_UNDO_FAILED
SNMP_AUTH_ERROR
SNMP_NOT_WRITABLE
SNMP_INCONSISTENT_NAME
SNMP_NO_SUCH_OBJ = 128
SNMP_NO_SUCH_INSTANCE = 129
SNMP_END_OF_MIB_VIEW = 130
Section
SNMP specific errors
Microchip TCP/IP Stack Help
Wrong encoding error
Wrong value for the var type
No creationg error
Inconsistent value error
Resource unavailbe error
Modification update failed error
Modification undo failed
Authorization failed error
Variable read only
Inconsistent name
No such object error
No such instance error
Reached to end of mib error
10.15.2.46
SNMP_GAUGE32 Macro
File
C
#define
SNMP_GAUGE32 (0x42)
Description
This is macro SNMP_GAUGE32.
10.15.2.47
SNMP_IP_ADDR Macro
File
C
#define
SNMP_IP_ADDR (0x40)
Description
This is macro SNMP_IP_ADDR.
10.15.2.48
SNMP_NMS_PORT Macro
File
C
#define
SNMP_NMS_PORT (162)
Description
This is macro SNMP_NMS_PORT.
SNMP Internal Members
362
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
10.15.2.49
SNMP_NOTIFY_INFO Structure
File
C typedef struct
{
char
community[NOTIFY_COMMUNITY_LEN];
BYTE communityLen;
BYTE notificationCode;
DWORD_VAL timestamp;
} SNMP_NOTIFY_INFO;
Members
Members
char community[NOTIFY_COMMUNITY_LEN];
BYTE communityLen;
SNMP_ID agentIDVar;
BYTE notificationCode;
UDP_SOCKET socket;
DWORD_VAL timestamp;
SNMP_ID trapIDVar;
Description
Community name array
Community name length
Agent id for trap identification
Trap notification code
Udp socket number
Time stamp for trap
SNMPV2 specific trap
Section
SNMP trap notification information for agent
10.15.2.50
SNMP_NSAP_ADDR Macro
File
C
#define
SNMP_NSAP_ADDR (0x45)
Description
This is macro SNMP_NSAP_ADDR.
10.15.2.51
IsValidLength Function
File
C
BYTE IsValidLength(
WORD * len
);
Description
Checks current packet and returns total length value as well as actual length bytes.We do not support any length byte count of more than 2 i.e. total length value must not be more than 16-bit.
363
10.15 SNMP
Remarks
None.
Preconditions
None
Parameters
Parameters
len
Return Values
Return Values
lengthBytes
Microchip TCP/IP Stack Help
Description
Pointer to memory where actual length is stored.
Description
Total length bytes are 0x80 itself plus tempData.
10.15.2.52
SNMP_OPAQUE Macro
File
C
#define
SNMP_OPAQUE (0x44)
Description
This is macro SNMP_OPAQUE.
10.15.2.53
SNMP_STATUS Union
File
C typedef union
{
struct
{
unsigned int
bIsFileOpen : 1;
} Flags;
BYTE Val;
} SNMP_STATUS;
Members
Members
unsigned int bIsFileOpen : 1;
BYTE Val;
Section
SNMP specific mib file access information
Description
MIB file access int flag
MIB file access byte flag
10.15.2.54
SNMP_TIME_TICKS Macro
File
C
#define
SNMP_TIME_TICKS (0x43)
SNMP Internal Members
364
10.15 SNMP
Description
This is macro SNMP_TIME_TICKS.
Microchip TCP/IP Stack Help
10.15.2.55
SNMP_V1 Macro
File
C
#define
SNMP_V1 (0)
Section
SNMP agent version types
10.15.2.56
SNMP_V2C Macro
File
C
#define
SNMP_V2C (1)
Description
This is macro SNMP_V2C.
10.15.2.57
SNMPAgentSocket Variable
File
C
UDP_SOCKET SNMPAgentSocket = INVALID_UDP_SOCKET;
Description
Snmp udp socket
10.15.2.58
SNMPNotifyInfo Variable
File
C
SNMP_NOTIFY_INFO SNMPNotifyInfo;
Description
notify info for trap
SNMP Internal Members
365
10.15 SNMP Microchip TCP/IP Stack Help
10.15.2.59
snmpReqVarErrStatus Variable
File
C
reqVarErrStatus snmpReqVarErrStatus;
Description
vars from req list processing err status
10.15.2.60
SNMPRxOffset Variable
File
C
WORD SNMPRxOffset = 0;
Description
Snmp udp buffer rx offset
10.15.2.61
SNMPStatus Variable
File
C
Description
MIB file access status
10.15.2.62
SNMPTxOffset Variable
File
C
WORD SNMPTxOffset;
Description
Snmp udp buffer tx offset
10.15.2.63
STRUCTURE Macro
File
SNMP Internal Members
366
10.15 SNMP
C
#define
STRUCTURE (0x30u)
Section
SNMP specific variables
Microchip TCP/IP Stack Help
10.15.2.64
TRAP Macro
File
C
#define
TRAP (0xa4)
Description
This is macro TRAP.
10.15.2.65
trapInfo Variable
File
CustomSNMPApp.c
C
TRAP_INFO trapInfo = { TRAP_TABLE_SIZE };
Description
Initialize trap table with no entries.
SNMP Internal Members
10.15.2.66
GetNextLeaf Function
File
C
BOOL GetNextLeaf(
);
Description
This routine searches for the next leaf node from the current node. The input to this function is the node from where next leaf node is to be located. The next leaf node will be a silbing else distant sibling or leaf node of next branch, if any present. The input parameter var pointer will be updated with the newly found leaf node OID info.
Remarks
None.
Preconditions
ProcessGetBulkVar ( see page 383)() else ProcessGetNextVar ( see page 384)() is called.
Parameters
Parameters
rec
Description
Pointer to SNMP MIB variable object information
367
10.15 SNMP
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help
Description
If next leaf node is found.
There is no next leaf node.
SNMP Internal Members
10.15.2.67
GetOIDStringByAddr Function
File
C
BOOL GetOIDStringByAddr(
BYTE* oidString,
BYTE* len
);
Description
This routine is called when a OID string is required to be searched from MPFS using node address.
Remarks
None.
Preconditions
None.
Parameters
Parameters
rec oidString len
Return Values
Return Values
TRUE
FLASE
Description
Pointer to SNMP MIB variable object information
Pointer to store the string of OID searched
Oid length
Description
If oid string is found.
Otherwise.
10.15.2.68
GetOIDStringByID Function
File
C
BOOL GetOIDStringByID(
BYTE* oidString,
BYTE* len
);
Description
This routine is called when a OID string is required to be searched from MPFS using agent id. The string is saved with agent.
pdu.
368
10.15 SNMP Microchip TCP/IP Stack Help
Remarks
This function is used only when TRAP is enabled.
Parameters
Parameters
id info oidString len
Return Values
Return Values
TRUE
FLASE
Description
System ID to use identify this agent.
Pointer to SNMP MIB variable object information
Pointer to store the string of OID serached
Oid length
Description
If oid string is found for the variable id in MPFS.
Otherwise.
SNMP Internal Members
10.15.2.69
IsValidCommunity Function
File
C static
BOOL IsValidCommunity(
char
* community,
BYTE* len
);
Description
This routine populates and validates the community datatype, community name and length from the received snmp request pdu. Community name is used for accessing public and private memebrs of the mib.
Remarks
None.
Preconditions
ProcessHeader ( see page 373)() is called.
Parameters
Parameters
community len
Return Values
Return Values
TRUE
FALSE
Description
Pointer to memory where community string will be stored.
Pointer to memory where comunity length gets stored.
Description
If valid community received.
If community is not valid.
10.15.2.70
IsValidInt Function
File
C
BOOL IsValidInt(
369
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
DWORD* val
);
Description
length for max 4 bytes.
Remarks
None.
Preconditions
ProcessHeader ( see page 373)() or ProcessGetSetHeader ( see page 372)() is called.
Parameters
Parameters
val
ReturnValues
FALSE
Description
Pointer to memory where int var value will be stored.
TRUE - If valid integer type and value is received.
Other than integer data type and value received .
10.15.2.71
IsValidOID Function
File
C static
BOOL IsValidOID(
BYTE* oid,
BYTE* len
);
Description
only var bind is processed. OID length and OID is populated. The max OID length can be 15.
Remarks
None.
Preconditions
ProcessVariabels() is called.
Parameters
Parameters
oid len
Return Values
Return Values
TRUE
FALSE
Description
Pointer to memory to store the received OID string
Pointer to memory to store OID length
Description
If value type is ASN_OID ( see page 350) and oid length not more than 15.
Otherwise.
10.15.2.72
IsValidPDU Function
File
370
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
C static
BOOL IsValidPDU(
);
Description
This routine populates and verifies for the received snmp request pdu type.
Remarks
None.
Preconditions
ProcessHeader ( see page 373)() is called.
Parameters
Parameters
val
Return Values
Return Values
TRUE
FALSE
Description
Pointer to memory where received snmp request type is stored.
Description
If this snmp request can be processed by the agent.
If the request can not be processed.
10.15.2.73
IsValidStructure Function
File
C
BYTE IsValidStructure(
WORD* dataLen
);
Description
variable binding structure length.
Remarks
None.
Preconditions
ProcessHeader ( see page 373)() is called.
Parameters
Parameters
datalen
Return Values
Return Values
headrbytes
FALSE
Description
Pointer to memory to store OID structure length.
Description
Variable binding length.
If variable data structure is not type STRUCTURE ( see page 366).
371
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
10.15.2.74
OIDLookup Function
File
C
BYTE OIDLookup(
BYTE* oid,
BYTE oidLen,
);
Description
The MIB database is stored with the agent in binary mib format. This is the binary mib format: , , ...>]}, ChildNode variable bind name is a dotted string of oid. Every oid is a node in the MIB tree and have varied information. This routine on reception of the snmp request, will search for every oid in the var name. This routine will return information whether the requested var name is part of the MIB tree data structre of this agent or not.
Remarks
This routine works for the MPFS2 mib storage format. It uses the MPFS2 APIs to read,search and collect information from the mib database.
Preconditions
Valid snmp request with valid OID format is received.
Parameters
Parameters
pduDbPtr oid oidLen rec
Return Values
Return Values
TRUE
FALSE
Description
Pointer to received snmp pdu elements information
Pointer to the string of OID to be searched
Oid length
Pointer to SNMP MIB variable object information
Description
If the complete OID string is found in the mib
If complete OID do not match. Also different erros returned are
SNMP_END_OF_MIB_VIEW SNMP_NO_SUCH_NAME
SNMP_NO_SUCH_OBJ SNMP_NO_SUCH_INSTANCE
10.15.2.75
ProcessGetSetHeader Function
File
C static
BOOL ProcessGetSetHeader(
);
Description
All the variables of snmp pdu request header are validated for their data types. Collects request_id for the snmp request pdu.
Fetch,validates error status,error index and discard as they are need not to be processed as received in request pdu.
Collects non repeaters and max repeaters values in case of Get_Bulk request.
372
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
Remarks
The request pdu will be processed only if this routine returns TRUE
Preconditions
Parameters
Description
Pointer to received pdu information database.
Parameters
pduDbPtr
Return Values
Return Values
TRUE
FALSE
Description
If the received request header is validated and passed.
If rxed request header is not valid.
10.15.2.76
ProcessHeader Function
File
C static
char
* community,
BYTE* len
);
Description
data payload. This function validates the received udp packet for these different variables of snmp pdu. The sequence in which these elements are received is important. The validation is done for the agent processing capabilities and the max
UDP packet length as UDP packets can not be fragmented.
Remarks
The received pdu will be processed only if this routine returns the pdu type else the pdu is discarded as not Snmp pdu.
Preconditions
check if there is any packet on SNMP Agent socket, should return TRUE.
Parameters
Parameters
pduDbPtr community len
Return Values
Return Values
Description
Pointer to received pdu information database
Pointer to var storing, community string in rxed pdu
Pointer to var storing, community string length rxed in pdu
Description
Snmp request pdu type.
373
10.15 SNMP Microchip TCP/IP Stack Help SNMP Internal Members
10.15.2.77
ProcessSetVar Function
File
C
BYTE ProcessSetVar(
);
Description
This routine processes the received snmp set request pdu for the variable binding in the request and also creates the response pdu.
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
pduDbPtr rec errorStatus
Return Values
Return Values
copiedBytes
Description
Received pdu information database pointer
Pointer to SNMP MIB variable object information
Pointer to update error status info
Description
Number of bytes copied by this routine to the snmp pdu tx buffer.
10.15.2.78
ProcessVariables Function
File
C static
BOOL ProcessVariables(
char
* community,
BYTE len
);
Description
Once the received pdu is validated as Snmp pdu, it is forwarded for processing to this routine. This rotuine handles Get,
Get_Next, Get_Bulk, Set request and creates appropriate response as Get_Response. This routine will decide on whether the request pdu should be processed or be discarded.
Remarks
None
Preconditions
374
10.15 SNMP
Parameters
Parameters
pduDbPtr community len
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help SNMP Internal Members
Description
Pointer to received pdu information database
Pointer to var, storing community string in rxed pdu
Pointer to var, storing community string length rxed in pdu
Description
If the snmp request processing is successful.
If the processing failed else the processing is not completed.
10.15.2.79
ReadMIBRecord Function
File
C static void
ReadMIBRecord(
DWORD h,
);
Returns
None.
Description
This routine is called when a OID string is required to be searched from MPFS using node address.
Remarks
None.
Preconditions
GetOIDStringByID ( see page 368)() or GetOIDStringByAddr ( see page 368)() is called.
Parameters
Parameters
h rec
Description
Node adderess whose oid is to be read.
Pointer to store SNMP MIB variable object information
10.15.2.80
SNMPCheckIfPvtMibObjRequested Function
File
C static
BOOL SNMPCheckIfPvtMibObjRequested(
BYTE* OIDValuePtr
);
Description
This routine is used to find whether requested object belongs to the private object group of the mib of agent. If yes, then that mib object can be accessed only with private community (supported in SNMPv2c).
375
10.15 SNMP Microchip TCP/IP Stack Help
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Description
Pointer to memory stored with received OID.
Parameters
OIDValuePtr
Return Values
Return Values
TRUE
FLASE
Description
If the requested object is of private branch of the mib.
If the requested object is publically accessible.
SNMP Stack Members
10.15.3
SNMP Stack Members
Functions
Name Description
Initialize SNMP module internals.
SNMPTask ( see page 377) Polls for every snmp pdu received.
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.15.3.1
SNMPInit Function
File
C void
SNMPInit();
Returns
None
Description
This function initializes the Snmp agent. One udp socket is intialized and opened at port 161. Agent will receive and transmit all the snmp pdus on this udp socket.
Remarks
This function is called only once during lifetime of the application. One UDP socket will be used.
Preconditions
At least one UDP socket must be available. UDPInit ( see page 627)() is already called.
376
10.15 SNMP Microchip TCP/IP Stack Help Functions
10.15.3.2
SNMPTask Function
File
C
BOOL SNMPTask();
Description
Handle incoming SNMP requests as well as any outgoing SNMP responses and timeout conditions.
Remarks
None
Preconditions
SNMPInit ( see page 376)() is already called.
Return Values
Return Values
TRUE
FALSE
Description
If SNMP module has finished with a state
If a state has not been finished.
10.15.4
Functions
Functions
Name
_IsSNMPv3ValidStructure ( see page 379)
_Snmpv3IsValidAuthStructure ( see page 379)
_Snmpv3IsValidInt ( see page 380)
FindOIDsFromSnmpV3Request ( see page 381) getSnmpV2GenTrapOid ( see page 381)
IsSnmpV3ASNNull ( see page 382)
IsSnmpv3ValidOID ( see page 382)
IsSNMPv3ValidStructure ( see page 383)
ProcessGetBulkVar ( see page 383)
ProcessGetNextVar ( see page 384)
ProcessSnmpv3MsgData ( see page 385)
SNMPGetExactIndex ( see page 386)
Description
Decode variable length structure.
Decode variable length structure.
Verifies variable datatype as INT and retrieves its value.
Finds number of varbinds in the varbind list received in a SNMPv3 pdu.
Resolves generic trap code to generic trap OID.
Verifies the value type as ASN_NULL ( see page 349).
Populates OID type, length and oid string from the received pdu.
Decode variable length structure.
This routine process the SNMPv2c Get Bulk Request.
Retrieves next node from the MIB database.
Processes snmp Get request pdu.
This routine processes the snmpv3 request and parallely creates the response pdu.
To search for exact index node in case of a Sequence variable.
377
10.15 SNMP Microchip TCP/IP Stack Help Functions
SNMPIdRecrdValidation ( see page 386)
SNMPIsValidSetLen ( see page 387)
Used to Restrict the access dynamic and non dynamic
OID string for A perticular SNMP Version.
Validates the set variable data length to data type.
Snmpv3AESDecryptRxedScopedPdu ( see page
Snmpv3AESEncryptResponseScopedPdu ( see page 388)
Incoming SNMPv3 scoped PDU decryption using AES decryption protocol.
outGoing SNMPv3 scoped PDU Encryption using AES encryption protocol.
Snmpv3AuthenticateRxedPduForDataIntegrity ( see page 389)
Authenticate an incoming SNMPV3 USM PDU using
MD5 or SHA
Snmpv3AuthenticateTxPduForDataIntegrity ( see page 389)
Authenticate to an outgoing SNMPV3 USM PDU using
MD5 or SHA
Snmpv3AuthKeyZeroing2HmacBufLen64 ( see page 390)
Snmpv3BufferPut ( see page 390)
Pad zero to the authentication key localized buffer.
Snmpv3CmprTrapSecNameAndSecLvlWithUSMDb
Copies BYTE data to dynamically allocated memory buffer.
Routine to find the index of the user name in the user data base table.
Snmpv3ComputeHMACIpadOpadForAuthLoclzedKey
Compute HMAC inner and outer pad for authorization localized key.
Snmpv3ComputeHmacMD5Digest ( see page 392)
Compute HMAC - MD5 authentication code
Snmpv3ComputeHmacShaDigest ( see page 393)
Compute HMAC - SHA authentication code
Snmpv3ComputeMd5HmacCode ( see page 393)
Compute HMAC - MD5 authentication code
Snmpv3ComputeShaHmacCode ( see page 394)
Snmpv3FormulateEngineID ( see page 394)
Compute HMAC - SHA authentication code
Formulates the snmpEngineID ( see page 433) for the
SNMPV3 engine.
Snmpv3FreeDynAllocMem ( see page 395)
Snmpv3GetAuthEngineTime ( see page 395)
Snmpv3GetBufferData ( see page 396)
Snmpv3GetSecurityLevel ( see page 396)
Snmpv3GetTrapSecurityLevel ( see page 397)
Allocated dynamic memory freeing is done by this routine.
Updates the snmp engine time variable
'snmpEngineTime ( see page 434)' for the SNMPV3
engine.
Reads BYTE data from dynamically allocated memory buffer.
Get Security level from authentication and Privacy type.
Routine to find the report, auth and privacy flags settings in the TRAP.
Snmpv3InitializeUserDataBase ( see page 398)
Snmpv3IsValidAuthStructure ( see page 398)
Snmpv3IsValidInt ( see page 399)
Snmpv3MsgProcessingModelProcessPDU ( see page 399)
SNMPv3 initialization.
Intialize default SNMPv3 global user database.
Decode variable length structure.
Verifies variable datatype as INT and retrieves its value.
This routine collects or populates the message processing model infomation from the received
SNMPv3 request PDU or to the response PDU respectively.
Creates and Sends SNMPv3 TRAP pdu.
Snmpv3Pswd2LocalizedAuthKeyMD5Hashing ( see page 400)
Convert MD5 Auth password to the localized Key using
SNMPEngineID.
Snmpv3Pswd2LocalizedAuthKeySHAHashing ( see page 401)
Snmpv3ReportPdu ( see page 401)
Convert SHA Auth password to the localized Key using
SNMPEngineID.
Constructs the report pdu infomration for the Report
Pdu.
Snmpv3ScopedPduProcessing ( see page 402)
Snmpv3SetErrorStatus ( see page 402)
This routine collects the scoped pdu header information from the received SNMPv3 request PDU or populates to the response PDU respectively.
Set snmpv3 error status in the response pdu.
378
10.15 SNMP Microchip TCP/IP Stack Help Functions
Snmpv3TrapScopedpdu ( see page 403)
Snmpv3UserSecurityModelProcessPDU ( see page
Snmpv3UsmAesEncryptDecryptInitVector ( see page 404)
TRAP PDU scoped pdu header construction.
This routine collects or populates the security model parametrs infomation from the received SNMPv3 request PDU or to the response PDU respectively.
AES Encryption and decryption init vector.(RFC 3826 )
Snmpv3UsmOutMsgAuthenticationParam ( see page 405)
Snmpv3USMOutMsgPrivParam ( see page 405)
Snmpv3UsmSnmpEngnAuthPrivPswdLocalization ( see page 405)
Snmpv3ValidateEngineId ( see page 406)
Snmpv3ValidateSecNameAndSecLvl ( see page
Snmpv3ValidateSecurityName ( see page 407)
Both MD5 and SHA1 is used for the outgoing message authentication.
SNMP USM out message uses Privacy protocol (RFC
3826 )
Convert Auth and Priv password to the localized Key using SNMPEngineID.
Validate engine ID.
Vaidate security name with Security level.
Validate SNMPV3 user name or security name.
Module
10.15.4.1
_IsSNMPv3ValidStructure Function
File
C
BOOL _IsSNMPv3ValidStructure(
UINT8* wholeMsgPtr,
WORD* pos,
WORD* dataLen
);
Description
data length for max 4 bytes.
Remarks
None.
Preconditions
None
Parameters
Parameters
wholeMsgPtr pos val
ReturnValues
FALSE
Description
Pointer to memory where int var value is be stored.
position in the memory buffer where data taype to be varified is stored
Pointer to memory where int var value will be stored.
TRUE - If valid integer type and value is received.
Other than integer data type and value received .
10.15.4.2
_Snmpv3IsValidAuthStructure Function
File
379
10.15 SNMP Microchip TCP/IP Stack Help Functions
C
BYTE _Snmpv3IsValidAuthStructure(
WORD* dataLen
);
Description
variable binding structure length. This rotuine only refers to the incoming snmpv3 request dynamically allocated memory
buffer 'gSnmpV3InPduWholeMsgBuf ( see page 427)' .
Remarks
None.
Preconditions
ProcessHeader ( see page 373)() is called.
Parameters
Description
Pointer to memory to store OID structure length.
Parameters
datalen
Return Values
Return Values
headrbytes
FALSE
Description
Variable binding length.
If variable data structure is not type STRUCTURE ( see page 366).
10.15.4.3
_Snmpv3IsValidInt Function
File
C
BOOL _Snmpv3IsValidInt(
UINT8 * wholeMsgPtr,
WORD* pos,
DWORD* val
);
Description
length for max 4 bytes.
Remarks
None.
Preconditions
None
Parameters
Parameters
wholeMsgPtr pos val
ReturnValues
FALSE
Description
Pointer to memory where int var value is be stored.
position in the memory buffer where data taype to be varified is stored
Pointer to memory where int var value will be stored.
TRUE - If valid integer type and value is received.
Other than integer data type and value received .
380
10.15 SNMP Microchip TCP/IP Stack Help
10.15.4.4
FindOIDsFromSnmpV3Request Function
File
C static
BYTE FindOIDsFromSnmpV3Request(
WORD pdulen
);
Description
This routine is used to find the number of OIDs requested in the received snmp pdu.
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
pdulen
Return Values
Return Values
varCount
Description
Length of snmp pdu request received.
Description
Number of OIDs found in a pdu request.
10.15.4.5
getSnmpV2GenTrapOid Function
File
C
BYTE * getSnmpV2GenTrapOid(
BYTE generic_trap_code,
BYTE * len
);
Description
This function resolves given generic trap code to generic trap OID.
Remarks
Preconditions
SNMPNotifyPrepare ( see page 340)() is already called.
Parameters
Parameters
generic_trap_code len
Return Values
Return Values
BYTE *
Description
GENERIC_TRAP_NOTIFICATION_TYPE ( see page 333)
generic trap OID length
Description
TRAP OID
Functions
381
10.15 SNMP Microchip TCP/IP Stack Help Functions
10.15.4.6
IsSnmpV3ASNNull Function
File
C static
BOOL IsSnmpV3ASNNull();
Description
value field must be NULL and . This routine verifies the data type and value fields in the received requests. The SET
Remarks
None.
Preconditions
None
Parameters
Parameters
TRUE
FALSE
Description
If value type is ASN_NULL ( see page 349) and value is NULL.
If data type and value is other than ASN_NULL ( see page 349) and NULL
resp.
10.15.4.7
IsSnmpv3ValidOID Function
File
C static
BOOL IsSnmpv3ValidOID(
BYTE* oid,
BYTE* len
);
Description
only var bind is processed. OID length and OID is populated. The max OID length can be 15.
Remarks
None.
Preconditions
ProcessVariabels() is called.
Parameters
Parameters
oid len
Description
Pointer to memory to store the received OID string
Pointer to memory to store OID length
382
10.15 SNMP
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help Functions
Description
If value type is ASN_OID ( see page 350) and oid length not more than 15.
Otherwise.
10.15.4.8
IsSNMPv3ValidStructure Function
File
C
BOOL IsSNMPv3ValidStructure(
WORD* dataLen
);
Description
variable binding structure length. This rotuine only refers to the incoming snmpv3 request dynamically allocated memory
buffer 'gSNMPv3ScopedPduRequestBuf ( see page 428)' .
Remarks
None.
Preconditions
ProcessHeader ( see page 373)() is called.
Parameters
Parameters
datalen
Return Values
Return Values
TRUE
FALSE
Description
Pointer to memory to store OID structure length.
Description
If valid Structure data type and value is received.
If variable data structure is not type STRUCTURE ( see page 366).
10.15.4.9
ProcessGetBulkVar Function
File
C
BYTE ProcessGetBulkVar(
BYTE* oidValuePtr,
BYTE* oidLenPtr,
BYTE* successor,
);
Description
variable binding list to produce a response pdu. Depending on the number of the Max_repetitions for every variable in the list for which Bulk information is expected, ProcessGetBulkVar() is executed. It searches for the next lexicographically ordered successor for of the OID received in the request. For each of the iterations upto max-repetitions, the next leaf node is searched in the MIB to that of the leaf node found in the last iteration, for the corresponding variable binding.
383
10.15 SNMP Microchip TCP/IP Stack Help
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
rec oidValuePtr oidLenPtr successor
Return Values
Return Values
FALSE temp.v[0]
Description
Pointer to SNMP MIB variable object information OID
Pointer to new node OID found in MIB
Oid length
'I'th lexicographic successor to be found value
Description
If no lexicographic successor found
Total number of bytes copied to response packet
Functions
10.15.4.10
ProcessGetNextVar Function
File
C
BYTE ProcessGetNextVar(
);
Description
This routine reads into the MIB stored with the agent in MPFS2 format. It will search for the first lexicographic successor of the variable binding's name in the incoming GetNextRequest-PDU. If found, the corresponding variable binding's name and value fields in the Response pdu are set to the name and value of the located variable. If the lexicographic succesor is not found, the vlaue filed is set to "endofMibView" and name field is retained as in request.
Remarks
None.
Preconditions
ProcessVariables ( see page 374) is called.
Parameters
Parameters
rec pduDbPtr
Return Values
Return Values
Value
FALSE
Description
Pointer to SNMP MIB object information for which next node to be found
Pointer to received pdu information database
Description
Total number of bytes copied to response packet if succesful.
If End of MIB is reached or processing is failure.
384
10.15 SNMP Microchip TCP/IP Stack Help Functions
10.15.4.11
ProcessGetVar Function
File
C
BYTE ProcessGetVar(
BOOL bAsOID,
);
Description
This routine processes the received snmp Get request pdu for the variable binding in the request and also creates the response pdu.
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
rec bAsOID
Return Values
Return Values
varLen
FALSE
Description
Pointer to SNMP MIB variable object information
Oid flag.
Description
Number of bytes put in response tx pdu
If any of the elements of the request pdu validation fails.
10.15.4.12
ProcessSnmpv3MsgData Function
File
C
BOOL ProcessSnmpv3MsgData(
);
Description
Once the received pdu is validated as Snmpv3 pdu, it is forwarded for processing to this routine. This rotuine handles Get,
Get_Next, Get_Bulk, Set request and creates appropriate response as Get_Response. This routine will decide on whether the request pdu should be processed or be discarded.
Remarks
None
Preconditions
The received udp packet is varified as valid SNMPv3 request.
385
10.15 SNMP
Parameters
Parameters
pduDbPtr
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help
Description
Pointer to received pdu information database
Functions
Description
If the snmp request processing is successful.
If the processing failed else the processing is not completed.
10.15.4.13
SNMPGetExactIndex Function
File
C
BOOL SNMPGetExactIndex(
);
Description
This is a callback function called by SNMP module. SNMP user must implement this function in user application and provide appropriate data when called. This function will only be called for OID variable of type sequence.
Remarks
Only sequence index needs to be handled in this function.
Preconditions
None
Parameters
Parameters
var index
Return Values
Return Values
TRUE
FALSE
Description
Variable id as per mib.h (input)
Index of variable (input)
Description
If the exact index value exists for given variable at given index.
Otherwise.
10.15.4.14
SNMPIdRecrdValidation Function
File
C
BOOL SNMPIdRecrdValidation(
BYTE * oidValuePtr,
BYTE oidLen
);
Description
This is a callback function called by SNMP module. SNMP user must implement this function as per SNMP version. One
386
10.15 SNMP Microchip TCP/IP Stack Help Functions need to add the new SNMP MIB IDs hereas per SNMP version. e.g - SYS_UP_TIME (250) is common for V1/V2/V3
ENGINE_ID - is the part of V3, So put the all the SNMPv3 var ids within Macro STACK_USE_SNMPV3_SERVER.
Remarks
None.
Preconditions
None
Parameters
Parameters
var oidValuePtr oidLen
Return Values
Return Values
TRUE
FALSE
Description
Variable rec whose record id need to be validated
OID Value oidValuePtr length
Description
If a Var ID exists .
Otherwise.
10.15.4.15
SNMPIsValidSetLen Function
File
C
BOOL SNMPIsValidSetLen(
BYTE len,
BYTE index
);
Description
This routine is used to validate the dyanmic variable data length to the variable data type. It is used when SET request is processed. This is a callback function called by module. User application must implement this function.
Remarks
357) (i.e. data length greater than 4 bytes)
Preconditions
ProcessSetVar ( see page 374)() is called.
Parameters
Parameters
var len index
Return Values
Return Values
TRUE
FALSE
Description
Variable id whose value is to be set
Length value that is to be validated.
instance of a OID
Description
if given var can be set to given len if otherwise.
387
10.15 SNMP Microchip TCP/IP Stack Help Functions
10.15.4.16
Snmpv3AESDecryptRxedScopedPdu Function
File
C
BYTE Snmpv3AESDecryptRxedScopedPdu();
Description
This routine decrypts SNMPV3 incoming PDU using AES protocol , but before this encrypted data length is verified.If the length of the encrypted OCTECT-STRING is not multiple of 8, then dryption will be halted. RFC - 3414. ( section 8)
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Return Values
Return Values
SNMPV3_MSG_PRIV_FAIL
SNMPV3_MSG_PRIV_PASS
Description
Failure
Success
10.15.4.17
Snmpv3AESEncryptResponseScopedPdu Function
File
C
BYTE Snmpv3AESEncryptResponseScopedPdu(
SNMPV3_RESPONSE_WHOLEMSG* plain_text
);
Description
This routine encrypts SNMPV3 outgoing PDU using AES protocol to maintain the data confidentiality. The data is encrypted in Cipher Block Chaining mode. The length of the encrypted data should be multiple of 8 and it is not then then data is padded in the end if necessary. RFC - 3414. ( section 8)
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
plain_text
Return Values
Return Values
SNMPV3_MSG_PRIV_FAIL
SNMPV3_MSG_PRIV_PASS
Description
whole PDU message
Description
Failure
Success
388
10.15 SNMP Microchip TCP/IP Stack Help Functions
10.15.4.18
Snmpv3AuthenticateRxedPduForDataIntegrity Function
File
C
BYTE Snmpv3AuthenticateRxedPduForDataIntegrity(
SNMPV3_REQUEST_WHOLEMSG* rxDataPtr
);
Description
This routine authenticates SNMPV3 incoming report PDU message and also for different type of GET requests with both
MD5 and SHA protocol.If the received PDU username is similar to "initial", then there shoud be report PDU. RFC - 3414.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
rxDataPtr
Return Values
Return Values
SNMPV3_MSG_AUTH_PASS
SNMPV3_MSG_AUTH_FAIL
Description
incoming PDU
Description
Authentication ( see page 91) success
Authentication ( see page 91) failure
10.15.4.19
Snmpv3AuthenticateTxPduForDataIntegrity Function
File
C
BYTE Snmpv3AuthenticateTxPduForDataIntegrity(
SNMPV3_RESPONSE_WHOLEMSG* txDataPtr
);
Description
This routine authenticates SNMPV3 outgoing report PDU message and also for GET Response PDU for whole message.
RFC - 3414.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
txDataPtr
Description
outgoing PDU
389
10.15 SNMP
Return Values
Return Values
SNMPV3_MSG_AUTH_PASS
SNMPV3_MSG_AUTH_FAIL
Microchip TCP/IP Stack Help
Description
Authentication ( see page 91) success
Authentication ( see page 91) failure
10.15.4.20
Snmpv3AuthKeyZeroing2HmacBufLen64 Function
File
C void
Snmpv3AuthKeyZeroing2HmacBufLen64(
UINT8* authKey,
UINT8 authKeyLen,
UINT8 hashType
);
Description
this routine will pad the (64-authKeyLen) number of zeros to the end of auth key localized buffer.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
authkey authKeylen hashType
Description
authentication key buffer authentication key length authentication type
Functions
10.15.4.21
Snmpv3BufferPut Function
File
C
BOOL Snmpv3BufferPut(
BYTE val,
);
Description
The SNMPv3 stack implementation uses dynamically allocated memory buffer for processing of request and response packets. This routine copies the BYTE data to the allocated buffer and updates the offset length couter.
Remarks
This routine is used by the SNMPv3 stack. If required to be used by the application code, valid pointers should be passed to this routine.
Preconditions
The SNMPv3 stack has sucessfully allocated dynamic memory buffer from the Heap
390
10.15 SNMP
Parameters
Parameters
val putbuf
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help
Description
BYTE value to be written to the buffer pointer to the dynamically allocated buffer to which the 'val' to be written
Functions
Description
if successfully write to the buffer failure in writing to the buffer
10.15.4.22
Snmpv3CmprTrapSecNameAndSecLvlWithUSMDb
Function
File
C
BOOL Snmpv3CmprTrapSecNameAndSecLvlWithUSMDb(
BYTE tragetIndex,
BYTE userTrapSecLen,
UINT8 * userTrapSecurityName,
STD_BASED_SNMPV3_SECURITY_LEVEL securityLevel
);
Description
request.
Remarks
None.
Preconditions
SET operation would be allowed if the USM security conditions and user security name in the request is matched to one of the user security name stored in the usm user database.
Parameters
Parameters
userTrapSecLen userTrapSecurityName securityLevel
Return Values
Return Values
TRUE
FLASE
Description
user sec name length in the SET request pointer to user sec name in the SET request trap security level to be SET on the agent
Description
if the trap target user sec level setting is successful
If the SET failed due to non matching of the security parameters
10.15.4.23
Snmpv3ComputeHMACIpadOpadForAuthLoclzedKey
Function
File
391
10.15 SNMP Microchip TCP/IP Stack Help
C void
Snmpv3ComputeHMACIpadOpadForAuthLoclzedKey(
UINT8 userDBIndex
);
Description
This routine computes HMAC inner and outer pad strings for authorization localized key. RFC - 2104.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
userDBIndex
Description
password storage poniter
Functions
10.15.4.24
Snmpv3ComputeHmacMD5Digest Function
File
C
UINT8* Snmpv3ComputeHmacMD5Digest(
UINT8 * inData,
UINT32 dataLen,
UINT8* userExtendedLclzdKeyIpad,
UINT8* userExtendedLclzdKeyOpad
);
Description
This routine supports data origin authentication and data integrity MD5 authentication . Both iPAD and OPAD is used to calculate the authencate digest string. RFC - 3414 ( section 6)
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
digestptr indata dataLen userExtendedLclzdKeyIpad userExtendedLclzdKeyOpad
Return Values
Return Values
UINT8 *
Description
output string input data input data length
IPAD
OPAD
Description
HMAC MD5 digest string
392
10.15 SNMP Microchip TCP/IP Stack Help Functions
10.15.4.25
Snmpv3ComputeHmacShaDigest Function
File
C
UINT8* Snmpv3ComputeHmacShaDigest(
UINT8 * inData,
UINT32 dataLen,
UINT8* userExtendedLclzdKeyIpad,
UINT8* userExtendedLclzdKeyOpad
);
Description
This routine supports data origin authentication and data integrity SHA authentication . Both iPAD and OPAD is used to calculate the authencate digest string. RFC - 3414 ( section 6)
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
digestptr indata dataLen userExtendedLclzdKeyIpad userExtendedLclzdKeyOpad
Return Values
Return Values
UINT8 *
Description
output string input data input data length
IPAD
OPAD
Description
HMAC SHA digest string
10.15.4.26
Snmpv3ComputeMd5HmacCode Function
File
C void
Snmpv3ComputeMd5HmacCode(
UINT8 xx_bits,
UINT8* digestptr,
UINT8 * indata,
UINT32 dataLen,
UINT8* userExtendedLclzdKeyIpad,
UINT8* userExtendedLclzdKeyOpad
);
Description
This routine supports data origin authentication and data integrity MD5 authentication . Both iPAD and OPAD is used to calculate the authencate digest string. RFC - 3414 ( section 6)
Remarks
None
393
10.15 SNMP Microchip TCP/IP Stack Help
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
xx_bits digestptr indata dataLen userExtendedLclzdKeyIpad userExtendedLclzdKeyOpad
Description
96 bit output string input data input data length
IPAD
OPAD
Functions
10.15.4.27
Snmpv3ComputeShaHmacCode Function
File
C void
Snmpv3ComputeShaHmacCode(
UINT8 xx_bits,
UINT8* digestptr,
UINT8 * indata,
UINT32 dataLen,
UINT8* userExtendedLclzdKeyIpad,
UINT8* userExtendedLclzdKeyOpad
);
Description
This routine supports data origin authentication and data integrity SHA authentication . Both iPAD and OPAD is used to calculate the authencate digest string. RFC - 3414 ( section 6)
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
xx_bits digestptr indata dataLen userExtendedLclzdKeyIpad userExtendedLclzdKeyOpad
Description
96 bit output string input data input data length
IPAD
OPAD
10.15.4.28
Snmpv3FormulateEngineID Function
File
C void
Snmpv3FormulateEngineID(
UINT8 fifthOctectIdentifier
394
10.15 SNMP Microchip TCP/IP Stack Help Functions
);
Description
using the application MAC address. 'fifthOctectIdentifier' defualt set to MAC_ADDR_ENGN_ID as the following octets used
for the snmpEngineID ( see page 433) are of mac address.
User can set this octet of their choice to fomulate new
fifthOctectIdentifier=IPV4_ADDR_ENGN_ID;
If fifthOctectIdentifier=ADMIN_ASSIGNED_TEXT; or fifthOctectIdentifier=ADMIN_ASSIGNED_OCTETS; then the following octets should be provided by the administrator through some custom application interface mechanism. API parameter
'fifthOctectIdentifier' has to be upated in the intefrace API before passing through Snmpv3FormulateEngineID().
Remarks
update the new localized keys at the agent as well as at the manager.
Preconditions
InitAppConfig(); is called.
Parameters
Parameters
fifthOctectIdentifier
Description
Value of the 5th octet in the snmpEngineID ( see page 433) which indicates
how the rest (6th and following octets) are formatted.
10.15.4.29
Snmpv3FreeDynAllocMem Function
File
C void
Snmpv3FreeDynAllocMem();
Description
On the successful completion of the processing of the SNMPv3 request, or the failure in the processing due to improper
PDU formats, the allocated dynamic memory is required to be freed. This routine calls the free(), to deallocate memory.
Remarks
The SNMPv3 stack does uses the dynamic memory extensively for different processing needs, hence incoming and outgoing pdu memory buffers are created. This routine checks for the memory is being allocated before it attempts for the deallocation.
Preconditions
The dyanmic memory buffer is allocated.
10.15.4.30
Snmpv3GetAuthEngineTime Function
File
C void
Snmpv3GetAuthEngineTime();
395
10.15 SNMP Microchip TCP/IP Stack Help Functions
Description
'snmpEngineTime ( see page 434)' cntr ovrflowed the (2^31 -1) value specified in RFC3411.
Remarks
Preconditions
SNMPInit ( see page 376)(); is called.
10.15.4.31
Snmpv3GetBufferData Function
File
C
BYTE Snmpv3GetBufferData(
UINT16 pos
);
Description
The SNMPv3 stack implementation uses dynamically allocated memory buffer for processing of request and response packets. This routine reads the BYTE data from the allocated buffer at the positions (offset) provided.
Remarks
The read position offset is required to be provided every time the routine is called. This API do not increment the buffer read offset automatically, everytime it is called.
Preconditions
The SNMPv3 stack has sucessfully allocated dynamic memory buffer from the Heap
Parameters
Parameters
getbuf pos
Return Values
Return Values
BYTE
Description
Structure from where to read the data byte.
position in the buffer from which the data to be read
Description
1 byte value read
10.15.4.32
Snmpv3GetSecurityLevel Function
File
C
BYTE Snmpv3GetSecurityLevel(
BYTE userIndex
);
396
10.15 SNMP Microchip TCP/IP Stack Help Functions
Description
This routine uses authenticationa dn privacy type to find out the exact security enum type.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Return Values
Return Values
NO_REPORT_PRIVACY_AND_AUTH_PROVIDED
Description
Only Privacy and Authentication ( see page 91)
NO_REPORT_NO_PRIVACY_BUT_AUTH_PROVIDED Only Auth , no privacy and no report
NO_REPORT_NO_PRIVACY_NO_AUTH
No report, no Privacy and no Authentication ( see page 91)
10.15.4.33
Snmpv3GetTrapSecurityLevel Function
File
C
BYTE Snmpv3GetTrapSecurityLevel(
STD_BASED_SNMPV3_SECURITY_LEVEL securityLevel
);
Description
This routine to find the report, auth and privacy flags setting for the trap to be generated. The message flags octet's least significant three bits: Reportable, PrivFlag, AuthFlag forms different secuity level combinations.
Remarks
None.
Preconditions
None
Return Values
Return Values
NO_REPORT_NO_PRIVACY_NO_AUTH
Description
No authentication, no encryption
NO_REPORT_NO_PRIVACY_BUT_AUTH_PROVIDED authentication but no encryption
NO_REPORT_PRIVACY_AND_AUTH_PROVIDED authentication and encryption
INVALID_MSG if security level doesn't match any of the above
10.15.4.34
Snmpv3Init Function
File
C void
Snmpv3Init();
Description
This routine will intialize SNMPv3 global data base ,engine ID and USM
397
10.15 SNMP Microchip TCP/IP Stack Help
Remarks
None
Preconditions
At least one UDP socket must be available. UDPInit ( see page 627)() is already called.
Functions
10.15.4.35
Snmpv3InitializeUserDataBase Function
File
C void
Snmpv3InitializeUserDataBase();
Description
There are three default username, authentication, authenticaton password and Privacy name and privacy password intialized with SNMPv3 global databse.
Remarks
None
Preconditions
SNMPv3Init() is called.
10.15.4.36
Snmpv3IsValidAuthStructure Function
File
C
BYTE Snmpv3IsValidAuthStructure(
WORD* dataLen
);
Description
variable binding structure length.
Remarks
None.
Preconditions
ProcessHeader ( see page 373)() is called.
Parameters
Parameters
datalen
Return Values
Return Values
headrbytes
FALSE
Description
Pointer to memory to store OID structure length.
Description
Variable binding length.
If variable data structure is not type STRUCTURE ( see page 366).
398
10.15 SNMP Microchip TCP/IP Stack Help Functions
10.15.4.37
Snmpv3IsValidInt Function
File
C
BOOL Snmpv3IsValidInt(
DWORD* val
);
Description
length for max 4 bytes. This rotuine only refers to the incoming snmpv3 request dynamically allocated memory buffer
'gSNMPv3ScopedPduRequestBuf ( see page 428)' .
Remarks
None.
Preconditions
None
Parameters
Parameters
val
ReturnValues
FALSE
Description
Pointer to memory where int var value will be stored.
TRUE - If valid integer type and value is received.
Other than integer data type and value received .
10.15.4.38
Snmpv3MsgProcessingModelProcessPDU Function
File
C
SNMP_ERR_STATUS Snmpv3MsgProcessingModelProcessPDU(
BYTE inOutPdu
);
Description
The recievd SNMPv3 PDU or the transmit PDU header has message processing data bytes infomration. This routine retrievs the messgae processing model infomration from the stored pdu or write the appropriate msg proc info to the repsonse msg buffer.
Remarks
The messgae processing model parameters like 'msgID', 'msgMaxSize', 'msgFlags' and 'msgSecurityModel' decides the
SNMPv3 engine processing modalities regarding request or response PDU
Preconditions
Valid SNMPv3 request msg is received.
Parameters
Parameters
inOutPdu
Description
indicates whether the incomig PDU is to be read for msg proc values to be retrieved or the response PDU is to be populated with these values
399
10.15 SNMP
Return Values
Return Values
SNMP_NO_CREATION
SNMP_NO_ERR
Microchip TCP/IP Stack Help Functions
Description
Failure due to improper msg processing information format in the received PDU or failure in constructing the response PDU.
The message processing infomration retrieval or response PDU fomration is successful
10.15.4.39
Snmpv3Notify Function
File
C
BOOL Snmpv3Notify(
UINT8 targetIndex
);
Description
This function creates SNMPv3 trap PDU and sends it to previously specified remoteHost.
Remarks
None
Preconditions
TRAP event is triggered.
Parameters
Parameters
var val index
Description
SNMP var ID that is to be used in notification
Value of var. Only value of BYTE, WORD or DWORD can be sent.
Index of var. If this var is a single,index would be 0, or else if this var Is a sequence, index could be any value from 0 to 127 targetIndex -index of the
'gSnmpv3TrapConfigData ( see page 429)' table's security user name for
which the TRAP PDU message header to constructed.
Return Values
Return Values
TRUE
FALSE
This would fail under following contions
4) Data type of given var is unknown
SNMPV3_MSG_AUTH_FAIL
Description
if SNMP notification was successful sent. This does not guarantee that remoteHost recieved it.
Notification sent failed.
1) Given SNMP_BIB_FILE does not exist in MPFS 2) Given var does not exist.
3) Previously given agentID does not exist only possible if MPFS itself was corrupted. SNMPV3_MSG_PRIV_FAIL
-encryption of the trap msg failed
HAMC of the trap msg failed
10.15.4.40
Snmpv3Pswd2LocalizedAuthKeyMD5Hashing Function
File
400
10.15 SNMP Microchip TCP/IP Stack Help
C void
Snmpv3Pswd2LocalizedAuthKeyMD5Hashing(
UINT8* pswdToLocalized,
UINT8 pswdLen
);
Description
This routine converts HMAC-MD5 authentication password key to localized key using snmpSngineID(RFC- 3414).
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
pswdToLocalized pswdLen
Description
password storage poniter password length.
Functions
10.15.4.41
Snmpv3Pswd2LocalizedAuthKeySHAHashing Function
File
C void
Snmpv3Pswd2LocalizedAuthKeySHAHashing(
UINT8* pswdToLocalized,
UINT8 pswdLen
);
Description
This routine converts HMAC-SHA authentication password key to localized key using snmpSngineID(RFC- 3414).
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
pswdToLocalized pswdLen
Description
password storage poniter password length.
10.15.4.42
Snmpv3ReportPdu Function
File
C void
Snmpv3ReportPdu(
SNMPV3MSGDATA * dynScopedBufPtr
);
401
10.15 SNMP Microchip TCP/IP Stack Help Functions
Description
The SNMPv3 PDU exchange starts with the agent sending a report pdu on reception of any Get_Request PDU for SNMPv3 request. This routine froms the report pdu for response to the requesting entity.
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called and a valid SNMPv3 request is received.
Parameters
Parameters
dynScopedBufPtr
Description
pointer to the response buffer memory where the 'report' response to be savced for transmission.
10.15.4.43
Snmpv3ScopedPduProcessing Function
File
C
SNMP_ERR_STATUS Snmpv3ScopedPduProcessing(
BYTE inOutPdu
);
Description
The recievd SNMPv3 PDU or the transmit PDU header has scoped pdu parameters like 'contextEngineID' 'context name' etc. This routine retrievs these parameters infomration from the stored incoming pdu or write the appropriate dynamically allocated memory for the transmit response PDU.
Remarks
The scoped pDu parameters msg data : - [==
Preconditions
Valid SNMPv3 request msg is received.
Parameters
Parameters
inOutPdu
Description
indicates whether the incomig PDU is to be read for scoped pdu paraemters to be retrieved or the response PDU to be populated with these values
Return Values
Return Values
SNMP_NO_CREATION
SNMP_NO_ERR
Description
Failure due to improper scoped pdu information format in the PDU or failure in constructing the response PDU.
The scoped parameters retrieval or response PDU fomration is successful
10.15.4.44
Snmpv3SetErrorStatus Function
File
C void
Snmpv3SetErrorStatus(
WORD errorStatusOffset,
402
10.15 SNMP Microchip TCP/IP Stack Help Functions
WORD errorIndexOffset,
BYTE errorIndex,
SNMPV3MSGDATA * dynScopedPduPutBuf
);
Returns
None.
Description
This routine processes the received snmp Get request pdu for the variable binding in the request and also creates the response pdu.
Remarks
None.
Preconditions
ProcessVariables ( see page 374)() is called.
Parameters
Parameters
errorStatusOffset errorIndexOffset errorStatus errorIndex dynScopedPduPutBuf
Description
Offset to update error status in Response Tx pdu
Offset to update error index
Snmp process error to be updated in response.
Index of the request varbind in the var bind list for which error status is to be updated.
dynamic snmpv3 scoped pdu buffer
10.15.4.45
Snmpv3TrapScopedpdu Function
File
C
UINT8 Snmpv3TrapScopedpdu(
UINT8 targetIndex
);
Description
This routine forms the trap scoped pdu header for the SNMPv3 trap PDU to be originated from this agent. Scoped pdu comprises of msg data : - [== For ASCII STR trap VAL(argument) contains the pointer address of the string variable.
Remarks
None.
Preconditions
TRAP event is triggered.
Parameters
Parameters
var val index
Description
var id of the variable whose value to be sent in the trap pdu value of the variable index of the variable in the multiple variable bind scenario targetIndex -index of
the 'gSnmpv3TrapConfigData ( see page 429)' table's security user name for
which the TRAP PDU message header to constructed.
403
10.15 SNMP
Return Values
Return Values
TRUE
Microchip TCP/IP Stack Help Functions
Description
The trap scoped pdu header generation is successful. FALSE -The trap scoped pdu header generation failed.
10.15.4.46
Snmpv3UserSecurityModelProcessPDU Function
File
C
SNMP_ERR_STATUS Snmpv3UserSecurityModelProcessPDU(
BYTE inOutPdu
);
Description
The recievd SNMPv3 PDU or the transmit PDU header has message security data bytes infomration. This routine retrievs the messgae security parameters infomration from the stored incoming pdu or write the appropriate security model info to the repsonse msg buffer.
Remarks
The user security parameter constitute the vital information for the message authentication and privacy of the message. The user security model parameters header structure MsgAuthEngnID+MsgAuthEngnBoots+MsgAuthEngnTime
+MsgUserName+MsgAuthParam+MsgPrivParam
Preconditions
Valid SNMPv3 request msg is received.
Parameters
Parameters
inOutPdu
Description
indicates whether the incomig PDU is to be read for user security model to be retrieved or the response PDU to be populated with these values
Return Values
Return Values
SNMP_NO_CREATION
SNMP_NO_ERR
Description
Failure due to improper security model processing information format in the received PDU or failure in constructing the response PDU.
The user security model retrieval or response PDU fomration is successful
10.15.4.47
Snmpv3UsmAesEncryptDecryptInitVector Function
File
C void
Snmpv3UsmAesEncryptDecryptInitVector(
BYTE inOutPdu
);
Description
snmpEngineTime ( see page 434) converted to subsequent four bytes.
Remarks
None
404
10.15 SNMP Microchip TCP/IP Stack Help
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
inOutPdu
Description
SNMP request PDU
10.15.4.48
Snmpv3UsmOutMsgAuthenticationParam Function
File
C void
Snmpv3UsmOutMsgAuthenticationParam(
UINT8 hashType
);
Description
This routine prepares out message with HMAC-MD5 or HMAC-SHA1 authentication protocol.(RFC- 3414 - section 6)
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
hashType
Description
authentication protocol type
10.15.4.49
Snmpv3USMOutMsgPrivParam Function
File
C void
Snmpv3USMOutMsgPrivParam();
Description
SNMPEngineTime is used to encrypt the outgoing message with a random value.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Functions
10.15.4.50
Snmpv3UsmSnmpEngnAuthPrivPswdLocalization
Function
File
405
10.15 SNMP Microchip TCP/IP Stack Help Functions
C void
Snmpv3UsmSnmpEngnAuthPrivPswdLocalization(
UINT8 userDBIndex
);
Description
This routine converts MD5 or SHA1 and AES privacy password key to localized key using snmpSngineID(RFC- 3414 section 6).
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Parameters
Parameters
userDBIndex
Description
authentication protocol type
10.15.4.51
Snmpv3ValidateEngineId Function
File
C
BOOL Snmpv3ValidateEngineId();
Description
This routine validates Engine ID.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Return Values
Return Values
FALSE
TRUE
Description
Failure
Success
10.15.4.52
Snmpv3ValidateSecNameAndSecLvl Function
File
C
BOOL Snmpv3ValidateSecNameAndSecLvl();
Description
This routine validates secuirity name and secuirty level with SNMP global data base for an incoming PDU.
Remarks
None
406
10.15 SNMP Microchip TCP/IP Stack Help
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Return Values
Return Values
TRUE
FALSE
Description
success failure
10.15.4.53
Snmpv3ValidateSecurityName Function
File
C
BOOL Snmpv3ValidateSecurityName();
Description
This routine validates user name.
Remarks
None
Preconditions
SNMPv3Init() and ProcessVariabels() are called.
Return Values
Return Values
FALSE
TRUE
Description
Failure
Success
Structs, Records, Enums
10.15.5
Structs, Records, Enums
Module
Structures
Name
AccessCtrlSubSysIsAccessAllowed ( see page 408)
Description
Applications are the typical clients of the service(s) of the Access
Control Subsystem. The following primitive is provided by the
Access Control Subsystem to check if access is allowed:
statusInformation ( see page 422) = -- success or errorIndication
dispatcherProcessPdu ( see page 409) Process Incoming Request or Notification PDU
Dispatcher provides the following primitive to pass an incoming snmp pdu to an application.
dispatcherStatusInfo ( see page 409)
Generate Outgoing Request or Notification
statusInformation ( see page 422) = -- sendPduHandle if success --
errorIndication if failure
dispathcerReturnResponsePdu ( see page 410)
Generate Outgoing Response
The PDU Dispatcher provides the following primitive for an application to return an SNMP Response PDU to the PDU
Dispatcher: result = SUCCESS or FAILURE
407
10.15 SNMP Microchip TCP/IP Stack Help Structs, Records, Enums
MsgProcModPrepareDataElements ( see page 411)
Prepare Data Elements from an Incoming SNMP Message
The Message Processing Subsystem provides this service primitive for preparing the abstract data elements from an incoming SNMP message: result = -- SUCCESS or errorIndication
MsgProcModPrepareOutgoingMessage
Prepare Outgoing SNMP Request or Notification Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Request or Notification Message
MsgProcModPrepareResponseMessage
Prepare an Outgoing SNMP Response Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Response Message: result = --
SUCCESS or FAILURE
processResponsePdu ( see page 413) Process Incoming Response PDU
The PDU Dispatcher provides the following primitive to pass an incoming SNMP Response PDU to an application: success or errorIndication
registerContextEngineID ( see page
SecuritySysGenerateRequestMsg ( see page 414)
SecuritySysGenerateResponseMsg ( see page 415)
This is record SecuritySysGenerateRequestMsg.
Generate a Response Message
The Security Subsystem provides the following primitive to generate a Response message:
unregisterContextEngineID ( see page
Release State Reference Information
All Subsystems which pass stateReference information also provide a primitive to release the memory that holds the referenced state information
This is record unregisterContextEngineID.
10.15.5.1
AccessCtrlSubSysIsAccessAllowed Structure
File
C struct
AccessCtrlSubSysIsAccessAllowed {
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE viewType;
BYTE* contextName;
BYTE* variableName;
};
Members
Members
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE viewType;
BYTE* contextName;
BYTE* variableName;
Description
Security Model in use principal who wants to access
Level of Security read, write, or notify view context containing variableName
OID for the managed object
Description
Applications are the typical clients of the service(s) of the Access Control Subsystem. The following primitive is provided by the Access Control Subsystem to check if access is allowed:
statusInformation ( see page 422) = -- success or errorIndication
408
10.15 SNMP Microchip TCP/IP Stack Help Structs, Records, Enums
10.15.5.2
dispatcherProcessPdu Structure
File
C struct
dispatcherProcessPdu {
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
DWORD_VAL maxSizeResponseScopedPDU;
UINT32 stateReference;
};
Members
Members
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
DWORD_VAL maxSizeResponseScopedPDU;
UINT32 stateReference;
Description
typically, SNMP version
Security Model in use on behalf of this principal
Level of Security data from/at this SNMP entity data from/in this context the version of the PDU
SNMP Protocol Data Unit maximum size of the Response PDU reference to state information needed when sending a response
Description
Process Incoming Request or Notification PDU
Dispatcher provides the following primitive to pass an incoming snmp pdu to an application.
10.15.5.3
dispatcherStatusInfo Structure
File
C struct
dispatcherStatusInfo {
BYTE transportDomain;
UINT32 transportAddress;
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
BOOL expectResponse;
};
409
10.15 SNMP Microchip TCP/IP Stack Help
Members
Members
BYTE transportDomain;
UINT32 transportAddress;
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
BOOL expectResponse;
Description
transport domain to be used transport address to be used typically, SNMP version
Security Model to use on behalf of this principal
Level of Security requested data from/at this entity data from/in this context the version of the PDU
SNMP Protocol Data Unit
TRUE or FALSE
Description
Generate Outgoing Request or Notification
statusInformation ( see page 422) = -- sendPduHandle if success -- errorIndication if failure
Structs, Records, Enums
10.15.5.4
dispathcerReturnResponsePdu Structure
File
C struct
dispathcerReturnResponsePdu {
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
UINT32 maxSizeResponseScopedPDU;
UINT32 stateReference;
};
Members
Members
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
Description
typically, SNMP version
Security Model in use on behalf of this principal same as on incoming request
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion; data from/at this SNMP entity data from/in this context the version of the PDU
BYTE* PDU; SNMP Protocol Data Unit
UINT32 maxSizeResponseScopedPDU;
maximum size sender can accept ( see page 174)
UINT32 stateReference; statusInformation statInfo; reference to state information as presented with the request success or errorIndication, error counter OID/value if error
410
10.15 SNMP Microchip TCP/IP Stack Help Structs, Records, Enums
Description
Generate Outgoing Response
The PDU Dispatcher provides the following primitive for an application to return an SNMP Response PDU to the PDU
Dispatcher: result = SUCCESS or FAILURE
10.15.5.5
MsgProcModPrepareDataElements Structure
File
C struct
MsgProcModPrepareDataElements {
BYTE transportDomain;
UINT32 transportAddress;
BYTE* wholeMsg;
UINT32 wholeMsgLength;
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
BYTE pduType;
UINT32 maxSizeResponseScopedPDU;
UINT32 stateReference;
};
Members
Members
BYTE transportDomain;
UINT32 transportAddress;
BYTE* wholeMsg;
UINT32 wholeMsgLength;
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
Description
origin transport domain origin transport address as received from the network as received from the network typically, SNMP version
Security Model to use on behalf of this principal
Level of Security requested
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion; data from/at this entity data from/in this context the version of the PDU
BYTE* PDU;
BYTE pduType;
SNMP Protocol Data Unit
SNMP PDU type OUT sendPduHandle; // handle for matched request
UINT32 maxSizeResponseScopedPDU;
maximum size sender can accept ( see page 174)
statusInformation statInfo;
UINT32 stateReference; success or errorIndication error counter OID/value if error reference to state information to be used for possible Response
Description
Prepare Data Elements from an Incoming SNMP Message
The Message Processing Subsystem provides this service primitive for preparing the abstract data elements from an incoming SNMP message: result = -- SUCCESS or errorIndication
411
10.15 SNMP Microchip TCP/IP Stack Help Structs, Records, Enums
10.15.5.6
MsgProcModPrepareOutgoingMessage Structure
File
C struct
MsgProcModPrepareOutgoingMessage {
BYTE transportDomain;
UINT32 transportAddress;
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
BOOL expectResponse;
BYTE destTransportDomain;
UINT32 destTransportAddress;
BYTE* outgoingMessage;
UINT32 outgoingMessageLength;
};
Members
Members
BYTE transportDomain;
UINT32 transportAddress;
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
BOOL expectResponse;
BYTE destTransportDomain;
UINT32 destTransportAddress;
BYTE* outgoingMessage;
UINT32 outgoingMessageLength;
Description
transport domain to be used transport address to be used typically, SNMP version
Security Model to use on behalf of this principal
Level of Security requested data from/at this entity data from/in this context the version of the PDU
SNMP Protocol Data Unit
TRUE or FALSE IN sendPduHandle; //the handle for matching incoming responses destination transport domain destination transport address the message to send its length
Description
Prepare Outgoing SNMP Request or Notification Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Request or Notification
Message
10.15.5.7
MsgProcModPrepareResponseMessage Structure
File
412
10.15 SNMP Microchip TCP/IP Stack Help Structs, Records, Enums
C struct
MsgProcModPrepareResponseMessage {
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
UINT32 maxSizeResponseScopedPDU;
UINT32 stateReference;
BYTE destTransportDomain;
UINT32 destTransportAddress;
BYTE* outgoingMessage;
UINT32 outgoingMessageLength;
};
Members
Members
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
Description
typically, SNMP version same as on incoming request same as on incoming request same as on incoming request
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU; data from/at this SNMP entity data from/in this context the version of the PDU
SNMP Protocol Data Unit
UINT32 maxSizeResponseScopedPDU;
maximum size able to accept ( see page 174)
UINT32 stateReference; reference to state information as presented with the request statusInformation statInfo; success or errorIndication, error counter OID/value if error
BYTE destTransportDomain;
UINT32 destTransportAddress;
BYTE* outgoingMessage;
UINT32 outgoingMessageLength; destination transport domain destination transport address the message to send its length
Description
Prepare an Outgoing SNMP Response Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Response Message: result = -- SUCCESS or FAILURE
10.15.5.8
processResponsePdu Structure
File
C struct
processResponsePdu {
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU;
413
10.15 SNMP Microchip TCP/IP Stack Help Structs, Records, Enums
};
Members
Members
BYTE messageProcessingModel;
BYTE securityModel;
BYTE* securityName;
BYTE securityLevel;
BYTE* contextEngineID;
BYTE* contextName;
BYTE pduVersion;
BYTE* PDU; statusInformation statInfo;
Description
Process Incoming Response PDU
Description
typically, SNMP version
Security Model in use on behalf of this principal
Level of Security data from/at this SNMP entity data from/in this context the version of the PDU
SNMP Protocol Data Unit success or errorIndication IN sendPduHandle; //handle from sendPdu
The PDU Dispatcher provides the following primitive to pass an incoming SNMP Response PDU to an application:
10.15.5.9
SecuritySysGenerateRequestMsg Structure
File
C struct
SecuritySysGenerateRequestMsg {
BYTE messageProcessingModel;
BYTE* globalData;
UINT32 maxMessageSize;
BYTE securityModel;
BYTE* securityEngineID;
BYTE* securityName;
BYTE securityLevel;
BYTE* scopedPDU;
BYTE* wholeMsg;
UINT32 wholeMsgLength;
};
Members
Members
BYTE messageProcessingModel;
BYTE* globalData;
UINT32 maxMessageSize;
BYTE securityModel;
BYTE* securityEngineID;
BYTE* securityName;
BYTE securityLevel;
BYTE* scopedPDU;
BYTE* wholeMsg;
UINT32 wholeMsgLength;
Description
typically, SNMP version message header, admin data of the sending SNMP entity for the outgoing message authoritative SNMP entity on behalf of this principal
Level of Security requested message (plaintext) payload OUT securityParameters; //filled in by Security
Module complete generated message length of the generated message
Description
This is record SecuritySysGenerateRequestMsg.
414
10.15 SNMP Microchip TCP/IP Stack Help Structs, Records, Enums
10.15.5.10
SecuritySysGenerateResponseMsg Structure
File
C struct
SecuritySysGenerateResponseMsg {
BYTE messageProcessingModel;
BYTE* globalData;
UINT32 maxMessageSize;
BYTE securityModel;
BYTE* securityEngineID;
BYTE* securityName;
BYTE securityLevel;
BYTE* scopedPDU;
BYTE* wholeMsg;
UINT32 wholeMsgLength;
};
Members
Members
BYTE messageProcessingModel;
BYTE* globalData;
UINT32 maxMessageSize;
BYTE securityModel;
BYTE* securityEngineID;
BYTE* securityName;
BYTE securityLevel;
BYTE* scopedPDU;
Description
typically, SNMP version message header, admin data of the sending SNMP entity for the outgoing message authoritative SNMP entity on behalf of this principal for the outgoing message message (plaintext) payload IN securityStateReference; //reference to security state information from original request OUT securityParameters; //filled in by
Security Module complete generated message length of the generated message
BYTE* wholeMsg;
UINT32 wholeMsgLength;
Description
Generate a Response Message
The Security Subsystem provides the following primitive to generate a Response message:
10.15.5.11
StateRelease Structure
File
C struct
StateRelease {
UINT32 stateReference;
};
Members
Members
UINT32 stateReference;
Description
Release State Reference Information
Description
handle of reference to be released
415
10.15 SNMP Microchip TCP/IP Stack Help Types
All Subsystems which pass stateReference information also provide a primitive to release the memory that holds the referenced state information
10.15.5.12
unregisterContextEngineID Structure
File
C struct
unregisterContextEngineID {
BYTE* contextEngineID;
BYTE pduType;
};
Members
Members
BYTE* contextEngineID;
BYTE pduType;
Description
This is record unregisterContextEngineID.
Description
give up responsibility for this one the pduType(s) to be unregistered
10.15.6
Types
Enumerations
Name
INOUT_SNMP_PDU ( see page 417)
REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS ( see page 417)
SNMP_ENGNID_OCTET_IDENTIFIER_VAL ( see page
SNMPV3_HMAC_HASH_TYPE ( see page 419)
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT ( see page 420)
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT ( see page 420)
SNMPV3_PRIV_PROT_TYPE ( see page 420)
Description
This is type INOUT_SNMP_PDU.
This is type
REPORT_FLAG_AND_SECURITY_LEVEL_FLAG
S.
The fifth octet indicates how the rest (6th and following octets) are formatted. Refer to RFC3411 section5 Page# 41
Type of hash being calculated
This is type
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT.
This is type
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT.
This is type SNMPV3_PRIV_PROT_TYPE.
STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL
This is type
STD_BASED_SNMP_MESSAGE_PROCESSING
_MODEL.
STD_BASED_SNMP_SECURITY_MODEL ( see page
Snmp Message Processing Model
STD_BASED_SNMPV3_SECURITY_LEVEL ( see page
USM_SECURITY_LEVEL ( see page 424)
This is type
STD_BASED_SNMPV3_SECURITY_LEVEL.
This is type USM_SECURITY_LEVEL.
Module
416
10.15 SNMP
Structures
Microchip TCP/IP Stack Help
Name
SecuritySysProcessIncomingMsg ( see page 418)
SNMPNONMIBRECDINFO ( see page 419)
Description
This is type SecuritySysProcessIncomingMsg.
This is type SNMPNONMIBRECDINFO.
This is type SNMPV3_REQUEST_WHOLEMSG.
This is type SNMPV3_RESPONSE_WHOLEMSG.
This is type snmpV3EngnUserDataBase.
snmpV3EngnUserDataBase ( see page 421)
SNMPv3
snmpV3TrapConfigDataBase ( see page 422)
snmpv3 target configuration with respect to trap.
statusInformation ( see page 422)
success or errorIndication
10.15.6.1
INOUT_SNMP_PDU Enumeration
File
C typedef enum
{
SNMP_RESPONSE_PDU = 0x01,
SNMP_REQUEST_PDU = 0x02
} INOUT_SNMP_PDU;
Description
This is type INOUT_SNMP_PDU.
10.15.6.2
REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS
Enumeration
File
C typedef enum
{
NO_REPORT_NO_PRIVACY_NO_AUTH = 0x00,
NO_REPORT_NO_PRIVACY_BUT_AUTH_PROVIDED = 0x01,
NO_REPORT_PRIVACY_PROVIDED_BUT_NO_AUTH = 0x02,
NO_REPORT_PRIVACY_AND_AUTH_PROVIDED = 0x03,
REPORT2REQ_NO_PRIVACY_NO_AUTH = 0x04,
REPORT2REQ_NO_PRIVACY_BUT_AUTH_PROVIDED = 0x05,
REPORT2REQ_PRIVACY_PROVIDED_BUT_NO_AUTH = 0x06,
REPORT2REQ_PRIVACY_AND_AUTH_PROVIDED = 0x07,
INVALID_MSG = 0xFF
} REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS;
Members
Members
NO_REPORT_NO_PRIVACY_NO_AUTH = 0x00
Description
00000000b
Types
417
10.15 SNMP Microchip TCP/IP Stack Help
NO_REPORT_NO_PRIVACY_BUT_AUTH_PROVIDED
= 0x01
NO_REPORT_PRIVACY_PROVIDED_BUT_NO_AUTH
= 0x02
NO_REPORT_PRIVACY_AND_AUTH_PROVIDED =
0x03
00000001b
00000010b Priv without Auth is not allowed
00000011b
REPORT2REQ_NO_PRIVACY_NO_AUTH = 0x04 00000100b
REPORT2REQ_NO_PRIVACY_BUT_AUTH_PROVIDED
= 0x05
00000101b
REPORT2REQ_PRIVACY_PROVIDED_BUT_NO_AUTH
= 0x06
00000110b Priv without Auth is not allowed
REPORT2REQ_PRIVACY_AND_AUTH_PROVIDED =
0x07
00000111b
Description
This is type REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS.
Types
10.15.6.3
SecuritySysProcessIncomingMsg Structure
File
C typedef struct
{
UINT32 maxMessageSize;
UINT32 wholeMsgLength;
BYTE* wholeMsg;
BYTE* securityEngineID;
BYTE* securityName;
BYTE* scopedPDU;
UINT32 maxSizeResponseScopedPDU;
BYTE messageProcessingModel;
BYTE securityModel;
BYTE securityLevel;
UINT8 securityEngineIDLen;
BYTE securityNameLength;
} SecuritySysProcessIncomingMsg;
Members
Members
UINT32 maxMessageSize;
UINT32 wholeMsgLength;
BYTE* wholeMsg;
Description
of the sending SNMP entity IN securityParameters; //for the received message length as received on the wire as received on the wire
BYTE* securityEngineID;
BYTE* securityName; authoritative SNMP entity identification of the principal
BYTE* scopedPDU; message (plaintext) payload OUT securityStateReference; //reference to security state
UINT32 maxSizeResponseScopedPDU; maximum size sender can handle
BYTE messageProcessingModel;
BYTE securityModel;
BYTE securityLevel;
UINT8 securityEngineIDLen; typically, SNMP version for the received message
Level of Security authoritative SNMP entity
Description
This is type SecuritySysProcessIncomingMsg.
418
10.15 SNMP Microchip TCP/IP Stack Help Types
10.15.6.4
SNMP_ENGNID_OCTET_IDENTIFIER_VAL Enumeration
File
C typedef enum
{
RESERVED = 0x0,
IPV4_ADDR_ENGN_ID = 0x01,
IPV6_ADDR_ENGN_ID = 0x02,
MAC_ADDR_ENGN_ID = 0x03,
ADMIN_ASSIGNED_TEXT = 0x04,
ADMIN_ASSIGNED_OCTETS = 0x05,
RESERVED_UNUSED = 0x06,
ENTERPRISE_DEFINED = 128
} SNMP_ENGNID_OCTET_IDENTIFIER_VAL;
Members
Members
IPV4_ADDR_ENGN_ID = 0x01
IPV6_ADDR_ENGN_ID = 0x02
MAC_ADDR_ENGN_ID = 0x03
RESERVED_UNUSED = 0x06
ENTERPRISE_DEFINED = 128
Description
4octets
16 octets
6 octets
6 to 127 are reserved and unused
128 to 255 as defiend by the enterprise maximum remaining length
Description
The fifth octet indicates how the rest (6th and following octets) are formatted. Refer to RFC3411 section5 Page# 41
10.15.6.5
SNMPNONMIBRECDINFO Structure
File
C typedef struct
{
UINT8 oidstr[16];
UINT8 version;
} SNMPNONMIBRECDINFO;
Description
This is type SNMPNONMIBRECDINFO.
10.15.6.6
SNMPV3_HMAC_HASH_TYPE Enumeration
File
C typedef enum
{
SNMPV3_HAMC_MD5 = 0u,
SNMPV3_HMAC_SHA1,
SNMPV3_NO_HMAC_AUTH
} SNMPV3_HMAC_HASH_TYPE;
419
10.15 SNMP
Members
Members
SNMPV3_HAMC_MD5 = 0u
SNMPV3_HMAC_SHA1
Description
Type of hash being calculated
Microchip TCP/IP Stack Help
Description
MD5 is being calculated
SHA-1 is being calculated
10.15.6.7
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT
Enumeration
File
C typedef enum
{
SNMPV3_MSG_AUTH_FAIL = 0x00,
SNMPV3_MSG_AUTH_PASS = 0x01
} SNMPV3_MSG_AUTH_SEC_PARAM_RESULT;
Description
This is type SNMPV3_MSG_AUTH_SEC_PARAM_RESULT.
10.15.6.8
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT
Enumeration
File
C typedef enum
{
SNMPV3_MSG_PRIV_FAIL = 0x00,
SNMPV3_MSG_PRIV_PASS = 0x01
} SNMPV3_MSG_PRIV_SEC_PARAM_RESULT;
Description
This is type SNMPV3_MSG_PRIV_SEC_PARAM_RESULT.
10.15.6.9
SNMPV3_PRIV_PROT_TYPE Enumeration
File
C typedef enum
{
SNMPV3_DES_PRIV = 0x0,
SNMPV3_AES_PRIV,
SNMPV3_NO_PRIV
} SNMPV3_PRIV_PROT_TYPE;
Description
This is type SNMPV3_PRIV_PROT_TYPE.
Types
420
10.15 SNMP Microchip TCP/IP Stack Help
10.15.6.10
SNMPV3_REQUEST_WHOLEMSG Structure
File
C typedef struct
{
UINT8* wholeMsgHead;
UINT8* snmpMsgHead;
WORD_VAL wholeMsgLen;
WORD_VAL snmpMsgLen;
WORD msgAuthParamOffsetInWholeMsg;
WORD scopedPduOffset;
BYTE scopedPduAuthStructVal;
WORD scopedPduStructLen;
} SNMPV3_REQUEST_WHOLEMSG;
Description
This is type SNMPV3_REQUEST_WHOLEMSG.
10.15.6.11
SNMPV3_RESPONSE_WHOLEMSG Structure
File
C typedef struct
{
UINT8* wholeMsgHead;
UINT8* snmpMsgHead;
WORD_VAL wholeMsgLen;
WORD_VAL snmpMsgLen;
UINT8* msgAuthParamOffsetOutWholeMsg;
UINT8* scopedPduOffset;
WORD scopedPduStructLen;
BYTE scopedPduAuthStructVal;
} SNMPV3_RESPONSE_WHOLEMSG;
Description
This is type SNMPV3_RESPONSE_WHOLEMSG.
10.15.6.12
snmpV3EngnUserDataBase Structure
File
C typedef struct
{
UINT8 userName[SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE];
UINT8 userAuthPswd[SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE];
UINT8 userPrivPswd[SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE];
UINT8 userAuthPswdLoclizdKey[SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE];
UINT8 userPrivPswdLoclizdKey[SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE];
UINT8 userAuthLocalKeyHmacIpad[64];
UINT8 userAuthLocalKeyHmacOpad[64];
UINT8 userDBIndex;
UINT8 userHashType;
UINT8 userNameLength;
UINT8 userAuthPswdLen;
UINT8 userPrivPswdLen;
Types
421
10.15 SNMP Microchip TCP/IP Stack Help Types
UINT8 userPrivType;
} snmpV3EngnUserDataBase;
Members
Members Description
UINT8 userAuthPswd[SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE];
RFC specifies not to save password with the managed nodes instead store pswd ipad and opad values.
UINT8 userAuthLocalKeyHmacIpad[64]; UINT8 userPrivPswdLoclizdKey[20];
Description
This is type snmpV3EngnUserDataBase.
10.15.6.13
SNMPV3MSGDATA Structure
File
C typedef struct
{
UINT8 * head;
WORD length;
WORD maxlength;
WORD msgAuthParamOffset;
} SNMPV3MSGDATA;
Description
SNMPv3
10.15.6.14
snmpV3TrapConfigDataBase Structure
File
C typedef struct
{
UINT8 userSecurityName[USER_SECURITY_NAME_LEN];
STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL messageProcessingModelType;
STD_BASED_SNMP_SECURITY_MODEL securityModelType;
STD_BASED_SNMPV3_SECURITY_LEVEL securityLevelType;
} snmpV3TrapConfigDataBase;
Description
snmpv3 target configuration with respect to trap.
10.15.6.15
statusInformation Structure
File
C typedef struct
registerContextEngineID {
BYTE* contextEngineID;
BYTE pduType;
} statusInformation;
422
10.15 SNMP
Members
Members
BYTE* contextEngineID;
BYTE pduType;
Description
success or errorIndication
Microchip TCP/IP Stack Help
Description
take responsibility for this one the pduType(s) to be registered
Types
10.15.6.16
STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL
Enumeration
File
C typedef enum
{
SNMPV1_MSG_PROCESSING_MODEL = 0X00,
SNMPV2C_MSG_PROCESSING_MODEL = 0X01,
SNMPV2U_V2_MSG_PROCESSING_MODEL = 0X02,
SNMPV3_MSG_PROCESSING_MODEL = 0X03
} STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL;
Description
This is type STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL.
10.15.6.17
STD_BASED_SNMP_SECURITY_MODEL Enumeration
File
C typedef enum
{
ANY_SECUTIRY_MODEL = 0x00,
SNMPV1_SECURITY_MODEL = 0X01,
SNMPV2C_SECURITY_MODEL = 0X02,
SNMPV3_USM_SECURITY_MODEL = 0X03
} STD_BASED_SNMP_SECURITY_MODEL;
Description
Snmp Message Processing Model
10.15.6.18
STD_BASED_SNMPV3_SECURITY_LEVEL Enumeration
File
C typedef enum
{
NO_AUTH_NO_PRIV = 1,
AUTH_NO_PRIV,
AUTH_PRIV
} STD_BASED_SNMPV3_SECURITY_LEVEL;
Description
This is type STD_BASED_SNMPV3_SECURITY_LEVEL.
423
10.15 SNMP Microchip TCP/IP Stack Help
10.15.6.19
USM_SECURITY_LEVEL Enumeration
File
C typedef enum
{
noAuthProtocol = 0x1,
hmacMD5Auth,
hmacSHAAuth,
noPrivProtocol,
desPrivProtocol = 0x5,
aesPrivProtocol = 0x6
} USM_SECURITY_LEVEL;
Description
This is type USM_SECURITY_LEVEL.
Variables
10.15.7
Variables
Module
Variables
Name
Description
This is variable authKey_iPad.
This is variable authKey_oPad.
authoritativeSnmpEngineBoots ( see page 426)
The number of times that the authoritative SNMP engine has
(re-)initialized itself since its snmpEngineID ( see page 433) was
last configured.
The number of seconds since the value of the
authoritativeSnmpEngineBoots ( see page 426) object last changed
This is variable cipher_text.
This is variable deciphered_text.
getZeroInstance ( see page 427)
This variable is used for gext next request for zero instance
gSnmpV3InPduWholeMsgBuf ( see page 427)
Dynamic memory stub and PDU details for Incoming stored PDU
gSnmpV3OUTPduWholeMsgBuf ( see page 428)
Dynamic memory stub details and constructed outgoing stored PDU details
Response PDU construction offset details
gSNMPv3PduHeaderBuf ( see page
428) gSNMPv3ScopedPduDataPos ( see page 428) gSNMPv3ScopedPduRequestBuf ( see page 428)
Offset to read scoped PDU data bytes for processing from dynamic memory stub
Stored request scoped pdu details
gSNMPv3ScopedPduResponseBuf ( see page 429) gSnmpv3TrapConfigData ( see page
Processed response scoped pdu details
SNMPv3 global configuration database to be used for trap notification
424
10.15 SNMP Microchip TCP/IP Stack Help Variables
gSNMPv3TrapMsgHeaderBuf ( see page 429)
TRAP message PDU header construction offset details
Dynamic memory stub details and constructed trap PDU details
gSNMPv3TrapScopedPduResponseBuf
TRAP scoped PDU construction offset details
gSNMPV3TrapSecurityLevel ( see page 430)
This is variable gSNMPV3TrapSecurityLevel.
Index to the particular reference configured in User security model
data base snmpV3UserDataBase ( see page 437).
gUsmStatsEngineID ( see page 430)
Global variable to find out how many times SNMPv3 engine id has been validated
hmacAuthKeyBuf ( see page 430)
This is variable hmacAuthKeyBuf.
This is variable HmacMd5Digest.
This is variable HmacSHADigest.
incomingPdu ( see page 431) incomingSnmpPDUmsgID ( see page
Incoming PDU details
Retrived Incoming Msg ID value from PDU
ivEncrptKeyOut ( see page 431)
This is variable ivEncrptKeyOut.
md5LocalizedAuthKey ( see page 432) This is variable md5LocalizedAuthKey.
msgSecrtyParamLenOffset ( see page
This is variable msgSecrtyParamLenOffset.
securityPrimitivesOfIncomingPdu ( see page 432)
Incoming PDU Security primitive details.
sha1LocalizedAuthKey ( see page
433) snmpEngineBoots ( see page 433)
This is variable session_key.
This is variable sha1LocalizedAuthKey.
The number of times that the SNMP engine has (re-)initialized itself
since snmpEngineID ( see page 433) was last configured.
Reserving 32 bytes for the snmpEngineID as the octet string length can vary form 5 to 32
The maximum message size the SNMP engine can handle.
snmpEngineMaxMessageSize ( see page 433) snmpEngineMsgProcessModel ( see page 433)
Type of Message processing model used. Value Maximum range
(2^31-1), RFC3411
snmpEngineSecurityModel ( see page
Type of security model used. Value Maximum range (2^31-1),
RFC3411
snmpEngineTime ( see page 434)
The number of seconds since the value of the snmpEngineBoots ( see page 433) object last changed
snmpEngineTimeOffset ( see page
Stores the time value in seconds since SNMP Engine reset
snmpEngnIDLength ( see page 434)
Engine ID length of the SNMP Engine
snmpInMsgAuthParamLen ( see page
Incoming SNMPv3 msg authentication parameters string is 12 bytes long.
snmpInMsgAuthParamStrng ( see page 435) snmpInMsgPrivParamLen ( see page
Reserving 12 bytes for the incoming SNMPv3 msg authentication parameters.
Incoming SNMPv3 msg privacy parameters string is 8 bytes long.
snmpInMsgPrvParamStrng ( see page
Reserving 8 bytes for the incoming SNMPv3 msg privacy parameters.
snmpMsgBufSeekPos ( see page 435) Offset to read PDU data bytes for processing from dynamic memory
stub
snmpOutMsgAuthParamLen ( see page 436)
Outgoing SNMPv3 msg authentication parameters string is 12 bytes long.
425
10.15 SNMP Microchip TCP/IP Stack Help Variables
Reserving 12 bytes for the outgoing SNMPv3 msg authentication parameters.
Outgoing SNMPv3 msg privacy parameters string is 8 bytes long.
Reserving 8 bytes for the outgoing SNMPv3 msg privacy parameters.
Type of Security for outgoing message in response to the incoming message.
Type of security. noAuthNoPriv(0),AuthNoPriv(1),AuthPriv(3)
128 Bit
128 Bit
This is variable snmpV3UserDataBase.
10.15.7.1
authKey_iPad Variable
File
C
UINT8 authKey_iPad[64];
Description
This is variable authKey_iPad.
10.15.7.2
authKey_oPad Variable
File
C
UINT8 authKey_oPad[64];
Description
This is variable authKey_oPad.
10.15.7.3
authoritativeSnmpEngineBoots Variable
File
C
DWORD_VAL authoritativeSnmpEngineBoots;
Description
was last configured.
426
10.15 SNMP Microchip TCP/IP Stack Help
10.15.7.4
authoritativeSnmpEngineTime Variable
File
C
DWORD_VAL authoritativeSnmpEngineTime;
Description
10.15.7.5
cipher_text Variable
File
C
UINT8 cipher_text[16];
Description
This is variable cipher_text.
10.15.7.6
deciphered_text Variable
File
C
UINT8 deciphered_text[16];
Description
This is variable deciphered_text.
10.15.7.7
getZeroInstance Variable
File
C
BOOL getZeroInstance = FALSE;
Description
This variable is used for gext next request for zero instance
10.15.7.8
gSnmpV3InPduWholeMsgBuf Variable
File
Variables
427
10.15 SNMP Microchip TCP/IP Stack Help
C
SNMPV3_REQUEST_WHOLEMSG gSnmpV3InPduWholeMsgBuf = {NULL,NULL,{0},{0},0,0,0,0};
Description
Dynamic memory stub and PDU details for Incoming stored PDU
10.15.7.9
gSnmpV3OUTPduWholeMsgBuf Variable
File
C
SNMPV3_RESPONSE_WHOLEMSG gSnmpV3OUTPduWholeMsgBuf = {NULL,NULL,{0},{0},0,0,0,0};
Description
Dynamic memory stub details and constructed outgoing stored PDU details
10.15.7.10
gSNMPv3PduHeaderBuf Variable
File
C
SNMPV3MSGDATA gSNMPv3PduHeaderBuf = {NULL,0,0,0};
Description
Response PDU construction offset details
10.15.7.11
gSNMPv3ScopedPduDataPos Variable
File
C
UINT16 gSNMPv3ScopedPduDataPos = 0;
Description
Offset to read scoped PDU data bytes for processing from dynamic memory stub
10.15.7.12
gSNMPv3ScopedPduRequestBuf Variable
File
C
SNMPV3MSGDATA gSNMPv3ScopedPduRequestBuf = {NULL,0,0,0};
Description
Stored request scoped pdu details
Variables
428
10.15 SNMP Microchip TCP/IP Stack Help
10.15.7.13
gSNMPv3ScopedPduResponseBuf Variable
File
C
SNMPV3MSGDATA gSNMPv3ScopedPduResponseBuf = {NULL,0,0,0};
Description
Processed response scoped pdu details
10.15.7.14
gSnmpv3TrapConfigData Variable
File
C
snmpV3TrapConfigDataBase gSnmpv3TrapConfigData[SNMPV3_USM_MAX_USER] = { \
{"microchip",SNMPV3_MSG_PROCESSING_MODEL,SNMPV3_USM_SECURITY_MODEL,AUTH_PRIV}, \
{"SnmpAdmin",SNMPV3_MSG_PROCESSING_MODEL,SNMPV3_USM_SECURITY_MODEL,AUTH_NO_PRIV}, \
{"root",SNMPV3_MSG_PROCESSING_MODEL,SNMPV3_USM_SECURITY_MODEL,NO_AUTH_NO_PRIV} \ };
Description
SNMPv3 global configuration database to be used for trap notification
10.15.7.15
gSNMPv3TrapMsgHeaderBuf Variable
File
C
SNMPV3MSGDATA gSNMPv3TrapMsgHeaderBuf;
Description
TRAP message PDU header construction offset details
10.15.7.16
gSnmpV3TrapOUTPduWholeMsgBuf Variable
File
C
SNMPV3_RESPONSE_WHOLEMSG gSnmpV3TrapOUTPduWholeMsgBuf = {NULL,NULL,{0},{0},0,0,0,0};
Description
Dynamic memory stub details and constructed trap PDU details
10.15.7.17
gSNMPv3TrapScopedPduResponseBuf Variable
File
Variables
429
10.15 SNMP Microchip TCP/IP Stack Help
C
SNMPV3MSGDATA gSNMPv3TrapScopedPduResponseBuf = {NULL,0,0,0};
Description
TRAP scoped PDU construction offset details
Variables
10.15.7.18
gSNMPV3TrapSecurityLevel Variable
File
C
UINT8 gSNMPV3TrapSecurityLevel = NO_REPORT_NO_PRIVACY_NO_AUTH;
Description
This is variable gSNMPV3TrapSecurityLevel.
10.15.7.19
gSnmpv3UserDBIndex Variable
File
C
WORD gSnmpv3UserDBIndex;
Description
10.15.7.20
gUsmStatsEngineID Variable
File
C
WORD_VAL gUsmStatsEngineID = {0};
Description
Global variable to find out how many times SNMPv3 engine id has been validated
10.15.7.21
hmacAuthKeyBuf Variable
File
C
UINT8 hmacAuthKeyBuf[64];
Description
This is variable hmacAuthKeyBuf.
430
10.15 SNMP Microchip TCP/IP Stack Help
10.15.7.22
HmacMd5Digest Variable
File
C
UINT8 HmacMd5Digest[16];
Description
This is variable HmacMd5Digest.
10.15.7.23
HmacSHADigest Variable
File
C
UINT8 HmacSHADigest[20];
Description
This is variable HmacSHADigest.
10.15.7.24
incomingPdu Variable
File
C struct
dispatcherProcessPdu incomingPdu;
Description
Incoming PDU details
10.15.7.25
incomingSnmpPDUmsgID Variable
File
C
DWORD_VAL incomingSnmpPDUmsgID;
Description
Retrived Incoming Msg ID value from PDU
10.15.7.26
ivEncrptKeyOut Variable
File
Variables
431
10.15 SNMP
C
UINT8 ivEncrptKeyOut[16];
Description
This is variable ivEncrptKeyOut.
Microchip TCP/IP Stack Help
10.15.7.27
md5LocalizedAuthKey Variable
File
C
UINT8 md5LocalizedAuthKey[16];
Description
This is variable md5LocalizedAuthKey.
10.15.7.28
msgSecrtyParamLenOffset Variable
File
C
WORD msgSecrtyParamLenOffset;
Description
This is variable msgSecrtyParamLenOffset.
10.15.7.29
securityPrimitivesOfIncomingPdu Variable
File
C
SecuritySysProcessIncomingMsg securityPrimitivesOfIncomingPdu;
Description
Incoming PDU Security primitive details.
10.15.7.30
session_key Variable
File
C
AES_SESSION_KEY_128_BIT session_key;
Description
This is variable session_key.
Variables
432
10.15 SNMP Microchip TCP/IP Stack Help Variables
10.15.7.31
sha1LocalizedAuthKey Variable
File
C
UINT8 sha1LocalizedAuthKey[20];
Description
This is variable sha1LocalizedAuthKey.
10.15.7.32
snmpEngineBoots Variable
File
C
UINT32 snmpEngineBoots = 0;
Description
configured.
10.15.7.33
snmpEngineID Variable
File
C
UINT8 snmpEngineID[32+1];
Description
Reserving 32 bytes for the snmpEngineID as the octet string length can vary form 5 to 32
10.15.7.34
snmpEngineMaxMessageSize Variable
File
C
DWORD_VAL snmpEngineMaxMessageSize;
Description
The maximum message size the SNMP engine can handle.
10.15.7.35
snmpEngineMsgProcessModel Variable
File
433
10.15 SNMP Microchip TCP/IP Stack Help
C
UINT32 snmpEngineMsgProcessModel = 0;
Description
Type of Message processing model used. Value Maximum range (2^31-1), RFC3411
10.15.7.36
snmpEngineSecurityModel Variable
File
C
UINT32 snmpEngineSecurityModel = 0;
Description
Type of security model used. Value Maximum range (2^31-1), RFC3411
10.15.7.37
snmpEngineTime Variable
File
C
DWORD_VAL snmpEngineTime;
Description
The number of seconds since the value of the snmpEngineBoots ( see page 433) object last changed
10.15.7.38
snmpEngineTimeOffset Variable
File
C
DWORD snmpEngineTimeOffset = 0;
Description
Stores the time value in seconds since SNMP Engine reset
10.15.7.39
snmpEngnIDLength Variable
File
C
UINT8 snmpEngnIDLength = 0;
Description
Engine ID length of the SNMP Engine
Variables
434
10.15 SNMP Microchip TCP/IP Stack Help
10.15.7.40
snmpInMsgAuthParamLen Variable
File
C
UINT8 snmpInMsgAuthParamLen;
Description
Incoming SNMPv3 msg authentication parameters string is 12 bytes long.
10.15.7.41
snmpInMsgAuthParamStrng Variable
File
C
UINT8 snmpInMsgAuthParamStrng[];
Description
Reserving 12 bytes for the incoming SNMPv3 msg authentication parameters.
10.15.7.42
snmpInMsgPrivParamLen Variable
File
C
UINT8 snmpInMsgPrivParamLen = 8;
Description
Incoming SNMPv3 msg privacy parameters string is 8 bytes long.
10.15.7.43
snmpInMsgPrvParamStrng Variable
File
C
UINT8 snmpInMsgPrvParamStrng[];
Description
Reserving 8 bytes for the incoming SNMPv3 msg privacy parameters.
10.15.7.44
snmpMsgBufSeekPos Variable
File
Variables
435
10.15 SNMP Microchip TCP/IP Stack Help
C
UINT16 snmpMsgBufSeekPos = 0;
Description
Offset to read PDU data bytes for processing from dynamic memory stub
10.15.7.45
snmpOutMsgAuthParamLen Variable
File
C
UINT8 snmpOutMsgAuthParamLen;
Description
Outgoing SNMPv3 msg authentication parameters string is 12 bytes long.
10.15.7.46
snmpOutMsgAuthParamStrng Variable
File
C
UINT8 snmpOutMsgAuthParamStrng[];
Description
Reserving 12 bytes for the outgoing SNMPv3 msg authentication parameters.
10.15.7.47
snmpOutMsgPrivParamLen Variable
File
C
UINT8 snmpOutMsgPrivParamLen = 8;
Description
Outgoing SNMPv3 msg privacy parameters string is 8 bytes long.
10.15.7.48
snmpOutMsgPrvParamStrng Variable
File
C
UINT8 snmpOutMsgPrvParamStrng[];
Description
Reserving 8 bytes for the outgoing SNMPv3 msg privacy parameters.
Variables
436
10.15 SNMP Microchip TCP/IP Stack Help
10.15.7.49
snmpResponseSecurityFlag Variable
File
C
UINT8 snmpResponseSecurityFlag = 0;
Description
Type of Security for outgoing message in response to the incoming message.
10.15.7.50
snmpSecurityLevel Variable
File
C
UINT8 snmpSecurityLevel = 0;
Description
Type of security. noAuthNoPriv(0),AuthNoPriv(1),AuthPriv(3)
10.15.7.51
snmpV3AesDecryptInitVector Variable
File
C
UINT8 snmpV3AesDecryptInitVector[16+1];
Description
128 Bit
10.15.7.52
snmpV3AesEncryptInitVector Variable
File
C
UINT8 snmpV3AesEncryptInitVector[16+1];
Description
128 Bit
10.15.7.53
snmpV3UserDataBase Variable
File
Variables
437
10.15 SNMP Microchip TCP/IP Stack Help
C
snmpV3EngnUserDataBase snmpV3UserDataBase[SNMPV3_USM_MAX_USER];
Description
This is variable snmpV3UserDataBase.
Macros
10.15.8
Macros
Macros
Name
AUTH_LOCALIZED_PASSWORD_KEY_LEN ( see page 439)
IS_SNMPV3_AUTH_STRUCTURE ( see page 440)
MSG_AUTHORITATIVE_HEADER_LEN ( see page 440)
MSGGLOBAL_HEADER_LEN ( see page 440)
PRIV_LOCALIZED_PASSWORD_KEY_LEN ( see page 441)
REPORT_RESPONSE ( see page 441)
SNMP_ENGINE_MAX_MSG_SIZE ( see page 441)
Description
SNMPv3 Authentication ( see page 91)
Localized passwed key lenegth size
This is macro INVALID_INDEX.
This is macro
IS_SNMPV3_AUTH_STRUCTURE.
Length of SNMPv3 authoratative msg header length = Header length ( 2 + 2
bytes) + engineID ( snmpEngnIDLength
• engine boot( 4 bytes)+ engine time(4 bytes)
+security name
(securityPrimitivesOfIncomingPdu ( see page 432) value) +authentication
parameters
(snmpOutMsgAuthParamLen ( see page 436) value) +privacy parameters
(snmpOutMsgAuthParamLen ( see page 436) value)
Length of the SNMPv3 msg header(x) =
Header length (2 bytes)
• MSGID size (type(1 byte) + length of value(1 byte)+4 bytes value)
• msgMAXSIZE(type + length of value +4 bytes value)
• msg flag(type + length of value +1 byte value)
• security model type(type + length of value +1 byte value)
#define
PRIV_LOCALIZED_PASSWORD_KEY_
LEN
16 SNMPv3 Privacy Pasword key length size
This is macro REPORT_RESPONSE.
SNMP_ENGINE_MAX_MSG_SIZE is determined as the minimum of the max msg size values supported among all of the transports available to and supported by the engine.
438
10.15 SNMP Microchip TCP/IP Stack Help Macros
SNMP_MAX_MSG_SIZE ( see page 441)
SNMP_MAX_OID_LEN_MEM_USE ( see page 442)
SNMP MIN and MAX message 484 bytes in size As per RFC 3411
snmpEngineMaxMessageSize ( see page 433) and RFC 1157 ( section 4-
protocol specification ) and implementation supports more than 484 whenever feasible.
This macro will be used to avoid SNMP
OID memory buffer corruption
This macro will be used to avoid SNMP
OID memory buffer corruption
SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE ( see page
This is macro SNMP_V3.
SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
SNMPv3 authentication localized Key length for memory validation
SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
This is macro SNMPV3_H.
SNMPv3 privacy key length size for memory validation
SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE ( see page
SNMPV3_USM_MAX_USER ( see page 443)
User security name length for memory validation
User Security Model should have atleast
1 user. Default is 3. User should change as per the requirement.
SNMPV3MSG_AUTHENTICATION_FAIL ( see page 444)
SNMPV3MSG_AUTHENTICATION_SUCCESS ( see page 444)
USER_SECURITY_NAME_LEN ( see page 444)
This is macro
SNMPV3MSG_AUTHENTICATION_FAI
L.
This is macro
SNMPV3MSG_AUTHENTICATION_SU
CCESS.
SNMPv3 User Security Name length
Module
10.15.8.1
AUTH_LOCALIZED_PASSWORD_KEY_LEN Macro
File
C
#define
AUTH_LOCALIZED_PASSWORD_KEY_LEN (20)
Description
SNMPv3 Authentication ( see page 91) Localized passwed key lenegth size
10.15.8.2
INVALID_INDEX Macro
File
C
#define
INVALID_INDEX 0xFF
Description
This is macro INVALID_INDEX.
439
10.15 SNMP Microchip TCP/IP Stack Help Macros
10.15.8.3
IS_SNMPV3_AUTH_STRUCTURE Macro
File
C
#define
IS_SNMPV3_AUTH_STRUCTURE(a) (a==SNMPV3_ENCRYPTION)
Description
This is macro IS_SNMPV3_AUTH_STRUCTURE.
10.15.8.4
MSG_AUTHORITATIVE_HEADER_LEN Macro
File
C
#define
MSG_AUTHORITATIVE_HEADER_LEN(x) ( x=(2+2 \
+1+1+4 \
+1+1+4 \
+1+1+securityPrimitivesOfIncomingPdu.securityNameLength
\
+1+1+snmpOutMsgPrivParamLen) \
)
Description
• engine boot( 4 bytes)+ engine time(4 bytes)
+security name
(securityPrimitivesOfIncomingPdu ( see page 432)
value) +authentication parameters
value)
10.15.8.5
MSGGLOBAL_HEADER_LEN Macro
File
C
#define
MSGGLOBAL_HEADER_LEN(x) ( x= (2 \
+1+1+4 \
+1+1+4 \
+1+1+1 \
+1+1+1)\
)
Description
Length of the SNMPv3 msg header(x) = Header length (2 bytes)
• MSGID size (type(1 byte) + length of value(1 byte)+4 bytes value)
• msgMAXSIZE(type + length of value +4 bytes value)
• msg flag(type + length of value +1 byte value)
440
10.15 SNMP Microchip TCP/IP Stack Help
• security model type(type + length of value +1 byte value)
10.15.8.6
PRIV_LOCALIZED_PASSWORD_KEY_LEN Macro
File
C
#define
PRIV_LOCALIZED_PASSWORD_KEY_LEN (20)
Description
#define PRIV_LOCALIZED_PASSWORD_KEY_LEN 16 SNMPv3 Privacy Pasword key length size
10.15.8.7
REPORT_RESPONSE Macro
File
C
#define
REPORT_RESPONSE (0xa8)
Description
This is macro REPORT_RESPONSE.
Macros
10.15.8.8
SNMP_ENGINE_MAX_MSG_SIZE Macro
File
C
#define
SNMP_ENGINE_MAX_MSG_SIZE 1024
Description
SNMP_ENGINE_MAX_MSG_SIZE is determined as the minimum of the max msg size values supported among all of the transports available to and supported by the engine.
10.15.8.9
SNMP_MAX_MSG_SIZE Macro
File
C
#define
SNMP_MAX_MSG_SIZE 484
Description
RFC 1157 ( section 4- protocol specification ) and implementation supports more than 484 whenever feasible.
441
10.15 SNMP Microchip TCP/IP Stack Help Macros
10.15.8.10
SNMP_MAX_OID_LEN_MEM_USE Macro
File
C
#define
SNMP_MAX_OID_LEN_MEM_USE (18)
Description
This macro will be used to avoid SNMP OID memory buffer corruption
10.15.8.11
SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE
Macro
File
C
#define
SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE (8)
Description
This macro will be used to avoid SNMP OID memory buffer corruption
10.15.8.12
SNMP_V3 Macro
File
C
#define
SNMP_V3 (3)
Description
This is macro SNMP_V3.
10.15.8.13
SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
Macro
File
C
#define
SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE (AUTH_LOCALIZED_PASSWORD_KEY_LEN+1)
Description
SNMPv3 authentication localized Key length for memory validation
442
10.15 SNMP Microchip TCP/IP Stack Help Macros
10.15.8.14
SNMPV3_H Macro
File
C
#define
SNMPV3_H
Description
This is macro SNMPV3_H.
10.15.8.15
SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
Macro
File
C
#define
SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE (PRIV_LOCALIZED_PASSWORD_KEY_LEN+1)
Description
SNMPv3 privacy key length size for memory validation
10.15.8.16
SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE
Macro
File
C
#define
SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE (USER_SECURITY_NAME_LEN+1)
Description
User security name length for memory validation
10.15.8.17
SNMPV3_USM_MAX_USER Macro
File
C
#define
SNMPV3_USM_MAX_USER 3
//User Security Model should have atleast 1 user. Default is
3. User should change as per the requirement.
Description
User Security Model should have atleast 1 user. Default is 3. User should change as per the requirement.
443
10.15 SNMP Microchip TCP/IP Stack Help
10.15.8.18
SNMPV3MSG_AUTHENTICATION_FAIL Macro
File
C
#define
SNMPV3MSG_AUTHENTICATION_FAIL 0
Description
This is macro SNMPV3MSG_AUTHENTICATION_FAIL.
10.15.8.19
SNMPV3MSG_AUTHENTICATION_SUCCESS Macro
File
C
#define
SNMPV3MSG_AUTHENTICATION_SUCCESS 1
Description
This is macro SNMPV3MSG_AUTHENTICATION_SUCCESS.
10.15.8.20
USER_SECURITY_NAME_LEN Macro
File
C
#define
USER_SECURITY_NAME_LEN (16)
Description
SNMPv3 User Security Name length
Files
10.15.9
Files
Files
Name
Description
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
444
10.15 SNMP
Microchip TCP/IP Stack Help
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
• Simple Network Management Protocol (SNMP) Version 1 Agent
• Simple Network Management Protocol (SNMP) Version 2 community based Agent
• Module for Microchip TCP/IP Stack
• -Provides SNMP API for doing stuff
*
• -Reference: RFC 1157 (for SNMP V1)
• RFC 3416 (for SNMPv2C)
• SNMP Defs for Microchip TCP/IP Stack
*
Files
Module
10.15.9.1
SNMPv3.c
Functions
Name
Description
Decode variable length structure.
Finds number of varbinds in the varbind list received in a SNMPv3 pdu.
IsSnmpV3ASNNull ( see page 382)
Verifies the value type as ASN_NULL ( see page 349).
Populates OID type, length and oid string from the received pdu.
IsSnmpv3ValidOID ( see page 382)
IsSNMPv3ValidStructure ( see page 383)
Snmpv3FreeDynAllocMem ( see page 395)
Decode variable length structure.
Allocated dynamic memory freeing is done by this routine.
Decode variable length structure.
445
10.15 SNMP Microchip TCP/IP Stack Help
Snmpv3ReportPdu ( see page 401)
Snmpv3SetErrorStatus ( see page 402)
Verifies variable datatype as INT and retrieves its value.
Constructs the report pdu infomration for the Report Pdu.
Set snmpv3 error status in the response pdu.
Macros
Files
Name
Description
This is macro INVALID_INDEX.
Length of SNMPv3 authoratative msg header length = Header length
( 2 + 2 bytes) + engineID ( snmpEngnIDLength ( see page 434)
bytes)
• engine boot( 4 bytes)+ engine time(4 bytes)
+security name (securityPrimitivesOfIncomingPdu ( see page
value) +authentication parameters
MSGGLOBAL_HEADER_LEN ( see page 440)
Length of the SNMPv3 msg header(x) = Header length (2 bytes)
• MSGID size (type(1 byte) + length of value(1 byte)+4 bytes value)
• msgMAXSIZE(type + length of value +4 bytes value)
• msg flag(type + length of value +1 byte value)
• security model type(type + length of value +1 byte value)
SNMP_ENGINE_MAX_MSG_SIZE ( see page 441)
SNMP_ENGINE_MAX_MSG_SIZE is determined as the minimum of the max msg size values supported among all of the transports available to and supported by the engine.
Variables
Name
gSnmpV3InPduWholeMsgBuf ( see page 427)
Description
Dynamic memory stub and PDU details for Incoming stored PDU
gSnmpV3OUTPduWholeMsgBuf ( see page 428)
Dynamic memory stub details and constructed outgoing stored PDU details
Response PDU construction offset details
gSNMPv3PduHeaderBuf ( see page
428) gSNMPv3ScopedPduDataPos ( see page 428) gSNMPv3ScopedPduRequestBuf ( see page 428)
Offset to read scoped PDU data bytes for processing from dynamic memory stub
Stored request scoped pdu details
gSNMPv3ScopedPduResponseBuf ( see page 429) gSnmpv3TrapConfigData ( see page
Processed response scoped pdu details
SNMPv3 global configuration database to be used for trap notification
Dynamic memory stub details and constructed trap PDU details
gSNMPv3TrapScopedPduResponseBuf
TRAP scoped PDU construction offset details
gSNMPV3TrapSecurityLevel ( see page 430)
This is variable gSNMPV3TrapSecurityLevel.
gUsmStatsEngineID ( see page 430)
Global variable to find out how many times SNMPv3 engine id has been validated
446
10.15 SNMP Microchip TCP/IP Stack Help Files
incomingPdu ( see page 431) incomingSnmpPDUmsgID ( see page
Incoming PDU details
Retrived Incoming Msg ID value from PDU
msgSecrtyParamLenOffset ( see page
This is variable msgSecrtyParamLenOffset.
Incoming PDU Security primitive details.
securityPrimitivesOfIncomingPdu ( see page 432)
snmpEngineBoots ( see page 433)
The number of times that the SNMP engine has (re-)initialized itself
since snmpEngineID ( see page 433) was last configured.
snmpEngineTimeOffset ( see page
Reserving 32 bytes for the snmpEngineID as the octet string length can vary form 5 to 32
The maximum message size the SNMP engine can handle.
snmpEngineMaxMessageSize ( see page 433) snmpEngineMsgProcessModel ( see page 433)
snmpEngineSecurityModel ( see page
Type of security model used. Value Maximum range (2^31-1),
RFC3411
snmpEngineTime ( see page 434)
Type of Message processing model used. Value Maximum range
(2^31-1), RFC3411
The number of seconds since the value of the snmpEngineBoots ( see page 433) object last changed
Stores the time value in seconds since SNMP Engine reset
snmpEngnIDLength ( see page 434)
Engine ID length of the SNMP Engine
snmpInMsgPrivParamLen ( see page
Incoming SNMPv3 msg privacy parameters string is 8 bytes long.
snmpMsgBufSeekPos ( see page 435) Offset to read PDU data bytes for processing from dynamic memory
stub
Outgoing SNMPv3 msg privacy parameters string is 8 bytes long.
snmpOutMsgPrivParamLen ( see page 436)
snmpResponseSecurityFlag ( see page 437)
Type of Security for outgoing message in response to the incoming message.
snmpSecurityLevel ( see page 437)
Type of security. noAuthNoPriv(0),AuthNoPriv(1),AuthPriv(3)
Snmp udp buffer tx offset
Description
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
*******************************************************************
• FileName: SNMPv3.c
• Dependencies: TCP/IP stack
• Processor: PIC32
• Compiler: Microchip C32
*
• Software License Agreement
*
• Copyright (C) 2012 Microchip Technology Inc. All rights
447
10.15 SNMP Microchip TCP/IP Stack Help
• reserved.
*
• Microchip licenses to you the right to use, modify, copy, and
• distribute:
• (i) the Software when embedded on a Microchip microcontroller or
• digital signal controller product ("Device") which is
• integrated into Licensee's product; or
• (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
• ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
• used in conjunction with a Microchip ethernet controller for
• the sole purpose of interfacing with the ethernet controller.
*
• You should refer to the license agreement accompanying this
• Software for additional information regarding your rights and
• obligations.
*
• THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
• WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
• LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
• PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
• MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
• CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
• PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
• BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
• THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
• SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
• (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
Files
10.15.9.2
SNMPv3.h
Enumerations
Name
REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS ( see page 417)
SNMP_ENGNID_OCTET_IDENTIFIER_VAL ( see page
SNMPV3_HMAC_HASH_TYPE ( see page 419)
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT ( see page 420)
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT ( see page 420)
SNMPV3_PRIV_PROT_TYPE ( see page 420)
Description
This is type
REPORT_FLAG_AND_SECURITY_LEVEL_FLAG
S.
The fifth octet indicates how the rest (6th and following octets) are formatted. Refer to RFC3411 section5 Page# 41
Type of hash being calculated
This is type
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT.
This is type
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT.
This is type SNMPV3_PRIV_PROT_TYPE.
448
10.15 SNMP Microchip TCP/IP Stack Help Files
STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL
This is type
STD_BASED_SNMP_MESSAGE_PROCESSING
_MODEL.
STD_BASED_SNMP_SECURITY_MODEL ( see page
Snmp Message Processing Model
STD_BASED_SNMPV3_SECURITY_LEVEL ( see page
USM_SECURITY_LEVEL ( see page 424)
This is type
STD_BASED_SNMPV3_SECURITY_LEVEL.
This is type USM_SECURITY_LEVEL.
Functions
Name
_IsSNMPv3ValidStructure ( see page 379)
Description
Decode variable length structure.
_Snmpv3IsValidInt ( see page 380)
Verifies variable datatype as INT and retrieves its value.
Snmpv3AESEncryptResponseScopedPdu ( see page 388)
outGoing SNMPv3 scoped PDU Encryption using AES encryption protocol.
Snmpv3AuthenticateRxedPduForDataIntegrity ( see page 389)
Authenticate an incoming SNMPV3 USM PDU using
MD5 or SHA
Snmpv3AuthenticateTxPduForDataIntegrity ( see page 389)
Authenticate to an outgoing SNMPV3 USM PDU using
MD5 or SHA
Snmpv3AuthKeyZeroing2HmacBufLen64 ( see page 390)
Pad zero to the authentication key localized buffer.
Snmpv3CmprTrapSecNameAndSecLvlWithUSMDb
Routine to find the index of the user name in the user data base table.
Snmpv3ComputeHMACIpadOpadForAuthLoclzedKey
Compute HMAC inner and outer pad for authorization localized key.
Snmpv3ComputeHmacMD5Digest ( see page 392)
Compute HMAC - MD5 authentication code
Snmpv3ComputeHmacShaDigest ( see page 393)
Compute HMAC - SHA authentication code
Snmpv3ComputeMd5HmacCode ( see page 393)
Snmpv3ComputeShaHmacCode ( see page 394)
Compute HMAC - MD5 authentication code
Compute HMAC - SHA authentication code
Snmpv3GetSecurityLevel ( see page 396)
Snmpv3GetTrapSecurityLevel ( see page 397)
Snmpv3InitializeUserDataBase ( see page 398)
Snmpv3USMOutMsgPrivParam ( see page 405)
Snmpv3UsmSnmpEngnAuthPrivPswdLocalization ( see page 405)
Get Security level from authentication and Privacy type.
Routine to find the report, auth and privacy flags settings in the TRAP.
SNMPv3 initialization.
Intialize default SNMPv3 global user database.
Snmpv3Pswd2LocalizedAuthKeyMD5Hashing ( see page 400)
Convert MD5 Auth password to the localized Key using
SNMPEngineID.
Snmpv3Pswd2LocalizedAuthKeySHAHashing ( see page 401)
Convert SHA Auth password to the localized Key using
SNMPEngineID.
SNMP USM out message uses Privacy protocol (RFC
3826 )
Convert Auth and Priv password to the localized Key using SNMPEngineID.
Macros
Name
AUTH_LOCALIZED_PASSWORD_KEY_LEN ( see page 439)
PRIV_LOCALIZED_PASSWORD_KEY_LEN ( see page 441)
Description
SNMPv3 Authentication ( see page 91)
Localized passwed key lenegth size
#define
PRIV_LOCALIZED_PASSWORD_KEY_
LEN
16 SNMPv3 Privacy Pasword key length size
449
10.15 SNMP Microchip TCP/IP Stack Help Files
SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
SNMPv3 authentication localized Key length for memory validation
SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM_USE
This is macro SNMPV3_H.
SNMPv3 privacy key length size for memory validation
SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE ( see page
SNMPV3_USM_MAX_USER ( see page 443)
SNMPV3MSG_AUTHENTICATION_FAIL ( see page 444)
User security name length for memory validation
User Security Model should have atleast
1 user. Default is 3. User should change as per the requirement.
This is macro
SNMPV3MSG_AUTHENTICATION_FAI
L.
SNMPV3MSG_AUTHENTICATION_SUCCESS ( see page 444)
USER_SECURITY_NAME_LEN ( see page 444)
This is macro
SNMPV3MSG_AUTHENTICATION_SU
CCESS.
SNMPv3 User Security Name length
Structures
Name
AccessCtrlSubSysIsAccessAllowed ( see page 408)
Description
Applications are the typical clients of the service(s) of the Access
Control Subsystem. The following primitive is provided by the
Access Control Subsystem to check if access is allowed:
statusInformation ( see page 422) = -- success or errorIndication
dispatcherProcessPdu ( see page 409) Process Incoming Request or Notification PDU
Dispatcher provides the following primitive to pass an incoming snmp pdu to an application.
dispatcherStatusInfo ( see page 409)
Generate Outgoing Request or Notification
statusInformation ( see page 422) = -- sendPduHandle if success --
errorIndication if failure
dispathcerReturnResponsePdu ( see page 410)
MsgProcModPrepareDataElements ( see page 411)
MsgProcModPrepareOutgoingMessage
Generate Outgoing Response
The PDU Dispatcher provides the following primitive for an application to return an SNMP Response PDU to the PDU
Dispatcher: result = SUCCESS or FAILURE
Prepare Data Elements from an Incoming SNMP Message
The Message Processing Subsystem provides this service primitive for preparing the abstract data elements from an incoming SNMP message: result = -- SUCCESS or errorIndication
Prepare Outgoing SNMP Request or Notification Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Request or Notification Message
MsgProcModPrepareResponseMessage
Prepare an Outgoing SNMP Response Message
The Message Processing Subsystem provides this service primitive for preparing an outgoing SNMP Response Message: result = --
SUCCESS or FAILURE
processResponsePdu ( see page 413) Process Incoming Response PDU
The PDU Dispatcher provides the following primitive to pass an incoming SNMP Response PDU to an application:
registerContextEngineID ( see page
success or errorIndication
This is record SecuritySysGenerateRequestMsg.
SecuritySysGenerateRequestMsg ( see page 414)
SecuritySysGenerateResponseMsg ( see page 415)
Generate a Response Message
The Security Subsystem provides the following primitive to generate a Response message:
450
10.15 SNMP Microchip TCP/IP Stack Help Files
unregisterContextEngineID ( see page
SecuritySysProcessIncomingMsg ( see page 418)
SNMPV3_REQUEST_WHOLEMSG ( see page 421)
( see page 421) snmpV3EngnUserDataBase ( see page 421)
snmpV3TrapConfigDataBase ( see page 422) statusInformation ( see page 422)
Release State Reference Information
All Subsystems which pass stateReference information also provide a primitive to release the memory that holds the referenced state information
This is record unregisterContextEngineID.
This is type SecuritySysProcessIncomingMsg.
This is type SNMPV3_REQUEST_WHOLEMSG.
This is type SNMPV3_RESPONSE_WHOLEMSG.
This is type snmpV3EngnUserDataBase.
snmpv3 target configuration with respect to trap.
success or errorIndication
Description
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
*******************************************************************
• FileName: SNMPv3.h
• Dependencies: TCP/IP stack
• Processor: PIC32
• Compiler: Microchip C32
*
• Software License Agreement
*
• Copyright (C) 2012 Microchip Technology Inc. All rights
• reserved.
*
• Microchip licenses to you the right to use, modify, copy, and
• distribute:
• (i) the Software when embedded on a Microchip microcontroller or
• digital signal controller product ("Device") which is
• integrated into Licensee's product; or
• (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
• ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
• used in conjunction with a Microchip ethernet controller for
• the sole purpose of interfacing with the ethernet controller.
*
451
10.15 SNMP Microchip TCP/IP Stack Help
• You should refer to the license agreement accompanying this
• Software for additional information regarding your rights and
• obligations.
*
• THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
• WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
• LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
• PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
• MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
• CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
• PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
• BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
• THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
• SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
• (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
Files
10.15.9.3
SNMPv3USM.c
Variables
Name
Description
This is variable authKey_iPad.
This is variable authKey_oPad.
The number of times that the authoritative SNMP engine has (re-)initialized
itself since its snmpEngineID ( see page 433) was last configured.
The number of seconds since the value of the authoritativeSnmpEngineBoots
( see page 426) object last changed
This is variable cipher_text.
This is variable deciphered_text.
TRAP message PDU header construction offset details
gSnmpv3UserDBIndex ( see page 430) hmacAuthKeyBuf ( see page
Index to the particular reference configured in User security model data base
snmpV3UserDataBase ( see page 437).
This is variable hmacAuthKeyBuf.
431) ivEncrptKeyOut ( see page
This is variable HmacMd5Digest.
This is variable HmacSHADigest.
This is variable ivEncrptKeyOut.
md5LocalizedAuthKey ( see page 432)
This is variable md5LocalizedAuthKey.
session_key ( see page 432) This is variable session_key.
sha1LocalizedAuthKey ( see page 433)
This is variable sha1LocalizedAuthKey.
452
10.15 SNMP Microchip TCP/IP Stack Help Files
snmpInMsgAuthParamLen ( see page 435) snmpInMsgAuthParamStrng
( see page 435) snmpInMsgPrvParamStrng ( see page 435)
( see page 436) snmpOutMsgAuthParamStrng
( see page 436) snmpOutMsgPrvParamStrng
( see page 437) snmpV3AesEncryptInitVector
( see page 437) snmpV3UserDataBase ( see page 437)
Incoming SNMPv3 msg authentication parameters string is 12 bytes long.
Reserving 12 bytes for the incoming SNMPv3 msg authentication parameters.
Reserving 8 bytes for the incoming SNMPv3 msg privacy parameters.
Outgoing SNMPv3 msg authentication parameters string is 12 bytes long.
Reserving 12 bytes for the outgoing SNMPv3 msg authentication parameters.
Reserving 8 bytes for the outgoing SNMPv3 msg privacy parameters.
128 Bit
128 Bit
This is variable snmpV3UserDataBase.
Description
• Simple Network Management Protocol (SNMP) Version 3 Agent
*
• Module for Microchip TCP/IP Stack
• -Provides SNMPv3 API for doing stuff
*
• -Reference: RFCs 3410, 3411, 3412, 3413, 3414
*******************************************************************
• FileName: SNMPv3USM.c
• Dependencies: TCP/IP stack
• Processor: PIC32
• Compiler: Microchip C32
*
• Software License Agreement
*
• Copyright (C) 2012 Microchip Technology Inc. All rights
• reserved.
*
• Microchip licenses to you the right to use, modify, copy, and
• distribute:
• (i) the Software when embedded on a Microchip microcontroller or
• digital signal controller product ("Device") which is
• integrated into Licensee's product; or
• (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
• ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
• used in conjunction with a Microchip ethernet controller for
• the sole purpose of interfacing with the ethernet controller.
453
10.15 SNMP Microchip TCP/IP Stack Help
*
• You should refer to the license agreement accompanying this
• Software for additional information regarding your rights and
• obligations.
*
• THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
• WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
• LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
• PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
• MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
• CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
• PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
• BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
• THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
• SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
• (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
Files
10.15.9.4
SNMP.c
Functions
Name
Description
Finds number of varbinds in the varbind list received in a pdu.
Verifies the value type as ASN_NULL ( see page 349).
Verifies for the community string datatype and the max community name and length, this agent can process.
Populates OID type, length and oid string from the received pdu.
ProcessGetSetHeader ( see page 372)
Verifies for the snmp request type.
Validates the received udp packet Get/Set request header.
Validates the received udp packet Snmp header.
ProcessVariables ( see page 374) This routine processes the snmp request and parallely creates the
response pdu.
Get OID string from MPFS using the node address.
To find whether requested OID is only for private access.
Variables
Name
appendZeroToOID ( see page 349)
Description
global flag to modify OID by appending zero
ASN format datatype for snmp v1 and v2c
This variable is used for gext next request for zero instance
MPFS file handler
454
10.15 SNMP Microchip TCP/IP Stack Help
SNMPAgentSocket ( see page 365)
snmpReqVarErrStatus ( see page 366)
Snmp udp socket notify info for trap vars from req list processing err status
Snmp udp buffer rx offset
MIB file access status
Description
• Simple Network Management Protocol (SNMP) Version 1 Agent
• Simple Network Management Protocol (SNMP) Version 2 community based Agent
• Module for Microchip TCP/IP Stack
• -Provides SNMP API for doing stuff
*
• -Reference: RFC 1157 (for SNMP V1)
• RFC 3416 (for SNMPv2C)
*******************************************************************
• FileName: SNMP.c
• Dependencies: UDP, ARP
• Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
• Compiler: Microchip C32 v1.05 or higher
• Microchip C30 v3.12 or higher
• Microchip C18 v3.30 or higher
• HI-TECH PICC-18 PRO 9.63PL2 or higher
• Company: Microchip Technology, Inc.
*
• Software License Agreement
*
• Copyright (C) 2002-2009 Microchip Technology Inc. All rights
• reserved.
*
• Microchip licenses to you the right to use, modify, copy, and
• distribute:
• (i) the Software when embedded on a Microchip microcontroller or
• digital signal controller product ("Device") which is
• integrated into Licensee's product; or
• (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
• ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
• used in conjunction with a Microchip ethernet controller for
• the sole purpose of interfacing with the ethernet controller.
*
Files
455
10.15 SNMP Microchip TCP/IP Stack Help
• You should refer to the license agreement accompanying this
• Software for additional information regarding your rights and
• obligations.
*
• THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
• WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
• LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
• PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
• MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
• CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
• PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
• BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
• THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
• SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
• (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
• Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
• Nilesh Rajbharti 1/9/03 Original (Rev 1.0)
• Dan Cohen 12/11/03 Removed trap support by #define if not
• required to lower code space requirements
• Amit Shirbhate 09/24/08 SNMPv2c Support, comments and function
• headers added.
• Hrisikesh Sahu 04/15/10 SNMPv2 Trap Format Support.
Files
10.15.9.5
SNMP.h
Enumerations
Name
COMMUNITY_TYPE ( see page 334)
Description
This is type COMMUNITY_TYPE.
GENERIC_TRAP_NOTIFICATION_TYPE ( see page 333)
INOUT_SNMP_PDU ( see page 417)
This is type GENERIC_TRAP_NOTIFICATION_TYPE.
This is type INOUT_SNMP_PDU.
This is the list of SNMP action a remote NMS can perform. This inforamtion is passed to application via
callback SNMPValidateCommunity ( see page 341)().
Application should validate the action for given community string.
SNMP_ERR_STATUS ( see page 361)
VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE
This is type
VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE.
456
10.15 SNMP
Functions
Microchip TCP/IP Stack Help Files
Name
_SNMPDuplexInit ( see page 347)
GetDataTypeInfo ( see page 355)
Description
Prepare for full duplex transfer.
Read byte from snmp udp socket rx buffer.
Copy byte to tx buffer.
Get ASN data type info.
GetOIDStringByAddr ( see page 368)
Searches for the next leaf node in the MIP tree.
Get OID string from MPFS using the node address.
GetOIDStringByID ( see page 368)
Get complete notification variable OID string from MPFS using var id.
getSnmpV2GenTrapOid ( see page 381) Resolves generic trap code to generic trap OID.
Verifies variable datatype as INT and retrieves its value.
Retrieves the packet length and actual pdu length.
Decode variable length structure.
IsValidStructure ( see page 371)
To search and validate whether the requested OID is in the MIB database.
This routine process the SNMPv2c Get Bulk Request.
ProcessGetBulkVar ( see page 383)
ProcessGetNextVar ( see page 384)
Retrieves next node from the MIB database.
Processes snmp Get request pdu.
ProcessSnmpv3MsgData ( see page
SetErrorStatus ( see page 360)
Processes snmp Set request pdu.
This routine processes the snmpv3 request and parallely creates the response pdu.
Set snmp error status in the response pdu.
SNMPGetExactIndex ( see page 386)
SNMPGetNextIndex ( see page 340)
To search for exact index node in case of a Sequence variable.
To search for next index node in case of a Sequence variable.
Used to Get/collect OID variable information.
SNMPIdRecrdValidation ( see page 386) Used to Restrict the access dynamic and non dynamic OID string
for A perticular SNMP Version.
SNMPIsNotifyReady ( see page 339)
Initialize SNMP module internals.
Resolves given remoteHost IP address into MAC address.
SNMPIsValidSetLen ( see page 387)
SNMPNotifyPrepare ( see page 340)
Validates the set variable data length to data type.
Creates and Sends TRAP pdu.
Collects trap notification info and send ARP to remote host.
Prepare, validate remote node which will receive trap and send trap pdu.
457
10.15 SNMP Microchip TCP/IP Stack Help Files
This routine Set the mib variable with the requested value.
Snmpv3AESDecryptRxedScopedPdu ( see page 388)
Snmpv3BufferPut ( see page 390)
Polls for every snmp pdu received.
Incoming SNMPv3 scoped PDU decryption using AES decryption protocol.
Copies BYTE data to dynamically allocated memory buffer.
Snmpv3FormulateEngineID ( see page
Formulates the snmpEngineID ( see page 433) for the SNMPV3
engine.
Snmpv3GetAuthEngineTime ( see page
Updates the snmp engine time variable 'snmpEngineTime ( see page 434)' for the SNMPV3 engine.
Snmpv3GetBufferData ( see page 396)
Reads BYTE data from dynamically allocated memory buffer.
Snmpv3MsgProcessingModelProcessPDU
This routine collects or populates the message processing model infomation from the received SNMPv3 request PDU or to the response PDU respectively.
Snmpv3ScopedPduProcessing ( see page 402)
Creates and Sends SNMPv3 TRAP pdu.
This routine collects the scoped pdu header information from the received SNMPv3 request PDU or populates to the response PDU respectively.
Snmpv3TrapScopedpdu ( see page 403) TRAP PDU scoped pdu header construction.
Snmpv3UserSecurityModelProcessPDU
This routine collects or populates the security model parametrs infomation from the received SNMPv3 request PDU or to the response PDU respectively.
AES Encryption and decryption init vector.(RFC 3826 )
Snmpv3UsmAesEncryptDecryptInitVector
Snmpv3UsmOutMsgAuthenticationParam
Both MD5 and SHA1 is used for the outgoing message authentication.
Validate engine ID.
Snmpv3ValidateEngineId ( see page
Snmpv3ValidateSecNameAndSecLvl ( see page 406)
Vaidate security name with Security level.
Snmpv3ValidateSecurityName ( see page 407)
SNMPValidateCommunity ( see page
Validate SNMPV3 user name or security name.
Validates community name for access control.
Macros
Name
_SNMPGetTxOffset ( see page 348)
_SNMPSetTxOffset ( see page 349)
AGENT_NOTIFY_PORT ( see page 349)
DATA_TYPE_TABLE_SIZE ( see page 351)
GET_BULK_REQUEST ( see page 352)
GET_NEXT_REQUEST ( see page 352)
Description
This is macro _SNMPGetTxOffset.
This is macro AGENT_NOTIFY_PORT.
This is macro ASN_INT.
This is macro ASN_NULL.
This is macro ASN_OID.
This is macro GET_BULK_REQUEST.
This is macro GET_NEXT_REQUEST.
458
10.15 SNMP Microchip TCP/IP Stack Help Files
IS_GET_NEXT_REQUEST ( see page 354)
IS_GET_REQUEST ( see page 354)
This is macro GET_RESPONSE.
This is macro IS_AGENT_PDU.
This is macro IS_ASN_INT.
This is macro IS_ASN_NULL.
This is macro IS_GET_NEXT_REQUEST.
This is macro IS_GET_REQUEST.
IS_GET_RESPONSE ( see page 355)
IS_OCTET_STRING ( see page 355)
This is macro IS_GET_RESPONSE.
This is macro IS_OCTET_STRING.
IS_SET_REQUEST ( see page 356)
This is macro IS_OID.
This is macro IS_SET_REQUEST.
IS_SNMPV3_AUTH_STRUCTURE ( see page 440) This is macro IS_SNMPV3_AUTH_STRUCTURE.
REPORT_RESPONSE ( see page 441)
This is macro IS_TRAP.
This is macro OCTET_STRING.
Change this to match your OID string length.
This is macro REPORT_RESPONSE.
This is macro SET_REQUEST.
SNMP_AGENT_PORT ( see page 360)
SNMP_BIB_FILE_NAME ( see page 360)
SNMP_COUNTER32 ( see page 361)
SNMP_END_OF_VAR ( see page 343)
SNMP_INDEX_INVALID ( see page 343)
SNMP_MAX_MSG_SIZE ( see page 441)
This is the file that contains SNMP bib file. File name must contain all upper case letter and must match with what was included in MPFS2 image.
This is macro SNMP_COUNTER32.
This is macro SNMP_END_OF_VAR.
This is macro SNMP_GAUGE32.
SNMP_MAX_OID_LEN_MEM_USE ( see page
SNMP_NSAP_ADDR ( see page 363)
This is macro SNMP_INDEX_INVALID.
This is macro SNMP_IP_ADDR.
SNMP MIN and MAX message 484 bytes in size As per
RFC 3411 snmpEngineMaxMessageSize ( see page
433) and RFC 1157 ( section 4- protocol specification )
and implementation supports more than 484 whenever feasible.
This macro will be used to avoid SNMP OID memory buffer corruption
This is macro SNMP_NMS_PORT.
This is macro SNMP_NSAP_ADDR.
This is macro SNMP_OPAQUE.
459
10.15 SNMP Microchip TCP/IP Stack Help Files
SNMP_START_OF_VAR ( see page 342)
SNMP_TIME_TICKS ( see page 364)
This is macro SNMP_START_OF_VAR.
This is macro SNMP_TIME_TICKS.
SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE
This macro will be used to avoid SNMP OID memory buffer corruption
This is macro SNMP_V2C.
This is macro SNMP_V3.
This is macro TRAP.
TRAP_COMMUNITY_MAX_LEN ( see page 343)
This is macro TRAP_COMMUNITY_MAX_LEN.
TRAP_TABLE_SIZE ( see page 343)
This is macro TRAP_TABLE_SIZE.
Structures
Name
DATA_TYPE_INFO ( see page 351)
SNMP_NOTIFY_INFO ( see page 363)
Description
This is type SNMPNONMIBRECDINFO.
SNMPv3
This is type TRAP_INFO.
Types
Name
Description
This is the SNMP OID variable id. This id is assigned via MIB file. Only dynamic and AgentID variables can contian ID. MIB2BIB utility enforces this rules when
BIB was generated.
This is type SNMP_INDEX.
Unions
Name
Description
SNMP_VAL ( see page 334) This is type SNMP_VAL.
Description
• SNMP Defs for Microchip TCP/IP Stack
*
*******************************************************************
• FileName: SNMP.h
460
10.16 SNTP Client Microchip TCP/IP Stack Help
• Dependencies: StackTsk.h
• UDP.h
• Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
• Compiler: Microchip C32 v1.05 or higher
• Microchip C30 v3.12 or higher
• Microchip C18 v3.30 or higher
• HI-TECH PICC-18 PRO 9.63PL2 or higher
• Company: Microchip Technology, Inc.
*
• Software License Agreement
*
• Copyright (C) 2002-2009 Microchip Technology Inc. All rights
• reserved.
*
• Microchip licenses to you the right to use, modify, copy, and
• distribute:
• (i) the Software when embedded on a Microchip microcontroller or
• digital signal controller product ("Device") which is
• integrated into Licensee's product; or
• (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
• ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
• used in conjunction with a Microchip ethernet controller for
• the sole purpose of interfacing with the ethernet controller.
*
• You should refer to the license agreement accompanying this
• Software for additional information regarding your rights and
• obligations.
*
• THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
• WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
• LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
• PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
• MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
• CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
• PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
• BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
• THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
• SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
• (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
• V5.36 ---- STACK_USE_MPFS has been removed
461
10.16 SNTP Client Microchip TCP/IP Stack Help SNTP Client Stack Members
10.16
SNTP Client
The SNTP module implements the Simple Network Time Protocol. The module (by default) updates its internal time every 10
The SNTP module is good for providing absolute time stamps. However, it should not be relied upon for measuring time differences (especially small differences). The pool of public time servers is implemented using round-robin DNS, so each update will come from a different server. Differing network delays and the fact that these servers are not verified implies that this time could be non-linear. While it is deemed reliable, it is not guaranteed to be accurate.
The Tick module provides much better accuracy (since it is driven by a hardware clock) and resolution, and should be used for measuring timeouts and other internal requirements.
or to specify a region when accessing time servers. The default is to use the global pool.
10.16.1
SNTP Client Public Members
Functions
Name
SNTPGetUTCSeconds ( see page 462)
Module
Description
Obtains the current time from the SNTP module.
Description
The following functions and variables are available to the stack application.
10.16.1.1
SNTPGetUTCSeconds Function
File
SNTP.h
C
DWORD SNTPGetUTCSeconds();
Returns
The number of seconds since the Epoch. (Default 01-Jan-1970 00:00:00)
Description
This function obtains the current time as reported by the SNTP module. Use this value for absolute time stamping. The value returned is (by default) the number of seconds since 01-Jan-1970 00:00:00.
Remarks
Do not use this function for time difference measurements. The Tick module is more appropriate for those requirements.
Preconditions
None
462
10.16 SNTP Client Microchip TCP/IP Stack Help SNTP Client Internal Members
10.16.2
SNTP Client Stack Members
Functions
Name Description
SNTPClient ( see page 463) Periodically checks the current time from a pool of servers.
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.16.2.1
SNTPClient Function
File
SNTP.h
C void
SNTPClient();
Returns
None
Description
This function periodically checks a pool of time servers to obtain the current date/time.
Remarks
This function requires once available UDP socket while processing, but frees that socket when the SNTP module is idle.
Preconditions
UDP is initialized.
10.16.3
SNTP Client Internal Members
Macros
Name Description
Reference Epoch to use. (default: 01-Jan-1970 00:00:00)
Defines how long to wait to retry an update after a failure. Updates may take up to 6 seconds to fail, so this 14 second delay is actually only an 8-second retry.
NTP_QUERY_INTERVAL ( see page 466)
Defines how frequently to resynchronize the date/time (default: 10 minutes)
NTP_REPLY_TIMEOUT ( see page 466)
Defines how long to wait before assuming the query has failed
463
10.16 SNTP Client Microchip TCP/IP Stack Help SNTP Client Internal Members
NTP_SERVER ( see page 466) These are normally available network time servers. The actual IP returned
from the pool will vary every minute so as to spread the load around stratum
1 timeservers. For best accuracy and network overhead you should locate the pool server closest to your geography, but it will still work if you use the global pool.ntp.org address or choose the wrong one or ship your embedded device to another geography.
NTP_SERVER_PORT ( see page 467)
Port for contacting NTP servers
Module
Structures
Name
Description
Defines the structure of an NTP packet
Variables
Name
dwLastUpdateTick ( see page 465) dwSNTPSeconds ( see page 465)
Description
Tick count of last update
Seconds value obtained by last update
Description
The following functions and variables are designated as internal to the SNTP Client module.
10.16.3.1
NTP_PACKET Structure
File
SNTP.c
C typedef struct
{
struct
{
BYTE mode : 3;
BYTE versionNumber : 3;
BYTE leapIndicator : 2;
} flags;
BYTE stratum;
CHAR poll;
CHAR precision;
DWORD root_delay;
DWORD root_dispersion;
DWORD ref_identifier;
DWORD ref_ts_secs;
DWORD ref_ts_fraq;
DWORD orig_ts_secs;
DWORD orig_ts_fraq;
DWORD recv_ts_secs;
DWORD recv_ts_fraq;
DWORD tx_ts_secs;
DWORD tx_ts_fraq;
} NTP_PACKET;
464
10.16 SNTP Client Microchip TCP/IP Stack Help
Members
Members
struct {
BYTE mode : 3;
BYTE versionNumber : 3;
BYTE leapIndicator : 2;
} flags;
BYTE mode : 3;
BYTE versionNumber : 3;
BYTE leapIndicator : 2;
BYTE stratum;
CHAR poll;
CHAR precision;
DWORD root_delay;
DWORD root_dispersion;
DWORD ref_identifier;
DWORD ref_ts_secs;
DWORD ref_ts_fraq;
DWORD orig_ts_secs;
DWORD orig_ts_fraq;
DWORD recv_ts_secs;
DWORD recv_ts_fraq;
DWORD tx_ts_secs;
DWORD tx_ts_fraq;
Description
Defines the structure of an NTP packet
Description
Flags for the packet
NTP mode
SNTP version number
Leap second indicator
Stratum level of local clock
Poll interval
Precision (seconds to nearest power of 2)
Root delay between local machine and server
Root dispersion (maximum error)
Reference clock identifier
Reference timestamp (in seconds)
Reference timestamp (fractions)
Origination timestamp (in seconds)
Origination timestamp (fractions)
Time at which request arrived at sender (seconds)
Time at which request arrived at sender (fractions)
Time at which request left sender (seconds)
Time at which request left sender (fractions)
SNTP Client Internal Members
10.16.3.2
dwLastUpdateTick Variable
File
SNTP.c
C
DWORD dwLastUpdateTick = 0;
Description
Tick count of last update
10.16.3.3
dwSNTPSeconds Variable
File
SNTP.c
C
DWORD dwSNTPSeconds = 0;
Description
Seconds value obtained by last update
465
10.16 SNTP Client Microchip TCP/IP Stack Help SNTP Client Internal Members
10.16.3.4
NTP_EPOCH Macro
File
SNTP.c
C
#define
NTP_EPOCH (86400ul * (365ul * 70ul + 17ul))
Description
Reference Epoch to use. (default: 01-Jan-1970 00:00:00)
10.16.3.5
NTP_FAST_QUERY_INTERVAL Macro
File
SNTP.c
C
#define
NTP_FAST_QUERY_INTERVAL (14ull * TICK_SECOND)
Description
Defines how long to wait to retry an update after a failure. Updates may take up to 6 seconds to fail, so this 14 second delay is actually only an 8-second retry.
10.16.3.6
NTP_QUERY_INTERVAL Macro
File
SNTP.c
C
#define
NTP_QUERY_INTERVAL (10ull*60ull * TICK_SECOND)
Description
Defines how frequently to resynchronize the date/time (default: 10 minutes)
10.16.3.7
NTP_REPLY_TIMEOUT Macro
File
SNTP.c
C
#define
NTP_REPLY_TIMEOUT (6ul*TICK_SECOND)
Description
Defines how long to wait before assuming the query has failed
10.16.3.8
NTP_SERVER Macro
File
SNTP.c
466
10.17 SSL Microchip TCP/IP Stack Help
C
#define
NTP_SERVER "pool.ntp.org"
Description
These are normally available network time servers. The actual IP returned from the pool will vary every minute so as to spread the load around stratum 1 timeservers. For best accuracy and network overhead you should locate the pool server closest to your geography, but it will still work if you use the global pool.ntp.org address or choose the wrong one or ship your embedded device to another geography.
10.16.3.9
NTP_SERVER_PORT Macro
File
SNTP.c
C
#define
NTP_SERVER_PORT (123ul)
Description
Port for contacting NTP servers
10.17
SSL
Files
Name
SSLClientSize.h ( see page 530)
Description
This is file SSLClientSize.h.
Description
The SSL module adds encryption support to the TCP layer by implementing the SSLv3 protocol. This protocol is the standard for secure communications across the Internet, and prevents snooping or tampering of data as it travels across an untrusted network. This implementation of SSL supports the RSA asymmetric encryption protocol and the ARCFOUR symmetric encryption protocol.
Compiler
C18
C30
C32
SSL Server Maximum RSA key length
(SSL_RSA_KEY_SIZE ( see page 475))
1024
1024
2048
SSL Client Maximum RSA key length
(SSL_RSA_CLIENT_SIZE ( see page 476))
1024
1024
2048
Previous versions of the MLA software distribution required that files containing cryptographic algorithm implementations be distributed separately to comply with U.S. Export Controls. In this version, the cryptographic modules are included with the
TCP/IP Stack.
SSL Client Support
An SSL client can be initiated by first opening a TCP connection, then calling TCPStartSSLSession to initiate the SSL handshake process. The handshake uses the public key from the certificate provided by the server. Key lengths up to 1024 bits are supported on all processors; key lengths up to 2048 bits are supported on PIC32 microcontrollers. The
SSL_RSA_CLIENT_SIZE ( see page 476)
SSLClientSize.h ( see page 530)
sets the maximum certificate key length that your client should process.
#define
SSL_RSA_CLIENT_SIZE (1024ul)
// Size of Encryption Buffer (must be larger
467
10.17 SSL Microchip TCP/IP Stack Help Generating Server Certificates
than key size)
the handshake has completed and all traffic is now secured using 128-bit ARCFOUR encryption. If the handshake fails for any reason, the TCP connection will automatically be terminated as required by the SSL protocol specification.
For faster performance, the SSL module caches security parameters for the most recently made connections. This allows quick reconnections to the same node without the computational expense of another RSA handshake. By default, the two most recent connections are cached, but this can be modified in TCPIPConfig.h.
SSL client support is already enabled for SMTP. When STACK_USE_SSL_CLIENT is defined, the SMTP module
client module will attempt to make an SSL connection before transmitting any data.
Note that TCP sockets using SSL may required an increase in TX/RX buffer size to support SSL. You can adjust the size of your sockets using the TCP/IP Configuration Utility included with the stack.
SSL Server Support
ports. Connections occurring on the originally opened port will proceed unsecured, while connections on the SSL port will first complete an SSL handshake to secure the data.
SSL server support is automatically enabled for HTTP2 when STACK_USE_SSL_SERVER is defined. By default, the
This SSL server implementation supports key lengths up to 1024 bits on most PIC microcontrollers, and 2048 bits on PIC32 microcontrollers. The
SSL_RSA_KEY_SIZE ( see page 475)
macro in TCPIPConfig.h sets the server certificate key length.
// Bits in SSL RSA key. This parameter is used for SSL sever
// connections only.
#define
SSL_RSA_KEY_SIZE (512ul)
Note that TCP sockets using SSL may required an increase in TX/RX buffer size to support SSL. You can adjust the size of your sockets using the TCP/IP Configuration Utility included with the stack.
Limitations
SSL was designed for desktop PCs with faster processors and significantly more resources than are available on an embedded platform. A few compromises must be made in order to use SSL in a less resource-intensive manner.
The SSL client module does not perform any validation or verification of certificates. Doing so would require many root certificates to be stored locally for verification, which is not feasible for memory-limited parts. This does not compromise security once the connection has been established, but does not provide complete security against man-in-the-middle attacks. (This sort of attack is uncommon and would be difficult to execute.)
Neither the SSL client nor the server can completely verify MACs before processing data. SSL records include a signature to
after at least every 16kB of traffic. (It usually is inserted much more frequently than that.) Without 16kB of RAM to buffer packets for each socket, incoming data must be handed to the application layer before the MAC can be completely verified.
Invalid MACs will still cause the connection to terminate immediately, but by the time this is detected some bad data may have already reached the application. Since the ARCFOUR cipher in use is a stream cipher, it would be difficult to exploit this in any meaningful way. An attacker would not be able to control what data is actually modified or inserted, as doing so without knowledge of the key would yield garbage. However, it is important to understand that incoming data is not completely verified before being passed to the application.
468
10.17 SSL Microchip TCP/IP Stack Help Generating Server Certificates
10.17.1
Generating Server Certificates
Module
Description
The SSL certificates used by the TCP/IP Stack's SSL module are stored in the CustomSSLCert.c source file. The following series of steps describe how to create the structures in CustomSSLCert.c using an SSL certificate.
1. Download and install the OpenSSL library. There are several third-party sites that offer SSL installers (e.g. http://www.slproweb.com/products/Win32OpenSSL.html
). Note that some distributions may not include all commands specified by the OpenSSL documentation.
2. Open a console and change directory to the OpenSSL/bin folder.
3. If you don't have a key and certificate, you can generate them first. The following example console commands will generate a a 512-bit key:
1. Generate the key: openssl genrsa -out 512bits.key 512
2. Generate the Certificate Signing Request (CSR). You will need to add additional information when prompted: openssl
req -new -key 512bits.key -out 512bits.csr
3. Generate the X.509 certificate if self-signing (or send the CSR to a Certificate Authority for signing): openssl x509 -req
-days 365 -in 512bits.csr -signkey 512bits.key -out 512bits.crt (note that if the -days option is not specified, the default expiration time is 30 days)
4. For additional documentation, refer to http://www.openssl.org/docs/apps/openssl.html
.
4. Parse your key file using the command: openssl.exe asn1parse -in "[directory containing your key]\512bits.key"
5. You should see a screen like this:
6. If you are not using an ENCX24J600 family device, then the last 5 integers displayed here are the SSL_P, SSL_Q,
SSL_dP, SSL_dQ, and SSL_qInv parameters, respectively. However, they are displayed here in big-endian format, and the Microchip cryptographic library implementation requires parameters in little-endian format, so you will have to enter the parameters into the C arrays in opposite order. For example, the INTEGER at offset 145:
145:d=1 h1=2 ;= 33 prim: INTEGER
:D777566780029FCD610200B66D89507D
915E3E5BDB6FAB0233B5DFA2E4 08 1D F7 will be swapped in the CustomSSLCert.c file:
ROM BYTE SSL_P[] = {
0xF7 , 0x1D , 0x08 , 0xE4, 0xA2, 0xDF, 0xB5, 0x33,
0x02, 0xAB, 0x6F, 0xDB, 0x5B, 0x3E, 0x5E, 0x91,
0x7D, 0x50, 0x89, 0x6D, 0xB6, 0x00, 0x02, 0x61,
0xCD, 0x9F, 0x02, 0x80, 0x67, 0x56, 0x77, 0xD7
469
10.17 SSL Microchip TCP/IP Stack Help Generating Server Certificates
};
7. If you are using an ENCX24J600 family device, then the second and fourth integers displayed here are the SSL_N and
SSL_D parameters, respectively. There is no need to do an endian format change for these parameters. For the example, the expected SSL_N and SSL_D values are shown in the figure below:
8. Parse your X.509 certificate using the command: openssl.exe asn1parse -in "[directory containing your
cert]\512bits.crt" -out cert.bin
9. Open the cert.bin output file in a hex editor. For example, here is the default certificate information generated from
512bits.crt given in the stack:
a large integer) so it does not get endian-swapped like the private key parameters.
= {
0x30, 0x82, 0x02, 0x08, 0x30, 0x82, 0x01, 0xb2, 0x02, 0x09, 0x00, 0xa5, 0x6a, 0xea, 0x1a, 0xa9,
0x52, 0x9d, 0x1e, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05,
0x05, 0x00, 0x30, 0x81, 0x8a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02,
0x55, 0x53, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x07, 0x41, 0x72, 0x69,
470
10.17 SSL Microchip TCP/IP Stack Help
0x7a, 0x6f, 0x6e, 0x61, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x08, 0x43,
0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x31, 0x23, 0x30, 0x21, 0x06, 0x03, 0x55, 0x04, 0x0a,
0x13, 0x1a, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x63, 0x68, 0x69, 0x70, 0x20, 0x54, 0x65, 0x63, 0x68,
0x6e, 0x6f, 0x6c, 0x6f, 0x67, 0x79, 0x2c, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x31, 0x1d, 0x30, 0x1b,
0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x14, 0x53, 0x53, 0x4c, 0x20, 0x44, 0x65, 0x6d, 0x6f, 0x20,
0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x31, 0x12, 0x30, 0x10, 0x06,
0x03, 0x55, 0x04, 0x03, 0x13, 0x09, 0x6d, 0x63, 0x68, 0x70, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x30,
0x1e, 0x17, 0x0d, 0x30, 0x37, 0x31, 0x30, 0x30, 0x39, 0x31, 0x38, 0x33, 0x37, 0x32, 0x37, 0x5a,
0x17, 0x0d, 0x31, 0x37, 0x31, 0x30, 0x30, 0x36, 0x31, 0x38, 0x33, 0x37, 0x32, 0x37, 0x5a, 0x30,
0x81, 0x8a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31,
0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x07, 0x41, 0x72, 0x69, 0x7a, 0x6f, 0x6e,
0x61, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x08, 0x43, 0x68, 0x61, 0x6e,
0x64, 0x6c, 0x65, 0x72, 0x31, 0x23, 0x30, 0x21, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x1a, 0x4d,
0x69, 0x63, 0x72, 0x6f, 0x63, 0x68, 0x69, 0x70, 0x20, 0x54, 0x65, 0x63, 0x68, 0x6e, 0x6f, 0x6c,
0x6f, 0x67, 0x79, 0x2c, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x31, 0x1d, 0x30, 0x1b, 0x06, 0x03, 0x55,
0x04, 0x0b, 0x13, 0x14, 0x53, 0x53, 0x4c, 0x20, 0x44, 0x65, 0x6d, 0x6f, 0x20, 0x43, 0x65, 0x72,
0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04,
0x03, 0x13, 0x09, 0x6d, 0x63, 0x68, 0x70, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x30, 0x5c, 0x30, 0x0d,
0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x4b, 0x00,
0x30, 0x48, 0x02, 0x41, 0x00, 0xaa, 0x96, 0xca, 0x97, 0xea, 0x27, 0xb0, 0xd7, 0xe9, 0x21, 0xd0,
0x40, 0xd4, 0x2c, 0x09, 0x5a, 0x2e, 0x3a, 0xe4, 0x12, 0x64, 0x2d, 0x4b, 0x1b, 0x92, 0xdf, 0x79,
0x68, 0x4e, 0x3c, 0x51, 0xf4, 0x43, 0x48, 0x0d, 0xf2, 0xc8, 0x50, 0x9b, 0x6e, 0xe5, 0xea, 0xfe,
0xef, 0xd9, 0x10, 0x41, 0x08, 0x14, 0xf9, 0x85, 0x49, 0xfc, 0x50, 0xd3, 0x57, 0x34, 0xdc, 0x3a,
0x0d, 0x79, 0xf8, 0xd3, 0x99, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x41, 0x00, 0x18, 0x18, 0xfe, 0x8b,
0x2d, 0x0d, 0xf7, 0x0d, 0x65, 0x9d, 0x29, 0xec, 0xb3, 0x51, 0x6e, 0x3b, 0x93, 0xbb, 0x40, 0x1a,
0x0b, 0x34, 0x07, 0x63, 0x5e, 0x6a, 0x1c, 0x74, 0x59, 0xd4, 0x54, 0xd2, 0x1b, 0xf3, 0x31, 0xb7,
0x57, 0x4b, 0xa5, 0xe6, 0xe2, 0x35, 0xf7, 0xb3, 0x6a, 0x15, 0x6e, 0x3c, 0x93, 0x85, 0xb2, 0xca,
0xf5, 0x35, 0x00, 0xf4, 0x49, 0xe7, 0x00, 0x8a, 0x00, 0xd8, 0xe8, 0xcf
};
11. Update the SSL_CERT_LEN ( see page 499) variable to contain the correct value.
SSL Public Members
10.17.2
SSL Public Members
Enumerations
Name Description
This is type SSL_SUPPLEMENTARY_DATA_TYPES.
Functions
Name
TCPAddSSLListener ( see page 472)
TCPSSLIsHandshaking ( see page 473)
Description
Listens for SSL connection on a specific port.
Determines if an SSL session is still handshaking.
TCPStartSSLClient ( see page 473)
Begins an SSL client session.
Determines if a TCP connection is secured with SSL.
SSLStartSession ( see page 474)
Begins a new SSL session for the given TCP connection.
Macros
Name
SSL_INVALID_ID ( see page 472)
Description
Identifier for invalid SSL allocations
471
10.17 SSL Microchip TCP/IP Stack Help SSL Public Members
SSL_RSA_KEY_SIZE ( see page 475)
SSL_RSA_CLIENT_SIZE ( see page 476)
Bits in SSL RSA key. This parameter is used for SSL sever connections only.
The only valid value is 512 bits (768 and 1024 bits do not work at this time).
Note, however, that SSL client operations do currently work up to 1024 bit RSA key length.
Size of Encryption Buffer (must be larger than key size)
Module
Structures
Name
Description
To hash the public key information, we need to actually get the public key information... 1024 bit key at 8 bits/byte = 128 bytes needed for the public key.
Description
The following functions and variables are available to the stack application.
10.17.2.1
SSL_INVALID_ID Macro
File
SSL.h
C
#define
SSL_INVALID_ID (0xFFu)
// Identifier for invalid SSL allocations
Description
Identifier for invalid SSL allocations
10.17.2.2
TCPAddSSLListener Function
File
TCP.h
C
BOOL TCPAddSSLListener(
WORD port
);
Description
This function adds an additional listening port to a TCP connection. Connections made on this alternate port will be secured via SSL.
Preconditions
TCP is initialized and hTCP is listening.
Parameters
Parameters
hTCP port
Return Values
Return Values
TRUE
Description
TCP connection to secure
SSL port to listen ( see page 180) on
Description
SSL port was added.
472
10.17 SSL
FALSE
Microchip TCP/IP Stack Help
The socket was not a listening socket.
SSL Public Members
10.17.2.3
TCPSSLIsHandshaking Function
File
TCP.h
C
BOOL TCPSSLIsHandshaking(
);
Description
continue with its normal data transfer (which is now secured).
Preconditions
TCP is initialized and hTCP is connected.
Parameters
Parameters
hTCP
Return Values
Return Values
TRUE
FALSE
Description
TCP connection to check
Description
SSL handshake is still progressing
SSL handshake has completed
10.17.2.4
TCPStartSSLClient Function
File
TCP.h
C
BOOL TCPStartSSLClient(
BYTE* host
);
Description
This function escalates the current connection to an SSL secured connection by initiating an SSL client handshake.
Remarks
The host parameter is currently ignored and is not validated.
Preconditions
TCP is initialized and hTCP is already connected.
Parameters
Parameters
hTCP host
Description
TCP connection to secure
Expected host name on certificate (currently ignored)
473
10.17 SSL
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help
Description
an SSL connection was initiated
Insufficient SSL resources (stubs) were available
10.17.2.5
TCPIsSSL Function
File
TCP.h
C
BOOL TCPIsSSL(
);
Description
Call this function to determine whether or not a TCP connection is secured with SSL.
Preconditions
TCP is initialized and hTCP is connected.
Parameters
Parameters
hTCP
Return Values
Return Values
TRUE
FALSE
Description
TCP connection to check
Description
Connection is secured via SSL
Connection is not secured
10.17.2.6
SSLStartSession Function
File
SSL.h
C
BYTE SSLStartSession(
void
* buffer,
BYTE supDataType
);
Description
Begins a new SSL session for the given TCP connection.
Preconditions
SSL has been initialized and hTCP is connected.
Parameters
Parameters
hTCP buffer supDataType
Description
the socket to begin the SSL connection on pointer to a supplementary data buffer type of supplementary data to store
SSL Public Members
474
10.17 SSL
Return Values
Return Values
SSL_INVALID_ID ( see page 472)
others
Microchip TCP/IP Stack Help
Description
insufficient SSL resources to start a new connection the allocated SSL stub ID
SSL Public Members
10.17.2.7
SSL_SUPPLEMENTARY_DATA_TYPES Enumeration
File
SSL.h
C typedef enum
{
SSL_SUPPLEMENTARY_DATA_NONE = 0,
SSL_SUPPLEMENTARY_DATA_CERT_PUBLIC_KEY
} SSL_SUPPLEMENTARY_DATA_TYPES;
Description
This is type SSL_SUPPLEMENTARY_DATA_TYPES.
10.17.2.8
SSL_PKEY_INFO Structure
File
SSL.h
C typedef struct
{
WORD pub_size_bytes;
BYTE pub_key[SSL_RSA_CLIENT_SIZE/8];
BYTE pub_e[3];
BYTE pub_guid;
} SSL_PKEY_INFO;
Members
Members
BYTE pub_guid;
Description
This is used as a TCP_SOCKET ( see page 558) which is a BYTE
Description
To hash the public key information, we need to actually get the public key information... 1024 bit key at 8 bits/byte = 128 bytes needed for the public key.
10.17.2.9
SSL_RSA_KEY_SIZE Macro
File
TCPIP MRF24W.h
C
#define
SSL_RSA_KEY_SIZE (512ul)
Description
Bits in SSL RSA key. This parameter is used for SSL sever connections only. The only valid value is 512 bits (768 and 1024 bits do not work at this time). Note, however, that SSL client operations do currently work up to 1024 bit RSA key length.
475
10.17 SSL Microchip TCP/IP Stack Help SSL Stack Members
10.17.2.10
SSL_RSA_CLIENT_SIZE Macro
File
SSLClientSize.h ( see page 530)
C
#define
SSL_RSA_CLIENT_SIZE (1024ul)
// Size of Encryption Buffer (must be larger than key size)
Description
Size of Encryption Buffer (must be larger than key size)
10.17.3
SSL Stack Members
Enumerations
Name
Description
This is type SSL_STATE.
Functions
Name
Description
Initializes the SSL engine.
Performs any periodic tasks for the SSL module.
TCPRequestSSLMessage ( see page 478)
Requests an SSL message to be transmitted.
Determines how many bytes are pending for a future SSL record.
TCPSSLHandleIncoming ( see page 479)
Hands newly arrive TCP data to the SSL module for processing.
Clears the SSL handshake flag.
Encrypts and MACs data in place in the TCP TX buffer.
TCPSSLPutRecordHeader ( see page 480)
Writes an SSL record header and sends an SSL record.
TCPStartSSLServer ( see page 481)
Begins an SSL server session.
Macros
Name Description
SSL_MIN_SESSION_LIFETIME ( see page 481)
Minimum lifetime for SSL Sessions Sessions cannot be reallocated until this much time has elapsed
Lifetime extension for RSA operations Sessions lifetime is extended by this amount when an RSA calculation is made
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
476
10.17 SSL Microchip TCP/IP Stack Help
10.17.3.1
SSL_STATE Enumeration
File
TCP.h
C typedef enum
{
SSL_NONE = 0,
SSL_HANDSHAKING,
SSL_ESTABLISHED,
SSL_CLOSED
} SSL_STATE;
Members
Members
SSL_NONE = 0
SSL_HANDSHAKING
SSL_ESTABLISHED
SSL_CLOSED
Description
This is type SSL_STATE.
Description
No security is enabled
Handshake is progressing (no application data allowed)
Connection is established and secured
Connection has been closed (no applicaiton data is allowed)
10.17.3.2
SSLInit Function
File
SSL.h
C void
SSLInit();
Returns
None
Description
Initializes the SSL engine.
Remarks
This function is called only one during lifetime of the application.
Preconditions
None
Section
Function Prototypes
10.17.3.3
SSLPeriodic Function
File
SSL.h
C void
SSLPeriodic(
SSL Stack Members
477
10.17 SSL Microchip TCP/IP Stack Help
);
Returns
None
Description
This function performs periodic tasks for the SSL module. This includes processing for RSA operations.
Preconditions
SSL has already been initialized.
Parameters
Parameters
hTCP id
Description
the socket for which to perform periodic functions the SSL stub to use
SSL Stack Members
10.17.3.4
TCPRequestSSLMessage Function
File
TCP.h
C
BOOL TCPRequestSSLMessage(
BYTE msg
);
Description
This function is called to request that a specific SSL message be transmitted. This message should only be called by the
SSL module.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP msg
Return Values
Return Values
TRUE
FALSE
Description
TCP connection to use
One of the SSL_MESSAGE types to transmit.
Description
The message was requested.
Another message is already pending transmission.
10.17.3.5
TCPSSLGetPendingTxSize Function
File
TCP.h
C
WORD TCPSSLGetPendingTxSize(
);
478
10.17 SSL Microchip TCP/IP Stack Help
Returns
None
Description
This function determines how many bytes are pending for a future SSL record.
Preconditions
TCP is initialized, and hTCP is connected with an active SSL connection.
Parameters
Parameters
hTCP
Description
TCP connection to check
SSL Stack Members
10.17.3.6
TCPSSLHandleIncoming Function
File
TCP.h
C void
TCPSSLHandleIncoming(
);
Returns
None
Description
This function processes incoming TCP data as an SSL record and performs any necessary repositioning and decrypting.
Remarks
This function should never be called by an application. It is used only by the SSL module itself.
Preconditions
TCP is initialized, and hTCP is connected with an active SSL session.
Parameters
Parameters
hTCP
Description
TCP connection to handle incoming data on
10.17.3.7
TCPSSLHandshakeComplete Function
File
TCP.h
C void
TCPSSLHandshakeComplete(
);
Returns
None
Description
This function clears the flag indicating that an SSL handshake is complete.
479
10.17 SSL Microchip TCP/IP Stack Help
Remarks
This function should never be called by an application. It is used only by the SSL module itself.
Preconditions
TCP is initialized and hTCP is connected.
Parameters
Parameters
hTCP
Description
TCP connection to set
SSL Stack Members
10.17.3.8
TCPSSLInPlaceMACEncrypt Function
File
TCP.h
C void
TCPSSLInPlaceMACEncrypt(
ARCFOUR_CTX* ctx,
BYTE* MACSecret,
WORD len
);
Returns
None
Description
This function encrypts data in the TCP buffer while calcuating a MAC. When encryption is finished, the MAC is appended to the buffer and the record will be ready to transmit.
Remarks
This function should never be called by an application. It is used only by the SSL module itself.
Preconditions
TCP is initialized, hTCP is connected, and ctx's Sbox is loaded.
Parameters
Parameters
hTCP ctx
MACSecret len
Description
TCP connection to encrypt in
ARCFOUR encryption context to use
MAC encryption secret to use
Number of bytes to crypt
10.17.3.9
TCPSSLPutRecordHeader Function
File
TCP.h
C void
TCPSSLPutRecordHeader(
BYTE* hdr,
BOOL recDone
);
480
10.17 SSL Microchip TCP/IP Stack Help SSL Stack Members
Returns
None
Description
This function writes an SSL record header to the pending TCP SSL data, then indicates that the data is ready to be sent by moving the txHead pointer.
If the record is complete, set recDone to TRUE. The sslTxHead pointer will be moved forward 5 bytes to leave space for a future record header. If the record is only partially sent, use FALSE and to leave the pointer where it is so that more data can be added to the record. Partial records can only be used for the SERVER_CERTIFICATE handshake message.
Remarks
This function should never be called by an application. It is used only by the SSL module itself.
Preconditions
TCP is initialized, and hTCP is connected with an active SSL session.
Parameters
Parameters
hTCP hdr recDone
Description
TCP connection to write the header and transmit with
Record header (5 bytes) to send or NULL to just move the pointerctx
TRUE if the record is done, FALSE otherwise
10.17.3.10
TCPStartSSLServer Function
File
TCP.h
C
BOOL TCPStartSSLServer(
);
Description
This function sets up an SSL server session when a new connection is established on an SSL port.
Preconditions
TCP is initialized and hTCP is already connected.
Parameters
Parameters
hTCP
Return Values
Return Values
TRUE
FALSE
Description
TCP connection to secure
Description
an SSL connection was initiated
Insufficient SSL resources (stubs) were available
10.17.3.11
SSL_MIN_SESSION_LIFETIME Macro
File
SSL.h
481
10.17 SSL Microchip TCP/IP Stack Help
C
#define
SSL_MIN_SESSION_LIFETIME (1*TICK_SECOND)
Description
Minimum lifetime for SSL Sessions Sessions cannot be reallocated until this much time has elapsed
SSL Internal Members
10.17.3.12
SSL_RSA_LIFETIME_EXTENSION Macro
File
SSL.h
C
#define
SSL_RSA_LIFETIME_EXTENSION (8*TICK_SECOND)
Description
Lifetime extension for RSA operations Sessions lifetime is extended by this amount when an RSA calculation is made
10.17.4
SSL Internal Members
Enumerations
Name Description
State machine for SSLRxServerHello ( see page 518)
Describes the two types of Alert records
SSL_ALERT_LEVEL ( see page 496)
SSL_SESSION_TYPE ( see page 504)
Describes the types of SSL messages (handshake and alerts)
SSL Session Type Enumeration
Functions
Name
CalculateFinishedHash ( see page 487)
GenerateHashRounds ( see page 488)
GenerateSessionKeys ( see page 488)
Description
Calculates the handshake hash over the data. hashID can be either MD5 or
SHA-1, and this function will calculate accordingly.
Generates hash rounds to find either the Master Secret or the Key Block.
Generates the session write keys and MAC secrets
Hashes ( see page 207) the message contents into the Handshake hash
structures and begins a new handshake hash.
Reads data from socket, transparently hashing it into the handshake hashes.
482
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
• Function: static WORD HSGetArray(TCP_SOCKET ( see page 558) skt,
BYTE *data, WORD len)
*
• PreCondition: None
*
• Input: skt - socket to read data from
• data - array to read into, or NULL
• len - number of bytes to read
*
• Output: Number of bytes read
*
• Side Effects: None
*
• Overview: Reads data from socket, transparently hashing it
• into the handshake hashes.
*
• Note: None
Writes data to socket, transparently hashing it into the handshake hashes.
• Function: static WORD HSPutArray(TCP_SOCKET ( see page 558) skt,
BYTE *data, BYTE len)
*
• PreCondition: None
*
• Input: skt - socket to write data to
• data - data to write
• len - number of bytes to write
*
• Output: Number of bytes written
*
• Side Effects: None
*
• Overview: Writes data to socket, transparently hashing it
• into the handshake hashes.
*
• Note: None
This is function HSPutROMArray.
HSPutWord ( see page 492) Writes data to socket, transparently hashing it into the handshake hashes.
Sets up the buffer to store data for handshake hash tracking
Copies data from Ethernet RAM to local RAM
483
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
Copies data in PIC RAM to the Ethernet RAM
Allocates a buffer for use.
Specified buffer is released
Specified buffer is loaded to RAM. Only loads if necessary, and saves any current buffer before switching.
Allocates a hash for use.
Specified hash is released
Specified hash is loaded to RAM. Only loads if necessary, and saves any current hash before switching.
Specified key set is loaded to RAM. Only loads if necessary, and saves any current key set before switching.
This is function SSLMACAdd.
This is function SSLMACBegin.
This is function SSLMACCalc.
SSLRSAOperation ( see page 513)
Pauses connection processing until RSA calculation is complete.
SSLRxAlert ( see page 513) Receives an alert message and decides what to do
SSLRxAntiqueClientHello ( see page 514)
Receives the SSLv2 ClientHello message, initiating a new SSL session with a client
SSLRxCCS ( see page 514) Receives a ChangeCipherSpec from the remote server
SSLRxClientHello ( see page 515)
Receives the ClientHello message, initiating a new SSL session with a client
Receives the ClientKeyExchange message and begins the decryption process.
Receives the Finished message from remote node
Receives a handshake message.
SSLRxHandshake ( see page 517)
SSLRxServerCertificate ( see page 518)
Receives an SSL record.
Receives ServerCertificate from the remote server, locates the public key information, and executes RSA operation.
Receives the ServerHello from the remote server
SSLRxServerHello ( see page 518)
SSLSessionMatchID ( see page 519)
SSLSessionMatchIP ( see page 520)
Locates a cached SSL session for reuse. Syncs found session into RAM.
Locates a cached SSL session for reuse
SSLSessionSync ( see page 521)
SSLStartPartialRecord ( see page 522)
Finds space for a new SSL session
Specified session is loaded to RAM. Only loads if necessary, and saves any current session before switching if it has been updated.
Begins a long SSL record.
Allocates a stub for use.
484
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
Generates the session keys from the master secret, then allocates and generates the encryption context. Once processing is complete, transmits the
Change Cipher Spec message and the Finished handshake message to the server.
SSLTxClientHello ( see page 526)
SSLTxClientKeyExchange ( see page 526)
Transmits the ClientHello message to initiate a new SSL session with the server.
Transmits the encrypted pre-master secret to the server and requests the
Change Cipher Spec. Also generates the Master Secret from the pre-master secret that was used.
Transmits an SSL message.
Transmits an SSL record.
SSLTxServerCertificate ( see page 528)
SSLTxServerHello ( see page 528)
SSLTxServerHelloDone ( see page 529)
Specified stub is released
Specified stub is loaded to RAM. Only loads if necessary, and saves any current stub before switching.
Terminates an SSL connection and releases allocated resources.
Transmits the Certificate message with the server's specified public key certificate.
Transmits the ServerHello message.
Transmits the ServerHelloDone message.
Macros
Name Description
RESERVED_SSL_MEMORY ( see page 494)
Total space needed by all SSL storage requirements
SSL_APPLICATION ( see page 497)
Protocol code for Alert records
Protocol code for Application data records
SSL_BASE_BUFFER_ADDR ( see page 497)
Base address for SSL buffers
SSL_BASE_HASH_ADDR ( see page 497)
Base address for SSL hashes
SSL_BASE_KEYS_ADDR ( see page 497)
Base address for SSL keys
SSL_BASE_SESSION_ADDR ( see page 498)
Base address for SSL sessions
SSL_BASE_STUB_ADDR ( see page 498)
Base address for SSL stubs
SSL_BUFFER_SIZE ( see page 498)
SSL_BUFFER_SPACE ( see page 499)
Amount of space needed by a single SSL buffer
Amount of space needed by all SSL buffer
SSL_CHANGE_CIPHER_SPEC ( see page 499) Protocol code for Change Cipher Spec records
SSL_HASH_SPACE ( see page 500)
Protocol code for Handshake records
Amount of space needed by a single SSL hash
Amount of space needed by all SSL hash
485
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
SSL_KEYS_SPACE ( see page 501)
Amount of space needed by a single SSL key
Amount of space needed by all SSL key
Module
Structures
SSL_RSA_EXPORT_WITH_ARCFOUR_40_MD5
This is macro
SSL_RSA_EXPORT_WITH_ARCFOUR_40_MD5.
This is macro SSL_RSA_WITH_ARCFOUR_128_MD5.
SSL_RSA_WITH_ARCFOUR_128_MD5 ( see page 502)
SSL_SESSION_SIZE ( see page 503)
Amount of space needed by a single SSL session
SSL_SESSION_SPACE ( see page 503)
SSL_STUB_SPACE ( see page 506)
Amount of space needed by all SSL session
Amount of space needed by a single SSL stub
Amount of space needed by all SSL stubs
SSL version number
SSL_VERSION_HI ( see page 506)
SSL_VERSION_LO ( see page 506)
SSLFinishPartialRecord ( see page 508)
SSLFlushPartialRecord ( see page 509)
SSLSessionUpdated ( see page 522)
SSL version number (high byte)
SSL version number (low byte)
This is macro SSLFinishPartialRecord.
This is macro SSLFlushPartialRecord.
This is macro SSLSessionUpdated.
Name Description
During the handshake, Local.random and Remote.random hold the
ServerRandom and ClientRandom values. Once the session keys are calculated, the Local.app and Remote.app contain the MAC secret, record sequence number, and encryption context for the ARCFOUR module.
Storage space for SSL Session identifiers. (The SessionID and MasterSecret)
SSL_SESSION_STUB ( see page 504)
Stub value for an SSL_SESSION ( see page 503). The tag associates this
session with a remote node, either by matching to a remote IP address when we are the client or the first 3 bytes of the session ID when we are the host.
When a session is free/expired, the tag is 0x00000000. The lastUsed value is the Tick count when the session was last used so that older sessions may be overwritten first.
SSL_STUB ( see page 504) Memory holder for general information associated with an SSL connections.
Unions
Name
Description
Generic buffer space for SSL. The hashRounds element is used when this buffer is needed for handshake hash calculations, and the full element is used as the Sbox for ARCFOUR calculations.
Variables
Name
Description
Indicates which buffers are in use
Masks for each bit in the is*Used variables
Used in buffering handshake results
SSL_CERT ( see page 499) RSA public certificate data ?
486
10.17 SSL Microchip TCP/IP Stack Help
RSA public certificate length ?
Which buffer is loaded
Hash storage
Which hash is loaded
The current SSL session
Which SSL_KEYS ( see page 500) are loaded
Which stub is using RSA, if any
Current session data
Which session is loaded
8 byte session stubs
sslSessionUpdated ( see page 522)
Whether or not it has been updated
The current SSL stub
Which SSL_STUB ( see page 504) is loaded
Description
The following functions and variables are designated as internal to the SSL module.
SSL Internal Members
10.17.4.1
CalculateFinishedHash Function
File
SSL.c
C static void
CalculateFinishedHash(
BYTE hashID,
BOOL fromClient,
BYTE * result
);
Side Effects
None
Returns
None
Description
Calculates the handshake hash over the data. hashID can be either MD5 or SHA-1, and this function will calculate accordingly.
Remarks
None
Preconditions
hashID has all handshake data hashed so far and the current session is synced in.
Parameters
Parameters
hashID fromClient result
Description
the hash sum to use
TRUE if client is sender where to store results
487
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.2
GenerateHashRounds Function
File
SSL.c
C static void
GenerateHashRounds(
BYTE num,
BYTE* rand1,
BYTE* rand2
);
Side Effects
Destroys the SSL Buffer space
Returns
None
Description
Generates hash rounds to find either the Master Secret or the Key Block.
Remarks
This function will overflow the buffer after 7 rounds, but in practice num = 3 or num = 4.
Preconditions
The SSL buffer is allocated for temporary usage and the data to run rounds on is in sslSession.masterSecret
Parameters
Parameters
num rand1 rand2
Description
how many rounds to compute the first random data block to use the second random data block to use
10.17.4.3
GenerateSessionKeys Function
File
SSL.c
C static void
GenerateSessionKeys();
Side Effects
Destroys the SSL Buffer Space
Returns
None
Description
Generates the session write keys and MAC secrets
Remarks
None
Preconditions
The SSL buffer is allocated for temporary usage, session keys are synced, and the TX and RX buffers are allocated for
488
10.17 SSL
S-boxes.
Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.4
HSEnd Function
File
SSL.c
C static void
HSEnd();
Side Effects
None
Returns
None
Description
Remarks
None
Preconditions
None
10.17.4.5
HSGet Function
File
SSL.c
C static
WORD HSGet(
BYTE * b
);
Side Effects
None
Returns
Number of bytes read
Description
Reads data from socket, transparently hashing it into the handshake hashes.
Remarks
None
Preconditions
None
Parameters
Parameters
skt b
Description
socket to read data from byte to read into
489
10.17 SSL Microchip TCP/IP Stack Help
10.17.4.6
HSGetArray Function
File
SSL.c
C static
WORD HSGetArray(
BYTE * data,
WORD len
);
Description
• Function: static WORD HSGetArray(TCP_SOCKET ( see page 558) skt, BYTE *data, WORD len)
*
• PreCondition: None
*
• Input: skt - socket to read data from
• data - array to read into, or NULL
• len - number of bytes to read
*
• Output: Number of bytes read
*
• Side Effects: None
*
• Overview: Reads data from socket, transparently hashing it
• into the handshake hashes.
*
• Note: None
10.17.4.7
HSGetWord Function
File
SSL.c
C static
WORD HSGetWord(
WORD * w
);
Side Effects
None
Returns
Number of bytes read
Description
Reads data from socket, transparently hashing it into the handshake hashes.
SSL Internal Members
490
10.17 SSL
Remarks
None
Preconditions
None
Parameters
Parameters
skt w
Microchip TCP/IP Stack Help
Description
socket to read data from word to read into
10.17.4.8
HSPut Function
File
SSL.c
C static
WORD HSPut(
BYTE b
);
Side Effects
None
Returns
Number of bytes written
Description
Writes data to socket, transparently hashing it into the handshake hashes.
Remarks
None
Preconditions
None
Parameters
Parameters
skt b
Description
socket to write data to byte to write
10.17.4.9
HSPutArray Function
File
SSL.c
C static
WORD HSPutArray(
BYTE * data,
WORD len
);
SSL Internal Members
491
10.17 SSL Microchip TCP/IP Stack Help
Description
• Function: static WORD HSPutArray(TCP_SOCKET ( see page 558) skt, BYTE *data, BYTE len)
*
• PreCondition: None
*
• Input: skt - socket to write data to
• data - data to write
• len - number of bytes to write
*
• Output: Number of bytes written
*
• Side Effects: None
*
• Overview: Writes data to socket, transparently hashing it
• into the handshake hashes.
*
• Note: None
SSL Internal Members
10.17.4.10
HSPutROMArray Function
File
SSL.c
C static
WORD HSPutROMArray(
ROM BYTE * data,
WORD len
);
Description
This is function HSPutROMArray.
10.17.4.11
HSPutWord Function
File
SSL.c
C static
WORD HSPutWord(
WORD w
);
Side Effects
None
Returns
Number of bytes written
492
10.17 SSL Microchip TCP/IP Stack Help
Description
Writes data to socket, transparently hashing it into the handshake hashes.
Remarks
None
Preconditions
None
Parameters
Parameters
skt w
Description
socket to write data to word to write
10.17.4.12
HSStart Function
File
SSL.c
C static void
HSStart();
Side Effects
None
Returns
None
Description
Sets up the buffer to store data for handshake hash tracking
Remarks
None
Preconditions
None
Section
Handshake Hash and I/O Functions
10.17.4.13
isBufferUsed Variable
File
SSL.c
C
WORD isBufferUsed;
Description
Indicates which buffers are in use
SSL Internal Members
493
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.14
isHashUsed Variable
File
SSL.c
C
WORD isHashUsed;
Description
Indicates which hashes are in use
10.17.4.15
isStubUsed Variable
File
SSL.c
C
WORD isStubUsed;
Description
Indicates which stubs are in use
10.17.4.16
masks Variable
File
SSL.c
C
ROM WORD masks[16] = { 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000, 0x8000 };
Description
Masks for each bit in the is*Used variables
10.17.4.17
ptrHS Variable
File
SSL.c
C
BYTE * ptrHS;
Description
Used in buffering handshake results
10.17.4.18
RESERVED_SSL_MEMORY Macro
File
SSL.h
494
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
C
#define
RESERVED_SSL_MEMORY ((DWORD)(SSL_STUB_SPACE + SSL_KEYS_SPACE + SSL_HASH_SPACE +
SSL_BUFFER_SPACE + SSL_SESSION_SPACE))
Description
Total space needed by all SSL storage requirements
10.17.4.19
LoadOffChip Function
File
SSL.c
C static void
LoadOffChip(
BYTE * ramAddr,
PTR_BASE ethAddr,
WORD len
);
Side Effects
None
Returns
None
Description
Copies data from Ethernet RAM to local RAM
Remarks
None
Preconditions
None
Parameters
Parameters
ramAddr ethAddr len
Description
destination address in RAM source address in Ethernet RAM number of bytes to copy
10.17.4.20
SaveOffChip Function
File
SSL.c
C static void
SaveOffChip(
BYTE * ramAddr,
PTR_BASE ethAddr,
WORD len
);
Side Effects
None
495
10.17 SSL Microchip TCP/IP Stack Help
Returns
None
Description
Copies data in PIC RAM to the Ethernet RAM
Remarks
None
Preconditions
None
Parameters
Parameters
ramAddr ethAddr len
Description
source address in RAM destination address in Ethernet RAM number of bytes to copy
10.17.4.21
SM_SSL_RX_SERVER_HELLO Enumeration
File
SSL.h
C typedef enum
{
RX_SERVER_CERT_START = 0u,
RX_SERVER_CERT_FIND_KEY,
RX_SERVER_CERT_FIND_N,
RX_SERVER_CERT_READ_N,
RX_SERVER_CERT_READ_E,
RX_SERVER_CERT_CLEAR
} SM_SSL_RX_SERVER_HELLO;
Description
State machine for SSLRxServerHello ( see page 518)
SSL Internal Members
10.17.4.22
SSL_ALERT Macro
File
SSL.h
C
#define
SSL_ALERT 21u
// Protocol code for Alert records
Description
Protocol code for Alert records
10.17.4.23
SSL_ALERT_LEVEL Enumeration
File
SSL.h
C typedef enum
{
496
10.17 SSL
SSL_ALERT_WARNING = 1u,
SSL_ALERT_FATAL = 2u
} SSL_ALERT_LEVEL;
Members
Members
SSL_ALERT_WARNING = 1u
SSL_ALERT_FATAL = 2u
Description
Describes the two types of Alert records
Microchip TCP/IP Stack Help
Description
Alert message is a warning (session can be resumed)
Alert message is fatal (session is non-resumable)
SSL Internal Members
10.17.4.24
SSL_APPLICATION Macro
File
SSL.h
C
#define
SSL_APPLICATION 23u
// Protocol code for Application data records
Description
Protocol code for Application data records
10.17.4.25
SSL_BASE_BUFFER_ADDR Macro
File
SSL.c
C
#define
SSL_BASE_BUFFER_ADDR (BASE_SSLB_ADDR + SSL_STUB_SPACE + SSL_KEYS_SPACE +
Description
Base address for SSL buffers
10.17.4.26
SSL_BASE_HASH_ADDR Macro
File
SSL.c
C
#define
SSL_BASE_HASH_ADDR (BASE_SSLB_ADDR + SSL_STUB_SPACE + SSL_KEYS_SPACE)
Description
Base address for SSL hashes
10.17.4.27
SSL_BASE_KEYS_ADDR Macro
File
SSL.c
C
#define
SSL_BASE_KEYS_ADDR (BASE_SSLB_ADDR + SSL_STUB_SPACE)
497
10.17 SSL
Description
Base address for SSL keys
Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.28
SSL_BASE_SESSION_ADDR Macro
File
SSL.c
C
#define
SSL_BASE_SESSION_ADDR (BASE_SSLB_ADDR + SSL_STUB_SPACE + SSL_KEYS_SPACE +
SSL_HASH_SPACE + SSL_BUFFER_SPACE)
Description
Base address for SSL sessions
10.17.4.29
SSL_BASE_STUB_ADDR Macro
File
SSL.c
C
#define
SSL_BASE_STUB_ADDR (BASE_SSLB_ADDR)
Description
Base address for SSL stubs
10.17.4.30
SSL_BUFFER Union
File
SSL.h
C typedef union
{
struct
{
BYTE md5_hash[16];
BYTE sha_hash[20];
BYTE temp[256-
sizeof
} hashRounds;
BYTE full[256];
} SSL_BUFFER;
Description
Generic buffer space for SSL. The hashRounds element is used when this buffer is needed for handshake hash calculations, and the full element is used as the Sbox for ARCFOUR calculations.
10.17.4.31
SSL_BUFFER_SIZE Macro
File
SSL.h
C
#define
SSL_BUFFER_SIZE ((DWORD)
sizeof
// Amount of space
498
10.17 SSL Microchip TCP/IP Stack Help
needed by a single SSL buffer
Description
Amount of space needed by a single SSL buffer
SSL Internal Members
10.17.4.32
SSL_BUFFER_SPACE Macro
File
SSL.h
C
#define
SSL_BUFFER_SPACE (SSL_BUFFER_SIZE*MAX_SSL_BUFFERS)
// Amount of space needed by all SSL buffer
Description
Amount of space needed by all SSL buffer
10.17.4.33
SSL_CERT Variable
File
SSL.c
C
ROM BYTE SSL_CERT[];
Description
RSA public certificate data ?
10.17.4.34
SSL_CERT_LEN Variable
File
SSL.c
C
ROM WORD SSL_CERT_LEN;
Description
RSA public certificate length ?
10.17.4.35
SSL_CHANGE_CIPHER_SPEC Macro
File
SSL.h
C
#define
SSL_CHANGE_CIPHER_SPEC 20u
// Protocol code for Change Cipher Spec records
Description
Protocol code for Change Cipher Spec records
499
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.36
SSL_HANDSHAKE Macro
File
SSL.h
C
#define
SSL_HANDSHAKE 22u
// Protocol code for Handshake records
Description
Protocol code for Handshake records
10.17.4.37
SSL_HASH_SIZE Macro
File
SSL.h
C
#define
SSL_HASH_SIZE ((DWORD)
sizeof
// Amount of space needed by a single SSL hash
Description
Amount of space needed by a single SSL hash
10.17.4.38
SSL_HASH_SPACE Macro
File
SSL.h
C
#define
SSL_HASH_SPACE ((DWORD)(SSL_HASH_SIZE*MAX_SSL_HASHES))
// Amount of space needed by all SSL hash
Description
Amount of space needed by all SSL hash
10.17.4.39
SSL_KEYS Structure
File
SSL.h
C typedef struct
{
union
{
struct
{
BYTE MACSecret[16];
DWORD sequence;
ARCFOUR_CTX cryptCtx;
BYTE reserved[6];
} app;
BYTE random[32];
} Local;
union
{
struct
{
BYTE MACSecret[16];
DWORD sequence;
500
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
ARCFOUR_CTX cryptCtx;
BYTE reserved[6];
} app;
BYTE random[32];
} Remote;
} SSL_KEYS;
Members
Members
BYTE MACSecret[16];
DWORD sequence;
ARCFOUR_CTX cryptCtx;
BYTE reserved[6];
BYTE random[32];
BYTE MACSecret[16];
DWORD sequence;
ARCFOUR_CTX cryptCtx;
BYTE reserved[6];
BYTE random[32];
Description
Server's MAC write secret
Server's write sequence number
Server's write encryption context
Future expansion
Server.random value
Client's MAC write secret
Client's write sequence number
Client's write encryption context
Future expansion
Client.random value
Description
Memory definition for SSL keys. This area is split into Local and Remote areas. During the handshake, Local.random and
Remote.random hold the ServerRandom and ClientRandom values. Once the session keys are calculated, the Local.app
and Remote.app contain the MAC secret, record sequence number, and encryption context for the ARCFOUR module.
10.17.4.40
SSL_KEYS_SIZE Macro
File
SSL.h
C
#define
SSL_KEYS_SIZE ((DWORD)
sizeof
// Amount of space needed by a single SSL key
Description
Amount of space needed by a single SSL key
10.17.4.41
SSL_KEYS_SPACE Macro
File
SSL.h
C
#define
SSL_KEYS_SPACE (SSL_KEYS_SIZE*MAX_SSL_CONNECTIONS)
// Amount of space needed by all SSL key
Description
Amount of space needed by all SSL key
10.17.4.42
SSL_MESSAGES Enumeration
File
SSL.h
501
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
C typedef enum
{
SSL_HELLO_REQUEST = 0u,
SSL_CLIENT_HELLO = 1u,
SSL_ANTIQUE_CLIENT_HELLO = 18u,
SSL_SERVER_HELLO = 2u,
SSL_CERTIFICATE = 11u,
SSL_SERVER_HELLO_DONE = 14u,
SSL_CLIENT_KEY_EXCHANGE = 16u,
SSL_FINISHED = 20u,
SSL_ALERT_CLOSE_NOTIFY = 0u+0x80,
SSL_ALERT_UNEXPECTED_MESSAGE = 10u+0x80,
SSL_ALERT_BAD_RECORD_MAC = 20u+0x80,
SSL_ALERT_HANDSHAKE_FAILURE = 40u+0x80,
SSL_NO_MESSAGE = 0xff
} SSL_MESSAGES;
Members
Members
SSL_HELLO_REQUEST = 0u
Description
HelloRequest handshake message (not currently supported)
SSL_CLIENT_HELLO = 1u ClientHello handshake message
SSL_ANTIQUE_CLIENT_HELLO = 18u SSLv2 ClientHello handshake message (Supported for backwards compatibility. This is an internally defined value.)
SSL_SERVER_HELLO = 2u
SSL_CERTIFICATE = 11u
ServerHello handshake message
ServerCertifiate handshake message
SSL_SERVER_HELLO_DONE = 14u
SSL_CLIENT_KEY_EXCHANGE = 16u
SSL_FINISHED = 20u
SSL_ALERT_HANDSHAKE_FAILURE =
40u+0x80
SSL_NO_MESSAGE = 0xff
ServerHelloDone handshake message
ClientKeyExchange handshake message
Finished handshake message
SSL_ALERT_CLOSE_NOTIFY = 0u+0x80 CloseNotify alert message (dummy value used internally)
SSL_ALERT_UNEXPECTED_MESSAGE
= 10u+0x80
UnexpectedMessage alert message (dummy value used internally)
SSL_ALERT_BAD_RECORD_MAC =
20u+0x80
BadRecordMAC alert message (dummy value used internally)
HandshakeFailure alert message (dummy value used internally)
No message is currently requested (internally used value)
Description
Describes the types of SSL messages (handshake and alerts)
10.17.4.43
SSL_RSA_EXPORT_WITH_ARCFOUR_40_MD5 Macro
File
SSL.c
C
#define
SSL_RSA_EXPORT_WITH_ARCFOUR_40_MD5 0x0003u
Description
This is macro SSL_RSA_EXPORT_WITH_ARCFOUR_40_MD5.
10.17.4.44
SSL_RSA_WITH_ARCFOUR_128_MD5 Macro
File
SSL.c
502
10.17 SSL Microchip TCP/IP Stack Help
C
#define
SSL_RSA_WITH_ARCFOUR_128_MD5 0x0004u
Description
This is macro SSL_RSA_WITH_ARCFOUR_128_MD5.
SSL Internal Members
10.17.4.45
SSL_SESSION Structure
File
SSL.h
C typedef struct
{
BYTE sessionID[32];
BYTE masterSecret[48];
} SSL_SESSION;
Members
Members
BYTE sessionID[32];
BYTE masterSecret[48];
Description
The SSL Session ID for this session
Associated Master Secret for this session
Description
Storage space for SSL Session identifiers. (The SessionID and MasterSecret)
10.17.4.46
SSL_SESSION_SIZE Macro
File
SSL.h
C
#define
SSL_SESSION_SIZE ((DWORD)
sizeof
// Amount of space needed by a single SSL session
Description
Amount of space needed by a single SSL session
10.17.4.47
SSL_SESSION_SPACE Macro
File
SSL.h
C
#define
SSL_SESSION_SPACE (SSL_SESSION_SIZE*MAX_SSL_SESSIONS)
// Amount of space needed by all SSL session
Description
Amount of space needed by all SSL session
503
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.48
SSL_SESSION_STUB Structure
File
SSL.h
C typedef struct
{
DWORD_VAL tag;
DWORD lastUsed;
} SSL_SESSION_STUB;
Members
Members
DWORD_VAL tag;
DWORD lastUsed;
Description
Identifying tag for connection When we're a client, this is the remote IP When we're a host, this is 0x00 followed by first 3 bytes of session ID When this stub is free/expired, this is 0x00
Tick count when session was last used
Description
to a remote IP address when we are the client or the first 3 bytes of the session ID when we are the host. When a session is free/expired, the tag is 0x00000000. The lastUsed value is the Tick count when the session was last used so that older sessions may be overwritten first.
10.17.4.49
SSL_SESSION_TYPE Enumeration
File
SSL.h
C typedef enum
{
SSL_CLIENT,
SSL_SERVER
} SSL_SESSION_TYPE;
Members
Members
SSL_CLIENT
SSL_SERVER
Description
SSL Session Type Enumeration
Description
Local device is the SSL client
Local device is the SSL host
10.17.4.50
SSL_STUB Structure
File
SSL.h
C typedef struct
{
WORD wRxBytesRem;
WORD wRxHsBytesRem;
BYTE rxProtocol;
BYTE rxHSType;
504
10.17 SSL Microchip TCP/IP Stack Help
BYTE idSession;
BYTE idMD5, idSHA1;
BYTE idRxHash;
BYTE idRxBuffer, idTxBuffer;
DWORD_VAL dwTemp;
struct
{
unsigned char
bIsServer : 1;
unsigned char
bClientHello : 1;
unsigned char
bServerHello : 1;
unsigned char
bServerCertificate : 1;
unsigned char
bServerHelloDone : 1;
unsigned char
bClientKeyExchange : 1;
unsigned char
bRemoteChangeCipherSpec : 1;
unsigned char
bRemoteFinished : 1;
unsigned char
bLocalChangeCipherSpec : 1;
unsigned char
bLocalFinished : 1;
unsigned char
bExpectingMAC : 1;
unsigned char
bNewSession : 1;
unsigned char
bCloseNotify : 1;
unsigned char
bDone : 1;
unsigned char
bRSAInProgress : 1;
unsigned char
bKeysValid : 1;
} Flags;
BYTE requestedMessage;
void
* supplementaryBuffer;
BYTE supplementaryDataType;
} SSL_STUB;
Members
Members
WORD wRxBytesRem;
WORD wRxHsBytesRem;
BYTE rxProtocol;
BYTE rxHSType;
BYTE idSession;
BYTE idRxHash;
DWORD_VAL dwTemp; unsigned char bIsServer : 1; unsigned char bClientHello : 1; unsigned char bServerHello : 1; unsigned char bServerCertificate : 1; unsigned char bServerHelloDone : 1; unsigned char bClientKeyExchange : 1; unsigned char bRemoteChangeCipherSpec : 1; unsigned char bRemoteFinished : 1; unsigned char bLocalChangeCipherSpec
: 1; unsigned char bLocalFinished : 1; unsigned char bExpectingMAC : 1; unsigned char bNewSession : 1; unsigned char bCloseNotify : 1; unsigned char bDone : 1; unsigned char bRSAInProgress : 1; unsigned char bKeysValid : 1;
BYTE requestedMessage;
Description
Bytes left to read in current record
Bytes left to read in current Handshake submessage
Protocol for message being read
Handshake message being received
ID for associated session
ID for MAC hash (TX needs no persistence)
Used for state machine in RxCertificate
We are the server
ClientHello has been sent/received
ServerHello has been sent/received
ServerCertificate has been sent/received
ServerHelloDone has been sent/received
ClientKeyExchange has been sent/received
Remote node has sent a ChangeCipherSpec message
Remote node has sent a Finished message
We have sent a ChangeCipherSpec message
We have sent a Finished message
We expect a MAC at end of message
TRUE if a new session, FALSE if resuming
Whether or not a CloseNotify has been sent/received
TRUE if the connection is closed
TRUE when RSA op is in progress
TRUE if the session keys have been generated
Currently requested message to send, or 0xff
Description
Memory holder for general information associated with an SSL connections.
SSL Internal Members
505
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.51
SSL_STUB_SIZE Macro
File
SSL.h
C
#define
SSL_STUB_SIZE ((DWORD)
sizeof
// Amount of space needed by a single SSL stub
Description
Amount of space needed by a single SSL stub
10.17.4.52
SSL_STUB_SPACE Macro
File
SSL.h
C
#define
SSL_STUB_SPACE (SSL_STUB_SIZE*MAX_SSL_CONNECTIONS)
// Amount of space needed by all SSL stubs
Description
Amount of space needed by all SSL stubs
10.17.4.53
SSL_VERSION Macro
File
SSL.h
C
#define
SSL_VERSION (0x0300u)
// SSL version number
Description
SSL version number
10.17.4.54
SSL_VERSION_HI Macro
File
SSL.h
C
#define
SSL_VERSION_HI (0x03u)
// SSL version number (high byte)
Description
SSL version number (high byte)
10.17.4.55
SSL_VERSION_LO Macro
File
SSL.h
506
10.17 SSL Microchip TCP/IP Stack Help
C
#define
SSL_VERSION_LO (0x00u)
// SSL version number (low byte)
Description
SSL version number (low byte)
10.17.4.56
SSLBufferAlloc Function
File
SSL.c
C static void
SSLBufferAlloc(
BYTE * id
);
Side Effects
None
Returns
id - Allocated buffer ID, or SSL_INVALID_ID ( see page 472) if none available
Description
Allocates a buffer for use.
Remarks
None
Preconditions
None
Parameters
Parameters
id
Description
Where to store the allocated ID
10.17.4.57
SSLBufferFree Function
File
SSL.c
C static void
SSLBufferFree(
BYTE * id
);
Side Effects
None
Description
Specified buffer is released
Remarks
None
Preconditions
None
SSL Internal Members
507
10.17 SSL
Parameters
Parameters
id
Outputs
Microchip TCP/IP Stack Help
Description
the buffer ID to free
id - SSL_INVALID_ID ( see page 472)
10.17.4.58
sslBufferID Variable
File
SSL.c
C
BYTE sslBufferID;
Description
Which buffer is loaded
SSL Internal Members
10.17.4.59
SSLBufferSync Function
File
SSL.c
C static void
SSLBufferSync(
BYTE id
);
Side Effects
None
Returns
None
Description
Specified buffer is loaded to RAM. Only loads if necessary, and saves any current buffer before switching.
Remarks
None
Preconditions
None
Parameters
Parameters
id
Description
the buffer ID to sync to RAM
10.17.4.60
SSLFinishPartialRecord Macro
File
SSL.h
C
#define
SSLFinishPartialRecord(a) TCPSSLPutRecordHeader(a, NULL, TRUE);
508
10.17 SSL
Description
This is macro SSLFinishPartialRecord.
Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.61
SSLFlushPartialRecord Macro
File
SSL.h
C
#define
SSLFlushPartialRecord(a) TCPSSLPutRecordHeader(a, NULL, FALSE);
Description
This is macro SSLFlushPartialRecord.
10.17.4.62
sslHash Variable
File
SSL.c
C
Description
Hash storage
10.17.4.63
SSLHashAlloc Function
File
SSL.c
C static void
SSLHashAlloc(
BYTE * id
);
Side Effects
None
Description
Allocates a hash for use.
Remarks
None
Preconditions
None
Parameters
Parameters
id
Outputs
Description
Where to store the allocated ID
id - Allocated hash ID, or SSL_INVALID_ID ( see page 472) if none available
509
10.17 SSL Microchip TCP/IP Stack Help
10.17.4.64
SSLHashFree Function
File
SSL.c
C static void
SSLHashFree(
BYTE * id
);
Side Effects
None
Description
Specified hash is released
Remarks
None
Preconditions
None
Parameters
Parameters
id
Outputs
Description
the hash ID to free
id - SSL_INVALID_ID ( see page 472)
10.17.4.65
sslHashID Variable
File
SSL.c
C
BYTE sslHashID;
Description
Which hash is loaded
10.17.4.66
SSLHashSync Function
File
SSL.c
C static void
SSLHashSync(
BYTE id
);
Side Effects
None
Returns
None
SSL Internal Members
510
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
Description
Specified hash is loaded to RAM. Only loads if necessary, and saves any current hash before switching.
Remarks
None
Preconditions
None
Parameters
Parameters
id
Description
the hash ID to sync to RAM
10.17.4.67
sslKeys Variable
File
SSL.c
C
Description
The current SSL session
10.17.4.68
sslKeysID Variable
File
SSL.c
C
BYTE sslKeysID;
Description
Which SSL_KEYS ( see page 500) are loaded
10.17.4.69
SSLKeysSync Function
File
SSL.c
C static void
SSLKeysSync(
BYTE id
);
Side Effects
None
Returns
None
Description
Specified key set is loaded to RAM. Only loads if necessary, and saves any current key set before switching.
511
10.17 SSL
Remarks
None
Preconditions
None
Parameters
Parameters
id
Microchip TCP/IP Stack Help
Description
the key set ID to sync to RAM
10.17.4.70
SSLMACAdd Function
File
SSL.h
C void
SSLMACAdd(
BYTE* data,
WORD len
);
Description
This is function SSLMACAdd.
10.17.4.71
SSLMACBegin Function
File
SSL.h
C void
SSLMACBegin(
BYTE* MACSecret,
DWORD seq,
BYTE protocol,
WORD len
);
Description
This is function SSLMACBegin.
10.17.4.72
SSLMACCalc Function
File
SSL.h
C void
SSLMACCalc(
BYTE* MACSecret,
BYTE* result
);
Description
This is function SSLMACCalc.
SSL Internal Members
512
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.73
SSLRSAOperation Function
File
SSL.c
C static
RSA_STATUS SSLRSAOperation();
Side Effects
None
Returns
None
Description
Pauses connection processing until RSA calculation is complete.
Remarks
This function exists outside of the handshaking functions so that the system does not incur the expense of resuming and suspending handshake hashes.
Preconditions
The RSA Module has been secured, an RSA operation is pending, sslStub.wRxHsBytesRem is the value of sslStub.wRxBytesRem after completion, and sslStub.wRxBytesRem is the value of sslStub.rxProtocol after completion. Also
requires sslStub ( see page 523) to be synchronized.
Section
Function Prototypes
************************************************************************
Cryptographic Calculation Functions
10.17.4.74
sslRSAStubID Variable
File
SSL.c
C
BYTE sslRSAStubID;
Description
Which stub is using RSA, if any
10.17.4.75
SSLRxAlert Function
File
SSL.c
C static void
SSLRxAlert(
);
513
10.17 SSL Microchip TCP/IP Stack Help
Side Effects
None
Returns
None
Description
Receives an alert message and decides what to do
Remarks
None
Preconditions
sslStub ( see page 523) is synchronized
Parameters
Parameters
hTCP
Description
the TCP Socket to read from
SSL Internal Members
10.17.4.76
SSLRxAntiqueClientHello Function
File
SSL.c
C static void
SSLRxAntiqueClientHello(
);
Side Effects
None
Returns
None
Description
Receives the SSLv2 ClientHello message, initiating a new SSL session with a client
Remarks
This is the only SSLv2 message we support, and is provided for browsers seeking backwards compatibility. Connections must be upgraded to SSLv3.0 immediately following, otherwise the connection will fail.
Preconditions
Handshake hasher is started, and SSL has a stub assigned.
Parameters
Parameters
hTCP
Description
the TCP Socket to send the message to
10.17.4.77
SSLRxCCS Function
File
SSL.c
514
10.17 SSL Microchip TCP/IP Stack Help
C static void
SSLRxCCS(
);
Side Effects
None
Returns
None
Description
Receives a ChangeCipherSpec from the remote server
Remarks
None
Preconditions
sslStub ( see page 523) is synchronized.
Parameters
Parameters
hTCP
Description
the TCP Socket to read from
10.17.4.78
SSLRxClientHello Function
File
SSL.c
C static void
SSLRxClientHello(
);
Side Effects
None
Returns
None
Description
Receives the ClientHello message, initiating a new SSL session with a client
Remarks
None
Preconditions
Handshake hasher is started, and SSL has a stub assigned.
Parameters
Parameters
hTCP
Description
the TCP Socket to send the message to
SSL Internal Members
515
10.17 SSL Microchip TCP/IP Stack Help
10.17.4.79
SSLRxClientKeyExchange Function
File
SSL.c
C static void
SSLRxClientKeyExchange(
);
Side Effects
None
Returns
None
Description
Receives the ClientKeyExchange message and begins the decryption process.
Remarks
None
Preconditions
sslStub ( see page 523) is synchronized and HSStart ( see page 493)() has been called.
Parameters
Parameters
hTCP
Description
the TCP Socket to read from
10.17.4.80
SSLRxFinished Function
File
SSL.c
C static void
SSLRxFinished(
);
Side Effects
None
Returns
None
Description
Receives the Finished message from remote node
Remarks
None
Preconditions
sslStub ( see page 523) is synchronized and HSStart ( see page 493)() has been called.
SSL Internal Members
516
10.17 SSL
Parameters
Parameters
hTCP
Microchip TCP/IP Stack Help
Description
the TCP Socket to read from
SSL Internal Members
10.17.4.81
SSLRxHandshake Function
File
SSL.h
C void
SSLRxHandshake(
);
Returns
None
Description
This function receives handshake messages, reads the handshake header, and passes the data off to the appropriate handshake parser.
Preconditions
The specified SSL stub is initialized and the TCP socket is connected. Also requires that rxBytesRem has been populated and the current SSL stub has been synced into memory.
Parameters
Parameters
hTCP
Description
The TCP socket to read a handshake message from
10.17.4.82
SSLRxRecord Function
File
SSL.h
C
WORD SSLRxRecord(
);
Returns
WORD indicating the number of data bytes there were decrypted but left in the stream.
Description
Reads at most one SSL Record header from the TCP stream and determines what to do with the rest of the data. If not all of the data is available for the record, then the function returns and future call(s) to SSLRxRecord() will process the remaining data until the end of the record is reached. If this call process data from a past record, the next record will not be started until the next call.
Remarks
SSL record headers, MAC footers, and symetric cipher block padding (if any) will be extracted from the TCP stream by this function. Data will be decrypted but left in the stream.
Preconditions
The specified SSL stub is initialized and the TCP socket is connected.
517
10.17 SSL
Parameters
Parameters
hTCP id
Microchip TCP/IP Stack Help
Description
The TCP socket from which to read
The active SSL stub ID
SSL Internal Members
10.17.4.83
SSLRxServerCertificate Function
File
SSL.c
C static void
SSLRxServerCertificate(
);
Side Effects
None
Returns
None
Description
Receives ServerCertificate from the remote server, locates the public key information, and executes RSA operation.
Remarks
This shortcuts full parsing of the certificate by just finding the Public Key Algorithm identifier for RSA. From there, the following ASN.1 struct is the public key. That struct consists of the value for N, followed by the value for E.
Preconditions
sslStub ( see page 523) is synchronized and HSStart ( see page 493)() has been called.
Parameters
Parameters
hTCP
Description
the TCP Socket to read from
10.17.4.84
SSLRxServerHello Function
File
SSL.c
C static void
SSLRxServerHello(
);
Side Effects
None
Returns
None
Description
Receives the ServerHello from the remote server
518
10.17 SSL Microchip TCP/IP Stack Help
Remarks
None
Preconditions
sslStub ( see page 523) is synchronized and HSStart ( see page 493)() has been called.
Parameters
Parameters
hTCP
Description
the TCP Socket to read from
10.17.4.85
sslSession Variable
File
SSL.c
C
Description
Current session data
10.17.4.86
sslSessionID Variable
File
SSL.c
C
BYTE sslSessionID;
Description
Which session is loaded
10.17.4.87
SSLSessionMatchID Function
File
SSL.c
C static
BYTE SSLSessionMatchID(
BYTE* SessionID
);
Side Effects
None
Returns
The matched session ID, or SSL_INVALID_ID ( see page 472) if not found
Description
Locates a cached SSL session for reuse. Syncs found session into RAM.
Remarks
None
SSL Internal Members
519
10.17 SSL
Preconditions
None
Parameters
Parameters
SessionID
Section
Server messages
Microchip TCP/IP Stack Help
Description
the session identifier to match
10.17.4.88
SSLSessionMatchIP Function
File
SSL.c
C static
BYTE SSLSessionMatchIP(
IP_ADDR ip
);
Side Effects
None
Returns
The matched session ID, or SSL_INVALID_ID ( see page 472) if not found
Description
Locates a cached SSL session for reuse
Remarks
None
Preconditions
None
Parameters
Parameters
ip
Section
Client messages
Description
the host session to match
10.17.4.89
SSLSessionNew Function
File
SSL.c
C static
BYTE SSLSessionNew();
Side Effects
None
Returns
Allocated Session ID, or SSL_INVALID_ID ( see page 472) if none available
SSL Internal Members
520
10.17 SSL
Description
Finds space for a new SSL session
Remarks
None
Preconditions
None
Microchip TCP/IP Stack Help
10.17.4.90
sslSessionStubs Variable
File
SSL.c
C
SSL_SESSION_STUB sslSessionStubs[MAX_SSL_SESSIONS];
Description
8 byte session stubs
SSL Internal Members
10.17.4.91
SSLSessionSync Function
File
SSL.c
C static void
SSLSessionSync(
BYTE id
);
Side Effects
None
Returns
None
Description
Specified session is loaded to RAM. Only loads if necessary, and saves any current session before switching if it has been updated.
Remarks
None
Preconditions
None
Parameters
Parameters
id
Description
the session ID to sync to RAM
521
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
10.17.4.92
SSLSessionUpdated Macro
File
SSL.c
C
#define
SSLSessionUpdated sslSessionUpdated = TRUE;
Description
This is macro SSLSessionUpdated.
10.17.4.93
sslSessionUpdated Variable
File
SSL.c
C
BOOL sslSessionUpdated;
Description
Whether or not it has been updated
10.17.4.94
SSLStartPartialRecord Function
File
SSL.h
C void
SSLStartPartialRecord(
BYTE txProtocol,
WORD wLen
);
Returns
None
Description
This function allows messages longer than the TCP buffer to be sent, which is frequently the case for the Certificate handshake message. The final message length is required to be known in order to transmit the header. Once called,
data, finalize, and prepare for a new record.
Remarks
Partial messages do not support the current cipher spec, so this can only be used during the handshake procedure.
Preconditions
The specified SSL stub is initialized and the TCP socket is connected.
Parameters
Parameters
hTCP id
Description
The TCP socket with data waiting to be transmitted
The active SSL stub ID
522
10.17 SSL txPortocol wLen
Microchip TCP/IP Stack Help
The SSL protocol number to attach to this record
The length of all the data to be sent
10.17.4.95
sslStub Variable
File
SSL.c
C
Description
The current SSL stub
10.17.4.96
SSLStubAlloc Function
File
SSL.c
C static
BOOL SSLStubAlloc();
Side Effects
None
Returns
TRUE if stub was allocated, FALSE otherwise
Description
Allocates a stub for use.
Remarks
None
Preconditions
None
Parameters
Parameters
Outputs
Description
None
10.17.4.97
SSLStubFree Function
File
SSL.c
C static void
SSLStubFree(
BYTE id
);
Side Effects
None
SSL Internal Members
523
10.17 SSL
Returns
None
Description
Specified stub is released
Remarks
None
Preconditions
None
Parameters
Parameters
id
Outputs
Microchip TCP/IP Stack Help
Description
the stub ID to free
None
10.17.4.98
sslStubID Variable
File
SSL.c
C
BYTE sslStubID;
Description
Which SSL_STUB ( see page 504) is loaded
10.17.4.99
SSLStubSync Function
File
SSL.c
C static void
SSLStubSync(
BYTE id
);
Side Effects
None
Returns
None
Description
Specified stub is loaded to RAM. Only loads if necessary, and saves any current stub before switching.
Remarks
None
Preconditions
None
SSL Internal Members
524
10.17 SSL
Parameters
Parameters
id
Section
Ethernet Buffer RAM Management
Microchip TCP/IP Stack Help
Description
the stub ID to sync to RAM
SSL Internal Members
10.17.4.100
SSLTerminate Function
File
SSL.h
C void
SSLTerminate(
BYTE sslStubId
);
Returns
None
Description
Terminates an SSL connection and releases allocated resources.
Preconditions
None
Parameters
Parameters
id
Description
the SSL stub ID to terminate
10.17.4.101
SSLTxCCSFin Function
File
SSL.c
C static void
SSLTxCCSFin(
);
Side Effects
None
Returns
None
Description
Generates the session keys from the master secret, then allocates and generates the encryption context. Once processing is complete, transmits the Change Cipher Spec message and the Finished handshake message to the server.
Remarks
None
Preconditions
525
10.17 SSL
Parameters
Parameters
hTCP
Section
Client and server messages
Microchip TCP/IP Stack Help
Description
the TCP Socket to write the message to
SSL Internal Members
10.17.4.102
SSLTxClientHello Function
File
SSL.c
C static void
SSLTxClientHello(
);
Side Effects
None
Returns
None
Description
Transmits the ClientHello message to initiate a new SSL session with the server.
Remarks
None
Preconditions
Enough space is available in hTCP to write the entire message.
Parameters
Parameters
hTCP
Description
the TCP Socket to send the message to
10.17.4.103
SSLTxClientKeyExchange Function
File
SSL.c
C static void
SSLTxClientKeyExchange(
);
Side Effects
None
Returns
None
Description
Transmits the encrypted pre-master secret to the server and requests the Change Cipher Spec. Also generates the Master
Secret from the pre-master secret that was used.
526
10.17 SSL Microchip TCP/IP Stack Help SSL Internal Members
Remarks
None
Preconditions
contains the encrypted pre-master secret at address 0x80.
Parameters
Parameters
hTCP
Description
the TCP Socket to write the message to
10.17.4.104
SSLTxMessage Function
File
SSL.h
C void
SSLTxMessage(
BYTE msg
);
Returns
None
Description
This function transmits a specific SSL message for handshakes and alert messages. Supported messages are listed in
Preconditions
The specified SSL stub is initialized and the TCP socket is connected.
Parameters
Parameters
hTCP id msg
Description
The TCP socket with data waiting to be transmitted
The active SSL stub ID
One of the SSL_MESSAGES ( see page 501) types to send
10.17.4.105
SSLTxRecord Function
File
SSL.h
C void
SSLTxRecord(
BYTE txProtocol
);
Returns
None
Description
Transmits all pending data in the TCP TX buffer as an SSL record using the specified protocol. This function transparently
527
10.17 SSL Microchip TCP/IP Stack Help encrypts and MACs the data if there is an active cipher spec.
Preconditions
The specified SSL stub is initialized and the TCP socket is connected.
Parameters
Parameters
hTCP id txPortocol
Description
The TCP socket with data waiting to be transmitted
The active SSL stub ID
The SSL protocol number to attach to this record
SSL Internal Members
10.17.4.106
SSLTxServerCertificate Function
File
SSL.c
C static void
SSLTxServerCertificate(
);
Side Effects
None
Returns
None
Description
Transmits the Certificate message with the server's specified public key certificate.
Remarks
Certificate is defined in CustomSSLCert.c. This function requires special handling for partial records because the certificate will likely be larger than the TCP buffer, and SSL handshake messages are constrained to fit in a single SSL handshake record
Preconditions
None
Parameters
Parameters
hTCP
Description
the TCP Socket to send the message to
10.17.4.107
SSLTxServerHello Function
File
SSL.c
C static void
SSLTxServerHello(
);
Side Effects
None
528
10.17 SSL
Returns
None
Description
Transmits the ServerHello message.
Remarks
None
Preconditions
None
Parameters
Parameters
hTCP
Microchip TCP/IP Stack Help
Description
the TCP Socket to send the message to
10.17.4.108
SSLTxServerHelloDone Function
File
SSL.c
C static void
SSLTxServerHelloDone(
);
Side Effects
None
Returns
None
Description
Transmits the ServerHelloDone message.
Remarks
None
Preconditions
None
Parameters
Parameters
hTCP
Description
the TCP Socket to send the message to
10.17.5
Files
Files
Name
SSLClientSize.h ( see page 530)
Module
Description
This is file SSLClientSize.h.
Files
529
10.18 TCP Microchip TCP/IP Stack Help
10.17.5.1
SSLClientSize.h
Macros
Name
SSL_RSA_CLIENT_SIZE ( see page 476)
Description
Size of Encryption Buffer (must be larger than key size)
Description
This is file SSLClientSize.h.
10.18
TCP
Functions
Name
Description
This is function WFGetTCBSize.
Variables
Name
Description
Tracking variable for next local client port number
Description
TCP is a standard transport layer protocol described in RFC 793. It provides reliable stream-based connections over unreliable networks, and forms the foundation for HTTP, SMTP, and many other protocol standards.
Connections made over TCP guarantee data transfer at the expense of throughput. Connections are made through a three-way handshake process, ensuring a one-to-one connection. Remote nodes advertise how much data they are ready to receive, and all data transmitted must be acknowledged. If a remote node fails to acknowledge the receipt of data, it is automatically retransmitted. This ensures that network errors such as lost, corrupted, or out-of-order packets are automatically corrected.
To accomplish this, TCP must operate in a buffer. Once the transmit buffer is full, no more data can be sent until the remote node has acknowledged receipt. For the Microchip TCP/IP Stack, the application must return to the main stack loop in order for this to happen. Likewise, the remote node cannot transmit more data until the local device has acknowledged receipt and that space is available in the buffer. When a local application needs to read more data, it must return to the main stack loop and wait for a new packet to arrive.
The TCP flow diagram below provides an overview for the use of the TCP module:
530
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
wait for client connections, or can make a client connection to the remote node. The remote node can be specified by a host name string to be resolved in DNS, an IP address, or a NODE_INFO struct containing previously resolved IP and MAC address information.
Once connected, applications can read and write data. On each entry, the application must verify that the socket is still
transmit data immediately. Alternately, return to the main stack loop. Data will be transmitted when either a) half of the transmit buffer becomes full or b) a delay time has passed (usually 40ms).
functions to locate data in the buffer. When no more data remains, return to the main stack loop to wait for more data to arrive.
and wait for the remote node to acknowledge the disconnection. Client sockets will return to the idle state, while listening sockets will wait for a new connection.
read the associated RFC.
10.18.1
TCP Public Members
Functions
Name
TCPAdjustFIFOSize ( see page 536)
Description
Adjusts the relative sizes of the RX and TX buffers.
Disconnects an open socket and destroys the socket handle, including server mode socket handles.
TCPDiscard ( see page 537) Discards any pending data in the TCP RX FIFO.
Disconnects an open socket.
TCPFindArrayEx ( see page 539)
Searches for a string in the TCP RX buffer.
TCPFindEx ( see page 540) Searches for a byte in the TCP RX buffer.
531
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
TCPFindROMArrayEx ( see page 541)
Searches for a ROM string in the TCP RX buffer.
Immediately transmits all pending TX data.
TCPGetRemoteInfo ( see page 543)
Retrieves a single byte to a TCP socket.
Reads an array of data bytes from a TCP socket's receive FIFO. The data is removed from the FIFO in the process.
Obtains information about a currently open socket.
TCPGetRxFIFOFree ( see page 544)
TCPGetTxFIFOFull ( see page 545)
TCPIsConnected ( see page 545)
Determines how many bytes are free in the RX FIFO.
Determines how many bytes are pending in the TCP TX FIFO.
Determines if a socket has an established connection.
Determines how many bytes can be read from the TCP RX buffer.
Determines how much free space is available in the TCP TX buffer.
Opens a TCP socket for listening or as a client.
Peaks at one byte in the TCP RX FIFO without removing it from the buffer.
Reads a specified number of data bytes from the TCP RX FIFO without removing them from the buffer.
Writes a single byte to a TCP socket.
Writes an array from RAM to a TCP socket.
TCPPutROMArray ( see page 550)
TCPPutROMString ( see page 551)
Writes an array from ROM to a TCP socket.
Writes a null-terminated string from ROM to a TCP socket. The null-terminator is not copied to the socket.
Writes a null-terminated string from RAM to a TCP socket. The null-terminator is not copied to the socket.
Copies data to/from various memory mediums.
Copies data to/from various memory mediums.
Self-clearing semaphore inidicating socket reset.
Macros
Name Description
INVALID_SOCKET ( see page 533) The socket is invalid or could not be opened
The socket is not known
Resize flag: extra bytes go to RX
Resize flag: extra bytes go to TX
Resize flag: attempt to preserve RX buffer
TCP_ADJUST_PRESERVE_RX ( see page 534)
TCP_ADJUST_PRESERVE_TX ( see page 534)
TCP_OPEN_IP_ADDRESS ( see page 534)
Resize flag: attempt to preserve TX buffer
Emit an undeclared identifier diagnostic if code tries to use
TCP_OPEN_IP_ADDRESS while STACK_CLIENT_MODE feature is not enabled.
532
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
TCP_OPEN_NODE_INFO ( see page 535)
TCP_OPEN_RAM_HOST ( see page 535)
TCP_OPEN_ROM_HOST ( see page 535)
Emit an undeclared identifier diagnostic if code tries to use
TCP_OPEN_NODE_INFO while STACK_CLIENT_MODE feature is not enabled.
Emit an undeclared identifier diagnostic if code tries to use
TCP_OPEN_RAM_HOST while STACK_CLIENT_MODE feature is not enabled.
Emit an undeclared identifier diagnostic if code tries to use
TCP_OPEN_ROM_HOST while STACK_CLIENT_MODE feature is not enabled.
Create a server socket and ignore dwRemoteHost.
Alias to TCPOpen ( see page 547) as a client.
Alias to TCPFindEx ( see page 540) with no length parameter.
Alias to TCPFindArrayEx ( see page 539) with no length parameter.
TCPFindROMArray ( see page 541) Alias to TCPFindROMArrayEx ( see page 541) with no length
parameter.
TCPGetRxFIFOFull ( see page 544) Alias to TCPIsGetReady ( see page 546) provided for API
completeness
Alias to TCPIsPutReady ( see page 546) provided for API
completeness
Alias to TCPOpen ( see page 547) as a server.
Module
Description
The following functions and variables are available to the stack application.
10.18.1.1
INVALID_SOCKET Macro
File
TCP.h
C
#define
INVALID_SOCKET (0xFE)
// The socket is invalid or could not be opened
Description
The socket is invalid or could not be opened
10.18.1.2
UNKNOWN_SOCKET Macro
File
TCP.h
C
#define
UNKNOWN_SOCKET (0xFF)
// The socket is not known
Description
The socket is not known
533
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
10.18.1.3
TCP_ADJUST_GIVE_REST_TO_RX Macro
File
TCP.h
C
#define
TCP_ADJUST_GIVE_REST_TO_RX 0x01u
// Resize flag: extra bytes go to RX
Description
Resize flag: extra bytes go to RX
10.18.1.4
TCP_ADJUST_GIVE_REST_TO_TX Macro
File
TCP.h
C
#define
TCP_ADJUST_GIVE_REST_TO_TX 0x02u
// Resize flag: extra bytes go to TX
Description
Resize flag: extra bytes go to TX
10.18.1.5
TCP_ADJUST_PRESERVE_RX Macro
File
TCP.h
C
#define
TCP_ADJUST_PRESERVE_RX 0x04u
// Resize flag: attempt to preserve RX buffer
Description
Resize flag: attempt to preserve RX buffer
10.18.1.6
TCP_ADJUST_PRESERVE_TX Macro
File
TCP.h
C
#define
TCP_ADJUST_PRESERVE_TX 0x08u
// Resize flag: attempt to preserve TX buffer
Description
Resize flag: attempt to preserve TX buffer
10.18.1.7
TCP_OPEN_IP_ADDRESS Macro
File
TCP.h
534
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
C
#define
TCP_OPEN_IP_ADDRESS You_need_to_enable_STACK_CLIENT_MODE_to_use_TCP_OPEN_IP_ADDRESS
Description
Emit an undeclared identifier diagnostic if code tries to use TCP_OPEN_IP_ADDRESS while STACK_CLIENT_MODE feature is not enabled.
10.18.1.8
TCP_OPEN_NODE_INFO Macro
File
TCP.h
C
#define
TCP_OPEN_NODE_INFO You_need_to_enable_STACK_CLIENT_MODE_to_use_TCP_OPEN_NODE_INFO
Description
Emit an undeclared identifier diagnostic if code tries to use TCP_OPEN_NODE_INFO while STACK_CLIENT_MODE feature is not enabled.
10.18.1.9
TCP_OPEN_RAM_HOST Macro
File
TCP.h
C
#define
TCP_OPEN_RAM_HOST You_need_to_enable_STACK_CLIENT_MODE_to_use_TCP_OPEN_RAM_HOST
Description
Emit an undeclared identifier diagnostic if code tries to use TCP_OPEN_RAM_HOST while STACK_CLIENT_MODE feature is not enabled.
10.18.1.10
TCP_OPEN_ROM_HOST Macro
File
TCP.h
C
#define
TCP_OPEN_ROM_HOST You_need_to_enable_STACK_CLIENT_MODE_to_use_TCP_OPEN_ROM_HOST
Description
Emit an undeclared identifier diagnostic if code tries to use TCP_OPEN_ROM_HOST while STACK_CLIENT_MODE feature is not enabled.
10.18.1.11
TCP_OPEN_SERVER Macro
File
TCP.h
C
#define
TCP_OPEN_SERVER 0u
535
10.18 TCP Microchip TCP/IP Stack Help
Description
Create a server socket and ignore dwRemoteHost.
TCP Public Members
10.18.1.12
TCPAdjustFIFOSize Function
File
TCP.h
C
BOOL TCPAdjustFIFOSize(
WORD wMinRXSize,
WORD wMinTXSize,
BYTE vFlags
);
Side Effects
Any unacknowledged or untransmitted data in the TX FIFO is always deleted.
Description
This function can be used to adjust the relative sizes of the RX and TX FIFO depending on the immediate needs of an application. Since a larger FIFO can allow more data to be sent in a given packet, adjusting the relative sizes on the fly can allow for optimal transmission speed for one-sided application protocols. For example, HTTP typically begins by receiving large amounts of data from the client, then switches to serving large amounts of data back. Adjusting the FIFO at these points can increase performance substantially. Once the FIFO is adjusted, a window update is sent.
Received data can be preserved as long as the buffer is expanding and has not wrapped.
Remarks
At least one byte must always be allocated to the RX buffer so that a FIN can be received. The function automatically corrects for this.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP wMinRXSize wMinTXSize vFlags
Description
The socket to be adjusted
Minimum number of byte for the RX FIFO
Minimum number of bytes for the RX FIFO
Any combination of TCP_ADJUST_GIVE_REST_TO_RX ( see page 534),
TCP_ADJUST_GIVE_REST_TO_TX ( see page 534),
TCP_ADJUST_PRESERVE_RX ( see page 534).
TCP_ADJUST_PRESERVE_TX ( see page 534) is not currently supported.
Return Values
Return Values
TRUE
FALSE
Description
The FIFOs were adjusted successfully
Minimum RX, Minimum TX, or flags couldn't be accommodated and therefore the socket was left unchanged.
536
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
10.18.1.13
TCPConnect Macro
File
TCP.h
C
#define
TCPConnect(remote,port) TCPOpen((DWORD)remote, TCP_OPEN_NODE_INFO, port,
TCP_PURPOSE_DEFAULT)
Description
10.18.1.14
TCPClose Function
File
TCP.h
C void
TCPClose(
);
Returns
None
Description
Disconnects an open socket and destroys the socket handle, including server mode socket handles. This function performs
relinquished to the TCP/IP stack upon return.
Preconditions
None
Parameters
Parameters
hTCP
Description
Handle to the socket to disconnect and close.
10.18.1.15
TCPDiscard Function
File
TCP.h
C void
TCPDiscard(
);
Returns
None
Description
Discards any pending data in the TCP RX FIFO.
537
10.18 TCP
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP
Microchip TCP/IP Stack Help TCP Public Members
Description
The socket whose RX FIFO is to be cleared.
10.18.1.16
TCPDisconnect Function
File
TCP.h
C void
TCPDisconnect(
);
Returns
None
Description
This function closes a connection to a remote node by sending a FIN (if currently connected).
The function can be called a second time to force a socket closed by sending a RST packet. This is useful when the application knows that the remote node will not send an ACK (if it has crashed or lost its link), or when the application needs to reuse the socket immediately regardless of whether or not the remote node would like to transmit more data before closing.
For client mode sockets, upon return, the hTCP handle is relinquished to the TCP/IP stack and must no longer be used by the application (except for an immediate subsequent call to TCPDisconnect() to force a RST transmission, if needed).
For server mode sockets, upon return, the hTCP handle is NOT relinquished to the TCP/IP stack. After closing, the socket returns to the listening state allowing future connection requests to be serviced. This leaves the hTCP handle in a valid state and must be retained for future operations on the socket. If you want to close the server and relinquish the socket back to
the TCP/IP stack, call the TCPClose ( see page 537)() API instead of TCPDisconnect().
Remarks
If the socket is using SSL, a CLOSE_NOTIFY record will be transmitted first to allow the SSL session to be resumed at a later time.
Preconditions
None
Parameters
Parameters
hTCP
Description
Handle of the socket to disconnect.
10.18.1.17
TCPFind Macro
File
TCP.h
C
#define
TCPFind(a,b,c,d) TCPFindEx(a,b,c,0,d)
538
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
Description
with an older API.
10.18.1.18
TCPFindArray Macro
File
TCP.h
C
#define
TCPFindArray(a,b,c,d,e) TCPFindArrayEx(a,b,c,d,0,e)
Description
compatibility with an older API.
10.18.1.19
TCPFindArrayEx Function
File
TCP.h
C
WORD TCPFindArrayEx(
BYTE* cFindArray,
WORD wLen,
WORD wStart,
WORD wSearchLen,
BOOL bTextCompare
);
Description
This function finds the first occurrance of an array of bytes in the TCP RX buffer. It can be used by an application to abstract searches out of their own application code. For increased efficiency, the function is capable of limiting the scope of search to a specific range of bytes. It can also perform a case-insensitive search if required.
For example, if the buffer contains "I love PIC MCUs!" and the search array is "love" with a length of 4, a value of 2 will be returned.
Remarks
Since this function usually must transfer data from external storage to internal RAM for comparison, its performance degrades significantly when the buffer is full and the array is not found. For better performance, try to search for characters that are expected to exist or limit the scope of the search as much as possible. The HTTP2 module, for example, uses this function to parse headers. However, it searches for newlines, then the separating colon, then reads the header name to
RAM for final comparison. This has proven to be significantly faster than searching for full header name strings outright.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP cFindArray wLen wStart
Description
The socket to search within.
The array of bytes to find in the buffer.
Length of cFindArray.
Zero-indexed starting position within the buffer.
539
10.18 TCP wSearchLen bTextCompare
Return Values
Return Values
0xFFFF
Otherwise
Microchip TCP/IP Stack Help TCP Public Members
Length from wStart to search in the buffer.
TRUE for case-insensitive text search, FALSE for binary search
Description
Search array not found
Zero-indexed position of the first occurrance
10.18.1.20
TCPFindEx Function
File
TCP.h
C
WORD TCPFindEx(
BYTE cFind,
WORD wStart,
WORD wSearchLen,
BOOL bTextCompare
);
Description
This function finds the first occurrance of a byte in the TCP RX buffer. It can be used by an application to abstract searches out of their own application code. For increased efficiency, the function is capable of limiting the scope of search to a specific range of bytes. It can also perform a case-insensitive search if required.
For example, if the buffer contains "I love PIC MCUs!" and the cFind byte is ' ', a value of 1 will be returned.
Remarks
Since this function usually must transfer data from external storage to internal RAM for comparison, its performance degrades significantly when the buffer is full and the array is not found. For better performance, try to search for characters that are expected to exist or limit the scope of the search as much as possible. The HTTP2 module, for example, uses this function to parse headers. However, it searches for newlines, then the separating colon, then reads the header name to
RAM for final comparison. This has proven to be significantly faster than searching for full header name strings outright.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP cFind wStart wSearchLen bTextCompare
Return Values
Return Values
0xFFFF
Otherwise
Description
The socket to search within.
The byte to find in the buffer.
Zero-indexed starting position within the buffer.
Length from wStart to search in the buffer.
TRUE for case-insensitive text search, FALSE for binary search
Description
Search array not found
Zero-indexed position of the first occurrance
540
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
10.18.1.21
TCPFindROMArray Macro
File
TCP.h
C
#define
TCPFindROMArray(a,b,c,d,e) TCPFindArray(a,(BYTE*)b,c,d,e)
Description
compatibility with an older API.
10.18.1.22
TCPFindROMArrayEx Function
File
TCP.h
C
WORD TCPFindROMArrayEx(
ROM BYTE* cFindArray,
WORD wLen,
WORD wStart,
WORD wSearchLen,
BOOL bTextCompare
);
Description
This function finds the first occurrance of an array of bytes in the TCP RX buffer. It can be used by an application to abstract searches out of their own application code. For increased efficiency, the function is capable of limiting the scope of search to a specific range of bytes. It can also perform a case-insensitive search if required.
For example, if the buffer contains "I love PIC MCUs!" and the search array is "love" with a length of 4, a value of 2 will be returned.
Remarks
Since this function usually must transfer data from external storage to internal RAM for comparison, its performance degrades significantly when the buffer is full and the array is not found. For better performance, try to search for characters that are expected to exist or limit the scope of the search as much as possible. The HTTP2 module, for example, uses this function to parse headers. However, it searches for newlines, then the separating colon, then reads the header name to
RAM for final comparison. This has proven to be significantly faster than searching for full header name strings outright.
This function is aliased to TCPFindArrayEx ( see page 539) on non-PIC18 platforms.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP cFindArray wLen wStart wSearchLen bTextCompare
Description
The socket to search within.
The array of bytes to find in the buffer.
Length of cFindArray.
Zero-indexed starting position within the buffer.
Length from wStart to search in the buffer.
TRUE for case-insensitive text search, FALSE for binary search
541
10.18 TCP
Return Values
Return Values
0xFFFF
Otherwise
Microchip TCP/IP Stack Help
Description
Search array not found
Zero-indexed position of the first occurrance
TCP Public Members
10.18.1.23
TCPFlush Function
File
TCP.h
C void
TCPFlush(
);
Returns
None
Description
This function immediately transmits all pending TX data with a PSH flag. If this function is not called, data will automatically
40ms) has elapsed.
Remarks
SSL application data is automatically flushed, so this function has no effect for SSL sockets.
Preconditions
TCP is initialized and the socket is connected.
Parameters
Parameters
hTCP
Description
The socket whose data is to be transmitted.
10.18.1.24
TCPGet Function
File
TCP.h
C
BOOL TCPGet(
BYTE* byte
);
Description
Retrieves a single byte to a TCP socket.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP byte
Description
The socket from which to read.
Pointer to location in which the read byte should be stored.
542
10.18 TCP
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help
Description
A byte was read from the buffer.
The buffer was empty, or the socket is not connected.
TCP Public Members
10.18.1.25
TCPGetArray Function
File
TCP.h
C
WORD TCPGetArray(
BYTE* buffer,
WORD count
);
Returns
The number of bytes read from the socket. If less than len, the RX FIFO buffer became empty or the socket is not conected.
Description
Reads an array of data bytes from a TCP socket's receive FIFO. The data is removed from the FIFO in the process.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP buffer len
Description
The socket from which data is to be read.
Pointer to the array to store data that was read.
Number of bytes to be read.
10.18.1.26
TCPGetRemoteInfo Function
File
TCP.h
C
SOCKET_INFO* TCPGetRemoteInfo(
);
Returns
function and is valid only until the next time TCPGetRemoteInfo() is called.
Description
structure with IP and MAC address (or gateway MAC) and the remote port.
Preconditions
TCP is initialized and the socket is connected.
543
10.18 TCP
Parameters
Parameters
hTCP
Microchip TCP/IP Stack Help
Description
The socket to check.
TCP Public Members
10.18.1.27
TCPGetRxFIFOFree Function
File
TCP.h
C
WORD TCPGetRxFIFOFree(
);
Returns
The number of bytes free in the TCP RX FIFO. If zero, no additional data can be received until the application removes
some data using one of the TCPGet ( see page 542) family functions.
Description
Determines how many bytes are free in the RX FIFO.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP
Description
The socket to check.
10.18.1.28
TCPGetRxFIFOFull Macro
File
TCP.h
C
#define
TCPGetRxFIFOFull(a) TCPIsGetReady(a)
Description
Alias to TCPIsGetReady ( see page 546) provided for API completeness
10.18.1.29
TCPGetTxFIFOFree Macro
File
TCP.h
C
#define
TCPGetTxFIFOFree(a) TCPIsPutReady(a)
Description
Alias to TCPIsPutReady ( see page 546) provided for API completeness
544
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
10.18.1.30
TCPGetTxFIFOFull Function
File
TCP.h
C
WORD TCPGetTxFIFOFull(
);
Returns
Number of bytes pending to be flushed in the TCP TX FIFO.
Description
Determines how many bytes are pending in the TCP TX FIFO.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP
Description
The socket to check.
10.18.1.31
TCPIsConnected Function
File
TCP.h
C
BOOL TCPIsConnected(
);
Description
This function determines if a socket has an established connection to a remote node. Call this function after calling
Remarks
opening or closing will return FALSE.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP
Return Values
Return Values
TRUE
FALSE
Description
The socket to check.
Description
The socket has an established connection to a remote node.
The socket is not currently connected.
545
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
10.18.1.32
TCPIsGetReady Function
File
TCP.h
C
WORD TCPIsGetReady(
);
Returns
The number of bytes available to be read from the TCP RX buffer.
Description
Call this function to determine how many bytes can be read from the TCP RX buffer. If this function returns zero, the application must return to the main stack loop before continuing in order to wait for more data to arrive.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP
Description
The socket to check.
10.18.1.33
TCPIsPutReady Function
File
TCP.h
C
WORD TCPIsPutReady(
);
Returns
The number of bytes available to be written in the TCP TX buffer.
Description
Call this function to determine how many bytes can be written to the TCP TX buffer. If this function returns zero, the application must return to the main stack loop before continuing in order to transmit more data.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP
Description
The socket to check.
10.18.1.34
TCPListen Macro
File
TCP.h
546
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
C
#define
TCPListen(port) TCPOpen(0, TCP_OPEN_SERVER, port, TCP_PURPOSE_DEFAULT)
Description
10.18.1.35
TCPOpen Function
File
TCP.h
C
DWORD dwRemoteHost,
BYTE vRemoteHostType,
WORD wPort,
BYTE vSocketPurpose
);
Description
Provides a unified method for opening TCP sockets. This function can open both client and server sockets. For client
binary form, or a previously resolved NODE_INFO structure containing the remote IP address and associated MAC address.
When a host name or IP address only is provided, the TCP module will internally perform the necessary DNS and/or ARP resolution steps before reporting that the TCP socket is connected (via a call to TCPISConnected returning TRUE). Server
sockets ignore this destination parameter and listen ( see page 180) only on the indicated port.
The vSocketPurpose field allows sockets to be opened with varying buffer size parameters and memory storage mediums.
This field corresponds to pre-defined sockets allocated in the TCPSocketInitializer[] array in TCPIPConfig.h. The
TCPIPConfig.h file can be edited using the TCP/IP Configuration Wizard.
allowing reuse).
Remarks
This function replaces the old TCPConnect ( see page 537) and TCPListen ( see page 546) functions.
type, the DNS client module must also be enabled (STACK_USE_DNS must be defined in TCPIPConfig.h).
Preconditions
TCP is initialized.
Example
// Open a server socket
skt = TCPOpen(NULL, TCP_OPEN_SERVER, HTTP_PORT, TCP_PURPOSE_HTTP_SERVER);
// Open a client socket to www.microchip.com
// The double cast here prevents compiler warnings
skt = TCPOpen((DWORD)(PTR_BASE)"www.microchip.com",
TCP_OPEN_ROM_HOST, 80, TCP_PURPOSE_DEFAULT);
// Reopen a client socket without repeating DNS or ARP
547
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
SOCKET_INFO cache = TCPGetSocketInfo(skt);
// Call with the old socket
skt = TCPOpen((DWORD)(PTR_BASE)&cache.remote, TCP_OPEN_NODE_INFO,
cache.remotePort.Val, TCP_PURPOSE_DEFAULT);
Parameters
Parameters
dwRemoteHost vRemoteHostType wPort
Description
For client sockets only. Provide a pointer to a null-terminated string of the remote host name (ex: "www.microchip.com" or "192.168.1.123"), a literal destination IP address (ex: 0x7B01A8C0 or an IP_ADDR data type), or a pointer to a NODE_INFO structure with the remote IP address and remote node or gateway MAC address specified. If a string is provided, note that it must be statically allocated in memory and cannot be modified or deallocated until
TCPIsConnected ( see page 545) returns TRUE.
This parameter is ignored for server sockets.
Any one of the following flags to identify the meaning of the dwRemoteHost parameter:
• TCP_OPEN_SERVER ( see page 535) - Open a server socket and
ignore the dwRemoteHost parameter.
• TCP_OPEN_RAM_HOST ( see page 535) - Open a client socket and
connect ( see page 176) it to a remote host who's name is stored as a
null terminated string in a RAM array. Ex: "www.microchip.com" or
"192.168.0.123" (BYTE* type)
• TCP_OPEN_ROM_HOST ( see page 535) - Open a client socket and
connect ( see page 176) it to a remote host who's name is stored as a
null terminated string in a literal string or ROM array. Ex:
"www.microchip.com" or "192.168.0.123" (ROM BYTE* type)
• TCP_OPEN_IP_ADDRESS ( see page 534) - Open a client socket and
connect ( see page 176) it to a remote IP address. Ex: 0x7B01A8C0 for
192.168.1.123 (DWORD type). Note that the byte ordering is big endian.
• TCP_OPEN_NODE_INFO ( see page 535) - Open a client socket and
connect ( see page 176) it to a remote IP and MAC addresses pair stored
in a NODE_INFO structure. dwRemoteHost must be a pointer to the
NODE_INFO structure. This option is provided for backwards compatibility with applications built against prior stack versions that only implemented
the TCPConnect ( see page 537)() function. It can also be used to skip
DNS and ARP resolution steps if connecting to a remote node which you've already connected to and have cached addresses for.
TCP port to listen ( see page 180) on or connect ( see page 176) to:
• Client sockets - the remote TCP port to which a connection should be made. The local port for client sockets will be automatically picked by the
TCP module.
• Server sockets - the local TCP port on which to listen ( see page 180) for
connections.
vSocketPurpose Any of the TCP_PURPOSE_* constants defined in TCPIPConfig.h or the
TCPIPConfig utility (see TCPSocketInitializer[] array).
Return Values
Return Values
INVALID_SOCKET ( see page 533)
Otherwise
Description
No sockets of the specified type were available to be opened.
A TCP_SOCKET ( see page 558) handle. Save this handle and use it when
calling all other TCP APIs.
10.18.1.36
TCPPeek Function
File
TCP.h
548
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
C
BYTE TCPPeek(
WORD wStart
);
Description
Peaks at one byte in the TCP RX FIFO without removing it from the buffer.
Remarks
in a loop.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP wStart
Description
The socket to peak from (read without removing from stream).
Zero-indexed starting position within the FIFO to peek from.
10.18.1.37
TCPPeekArray Function
File
TCP.h
C
WORD TCPPeekArray(
BYTE * vBuffer,
WORD wLen,
WORD wStart
);
Description
Reads a specified number of data bytes from the TCP RX FIFO without removing them from the buffer. No TCP control actions are taken as a result of this function (ex: no window update is sent to the remote node).
Remarks
None
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP vBuffer wLen wStart
Description
The socket to peak from (read without removing from stream).
Destination to write the peeked data bytes.
Length of bytes to peak from the RX FIFO and copy to vBuffer.
Zero-indexed starting position within the FIFO to start peeking from.
10.18.1.38
TCPPut Function
File
TCP.h
549
10.18 TCP
C
BOOL TCPPut(
BYTE byte
);
Description
Writes a single byte to a TCP socket.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP byte
Return Values
Return Values
TRUE
FALSE
Microchip TCP/IP Stack Help
Description
The socket to which data is to be written.
The byte to write.
TCP Public Members
Description
The byte was written to the transmit buffer.
The transmit buffer was full, or the socket is not connected.
10.18.1.39
TCPPutArray Function
File
TCP.h
C
WORD TCPPutArray(
BYTE* Data,
WORD Len
);
Returns
The number of bytes written to the socket. If less than len, the buffer became full or the socket is not conected.
Description
Writes an array from RAM to a TCP socket.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP data len
Description
The socket to which data is to be written.
Pointer to the array to be written.
Number of bytes to be written.
10.18.1.40
TCPPutROMArray Function
File
TCP.h
550
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
C
WORD TCPPutROMArray(
ROM BYTE* Data,
WORD Len
);
Returns
The number of bytes written to the socket. If less than len, the buffer became full or the socket is not conected.
Description
Writes an array from ROM to a TCP socket.
Remarks
This function is aliased to TCPPutArray ( see page 550) on non-PIC18 platforms.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP data len
Description
The socket to which data is to be written.
Pointer to the array to be written.
Number of bytes to be written.
10.18.1.41
TCPPutROMString Function
File
TCP.h
C
ROM BYTE* TCPPutROMString(
ROM BYTE* Data
);
Returns
Pointer to the byte following the last byte written to the socket. If this pointer does not dereference to a NUL byte, the buffer became full or the socket is not connected.
Description
Writes a null-terminated string from ROM to a TCP socket. The null-terminator is not copied to the socket.
Remarks
initialize the *data pointer to the first byte, then call this function repeatedly (breaking to the main stack loop after each call) until the return value dereferences to a NUL byte. Save the return value as the new starting *data pointer otherwise.
This function is aliased to TCPPutString ( see page 552) on non-PIC18 platforms.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP data
Description
The socket to which data is to be written.
Pointer to the string to be written.
551
10.18 TCP Microchip TCP/IP Stack Help TCP Public Members
10.18.1.42
TCPPutString Function
File
TCP.h
C
BYTE* TCPPutString(
BYTE* Data
);
Returns
Pointer to the byte following the last byte written to the socket. If this pointer does not dereference to a NUL byte, the buffer became full or the socket is not connected.
Description
Writes a null-terminated string from RAM to a TCP socket. The null-terminator is not copied to the socket.
Remarks
initialize the *data pointer to the first byte, then call this function repeatedly (breaking to the main stack loop after each call) until the return value dereferences to a NUL byte. Save the return value as the new starting *data pointer otherwise.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP data
Description
The socket to which data is to be written.
Pointer to the string to be written.
10.18.1.43
TCPRAMCopy Function
File
TCP.c
C static void
TCPRAMCopy(
PTR_BASE wDest,
BYTE vDestType,
PTR_BASE wSource,
BYTE vSourceType,
WORD wLength
);
Returns
None
Description
This function copies data between memory mediums (PIC RAM, SPI RAM, and Ethernet buffer RAM).
Remarks
Copying to a destination region that overlaps with the source address is supported only if the destination start address is at a lower memory address (closer to 0x0000) than the source pointer. However, if they do overlap there must be at least 4 bytes of non-overlap to ensure correct results due to hardware DMA requirements.
552
10.18 TCP
Preconditions
TCP is initialized.
Parameters
Parameters
ptrDest vDestType ptrSource vSourceType wLength
Section
Function Prototypes
Microchip TCP/IP Stack Help TCP Public Members
Description
Address ( see page 152) to write to
Destination meidum (TCP_PIC_RAM, TCP_ETH_RAM, TCP_SPI_RAM)
Address ( see page 152) to copy from
Source medium (TCP_PIC_RAM, TCP_ETH_RAM, or TCP_SPI_RAM)
Number of bytes to copy
10.18.1.44
TCPRAMCopyROM Function
File
TCP.c
C static void
TCPRAMCopyROM(
PTR_BASE wDest,
BYTE wDestType,
ROM BYTE* wSource,
WORD wLength
);
Returns
None
Description
This function copies data between memory mediums (PIC RAM, SPI RAM, and Ethernet buffer RAM). This function is to be used when copying from ROM.
Remarks
Copying to a destination region that overlaps with the source address is supported only if the destination start address is at a lower memory address (closer to 0x0000) than the source pointer.
This function is aliased to TCPRAMCopy ( see page 552) on non-PIC18 platforms.
Preconditions
TCP is initialized.
Parameters
Parameters
wDest wDestType wSource wLength
Description
Address ( see page 152) to write to
Destination meidum (TCP_PIC_RAM, TCP_ETH_RAM, TCP_SPI_RAM)
Address ( see page 152) to copy from
Number of bytes to copy
10.18.1.45
TCPWasReset Function
File
TCP.h
553
10.18 TCP Microchip TCP/IP Stack Help TCP Stack Members
C
BOOL TCPWasReset(
);
Description
This function is a self-clearing semaphore indicating whether or not a socket has been disconnected since the previous call.
FALSE to check for a condition requiring a state machine reset. If a socket is closed (due to a FIN ACK) and then
for protocols such as HTTP in which a client will immediately open a new connection upon closing of a prior one. Relying on this function instead allows applications to trap those conditions and properly reset their internal state for the new connection.
Preconditions
TCP is initialized.
Parameters
Parameters
hTCP
Return Values
Return Values
TRUE
FALSE
Description
The socket to check.
Description
The socket has been disconnected since the previous call.
The socket has not been disconnected since the previous call.
10.18.2
TCP Stack Members
Enumerations
Name
Description
TCP States as defined by RFC 793
Functions
Name
Description
Initializes the TCP module.
Handles incoming TCP segments.
TCPSSLDecryptMAC ( see page 560)
TCPStartSSLClientEx ( see page 561)
Performs periodic TCP tasks.
Decrypts and MACs data arriving via SSL.
Begins an SSL client session.
Module
554
10.18 TCP Microchip TCP/IP Stack Help TCP Stack Members
Structures
Name
Description
Information about a socket
Remainder of TCP Control Block data. The rest of the TCB is stored in Ethernet buffer RAM or elsewhere as defined by vMemoryMedium. Current size is 41
(PIC18), 42 (PIC24/dsPIC), or 48 bytes (PIC32)
for speed. Current size is 34 bytes (PIC18), 36 bytes (PIC24/dsPIC), or 56
(PIC32)
Types
Name
Description
A TCP_SOCKET is stored as a single BYTE
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.18.2.1
SOCKET_INFO Structure
File
TCP.h
C typedef struct
{
NODE_INFO remote;
WORD_VAL remotePort;
} SOCKET_INFO;
Members
Members
NODE_INFO remote;
WORD_VAL remotePort;
Description
Information about a socket
Description
NODE_INFO structure for remote node
Port number associated with remote node
10.18.2.2
TCB Structure
File
TCP.h
C typedef struct
{
DWORD retryInterval;
DWORD MySEQ;
DWORD RemoteSEQ;
PTR_BASE txUnackedTail;
WORD_VAL remotePort;
WORD_VAL localPort;
WORD remoteWindow;
WORD wFutureDataSize;
union
{
NODE_INFO niRemoteMACIP;
555
10.18 TCP Microchip TCP/IP Stack Help TCP Stack Members
DWORD dwRemoteHost;
} remote;
SHORT sHoleSize;
struct
{
unsigned char
bFINSent : 1;
unsigned char
bSYNSent : 1;
unsigned char
bRemoteHostIsROM : 1;
unsigned char
bRXNoneACKed1 : 1;
unsigned char
bRXNoneACKed2 : 1;
unsigned char
filler : 3;
} flags;
WORD wRemoteMSS;
WORD_VAL localSSLPort;
BYTE retryCount;
BYTE vSocketPurpose;
} TCB;
Members
Members
DWORD retryInterval;
DWORD MySEQ;
DWORD RemoteSEQ;
PTR_BASE txUnackedTail;
WORD_VAL remotePort;
WORD_VAL localPort;
WORD remoteWindow;
WORD wFutureDataSize;
NODE_INFO niRemoteMACIP;
DWORD dwRemoteHost;
SHORT sHoleSize; unsigned char bFINSent : 1; unsigned char bSYNSent : 1; unsigned char bRemoteHostIsROM : 1; unsigned char bRXNoneACKed1 : 1; unsigned char bRXNoneACKed2 : 1; unsigned char filler : 3;
WORD wRemoteMSS;
WORD_VAL localSSLPort;
BYTE retryCount;
BYTE vSocketPurpose;
Description
How long to wait before retrying transmission
Local sequence number
Remote sequence number
TX tail pointer for data that is not yet acked
Remote port number
Local port number
Remote window size
How much out-of-order data has been received
10 bytes for MAC and IP address
RAM or ROM pointer to a hostname string (ex: "www.microchip.com")
Size of the hole, or -1 for none exists. (0 indicates hole has just been filled)
A FIN has been sent
A SYN has been sent
Remote host is stored in ROM
A duplicate ACK was likely received
A second duplicate ACK was likely received future use
Maximum Segment Size option advirtised by the remote node during initial handshaking
Local SSL port number (for listening sockets)
Counter for transmission retries
Purpose of socket (as defined in TCPIPConfig.h)
Description
Remainder of TCP Control Block data. The rest of the TCB is stored in Ethernet buffer RAM or elsewhere as defined by vMemoryMedium. Current size is 41 (PIC18), 42 (PIC24/dsPIC), or 48 bytes (PIC32)
10.18.2.3
TCB_STUB Structure
File
TCP.h
C typedef struct
{
PTR_BASE bufferTxStart;
PTR_BASE bufferRxStart;
PTR_BASE bufferEnd;
556
10.18 TCP Microchip TCP/IP Stack Help TCP Stack Members
PTR_BASE txHead;
PTR_BASE txTail;
PTR_BASE rxHead;
PTR_BASE rxTail;
DWORD eventTime;
WORD eventTime2;
union
{
WORD delayedACKTime;
WORD closeWaitTime;
} OverlappedTimers;
struct
{
unsigned char
vUnackedKeepalives : 3;
unsigned char
bServer : 1;
unsigned char
bTimerEnabled : 1;
unsigned char
bTimer2Enabled : 1;
unsigned char
bDelayedACKTimerEnabled : 1;
unsigned char
bOneSegmentReceived : 1;
unsigned char
bHalfFullFlush : 1;
unsigned char
bTXASAP : 1;
unsigned char
bTXASAPWithoutTimerReset : 1;
unsigned char
bTXFIN : 1;
unsigned char
bSocketReset : 1;
unsigned char
bSSLHandshaking : 1;
unsigned char
filler : 2;
} Flags;
WORD_VAL remoteHash;
PTR_BASE sslTxHead;
PTR_BASE sslRxHead;
BYTE sslReqMessage;
BYTE vMemoryMedium;
} TCB_STUB;
Members
Members
PTR_BASE bufferTxStart;
PTR_BASE bufferRxStart;
PTR_BASE bufferEnd;
PTR_BASE txHead;
PTR_BASE txTail;
PTR_BASE rxHead;
PTR_BASE rxTail;
DWORD eventTime;
WORD eventTime2;
WORD delayedACKTime;
WORD closeWaitTime;
TCP_STATE smState; unsigned char vUnackedKeepalives : 3; unsigned char bServer : 1;
Description
First byte of TX buffer
First byte of RX buffer. TX buffer ends 1 byte prior
Last byte of RX buffer
Head pointer for TX
Tail pointer for TX
Head pointer for RX
Tail pointer for RX
Packet retransmissions, state changes
Window updates, automatic transmission
Delayed Acknowledgement timer
TCP_CLOSE_WAIT timeout timer
State of this socket
Count of how many keepalives have been sent with no response
Socket should return to listening state when closed unsigned char bTimerEnabled : 1; unsigned char bTimer2Enabled : 1; unsigned char bDelayedACKTimerEnabled : 1;
DelayedACK timer is enabled unsigned char bOneSegmentReceived : 1; A segment has been received unsigned char bHalfFullFlush : 1;
Timer is enabled
Second timer is enabled unsigned char bTXASAP : 1; unsigned char bTXASAPWithoutTimerReset : 1;
Flush is for being half full
Transmit as soon as possible (for Flush)
Transmit as soon as possible (for Flush), but do not reset retransmission timers unsigned char bTXFIN : 1; FIN needs to be transmitted
557
10.18 TCP Microchip TCP/IP Stack Help TCP Stack Members unsigned char bSocketReset : 1; unsigned char bSSLHandshaking : 1; unsigned char filler : 2;
WORD_VAL remoteHash;
PTR_BASE sslTxHead;
PTR_BASE sslRxHead;
BYTE sslStubID;
BYTE sslReqMessage;
BYTE vMemoryMedium;
Socket has been reset (self-clearing semaphore)
Socket is in an SSL handshake
Future expansion
Consists of remoteIP, remotePort, localPort for connected sockets. It is a localPort number only for listening server sockets.
Position of data being written in next SSL application record Also serves as cache of localSSLPort when smState = TCP_LISTENING
Position of incoming data not yet handled by SSL
Which sslStub ( see page 523) is associated with this connection
Currently requested SSL message
Which memory medium the TCB is actually stored
Description
TCP Control Block (TCB) stub data storage. Stubs are stored in local PIC RAM for speed. Current size is 34 bytes (PIC18),
36 bytes (PIC24/dsPIC), or 56 (PIC32)
10.18.2.4
TCP_SOCKET Type
File
TCP.h
C typedef
BYTE TCP_SOCKET;
Description
A TCP_SOCKET is stored as a single BYTE
10.18.2.5
TCP_STATE Enumeration
File
TCP.h
C typedef enum
{
TCP_GET_DNS_MODULE,
TCP_DNS_RESOLVE,
TCP_GATEWAY_SEND_ARP,
TCP_GATEWAY_GET_ARP,
TCP_LISTEN,
TCP_SYN_SENT,
TCP_SYN_RECEIVED,
TCP_ESTABLISHED,
TCP_FIN_WAIT_1,
TCP_FIN_WAIT_2,
TCP_CLOSING,
TCP_CLOSE_WAIT,
TCP_LAST_ACK,
TCP_CLOSED,
TCP_CLOSED_BUT_RESERVED
} TCP_STATE;
Members
Members
TCP_GET_DNS_MODULE
TCP_DNS_RESOLVE
TCP_GATEWAY_SEND_ARP
Description
Special state for TCP client mode sockets
Special state for TCP client mode sockets
Special state for TCP client mode sockets
558
10.18 TCP
TCP_GATEWAY_GET_ARP
TCP_LISTEN
TCP_SYN_SENT
TCP_SYN_RECEIVED
TCP_ESTABLISHED
TCP_FIN_WAIT_1
TCP_FIN_WAIT_2
TCP_CLOSING
TCP_CLOSE_WAIT
TCP_LAST_ACK
TCP_CLOSED
TCP_CLOSED_BUT_RESERVED
Description
TCP States as defined by RFC 793
Microchip TCP/IP Stack Help TCP Stack Members
Special state for TCP client mode sockets
Socket is listening for connections
A SYN has been sent, awaiting an SYN+ACK
A SYN has been received, awaiting an ACK
Socket is connected and connection is established
FIN WAIT state 1
FIN WAIT state 2
Socket is closing TCP_TIME_WAIT, state is not implemented
Waiting to close the socket
The final ACK has been sent
Socket is idle and unallocated
Special state for TCP client mode sockets. Socket is idle, but still allocated pending application closure of the handle.
10.18.2.6
TCPInit Function
File
TCP.h
C void
TCPInit();
Returns
None
Description
Initializes the TCP module. This function sets up the TCP buffers in memory and initializes each socket to the CLOSED state. If insufficient memory was allocated for the TCP sockets, the function will hang here to be captured by the debugger.
Remarks
This function is called only one during lifetime of the application.
Preconditions
None
Section
Function Declarations
10.18.2.7
TCPProcess Function
File
TCP.h
C
BOOL TCPProcess(
NODE_INFO* remote,
IP_ADDR* localIP,
WORD len
);
559
10.18 TCP Microchip TCP/IP Stack Help TCP Stack Members
Description
This function handles incoming TCP segments. When a segment arrives, it is compared to open sockets using a hash of the
Preconditions
TCP is initialized and a TCP segment is ready in the MAC buffer.
Parameters
Parameters
remote localIP len
Return Values
Return Values
TRUE
FALSE
Description
Remote NODE_INFO structure
This stack's IP address (for header checking)
Total length of the waiting TCP segment
Description
the segment was properly handled.
otherwise
10.18.2.8
TCPTick Function
File
TCP.h
C void
TCPTick();
Returns
None
Description
This function performs any required periodic TCP tasks. Each socket's state machine is checked, and any elapsed timeout periods are handled.
Preconditions
TCP is initialized.
10.18.2.9
TCPSSLDecryptMAC Function
File
TCP.h
C void
TCPSSLDecryptMAC(
ARCFOUR_CTX* ctx,
WORD len
);
Returns
None
Description
This function decrypts data in the TCP buffer and calculates the MAC over the data. All data is left in the exact same location in the TCP buffer. It is called to help process incoming SSL records.
560
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
Remarks
This function should never be called by an application. It is used only by the SSL module itself.
Preconditions
TCP is initialized, hTCP is connected, and ctx's Sbox is loaded.
Parameters
Parameters
hTCP ctx len inPlace
Description
TCP connection to decrypt in
ARCFOUR encryption context to use
Number of bytes to crypt
TRUE to write back in place, FALSE to write at end of currently visible data.
10.18.2.10
TCPStartSSLClientEx Function
File
TCP.h
C
BOOL TCPStartSSLClientEx(
BYTE* host,
void
* buffer,
BYTE suppDataType
);
Description
This function escalates the current connection to an SSL secured connection by initiating an SSL client handshake.
Remarks
The host parameter is currently ignored and is not validated.
Preconditions
TCP is initialized and hTCP is already connected.
Parameters
Parameters
hTCP host buffer suppDataType
Return Values
Return Values
TRUE
FALSE
Description
TCP connection to secure
Expected host name on certificate (currently ignored)
Buffer for supplementary data return
Type of supplementary data to copy
Description
an SSL connection was initiated
Insufficient SSL resources (stubs) were available
561
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
10.18.3
TCP Internal Members
Functions
Name
Description
Closes a TCP socket.
FindMatchingSocket ( see page 564)
Finds a suitable socket for a TCP segment.
Processes an incoming TCP segment.
Transmits a TPC segment.
Swaps endian-ness of a TCP header.
Flushes MyTCB cache and loads up the specified TCB. Does nothing on cache hit.
Macros
Name
LOCAL_PORT_END_NUMBER ( see page 566)
LOCAL_PORT_START_NUMBER ( see page 566)
SENDTCP_RESET_TIMERS ( see page
Description
Acknowledge Flag as defined in RFC
FIN Flag as defined in RFC
End port for client sockets
Starting port for client sockets
Push Flag as defined in RFC
Reset Flag as defined in RFC
Instead of transmitting normal data, a garbage octet is transmitted according to RFC 1122 section 4.2.3.6
Indicates if this packet is a retransmission (no reset) or a new packet (reset required)
SYN Flag as defined in RFC
Flushes MyTCBStub ( see page 566) cache and loads up the
specified TCB_STUB ( see page 556). Does nothing on cache
hit.
Timeout before automatically transmitting unflushed data
Timeout before automatically transmitting a window update due to
a TCPGet ( see page 542)() or TCPGetArray ( see page 543)()
function call
TCP_CLOSE_WAIT_TIMEOUT ( see page 570)
Timeout for the CLOSE_WAIT state
Timeout for delayed-acknowledgement algorithm
TCP_DELAYED_ACK_TIMEOUT ( see page 570)
TCP_FIN_WAIT_2_TIMEOUT ( see page 571)
TCP_KEEP_ALIVE_TIMEOUT ( see page 572)
TCP_MAX_RETRIES ( see page 572)
Timeout for FIN WAIT 2 state
Timeout for keep-alive messages when no traffic is sent
Maximum number of retransmission attempts
562
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
TCP_MAX_SEG_SIZE_RX ( see page
TCP_MAX_SEG_SIZE_TX ( see page
TCP Maximum Segment Size for RX. This value is advirtised during connection establishment and the remote node should obey it. This should be set to 536 to avoid IP layer fragmentation from causing packet loss. However, raising its value can enhance performance at the (small) risk of introducing incompatibility with certain special remote nodes (ex: ones connected via a slow dial up modem).
TCP Maximum Segment Size for TX. The TX maximum segment size is actually govered by the remote node's MSS option advirtised during connection establishment. However, if the remote node specifies an unhandlably large MSS (ex: > Ethernet
MTU), this define sets a hard limit so that we don't cause any TX buffer overflows. If the remote node does not advirtise a MSS option, all TX segments are fixed at 536 bytes maximum.
Smaller than all other retries to reduce SYN flood DoS duration
TCP_MAX_SYN_RETRIES ( see page
TCP_MAX_UNACKED_KEEP_ALIVES ( see page 573)
TCP_OPTIMIZE_FOR_SIZE ( see page
Maximum number of keep-alive messages that can be sent without receiving a response before automatically closing the connection
For smallest size and best throughput,
TCP_OPTIMIZE_FOR_SIZE should always be enabled on
PIC24/dsPIC products. On PIC32 products there is very little difference and depnds on compiler optimization level
End of List TCP Option Flag
TCP_OPTIONS_END_OF_LIST ( see page 574)
TCP_OPTIONS_MAX_SEG_SIZE ( see page 574)
TCP_SYN_QUEUE_MAX_ENTRIES ( see page 576)
TCP_SYN_QUEUE_TIMEOUT ( see page 576)
Maximum segment size TCP flag
TCP_OPTIONS_NO_OP ( see page 574) No Op TCP Option
TCP_SOCKET_COUNT ( see page 575)
Determines the number of defined TCP sockets
TCP_START_TIMEOUT_VAL ( see page 575)
Timeout to retransmit unacked data
Number of TCP RX SYN packets to save if they cannot be serviced immediately
Timeout for when SYN queue entries are deleted if unserviceable
Urgent Flag as defined in RFC
Module
Structures
Name
Description
TCP Header Data Structure
TCP Options data structure
Structure containing all the important elements of an incomming SYN packet in order to establish a connection at a future time if all sockets on the listening port are already connected to someone
Variables
Name
Description
Current TCP socket
Currently loaded TCB
MyTCBStub ( see page 566) Alias to current TCP stub.
SYNQueue ( see page 569) Array of saved incoming SYN requests that need to be serviced later
563
10.18 TCP Microchip TCP/IP Stack Help
This is variable TCBStubs.
Description
The following functions and variables are designated as internal to the TCP module.
TCP Internal Members
10.18.3.1
ACK Macro
File
TCP.c
C
#define
ACK (0x10)
// Acknowledge Flag as defined in RFC
Description
Acknowledge Flag as defined in RFC
10.18.3.2
CloseSocket Function
File
TCP.c
C static void
CloseSocket();
Returns
None
Description
This function closes a TCP socket. All socket state information is reset, and any buffered bytes are discarded. The socket is no longer accessible by the application after this point.
Preconditions
The TCPStub corresponding to the socket to be closed is synced.
10.18.3.3
FIN Macro
File
TCP.c
C
#define
FIN (0x01)
// FIN Flag as defined in RFC
Description
FIN Flag as defined in RFC
10.18.3.4
FindMatchingSocket Function
File
TCP.c
C static
BOOL FindMatchingSocket(
564
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
NODE_INFO* remote
);
Description
This function searches through the sockets and attempts to match one with a given TCP header and NODE_INFO structure.
Preconditions
TCP is initialized.
Parameters
Parameters
h remote
Return Values
Return Values
TRUE
FALSE
Description
TCP header to be matched against
The remote node who sent this header
Description
A match was found and is loaded in hCurrentTCP ( see page 565)
No suitable socket was found and hCurrentTCP ( see page 565) is
INVALID_SOCKET ( see page 533)
10.18.3.5
HandleTCPSeg Function
File
TCP.c
C static void
HandleTCPSeg(
WORD len
);
Returns
None
Description
Once an incoming segment has been matched to a socket, this function performs the necessary processing with the data.
Depending on the segment and the state, this may include copying data to the TCP buffer, re-assembling out-of order packets, continuing an initialization or closing handshake, or closing the socket altogether.
Preconditions
TCP is initialized and the current TCP stub is already synced.
Parameters
Parameters
h len
Description
The TCP header for this packet
The total buffer length of this segment
10.18.3.6
hCurrentTCP Variable
File
TCP.c
565
10.18 TCP Microchip TCP/IP Stack Help
C
TCP_SOCKET hCurrentTCP = INVALID_SOCKET;
Description
Current TCP socket
10.18.3.7
LOCAL_PORT_END_NUMBER Macro
File
TCP.c
C
#define
LOCAL_PORT_END_NUMBER (5000u)
Description
End port for client sockets
10.18.3.8
LOCAL_PORT_START_NUMBER Macro
File
TCP.c
C
#define
LOCAL_PORT_START_NUMBER (1024u)
Description
Starting port for client sockets
10.18.3.9
MyTCB Variable
File
TCP.c
C
TCB MyTCB;
Description
Currently loaded TCB
10.18.3.10
MyTCBStub Variable
File
TCP.c
C
Description
Alias to current TCP stub.
TCP Internal Members
566
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
10.18.3.11
PSH Macro
File
TCP.c
C
#define
PSH (0x08)
// Push Flag as defined in RFC
Description
Push Flag as defined in RFC
10.18.3.12
RST Macro
File
TCP.c
C
#define
RST (0x04)
// Reset Flag as defined in RFC
Description
Reset Flag as defined in RFC
10.18.3.13
SendTCP Function
File
TCP.c
C static void
SendTCP(
BYTE vTCPFlags,
BYTE vSendFlags
);
Returns
None
Description
This function assembles and transmits a TCP segment, including any pending data. It also supports retransmissions, keep-alives, and other packet types.
Preconditions
TCP is initialized.
Parameters
Parameters
vTCPFlags vSendFlags
Description
Additional TCP flags to include
Any combinations of SENDTCP_* constants to modify the transmit behavior or contents.
567
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
10.18.3.14
SENDTCP_KEEP_ALIVE Macro
File
TCP.c
C
#define
SENDTCP_KEEP_ALIVE 0x02
Description
Instead of transmitting normal data, a garbage octet is transmitted according to RFC 1122 section 4.2.3.6
10.18.3.15
SENDTCP_RESET_TIMERS Macro
File
TCP.c
C
#define
SENDTCP_RESET_TIMERS 0x01
Description
Indicates if this packet is a retransmission (no reset) or a new packet (reset required)
10.18.3.16
SwapTCPHeader Function
File
TCP.c
C static void
SwapTCPHeader(
);
Returns
None
Description
This function swaps the endian-ness of a given TCP header for comparison.
Preconditions
None
Parameters
Parameters
header
Description
The TCP header that is to be swapped
10.18.3.17
SYN Macro
File
TCP.c
C
#define
SYN (0x02)
// SYN Flag as defined in RFC
568
10.18 TCP
Description
SYN Flag as defined in RFC
Microchip TCP/IP Stack Help TCP Internal Members
10.18.3.18
SyncTCB Function
File
TCP.c
C static void
SyncTCB();
Description
Flushes MyTCB cache and loads up the specified TCB. Does nothing on cache hit.
10.18.3.19
SyncTCBStub Macro
File
TCP.c
C
#define
SyncTCBStub(a) hCurrentTCP = (a)
Description
cache hit.
10.18.3.20
SYNQueue Variable
File
TCP.c
C
TCP_SYN_QUEUE SYNQueue[TCP_SYN_QUEUE_MAX_ENTRIES];
Description
Array of saved incoming SYN requests that need to be serviced later
10.18.3.21
TCBStubs Variable
File
TCP.c
C
TCB_STUB TCBStubs[TCP_SOCKET_COUNT];
Description
This is variable TCBStubs.
569
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
10.18.3.22
TCP_AUTO_TRANSMIT_TIMEOUT_VAL Macro
File
TCP.c
C
#define
TCP_AUTO_TRANSMIT_TIMEOUT_VAL (TICK_SECOND/25ull)
// Timeout before automatically transmitting unflushed data
Description
Timeout before automatically transmitting unflushed data
10.18.3.23
TCP_WINDOW_UPDATE_TIMEOUT_VAL Macro
File
TCP.c
C
#define
TCP_WINDOW_UPDATE_TIMEOUT_VAL (TICK_SECOND/5ull)
// Timeout before automatically transmitting a window update due to a TCPGet() or TCPGetArray() function call
Description
10.18.3.24
TCP_CLOSE_WAIT_TIMEOUT Macro
File
TCP.c
C
#define
TCP_CLOSE_WAIT_TIMEOUT ((DWORD)TICK_SECOND/5)
// Timeout for the CLOSE_WAIT state
Description
Timeout for the CLOSE_WAIT state
10.18.3.25
TCP_DELAYED_ACK_TIMEOUT Macro
File
TCP.c
C
#define
TCP_DELAYED_ACK_TIMEOUT ((DWORD)TICK_SECOND/10)
// Timeout for delayed-acknowledgement algorithm
Description
Timeout for delayed-acknowledgement algorithm
570
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members
10.18.3.26
TCP_FIN_WAIT_2_TIMEOUT Macro
File
TCP.c
C
#define
TCP_FIN_WAIT_2_TIMEOUT ((DWORD)TICK_SECOND*5)
// Timeout for FIN WAIT 2 state
Description
Timeout for FIN WAIT 2 state
10.18.3.27
TCP_HEADER Structure
File
TCP.c
C typedef struct
{
WORD SourcePort;
WORD DestPort;
DWORD SeqNumber;
DWORD AckNumber;
struct
{
unsigned char
Reserved3 : 4;
unsigned char
Val : 4;
} DataOffset;
union
{
struct
{
unsigned char
flagFIN : 1;
unsigned char
flagSYN : 1;
unsigned char
flagRST : 1;
unsigned char
flagPSH : 1;
unsigned char
flagACK : 1;
unsigned char
flagURG : 1;
unsigned char
Reserved2 : 2;
} bits;
BYTE byte;
} Flags;
WORD Window;
WORD Checksum;
WORD UrgentPointer;
} TCP_HEADER;
Members
Members
WORD SourcePort;
WORD DestPort;
DWORD SeqNumber;
DWORD AckNumber; struct { unsigned char Reserved3 : 4; unsigned char Val : 4;
} DataOffset;
Description
Local port number
Remote port number
Local sequence number
Acknowledging remote sequence number
Data offset flags nibble
571
10.18 TCP union { struct { unsigned char flagFIN : 1; unsigned char flagSYN : 1; unsigned char flagRST : 1; unsigned char flagPSH : 1; unsigned char flagACK : 1; unsigned char flagURG : 1; unsigned char Reserved2 : 2;
} bits;
BYTE byte;
} Flags;
WORD Window;
WORD Checksum;
WORD UrgentPointer;
Description
TCP Header Data Structure
Microchip TCP/IP Stack Help
TCP Flags as defined in RFC
Local free RX buffer window
Data payload checksum
Urgent pointer
TCP Internal Members
10.18.3.28
TCP_KEEP_ALIVE_TIMEOUT Macro
File
TCP.c
C
#define
TCP_KEEP_ALIVE_TIMEOUT ((DWORD)TICK_SECOND*10)
// Timeout for keep-alive messages when no traffic is sent
Description
Timeout for keep-alive messages when no traffic is sent
10.18.3.29
TCP_MAX_RETRIES Macro
File
TCP.c
C
#define
TCP_MAX_RETRIES (5u)
// Maximum number of retransmission attempts
Description
Maximum number of retransmission attempts
10.18.3.30
TCP_MAX_SEG_SIZE_RX Macro
File
TCP.c
C
#define
TCP_MAX_SEG_SIZE_RX (536u)
Description
TCP Maximum Segment Size for RX. This value is advirtised during connection establishment and the remote node should obey it. This should be set to 536 to avoid IP layer fragmentation from causing packet loss. However, raising its value can
572
10.18 TCP Microchip TCP/IP Stack Help TCP Internal Members enhance performance at the (small) risk of introducing incompatibility with certain special remote nodes (ex: ones connected via a slow dial up modem).
10.18.3.31
TCP_MAX_SEG_SIZE_TX Macro
File
TCP.c
C
#define
TCP_MAX_SEG_SIZE_TX (1460u)
Description
TCP Maximum Segment Size for TX. The TX maximum segment size is actually govered by the remote node's MSS option advirtised during connection establishment. However, if the remote node specifies an unhandlably large MSS (ex: > Ethernet
MTU), this define sets a hard limit so that we don't cause any TX buffer overflows. If the remote node does not advirtise a
MSS option, all TX segments are fixed at 536 bytes maximum.
10.18.3.32
TCP_MAX_SYN_RETRIES Macro
File
TCP.c
C
#define
TCP_MAX_SYN_RETRIES (2u)
// Smaller than all other retries to reduce SYN flood
DoS duration
Description
Smaller than all other retries to reduce SYN flood DoS duration
10.18.3.33
TCP_MAX_UNACKED_KEEP_ALIVES Macro
File
TCP.c
C
#define
TCP_MAX_UNACKED_KEEP_ALIVES (6u)
// Maximum number of keep-alive messages that can be sent without receiving a response before automatically closing the connection
Description
Maximum number of keep-alive messages that can be sent without receiving a response before automatically closing the connection
10.18.3.34
TCP_OPTIMIZE_FOR_SIZE Macro
File
TCP.c
C
#define
TCP_OPTIMIZE_FOR_SIZE
Description
For smallest size and best throughput, TCP_OPTIMIZE_FOR_SIZE should always be enabled on PIC24/dsPIC products.
573
10.18 TCP Microchip TCP/IP Stack Help
On PIC32 products there is very little difference and depnds on compiler optimization level
10.18.3.35
TCP_OPTIONS Structure
File
TCP.c
C typedef struct
{
BYTE Kind;
BYTE Length;
WORD_VAL MaxSegSize;
} TCP_OPTIONS;
Members
Members
BYTE Kind;
BYTE Length;
WORD_VAL MaxSegSize;
Description
TCP Options data structure
Description
Type of option
Length
Maximum segment size
TCP Internal Members
10.18.3.36
TCP_OPTIONS_END_OF_LIST Macro
File
TCP.c
C
#define
TCP_OPTIONS_END_OF_LIST (0x00u)
// End of List TCP Option Flag
Description
End of List TCP Option Flag
10.18.3.37
TCP_OPTIONS_MAX_SEG_SIZE Macro
File
TCP.c
C
#define
TCP_OPTIONS_MAX_SEG_SIZE (0x02u)
// Maximum segment size TCP flag
Description
Maximum segment size TCP flag
10.18.3.38
TCP_OPTIONS_NO_OP Macro
File
TCP.c
C
#define
TCP_OPTIONS_NO_OP (0x01u)
// No Op TCP Option
574
10.18 TCP
Description
No Op TCP Option
Microchip TCP/IP Stack Help TCP Internal Members
10.18.3.39
TCP_SOCKET_COUNT Macro
File
TCP.c
C
#define
TCP_SOCKET_COUNT (
sizeof
(TCPSocketInitializer)/
sizeof
(TCPSocketInitializer[0]))
Description
Determines the number of defined TCP sockets
10.18.3.40
TCP_START_TIMEOUT_VAL Macro
File
TCP.c
C
#define
TCP_START_TIMEOUT_VAL ((DWORD)TICK_SECOND*1)
// Timeout to retransmit unacked data
Description
Timeout to retransmit unacked data
10.18.3.41
TCP_SYN_QUEUE Structure
File
TCP.c
C typedef struct
{
NODE_INFO niSourceAddress;
WORD wSourcePort;
DWORD dwSourceSEQ;
WORD wDestPort;
WORD wTimestamp;
} TCP_SYN_QUEUE;
Members
Members
NODE_INFO niSourceAddress;
WORD wSourcePort;
DWORD dwSourceSEQ;
WORD wDestPort;
WORD wTimestamp;
Description
Remote IP address and MAC address
Remote TCP port number that the response SYN needs to be sent to
Remote TCP SEQuence number that must be ACKnowledged when we send our response SYN
Local TCP port which the original SYN was destined for
Timer to expire old SYN packets that can't be serviced at all
Description
Structure containing all the important elements of an incomming SYN packet in order to establish a connection at a future time if all sockets on the listening port are already connected to someone
575
10.18 TCP Microchip TCP/IP Stack Help Functions
10.18.3.42
TCP_SYN_QUEUE_MAX_ENTRIES Macro
File
TCP.c
C
#define
TCP_SYN_QUEUE_MAX_ENTRIES (3u)
// Number of TCP RX SYN packets to save if they cannot be serviced immediately
Description
Number of TCP RX SYN packets to save if they cannot be serviced immediately
10.18.3.43
TCP_SYN_QUEUE_TIMEOUT Macro
File
TCP.c
C
#define
TCP_SYN_QUEUE_TIMEOUT ((DWORD)TICK_SECOND*3)
// Timeout for when SYN queue entries are deleted if unserviceable
Description
Timeout for when SYN queue entries are deleted if unserviceable
10.18.3.44
URG Macro
File
TCP.c
C
#define
URG (0x20)
// Urgent Flag as defined in RFC
Description
Urgent Flag as defined in RFC
10.18.4
Functions
Functions
Name
Description
This is function WFGetTCBSize.
Module
10.18.4.1
WFGetTCBSize Function
File
TCP.c
576
10.19 Telnet
C
UINT16 WFGetTCBSize();
Description
This is function WFGetTCBSize.
Microchip TCP/IP Stack Help
10.18.5
Variables
Module
Variables
Name
Description
Tracking variable for next local client port number
10.18.5.1
NextPort Variable
File
TCP.c
C
WORD NextPort;
Description
Tracking variable for next local client port number
Telnet Public Members
10.19
Telnet
Telnet provides bidirectional, interactive communication between two nodes on the Internet or on a Local Area Network. The
Telnet code included with Microchip's TCP/IP stack is a demonstration of the structure of a Telnet application. This demo begins by listening for a Telnet connection. When a client attempts to make one, the demo will prompt the client for a username and password, and if the correct one is provided, will output and periodically refresh several values obtained from the demo board.
There are several changes that you may need to make to
Telnet.c
and/or
Telnet.h
to suit your application. All of the
Telnet Public members can be re-defined in the application-specific section of
TCPIPConfig.h
. You may also wish to change some of the Telnet Internal Member strings, located in
Telnet.c
, to more accurately reflect your application. You will also need to modify the
function to include the functionality you'd like. You may
577
10.19 Telnet Microchip TCP/IP Stack Help Telnet Public Members
10.19.1
Telnet Public Members
Macros
Name Description
Number of simultaneously allowed Telnet ( see page 577) sessions. Note
that you must have an equal number of TCP_PURPOSE_TELNET type TCP sockets declared in the TCPSocketInitializer[] array above for multiple connections to work. If fewer sockets are available than this definition, then the the lesser of the two quantities will be the actual limit.
Default Telnet ( see page 577) password
TELNET_PASSWORD ( see page 578)
TELNET_USERNAME ( see page 579)
Default local listening port for the Telnet ( see page 577) server. Port 23 is
the protocol default.
Default local listening port for the Telnet ( see page 577) server when SSL
secured. Port 992 is the telnets protocol default.
Default username and password required to login to the Telnet ( see page
Module
Description
The following functions and variables are available to the stack application.
10.19.1.1
MAX_TELNET_CONNECTIONS Macro
File
TCPIP MRF24W.h
C
#define
MAX_TELNET_CONNECTIONS (1u)
Description
TCP_PURPOSE_TELNET type TCP sockets declared in the TCPSocketInitializer[] array above for multiple connections to work. If fewer sockets are available than this definition, then the the lesser of the two quantities will be the actual limit.
10.19.1.2
TELNET_PASSWORD Macro
File
TCPIP MRF24W.h
C
#define
TELNET_PASSWORD "microchip"
Description
Default Telnet ( see page 577) password
578
10.19 Telnet Microchip TCP/IP Stack Help Telnet Stack Members
10.19.1.3
TELNET_PORT Macro
File
TCPIP MRF24W.h
C
#define
TELNET_PORT 23
Description
Default local listening port for the Telnet ( see page 577) server. Port 23 is the protocol default.
10.19.1.4
TELNETS_PORT Macro
File
TCPIP MRF24W.h
C
#define
TELNETS_PORT 992
Description
10.19.1.5
TELNET_USERNAME Macro
File
TCPIP MRF24W.h
C
#define
TELNET_USERNAME "admin"
Description
Default username and password required to login to the Telnet ( see page 577) server.
10.19.2
Telnet Stack Members
Functions
Name Description
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
579
10.19 Telnet Microchip TCP/IP Stack Help Telnet Internal Members
10.19.2.1
TelnetTask Function
File
Telnet.h
C void
TelnetTask();
Side Effects
None
Returns
None
Description
tracking variables.
Remarks
None
Preconditions
Stack is initialized()
10.19.3
Telnet Internal Members
Module
Variables
Name Description
String with extra spaces, for Demo
Successful authentication message
Demo output string
strGoodBye ( see page 581) Demo disconnection message strPassword ( see page
DO Suppress Local Echo (stop telnet client from printing typed characters)
Access denied message
Demo title string
Description
10.19.3.1
strSpaces Variable
File
Telnet.c
C
ROM BYTE strSpaces[] = " ";
580
10.19 Telnet
Description
String with extra spaces, for Demo
Microchip TCP/IP Stack Help Telnet Internal Members
10.19.3.2
strAuthenticated Variable
File
Telnet.c
C
ROM BYTE strAuthenticated[] = "\r\nLogged in successfully\r\n\r\n" "\r\nPress 'q' to quit\r\n";
Description
Successful authentication message
10.19.3.3
strDisplay Variable
File
Telnet.c
C
ROM BYTE strDisplay[] = "\r\nSNTP Time: (disabled)" "\r\nAnalog: 1023"
"\r\nButtons: 3 2 1 0" "\r\nLEDs: 7 6 5 4 3 2 1 0";
Description
Demo output string
10.19.3.4
strGoodBye Variable
File
Telnet.c
C
ROM BYTE strGoodBye[] = "\r\n\r\nGoodbye!\r\n";
Description
Demo disconnection message
10.19.3.5
strPassword Variable
File
Telnet.c
C
ROM BYTE strPassword[] = "Password: \xff\xfd\x2d";
Description
DO Suppress Local Echo (stop telnet client from printing typed characters) Access denied message
581
10.20 TFTP Microchip TCP/IP Stack Help
10.19.3.6
strTitle Variable
File
Telnet.c
C
ROM BYTE strTitle[] = "\x1b[2J\x1b[31m\x1b[1m" "Microchip Telnet Server 1.1\x1b[0m\r\n"
"(for this demo, type 'admin' for the login and 'microchip' for the password.)\r\n" "Login:
";
Description
Demo title string
10.20
TFTP
The Trivial File Transfer Protocol provides unreliable upload and download services to applications connected to the
UDP-based TFTP server.
582
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
10.20.1
TFTP Public Members
Enumerations
Name
TFTP_ACCESS_ERROR ( see page 592)
TFTP_FILE_MODE ( see page 592)
_TFTP_FILE_MODE ( see page 592)
Description
Standard error codes as defined by TFTP spec. Use to decode value retuned
by TFTPGetError ( see page 586)().
Standard error codes as defined by TFTP spec. Use to decode value retuned
by TFTPGetError ( see page 586)().
File open mode as used by TFTPFileOpen().
File open mode as used by TFTPFileOpen().
Enum. of results returned by most of the TFTP functions.
583
10.20 TFTP
Microchip TCP/IP Stack Help
Enum. of results returned by most of the TFTP functions.
TFTP Public Members
Functions
Name
TFTPIsFileClosed ( see page 587)
Description
Sends file closing messages.
Gets a data byte from data that was read.
Determines if the file was closed.
TFTPIsFileOpened ( see page 587)
TFTPIsGetReady ( see page 588)
Determines if file has been opened.
Determines if a data block is ready to be read.
Determines if the TFTP connection is open.
TFTPIsPutReady ( see page 589)
Determines if data can be written to a file.
Initializes TFTP module.
Prepares and sends TFTP file name and mode packet.
TFTPOpenROMFile ( see page 591) PIC18 ROM argument implementation of TFTPOpenFile ( see page 591)
Write a byte to a file.
TFTPGetUploadStatus ( see page 593) Returns the TFTP file upload status started by calling the
TFTPUploadRAMFileToHost ( see page 595)() or
TFTPUploadFragmentedRAMFileToHost ( see page 594)()
functions.
TFTPUploadFragmentedRAMFileToHost
Uploads an random, potentially non-contiguous, array of RAM bytes as a file to a remote TFTP server.
TFTPUploadRAMFileToHost ( see page 595)
Uploads a contiguous array of RAM bytes as a file to a remote TFTP server.
Macros
Name
TFTPIsFileOpenReady ( see page 588)
Description
Macro: void TFTPClose(void)
Closes TFTP client socket.
Macro: WORD TFTPGetError(void)
Returns previously saved error code.
Macro: BOOL TFTPIsFileOpenReady(void)
Checks to see if it is okay to send TFTP file open request to remote server.
TFTP_UPLOAD_COMPLETE ( see page
Status codes for TFTPGetUploadStatus ( see page 593)()
function. Zero means upload success, >0 means working and
<0 means fatal error.
TFTP_UPLOAD_CONNECT ( see page 596) This is macro TFTP_UPLOAD_CONNECT.
TFTP_UPLOAD_CONNECT_TIMEOUT ( see page 596)
This is macro TFTP_UPLOAD_CONNECT_TIMEOUT.
TFTP_UPLOAD_GET_DNS ( see page 596)
This is macro TFTP_UPLOAD_GET_DNS.
TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT
This is macro TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT.
TFTP_UPLOAD_RESOLVE_HOST ( see page 597)
This is macro TFTP_UPLOAD_RESOLVE_HOST.
584
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
TFTP_UPLOAD_SEND_DATA ( see page
TFTP_UPLOAD_SEND_FILENAME ( see page 597)
TFTP_UPLOAD_SERVER_ERROR ( see page 597)
TFTP_UPLOAD_WAIT_FOR_CLOSURE ( see page 598)
Module
This is macro TFTP_UPLOAD_SEND_DATA.
This is macro TFTP_UPLOAD_SEND_FILENAME.
This is macro TFTP_UPLOAD_SERVER_ERROR.
This is macro TFTP_UPLOAD_WAIT_FOR_CLOSURE.
Structures
Name Description
This is type TFTP_CHUNK_DESCRIPTOR.
Description
The following functions and variables are available to the stack application.
10.20.1.1
TFTPClose Macro
File
TFTPc.h
C
#define
TFTPClose(
void
Side Effects
None
Returns
None
Description
Macro: void TFTPClose(void)
Closes TFTP client socket.
Remarks
Once closed, application must do TFTPOpen ( see page 590) to perform any new TFTP operations.
If TFTP server does not change during application life-time, one may not need to call TFTPClose and keep TFTP socket open.
Preconditions
TFTPOpen ( see page 590) is already called and TFTPIsOpened ( see page 589)() returned TFTP_OK.
10.20.1.2
TFTPCloseFile Function
File
TFTPc.h
C void
TFTPCloseFile();
585
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
Side Effects
None
Returns
None
Description
If file is opened in read mode, it makes sure that last ACK is sent to server If file is opened in write mode, it makes sure that last block is sent out to server and waits for server to respond with ACK.
Remarks
TFTPIsFileClosed ( see page 587)() must be called to confirm if file was really closed.
Preconditions
10.20.1.3
TFTPGet Function
File
TFTPc.h
C
BYTE TFTPGet();
Side Effects
None
Returns
data byte as received from remote server.
Description
Fetches next data byte from TFTP socket. If end of data block is reached, it issues ack to server so that next data block can be received.
Remarks
Use this function to read file from server.
Preconditions
TRUE
10.20.1.4
TFTPGetError Macro
File
TFTPc.h
C
#define
Side Effects
None
Returns
standard error code.
586
10.20 TFTP Microchip TCP/IP Stack Help
Description
Macro: WORD TFTPGetError(void)
Returns previously saved error code.
Remarks
None
Preconditions
One of the TFTP function returned with TFTP_ERROR result.
TFTP Public Members
10.20.1.5
TFTPIsFileClosed Function
File
TFTPc.h
C
TFTP_RESULT TFTPIsFileClosed();
Side Effects
None
Returns
TFTP_OK if file was successfully closdd
TFTP_RETRY if file mode was Write and remote server did not receive last packet. Application must retry with last block.
TFTP_TIMEOUT if all attempts were exhausted in closing file.
TFTP_ERROR if remote server sent an error in response to last block. Actual error code may be read by calling
TFTPGetError ( see page 586)()
TFTP_NOT_READY if file is not closed yet.
Description
If file mode is Read, it simply makes that last block is acknowledged. If file mode is Write, it waits for server ack. If no ack was received within specified timeout instructs appliaction to resend last block. It keeps track of retries and declares timeout all attempts were exhausted.
Remarks
None
Preconditions
TFTPCloseFile ( see page 585)() is already called.
10.20.1.6
TFTPIsFileOpened Function
File
TFTPc.h
C
TFTP_RESULT TFTPIsFileOpened();
Side Effects
None
587
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
Returns
TFTP_OK if file is ready to be read or written
TFTP_RETRY if previous attempt was timed out needs to be retried.
TFTP_TIMEOUT if all attempts were exhausted.
TFTP_ERROR if remote server responded with error
TFTP_NOT_READY if file is not yet opened.
Description
Waits for remote server response regarding previous attempt to open file. If no response is received within specified timeout, fnction returns with TFTP_RETRY and application logic must issue another TFTPFileOpen().
Remarks
None
Preconditions
TFTPOpenFile ( see page 591)() is called.
10.20.1.7
TFTPIsFileOpenReady Macro
File
TFTPc.h
C
#define
TFTPIsFileOpenReady UDPIsPutReady(_tftpSocket)
Side Effects
None
Returns
TRUE, if it is ok to call TFTPOpenFile ( see page 591)() FALSE, if otherwise.
Description
Macro: BOOL TFTPIsFileOpenReady(void)
Checks to see if it is okay to send TFTP file open request to remote server.
Remarks
None
Preconditions
TFTPOpen ( see page 590) is already called and TFTPIsOpened ( see page 589)() returned TFTP_OK.
10.20.1.8
TFTPIsGetReady Function
File
TFTPc.h
C
Side Effects
None
588
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
Returns
TFTP_OK if it there is more data byte available to read
TFTP_TIMEOUT if timeout occurred waiting for new data.
TFTP_END_OF_FILE if end of file has reached.
TFTP_NOT_READY if still waiting for new data.
Description
Waits for data block. If data block does not arrive within specified timeout, it automatically sends out ack for previous block to remind server to send next data block. If all attempts are exhausted, it returns with TFTP_TIMEOUT.
Remarks
By default, this funciton uses "octet" or binary mode of file transfer.
Preconditions
returned with TRUE.
10.20.1.9
TFTPIsOpened Function
File
TFTPc.h
C
Side Effects
None
Returns
TFTP_OK if previous call to TFTPOpen ( see page 590) is complete
TFTP_TIMEOUT if remote host did not respond to previous ARP request.
TFTP_NOT_READY if remote has still not responded and timeout has not expired.
Description
Waits for ARP reply and opens a UDP socket to perform further TFTP operations.
Remarks
operations.
Preconditions
TFTPOpen ( see page 590)() is already called.
10.20.1.10
TFTPIsPutReady Function
File
TFTPc.h
589
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
C
Side Effects
None
Returns
TFTP_OK if it is okay to write more data byte.
TFTP_TIMEOUT if timeout occurred waiting for ack from server
TFTP_RETRY if all server did not send ack on time and application needs to resend last block.
TFTP_NOT_READY if still waiting...
Description
Waits for ack from server. If ack does not arrive within specified timeout, it it instructs application to retry last block by returning TFTP_RETRY.
If all attempts are exhausted, it returns with TFTP_TIMEOUT.
Remarks
None
Preconditions
returned with TRUE.
10.20.1.11
TFTPOpen Function
File
TFTPc.h
C void
TFTPOpen(
IP_ADDR * host
);
Side Effects
None
Returns
None
Description
Initiates ARP for given host and prepares TFTP module for next sequence of function calls.
Remarks
Use TFTPIsOpened ( see page 589)() to check if a connection was successfully opened or not.
Preconditions
UDP module is already initialized and at least one UDP socket is available.
590
10.20 TFTP
Parameters
Parameters
host
Microchip TCP/IP Stack Help
Description
IP address of remote TFTP server
TFTP Public Members
10.20.1.12
TFTPOpenFile Function
File
TFTPc.h
C void
TFTPOpenFile(
BYTE * fileName,
);
Side Effects
None
Returns
None
Description
Prepares and sends TFTP file name and mode packet.
Remarks
file is ready to be read or written.
Preconditions
TFPTIsFileOpenReady() = TRUE
Parameters
Parameters
fileName mode
Description
File name that is to be opened.
Mode of file access Must be TFTP_FILE_MODE_READ for read
TFTP_FILE_MODE_WRITE for write
10.20.1.13
TFTPOpenROMFile Function
File
TFTPc.h
C void
TFTPOpenROMFile(
ROM BYTE * fileName,
);
Description
PIC18 ROM argument implementation of TFTPOpenFile ( see page 591)
591
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
10.20.1.14
TFTPPut Function
File
TFTPc.h
C void
TFTPPut(
BYTE c
);
Side Effects
None
Returns
None
Description
Puts given data byte into TFTP socket. If end of data block is reached, it transmits entire block.
Remarks
Use this function to write file to server.
Preconditions
TRUE
Parameters
Parameters
c
Description
Data byte that is to be written
10.20.1.15
TFTP_ACCESS_ERROR Enumeration
File
TFTPc.h
C typedef enum
_TFTP_ACCESS_ERROR {
TFTP_ERROR_NOT_DEFINED = 0,
TFTP_ERROR_FILE_NOT_FOUND,
TFTP_ERROR_ACCESS_VIOLATION,
TFTP_ERROR_DISK_FULL,
TFTP_ERROR_INVALID_OPERATION,
TFTP_ERROR_UNKNOWN_TID,
TFTP_ERROR_FILE_EXISTS,
TFTP_ERROR_NO_SUCH_USE
} TFTP_ACCESS_ERROR;
Description
10.20.1.16
TFTP_FILE_MODE Enumeration
File
TFTPc.h
592
10.20 TFTP
C typedef enum
_TFTP_FILE_MODE {
TFTP_FILE_MODE_READ = 1,
TFTP_FILE_MODE_WRITE = 2
} TFTP_FILE_MODE;
Description
File open mode as used by TFTPFileOpen().
Microchip TCP/IP Stack Help TFTP Public Members
10.20.1.17
TFTP_RESULT Enumeration
File
TFTPc.h
C typedef enum
_TFTP_RESULT {
TFTP_OK = 0,
TFTP_NOT_READY,
TFTP_END_OF_FILE,
TFTP_ERROR,
TFTP_RETRY,
TFTP_TIMEOUT
} TFTP_RESULT;
Description
Enum. of results returned by most of the TFTP functions.
10.20.1.18
TFTPGetUploadStatus Function
File
TFTPc.h
C
CHAR TFTPGetUploadStatus();
Returns
A status code. Negative results are fatal errors. Positive results indicate the TFTP upload operation is still being processed.
A zero result indicates successful file upload completion (TFTP API is now idle and available for further calls). Specific return
values are as follows: 0 (TFTP_UPLOAD_COMPLETE ( see page 596)): Upload completed successfully 1
(TFTP_UPLOAD_GET_DNS ( see page 596)):
Attempting to obtain DNS client module 2
(TFTP_UPLOAD_RESOLVE_HOST ( see page 597)):
Attempting to resolve TFTP hostname 3
(TFTP_UPLOAD_CONNECT ( see page 596)): Attempting to ARP and contact the TFTP server 4
acknowledgement. -1 (TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT ( see page 597)): Couldn't resolve hostname -2
(TFTP_UPLOAD_CONNECT_TIMEOUT ( see page 596)):
Couldn't finish ARP and reach server -3
failed due to a timeout (partial file may have been uploaded).
Description
TFTPUploadFragmentedRAMFileToHost ( see page 594)() functions.
Remarks
The DNS client module must be enabled to use this function. i.e. STACK_USE_DNS must be defined in TCPIPConfig.h.
593
10.20 TFTP
Preconditions
None
Microchip TCP/IP Stack Help TFTP Public Members
10.20.1.19
TFTPUploadFragmentedRAMFileToHost Function
File
TFTPc.h
C void
TFTPUploadFragmentedRAMFileToHost(
ROM BYTE * vRemoteHost,
ROM BYTE * vFilename,
TFTP_CHUNK_DESCRIPTOR * vFirstChunkDescriptor
);
Returns
None
Description
Uploads an random, potentially non-contiguous, array of RAM bytes as a file to a remote TFTP server.
Remarks
The DNS client module must be enabled to use this function. i.e. STACK_USE_DNS must be defined in TCPIPConfig.h.
Call the TFTPGetUploadStatus ( see page 593)() function to determine the status of the file upload.
It is only possible to have one TFTP operation active at any given time. After starting a TFTP operation by calling
functions.
Preconditions
None
Parameters
Parameters
vRemoteHost vFilename vFirstChunkDescriptor
Description
ROM string of the remote TFTP server to upload to (ex: "www.myserver.com").
For device architectures that make no distinction between RAM and ROM pointers (PIC24, dsPIC and PIC32), this string must remain allocated and unmodified in RAM until the TFTP upload process completes (as indicated by
TFTPGetUploadStatus ( see page 593)()).
ROM string of the remote file to create/overwrite (ex: "status.txt"). For device architectures that make no distinction between RAM and ROM pointers (PIC24, dsPIC and PIC32), this string must remain allocated and unmodified in RAM until the TFTP upload process completes (as indicated by
TFTPGetUploadStatus ( see page 593)()).
Pointer to a static or global (persistent) array of TFTP_CHUNK_DESCRIPTOR
( see page 595) structures describing what RAM memory addresses the file
contents should be obtained from. The
TFTP_CHUNK_DESCRIPTOR.vDataPointer field should be set to the memory address of the data to transmit, and the
TFTP_CHUNK_DESCRIPTOR.wDataLength field should be set to the number
of bytes to transmit from the given pointer. The TFTP_CHUNK_DESCRIPTOR
( see page 595) array must be terminated by a dummy descriptor whos
TFTP_CHUNK_DESCRIPTOR.vDataPointer pointer is set to NULL. Refer to
the TFTPUploadRAMFileToHost ( see page 595)() API for an example calling
sequence since it merely a wrapper to this
TFTPUploadFragmentedRAMFileToHost() function.
594
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
10.20.1.20
TFTPUploadRAMFileToHost Function
File
TFTPc.h
C void
TFTPUploadRAMFileToHost(
ROM BYTE * vRemoteHost,
ROM BYTE * vFilename,
BYTE * vData,
WORD wDataLength
);
Returns
None
Description
Uploads a contiguous array of RAM bytes as a file to a remote TFTP server.
Remarks
The DNS client module must be enabled to use this function. i.e. STACK_USE_DNS must be defined in TCPIPConfig.h.
Call the TFTPGetUploadStatus ( see page 593)() function to determine the status of the file upload.
It is only possible to have one TFTP operation active at any given time. After starting a TFTP operation by calling
functions.
Preconditions
None
Parameters
Parameters
vRemoteHost vFilename vData wDataLength
Description
ROM string of the remote TFTP server to upload to (ex: "www.myserver.com").
For device architectures that make no distinction between RAM and ROM pointers (PIC24, dsPIC and PIC32), this string must remain allocated and unmodified in RAM until the TFTP upload process completes (as indicated by
TFTPGetUploadStatus ( see page 593)()).
ROM string of the remote file to create/overwrite (ex: "status.txt"). For device architectures that make no distinction between RAM and ROM pointers (PIC24, dsPIC and PIC32), this string must remain allocated and unmodified in RAM until the TFTP upload process completes (as indicated by
TFTPGetUploadStatus ( see page 593)()).
Pointer to a RAM array of data to write to the file.
Number of bytes pointed to by vData. This will be the final file size of the uploaded file. Note that since this is defined as a WORD type, the maximum possible file size is 65535 bytes. For longer files, call the
TFTPUploadFragmentedRAMFileToHost ( see page 594)() function instead.
10.20.1.21
TFTP_CHUNK_DESCRIPTOR Structure
File
TFTPc.h
C typedef struct
{
595
10.20 TFTP
BYTE * vDataPointer;
WORD wDataLength;
} TFTP_CHUNK_DESCRIPTOR;
Description
This is type TFTP_CHUNK_DESCRIPTOR.
Microchip TCP/IP Stack Help TFTP Public Members
10.20.1.22
TFTP_UPLOAD_COMPLETE Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_COMPLETE 0
Description
<0 means fatal error.
10.20.1.23
TFTP_UPLOAD_CONNECT Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_CONNECT 3
Description
This is macro TFTP_UPLOAD_CONNECT.
10.20.1.24
TFTP_UPLOAD_CONNECT_TIMEOUT Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_CONNECT_TIMEOUT -2
Description
This is macro TFTP_UPLOAD_CONNECT_TIMEOUT.
10.20.1.25
TFTP_UPLOAD_GET_DNS Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_GET_DNS 1
Description
This is macro TFTP_UPLOAD_GET_DNS.
596
10.20 TFTP Microchip TCP/IP Stack Help TFTP Public Members
10.20.1.26
TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT -1
Description
This is macro TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT.
10.20.1.27
TFTP_UPLOAD_RESOLVE_HOST Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_RESOLVE_HOST 2
Description
This is macro TFTP_UPLOAD_RESOLVE_HOST.
10.20.1.28
TFTP_UPLOAD_SEND_DATA Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_SEND_DATA 5
Description
This is macro TFTP_UPLOAD_SEND_DATA.
10.20.1.29
TFTP_UPLOAD_SEND_FILENAME Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_SEND_FILENAME 4
Description
This is macro TFTP_UPLOAD_SEND_FILENAME.
10.20.1.30
TFTP_UPLOAD_SERVER_ERROR Macro
File
TFTPc.h
597
10.20 TFTP Microchip TCP/IP Stack Help
C
#define
TFTP_UPLOAD_SERVER_ERROR -3
Description
This is macro TFTP_UPLOAD_SERVER_ERROR.
TFTP Stack Members
10.20.1.31
TFTP_UPLOAD_WAIT_FOR_CLOSURE Macro
File
TFTPc.h
C
#define
TFTP_UPLOAD_WAIT_FOR_CLOSURE 6
Description
This is macro TFTP_UPLOAD_WAIT_FOR_CLOSURE.
10.20.2
TFTP Stack Members
Macros
Name
TFTP_MAX_RETRIES ( see page 599)
Description
Number of seconds to wait before declaring TIMEOUT error on Put
Number of seconds to wait before declaring TIMEOUT error on Get.
Number of attempts before declaring TIMEOUT error.
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.20.2.1
TFTP_ARP_TIMEOUT_VAL Macro
File
TFTPc.h
C
#define
TFTP_ARP_TIMEOUT_VAL (3u * TICKS_PER_SECOND)
Description
Number of seconds to wait before declaring TIMEOUT error on Put
598
10.20 TFTP Microchip TCP/IP Stack Help
10.20.2.2
TFTP_GET_TIMEOUT_VAL Macro
File
TFTPc.h
C
#define
TFTP_GET_TIMEOUT_VAL (3u * TICKS_PER_SECOND)
Description
Number of seconds to wait before declaring TIMEOUT error on Get.
10.20.2.3
TFTP_MAX_RETRIES Macro
File
TFTPc.h
C
#define
TFTP_MAX_RETRIES (3u)
Description
Number of attempts before declaring TIMEOUT error.
TFTP Internal Members
10.20.3
TFTP Internal Members
Enumerations
Name
Description
Enumeration of TFTP opcodes
The TFTP state machine
Functions
Name
_TFTPSendFileName ( see page 603)
Description
Private helper function
Private helper function
PIC18 ROM variable argument implementation of _TFTPSendFileName ( see page 603)
Macros
Name
TFTP_BLOCK_SIZE ( see page 601)
TFTP_CLIENT_PORT ( see page 601)
TFTP_SERVER_PORT ( see page 602)
Description
The size of a TFTP block - 512 bytes
The MSB of the TFTP_BLOCK_SIZE ( see page 601)
The TFTP Client port - a unique port on this device
The TFTP Server Port
599
10.20 TFTP Microchip TCP/IP Stack Help TFTP Internal Members
Module
Variables
Name
_tftpStartTick ( see page 604)
Description
Mutually Exclusive variable groups to conserve RAM.
Variable to preserve error condition causes for later transmission
TFTP status flags
Tracker variable for the number of TFTP retries
TFTP Socket for TFTP server link
Timing variable used to detect timeout conditions
_tftpState ( see page 604) smUpload ( see page 604)
TFTP state machine tracker variable
This is variable smUpload.
uploadChunkDescriptor ( see page
This is variable uploadChunkDescriptor.
uploadChunkDescriptorForRetransmit
This is variable uploadChunkDescriptorForRetransmit.
vUploadFilename ( see page 605)
This is variable vUploadFilename.
TFTPUploadRAMFileToHost ( see page 595)(),
TFTPUploadFragmentedRAMFileToHost ( see page 594)() and
TFTPGetUploadStatus ( see page 593)() functions require the DNS
client module to be enabled for them to work. The RAM and ROM resources for these functions can be preserved if the DNS client module isn't enabled.
This is variable wUploadChunkOffset.
606) wUploadChunkOffsetForRetransmit
This is variable wUploadChunkOffsetForRetransmit.
Description
The following functions and variables are designated as internal to the TFTP module.
10.20.3.1
MutExVar Variable
File
TFTPc.c
C union
{
struct
{
NODE_INFO _hostInfo;
} group1;
struct
{
WORD_VAL _tftpBlockNumber;
WORD_VAL _tftpDuplicateBlock;
WORD_VAL _tftpBlockLength;
} group2;
} MutExVar;
Description
Mutually Exclusive variable groups to conserve RAM.
600
10.20 TFTP Microchip TCP/IP Stack Help
10.20.3.2
TFTP_BLOCK_SIZE Macro
File
TFTPc.c
C
#define
TFTP_BLOCK_SIZE (0x200L)
Description
The size of a TFTP block - 512 bytes
10.20.3.3
TFTP_BLOCK_SIZE_MSB Macro
File
TFTPc.c
C
#define
TFTP_BLOCK_SIZE_MSB (0x02u)
Description
The MSB of the TFTP_BLOCK_SIZE ( see page 601)
10.20.3.4
TFTP_CLIENT_PORT Macro
File
TFTPc.c
C
#define
TFTP_CLIENT_PORT 65352L
Description
The TFTP Client port - a unique port on this device
10.20.3.5
TFTP_OPCODE Enumeration
File
TFTPc.c
C typedef enum
{
TFTP_OPCODE_RRQ = 1,
TFTP_OPCODE_WRQ,
TFTP_OPCODE_DATA,
TFTP_OPCODE_ACK,
TFTP_OPCODE_ERROR
} TFTP_OPCODE;
Members
Members
TFTP_OPCODE_RRQ = 1
TFTP_OPCODE_WRQ
TFTP_OPCODE_DATA
Description
Get
Put
Actual data
TFTP Internal Members
601
10.20 TFTP
TFTP_OPCODE_ACK
TFTP_OPCODE_ERROR
Description
Enumeration of TFTP opcodes
Microchip TCP/IP Stack Help
Ack for Get/Put
Error
10.20.3.6
TFTP_SERVER_PORT Macro
File
TFTPc.c
C
#define
TFTP_SERVER_PORT (69L)
Description
The TFTP Server Port
10.20.3.7
TFTP_STATE Enumeration
File
TFTPc.c
C typedef enum
{
SM_TFTP_WAIT = 0,
SM_TFTP_READY,
SM_TFTP_WAIT_FOR_DATA,
SM_TFTP_WAIT_FOR_ACK,
SM_TFTP_DUPLICATE_ACK,
SM_TFTP_SEND_ACK,
SM_TFTP_SEND_LAST_ACK
} TFTP_STATE;
Description
The TFTP state machine
10.20.3.8
_tftpError Variable
File
TFTPc.c
C
WORD _tftpError;
Description
Variable to preserve error condition causes for later transmission
10.20.3.9
_tftpFlags Variable
File
TFTPc.c
TFTP Internal Members
602
10.20 TFTP
C union
{
struct
{
unsigned int
bIsFlushed : 1;
unsigned int
bIsAcked : 1;
unsigned int
bIsClosed : 1;
unsigned int
bIsClosing : 1;
unsigned int
bIsReading : 1;
} bits;
BYTE Val;
} _tftpFlags;
Description
TFTP status flags
Microchip TCP/IP Stack Help
10.20.3.10
_tftpRetries Variable
File
TFTPc.c
C
BYTE _tftpRetries;
Description
Tracker variable for the number of TFTP retries
10.20.3.11
_TFTPSendAck Function
File
TFTPc.c
C static void
_TFTPSendAck(
WORD_VAL blockNumber
);
Description
Private helper function
10.20.3.12
_TFTPSendFileName Function
File
TFTPc.c
C static void
_TFTPSendFileName(
BYTE * fileName
);
Description
Private helper function
TFTP Internal Members
603
10.20 TFTP Microchip TCP/IP Stack Help
10.20.3.13
_TFTPSendROMFileName Function
File
TFTPc.c
C static void
_TFTPSendROMFileName(
ROM BYTE * fileName
);
Description
PIC18 ROM variable argument implementation of _TFTPSendFileName ( see page 603)
10.20.3.14
_tftpSocket Variable
File
TFTPc.c
C
UDP_SOCKET _tftpSocket = TFTP_UPLOAD_COMPLETE;
Description
TFTP Socket for TFTP server link
10.20.3.15
_tftpStartTick Variable
File
TFTPc.c
C
DWORD _tftpStartTick;
Description
Timing variable used to detect timeout conditions
10.20.3.16
_tftpState Variable
File
TFTPc.c
C
Description
TFTP state machine tracker variable
10.20.3.17
smUpload Variable
File
TFTPc.c
TFTP Internal Members
604
10.20 TFTP Microchip TCP/IP Stack Help
C
CHAR smUpload = TFTP_UPLOAD_COMPLETE;
Description
This is variable smUpload.
TFTP Internal Members
10.20.3.18
uploadChunkDescriptor Variable
File
TFTPc.c
C
TFTP_CHUNK_DESCRIPTOR * uploadChunkDescriptor;
Description
This is variable uploadChunkDescriptor.
10.20.3.19
uploadChunkDescriptorForRetransmit Variable
File
TFTPc.c
C
TFTP_CHUNK_DESCRIPTOR * uploadChunkDescriptorForRetransmit;
Description
This is variable uploadChunkDescriptorForRetransmit.
10.20.3.20
vUploadFilename Variable
File
TFTPc.c
C
ROM BYTE * vUploadFilename;
Description
This is variable vUploadFilename.
10.20.3.21
vUploadRemoteHost Variable
File
TFTPc.c
C
ROM BYTE * vUploadRemoteHost;
Description
see page 595)(), TFTPUploadFragmentedRAMFileToHost ( see page 594)() and
RAM and ROM resources for these functions can be preserved if the DNS client module isn't enabled.
605
10.21 Tick Module Microchip TCP/IP Stack Help
10.20.3.22
wUploadChunkOffset Variable
File
TFTPc.c
C
WORD wUploadChunkOffset;
Description
This is variable wUploadChunkOffset.
10.20.3.23
wUploadChunkOffsetForRetransmit Variable
File
TFTPc.c
C
WORD wUploadChunkOffsetForRetransmit;
Description
This is variable wUploadChunkOffsetForRetransmit.
10.21
Tick Module
The Tick module provides accurate time-keeping capabilities based on the hardware clock. By default, it uses Timer 0 on
8-bit parts and Timer 1 on 16- and 32-bit families. The module is interrupt driven, which makes the timing stable and accurate. As such, it is also suitable for a real-time clock.
The Tick module exists to assist with the implementation of non-blocking delays and timeouts. Rather than using a loop to count to a specific number, use the Tick module and compare a previous time with the current time. In this fashion applications can return its unused cycles to the stack during long delays, which increases the overall efficiency of the system.
the main stack application, and on future calls compare the current Tick value to the stored one. The constants
compare against logical time increments.
The following example implements a delay of 0.5 seconds using the Tick module:
TICK startTime;
// ...state machine and other states
case
SM_SET_DELAY:
startTime = TickGet();
sm = SM_DELAY_WAIT;
return
;
case
SM_DELAY_WAIT:
if
((LONG)(TickGet() - startTime) < TICK_SECOND/2)
return
;
case
SM_DELAY_DONE:
// This state is entered only after 0.5 second elapses.
606
10.21 Tick Module Microchip TCP/IP Stack Help Tick Public Members
to a few years.
If absolute timestamps are required, the SNTP Client module may be more appropriate.
10.21.1
Tick Public Members
Functions
Name
Description
Converts a Tick value or difference to milliseconds.
Obtains the current Tick value.
Obtains the current Tick value divided by 256.
Obtains the current Tick value divided by 64K.
Macros
Module
Types
Name
Description
Represents one hour in Ticks
Represents one minute in Ticks
Represents one second in Ticks
Name
Description
All TICKS are stored as 32-bit unsigned integers. This is deprecated since it conflicts with other TICK definitions used in other Microchip software libraries and therefore poses a merge and maintence problem. Instead of using the
TICK data type, just use the base DWORD data type instead.
Description
The following functions and variables are available to the stack application.
10.21.1.1
TICK Type
File
Tick.h
C typedef
DWORD TICK;
Description
All TICKS are stored as 32-bit unsigned integers. This is deprecated since it conflicts with other TICK definitions used in other Microchip software libraries and therefore poses a merge and maintence problem. Instead of using the TICK data type, just use the base DWORD data type instead.
607
10.21 Tick Module Microchip TCP/IP Stack Help Tick Public Members
10.21.1.2
TICK_HOUR Macro
File
Tick.h
C
#define
TICK_HOUR ((QWORD)TICKS_PER_SECOND*3600ull)
Description
Represents one hour in Ticks
10.21.1.3
TICK_MINUTE Macro
File
Tick.h
C
#define
TICK_MINUTE ((QWORD)TICKS_PER_SECOND*60ull)
Description
Represents one minute in Ticks
10.21.1.4
TICK_SECOND Macro
File
Tick.h
C
#define
TICK_SECOND ((QWORD)TICKS_PER_SECOND)
Description
Represents one second in Ticks
10.21.1.5
TickConvertToMilliseconds Function
File
Tick.h
C
DWORD TickConvertToMilliseconds(
DWORD dwTickValue
);
Returns
Input value expressed in milliseconds.
Description
This function converts a Tick value or difference to milliseconds. For example, TickConvertToMilliseconds(32768) returns
1000 when a 32.768kHz clock with no prescaler drives the Tick module interrupt.
Remarks
This function performs division on DWORDs, which is slow. Avoid using it unless you absolutely must (such as displaying
608
10.21 Tick Module Microchip TCP/IP Stack Help Tick Public Members
608), which will be calculated only once at compile time.
Preconditions
None
Parameters
Parameters
dwTickValue
Description
Value to convert to milliseconds
10.21.1.6
TickGet Function
File
Tick.h
C
DWORD TickGet();
Returns
Lower 32 bits of the current Tick value.
Description
This function retrieves the current Tick value, allowing timing and measurement code to be written in a non-blocking fashion.
This function retrieves the least significant 32 bits of the internal tick counter, and is useful for measuring time increments
for longer periods of time.
Preconditions
None
10.21.1.7
TickGetDiv256 Function
File
Tick.h
C
DWORD TickGetDiv256();
Returns
Middle 32 bits of the current Tick value.
Description
This function retrieves the current Tick value, allowing timing and measurement code to be written in a non-blocking fashion.
This function retrieves the middle 32 bits of the internal tick counter, and is useful for measuring time increments ranging
for longer ones.
Preconditions
None
609
10.21 Tick Module Microchip TCP/IP Stack Help Tick Stack Functions
10.21.1.8
TickGetDiv64K Function
File
Tick.h
C
DWORD TickGetDiv64K();
Returns
Upper 32 bits of the current Tick value.
Description
This function retrieves the current Tick value, allowing timing and measurement code to be written in a non-blocking fashion.
This function retrieves the most significant 32 bits of the internal tick counter, and is useful for measuring time increments
TickGetDiv256 ( see page 609) for shorter periods of time.
Preconditions
None
10.21.2
Tick Stack Functions
Functions
Name
Description
Initializes the Tick manager module.
TickUpdate ( see page 611) Updates the tick value when an interrupt occurs.
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
10.21.2.1
TickInit Function
File
Tick.h
C void
TickInit();
Returns
None
Description
Configures the Tick module and any necessary hardware resources.
Remarks
This function is called only one during lifetime of the application.
610
10.21 Tick Module
Preconditions
None
Microchip TCP/IP Stack Help
10.21.2.2
TickUpdate Function
File
Tick.h
C void
TickUpdate();
Returns
None
Description
Updates the tick value when an interrupt occurs.
Preconditions
None
Tick Internal Members
10.21.3
Tick Internal Members
Functions
Name
Macros
Name
TICKS_PER_SECOND ( see page 612)
Module
Description
Reads the tick value.
Description
Internal core clock drives timer with 1:256 prescaler #define
TICKS_PER_SECOND (32768ul) // 32kHz crystal drives timer with no scalar
Variables
Name
Description
Internal counter to store Ticks. This variable is incremented in an ISR and therefore must be marked volatile to prevent the compiler optimizer from reordering code to use this value in the main context while interrupts are disabled.
6-byte value to store Ticks. Allows for use over longer periods of time.
Description
The following functions and variables are designated as internal to the Tick module.
10.21.3.1
dwInternalTicks Variable
File
Tick.c
611
10.22 UDP Microchip TCP/IP Stack Help
C volatile
DWORD dwInternalTicks = 0;
Description
Internal counter to store Ticks. This variable is incremented in an ISR and therefore must be marked volatile to prevent the compiler optimizer from reordering code to use this value in the main context while interrupts are disabled.
10.21.3.2
GetTickCopy Function
File
Tick.c
C static void
GetTickCopy();
Returns
None
Description
This function performs an interrupt-safe and synchronized read of the 48-bit Tick value.
Preconditions
None
10.21.3.3
TICKS_PER_SECOND Macro
File
Tick.h
C
#define
TICKS_PER_SECOND ((GetPeripheralClock()+128ull)/256ull)
// Internal core clock drives timer with 1:256 prescaler
Description
Internal core clock drives timer with 1:256 prescaler #define TICKS_PER_SECOND (32768ul) // 32kHz crystal drives timer with no scalar
10.21.3.4
vTickReading Variable
File
Tick.c
C
BYTE vTickReading[6];
Description
6-byte value to store Ticks. Allows for use over longer periods of time.
612
10.22 UDP Microchip TCP/IP Stack Help
10.22
UDP
Types
Name
Description
UDP States
Description
UDP is a standard transport layer protocol described in RFC 768. It provides fast but unreliable data-gram based transfers over networks, and forms the foundation SNTP, SNMP, DNS, and many other protocol standards.
Connections over UDP should be thought of as data-gram based transfers. Each packet is a separate entity, the application should expect some packets to arrive out-of-order or even fail to reach the destination node. This is in contrast to TCP, in which the connection is thought of as a stream and network errors are automatically corrected. These tradeoffs in reliability are made for an increase in throughput. In general, UDP transfers operate 2 to 3 times faster than those made over TCP.
Since UDP is packet-oriented, each packet must be dealt with in its entirety by your application before returning to the main stack loop. When a packet is received, your application will be called to handle it. This packet will no longer be available the next time your application is called, so you must either perform all necessary processing or copy the data elsewhere before returning. When transmitting a packet, your application must build and transmit the complete packet in one cycle.
The UDP flow diagram below provides an overview for the use of the UDP module:
wait for incoming segments, or can make a client connection to a remote node. When making a client connection, you will
data may be lost or the module may behave unpredictably.
613
10.22 UDP Microchip TCP/IP Stack Help UDP Public Members
to the main stack loop to wait for an additional segment. UDP segments are only stored for one iteration of the cooperative multi-tasking loop, so your application must complete its processing on a segment or copy it elsewhere before returning.
Note that this behavior differs from TCP, which buffers incoming data through multiple stack cycles.
10.22.1
UDP Public Members
Functions
Name
Description
Opens a UDP socket for a client.
Closes a UDP socket and frees the handle.
Discards any remaining RX data from a UDP socket.
Transmits all pending data in a UDP socket.
Reads a byte from the currently active socket.
Reads an array of bytes from the currently active socket.
Determines how many bytes can be read from the UDP socket.
Determines how many bytes can be written to the UDP socket.
Writes a byte to the currently active socket.
Writes an array of bytes to the currently active socket.
Writes an array of bytes from ROM to the currently active socket.
UDPPutROMArray ( see page 622)
UDPPutROMString ( see page 623)
Writes null-terminated string from ROM to the currently active socket.
Writes null-terminated string to the currently active socket.
UDPSetRxBuffer ( see page 624)
Moves the pointer within the RX buffer.
Moves the pointer within the TX buffer.
Determines if a socket has an established connection.
Macros
Name
INVALID_UDP_SOCKET ( see page 615)
Description
INVALID_UDP_PORT ( see page 615)
Indicates a UDP port that is not valid
Indicates a UDP socket that is not valid
Macro of the legacy version of UDPOpen.
Create a client socket and use dwRemoteHost as a literal IP address.
Create a client socket and use dwRemoteHost as a pointer to a NODE_INFO structure containing the exact remote IP address and MAC address to use.
614
10.22 UDP Microchip TCP/IP Stack Help UDP Public Members
UDP_OPEN_RAM_HOST ( see page 626)
Emit an undeclared identifier diagnostic if code tries to use
UDP_OPEN_RAM_HOST while the DNS client module is not enabled.
UDP_OPEN_ROM_HOST ( see page 626)
UDP_OPEN_SERVER ( see page 626)
Emit an undeclared identifier diagnostic if code tries to use
UDP_OPEN_ROM_HOST while the DNS client module is not enabled.
Create a server socket and ignore dwRemoteHost.
Module
Types
Name
Description
Provides a handle to a UDP Socket
Description
The following functions and variables are available to the stack application.
10.22.1.1
INVALID_UDP_PORT Macro
File
UDP.h
C
#define
INVALID_UDP_PORT (0ul)
// Indicates a UDP port that is not valid
Description
Indicates a UDP port that is not valid
10.22.1.2
INVALID_UDP_SOCKET Macro
File
UDP.h
C
#define
INVALID_UDP_SOCKET (0xffu)
// Indicates a UDP socket that is not valid
Description
Indicates a UDP socket that is not valid
10.22.1.3
UDP_SOCKET Type
File
UDP.h
C typedef
BYTE UDP_SOCKET;
Description
Provides a handle to a UDP Socket
615
10.22 UDP Microchip TCP/IP Stack Help UDP Public Members
10.22.1.4
UDPOpenEx Function
File
UDP.h
C
DWORD remoteHost,
BYTE remoteHostType,
);
Description
Provides a unified method for opening UDP sockets. This function can open both client and server sockets. For client
binary form, or a previously resolved NODE_INFO structure containing the remote IP address and associated MAC address.
Remarks
the handle.
Preconditions
UDPInit ( see page 627) should be called.
Parameters
Parameters
remoteHost
Description
Pointer to remote node info (MAC and IP address) for this connection. If this is a server socket (receives the first packet) or the destination is the broadcast address, then this parameter should be NULL. For client sockets only. Provide a pointer to a null-terminated string of the remote host name
(ex:"www.microchip.com" or "192.168.1.123"), a literal destination IP address
(ex: 0x7B01A8C0 or an IP_ADDR data type), or a pointer to a NODE_INFO structure with the remote IP address and remote node or gateway MAC address specified, If a string is provided.
616
10.22 UDP remoteHostType
Microchip TCP/IP Stack Help UDP Public Members
Any one of the following flags to identify the meaning of the remoteHost parameter:
• UDP_OPEN_SERVER ( see page 626) = Open a server socket and
ignore the remoteHost parameter. (e.g. - SNMP agent, DHCP server,
• UDP_OPEN_IP_ADDRESS ( see page 625) = Open a client socket and
connect ( see page 176) it to a remote IP address. Ex: 0x7B01A8C0 for
192.168.1.123 (DWORD type). Note that the byte ordering is big endian.
• UDP_OPEN_NODE_INFO ( see page 625) = Open a client socket and
connect ( see page 176) it to a remote IP and MAC addresses pair stored
in a NODE_INFO structure.
• UDP_OPEN_RAM_HOST ( see page 626) = Open a client socket and
connect ( see page 176) it to a remote host who's name is stored as a
null terminated string in a RAM array. Ex:"www.microchip.com" or
"192.168.0.123"
• UDP_OPEN_ROM_HOST ( see page 626) = Open a client socket and
connect ( see page 176) it to a remote host who's name is stored as a
null terminated string in a literal string or ROM array. Ex:
"www.microchip.com" or "192.168.0.123"
UDP port number to listen ( see page 180) on. If 0, stack will dynamically
assign a unique port number to use.
For client sockets, the remote port number.
localPort remotePort
Return Values
Return Values
Success
Failure
Description
A UDP socket handle that can be used for subsequent UDP API calls.
INVALID_UDP_SOCKET ( see page 615). This function fails when no more
UDP socket handles are available. Increase MAX_UDP_SOCKETS to make more sockets available.
10.22.1.5
UDPOpen Macro
File
UDP.h
C
#define
UDPOpen(localPort,remoteNode,remotePort)
UDPOpenEx((DWORD)remoteNode,UDP_OPEN_NODE_INFO,localPort,remotePort)
Description
UDPOpen is a macro replacement of the legacy implementation of UDPOpen. Creates a UDP socket handle for transmiting or receiving UDP packets. Call this function to obtain a handle required by other UDP function.
Remarks
the handle.
Preconditions
UDPInit ( see page 627)() must have been previously called.
Parameters
Parameters
localPort
Description
UDP port number to listen ( see page 180) on. If 0, stack will dynamically
assign a unique port number to use.
617
10.22 UDP remoteNode
Microchip TCP/IP Stack Help UDP Public Members
Pointer to remote node info (MAC and IP address) for this connection. If this is a server socket (receives the first packet) or the destination is the broadcast address, then this parameter should be NULL.
For client sockets, the remote port number.
remotePort
Return Values
Return Values
Success
Failure
Description
A UDP socket handle that can be used for subsequent UDP API calls.
INVALID_UDP_SOCKET ( see page 615). This function fails when no more
UDP socket handles are available. Increase MAX_UDP_SOCKETS to make more sockets available.
10.22.1.6
UDPClose Function
File
UDP.h
C void
UDPClose(
);
Returns
None
Description
see page 617)(UDP_PORT ( see page 631) localPort, NODE_INFO
*remoteNode, UDP_PORT ( see page 631) remotePort);
Closes a UDP socket and frees the handle. Call this function to release a socket and return it to the pool for use by future communications.
Remarks
This function does not affect the previously designated active socket.
Preconditions
UDPInit ( see page 627)() must have been previously called.
Parameters
Parameters
s
Description
The socket handle to be released. If an illegal handle value is provided, the function safely does nothing.
10.22.1.7
UDPDiscard Function
File
UDP.h
C void
UDPDiscard();
Returns
None
Description
This function discards any remaining received data in the currently active UDP socket.
618
10.22 UDP Microchip TCP/IP Stack Help
Remarks
It is safe to call this function more than is necessary. If no data is available, this function does nothing.
Preconditions
UDPIsGetReady ( see page 620)() was previously called to select the currently active socket.
UDP Public Members
10.22.1.8
UDPFlush Function
File
UDP.h
C void
UDPFlush();
Returns
None
Description
This function builds a UDP packet with the pending TX data and marks it for transmission over the network interface. Since
UDP is a frame-based protocol, this function must be called before returning to the main stack loop whenever any data is written.
Remarks
auto transmit for UDP segments.
Preconditions
10.22.1.9
UDPGet Function
File
UDP.h
C
BOOL UDPGet(
BYTE * v
);
Description
This function reads a single byte from the currently active UDP socket, while decrementing the remaining buffer length.
Preconditions
UDPIsGetReady ( see page 620)() was previously called to specify the current socket.
Parameters
Description
The buffer to receive the data being read.
Parameters
v
Return Values
Return Values
TRUE
Description
A byte was successfully read
619
10.22 UDP
FALSE
Microchip TCP/IP Stack Help
No data remained in the read buffer
UDP Public Members
10.22.1.10
UDPGetArray Function
File
UDP.h
C
WORD UDPGetArray(
BYTE * cData,
WORD wDataLen
);
Returns
The number of bytes successfully read from the UDP buffer. If this value is less than wDataLen, then the buffer was emptied and no more data is available.
Description
This function reads an array of bytes from the currently active UDP socket, while decrementing the remaining bytes
Preconditions
UDPIsGetReady ( see page 620)() was previously called to specify the current socket.
Parameters
Parameters
cData wDateLen
Description
The buffer to receive the bytes being read. If NULL, the bytes are simply discarded without being written anywhere (effectively skips over the bytes in the
RX buffer, although if you need to skip a lot of data, seeking using the
UDPSetRxBuffer ( see page 624)() will be more efficient).
Number of bytes to be read from the socket.
10.22.1.11
UDPIsGetReady Function
File
UDP.h
C
WORD UDPIsGetReady(
);
Returns
The number of bytes that can be read from this socket.
Description
This function determines if bytes can be read from the specified UDP socket. It also prepares the UDP module for reading by setting the indicated socket as the currently active connection.
Preconditions
UDPInit ( see page 627)() must have been previously called.
Parameters
Parameters
s
Description
The socket to be made active (which has already been opened or is listening)
620
10.22 UDP Microchip TCP/IP Stack Help UDP Public Members
10.22.1.12
UDPIsPutReady Function
File
UDP.h
C
WORD UDPIsPutReady(
);
Returns
The number of bytes that can be written to this socket.
Description
This function determines if bytes can be written to the specified UDP socket. It also prepares the UDP module for writing by setting the indicated socket as the currently active connection.
Preconditions
UDPInit ( see page 627)() must have been previously called.
Parameters
Parameters
s
Description
The socket to be made active
10.22.1.13
UDPPut Function
File
UDP.h
C
BOOL UDPPut(
BYTE v
);
Description
( see page 621) should be used before calling this function to specify the currently active socket.
Preconditions
UDPIsPutReady ( see page 621)() was previously called to specify the current socket.
Parameters
Description
The byte to be loaded into the transmit buffer.
Parameters
v
Return Values
Return Values
TRUE
FALSE
Description
The byte was successfully written to the socket.
The transmit buffer is already full and so the write failed.
621
10.22 UDP Microchip TCP/IP Stack Help UDP Public Members
10.22.1.14
UDPPutArray Function
File
UDP.h
C
WORD UDPPutArray(
BYTE * cData,
WORD wDataLen
);
Returns
The number of bytes successfully placed in the UDP transmit buffer. If this value is less than wDataLen, then the buffer became full and the input was truncated.
Description
This function writes an array of bytes to the currently active UDP socket, while incrementing the buffer length.
Preconditions
UDPIsPutReady ( see page 621)() was previously called to specify the current socket.
Parameters
Parameters
cData wDateLen
Description
The array to write to the socket.
Number of bytes from cData to be written.
10.22.1.15
UDPPutROMArray Function
File
UDP.h
C
WORD UDPPutROMArray(
ROM BYTE * cData,
WORD wDataLen
);
Returns
The number of bytes successfully placed in the UDP transmit buffer. If this value is less than wDataLen, then the buffer became full and the input was truncated.
Description
ROM function variants for PIC18
This function writes an array of bytes from ROM to the currently active UDP socket, while incrementing the buffer length.
Remarks
This function is aliased to UDPPutArray ( see page 622) on non-PIC18 platforms.
Preconditions
UDPIsPutReady ( see page 621)() was previously called to specify the current socket.
622
10.22 UDP
Parameters
Parameters
cData wDateLen
Microchip TCP/IP Stack Help
Description
The array to write to the socket.
Number of bytes from cData to be written.
UDP Public Members
10.22.1.16
UDPPutROMString Function
File
UDP.h
C
ROM BYTE* UDPPutROMString(
ROM BYTE * strData
);
Returns
functions. If this pointer does not dereference to a NULL byte, then the buffer became full and the input data was truncated.
Description
This function writes a null-terminated string from ROM to the currently active UDP socket, while incrementing the buffer
Remarks
This function is aliased to UDPPutString ( see page 623) on non-PIC18 platforms.
Preconditions
UDPIsPutReady ( see page 621)() was previously called to specify the current socket.
Parameters
Parameters
cData
Description
Pointer to the string to be written to the socket.
10.22.1.17
UDPPutString Function
File
UDP.h
C
BYTE* UDPPutString(
BYTE * strData
);
Returns
functions. If this pointer does not dereference to a NULL byte, then the buffer became full and the input data was truncated.
Description
This function writes a null-terminated string to the currently active UDP socket, while incrementing the buffer length.
Preconditions
UDPIsPutReady ( see page 621)() was previously called to specify the current socket.
623
10.22 UDP
Parameters
Parameters
cData
Microchip TCP/IP Stack Help
Description
Pointer to the string to be written to the socket.
UDP Public Members
10.22.1.18
UDPSetRxBuffer Function
File
UDP.h
C void
UDPSetRxBuffer(
WORD wOffset
);
Returns
None
Description
UDPGetArray ( see page 620) will read data from the indicated location forward.
Preconditions
UDPInit ( see page 627)() must have been previously called and a socket is currently active.
Parameters
Parameters
wOffset
Description
Offset from beginning of UDP packet data payload to place the read pointer.
10.22.1.19
UDPSetTxBuffer Function
File
UDP.h
C void
UDPSetTxBuffer(
WORD wOffset
);
Returns
None
Description
Preconditions
UDPInit ( see page 627)() must have been previously called and a socket is currently active.
Parameters
Parameters
wOffset
Description
Offset from beginning of UDP packet data payload to place the write pointer.
624
10.22 UDP Microchip TCP/IP Stack Help UDP Public Members
10.22.1.20
UDPIsOpened Function
File
UDP.h
C
BOOL UDPIsOpened(
);
Description
This function determines if a socket has an established connection to a remote node . Call this function after calling
UDPOpen ( see page 617) to determine when the connection is set up and ready for use.
Remarks
None
Preconditions
UDP is initialized.
Parameters
Parameters
Return Values
Return Values
TRUE
FALSE
Description
The socket to check.
Description
The socket has been opened and ARP has been resolved.
The socket is not currently connected.
10.22.1.21
UDP_OPEN_IP_ADDRESS Macro
File
UDP.h
C
#define
UDP_OPEN_IP_ADDRESS 3u
Description
Create a client socket and use dwRemoteHost as a literal IP address.
10.22.1.22
UDP_OPEN_NODE_INFO Macro
File
UDP.h
C
#define
UDP_OPEN_NODE_INFO 4u
Description
Create a client socket and use dwRemoteHost as a pointer to a NODE_INFO structure containing the exact remote IP address and MAC address to use.
625
10.22 UDP Microchip TCP/IP Stack Help UDP Stack Members
10.22.1.23
UDP_OPEN_RAM_HOST Macro
File
UDP.h
C
#define
UDP_OPEN_RAM_HOST You_need_to_enable_STACK_USE_DNS_to_use_UDP_OPEN_RAM_HOST
Description
Emit an undeclared identifier diagnostic if code tries to use UDP_OPEN_RAM_HOST while the DNS client module is not enabled.
10.22.1.24
UDP_OPEN_ROM_HOST Macro
File
UDP.h
C
#define
UDP_OPEN_ROM_HOST You_need_to_enable_STACK_USE_DNS_to_use_UDP_OPEN_ROM_HOST
Description
Emit an undeclared identifier diagnostic if code tries to use UDP_OPEN_ROM_HOST while the DNS client module is not enabled.
10.22.1.25
UDP_OPEN_SERVER Macro
File
UDP.h
C
#define
UDP_OPEN_SERVER 0u
Description
Create a server socket and ignore dwRemoteHost.
10.22.2
UDP Stack Members
Functions
Name
Description
Initializes the UDP module.
Handles an incoming UDP segment.
Performs state management and housekeeping for UDP.
Module
Description
The following functions and variables are public, but are intended only to be accessed by the stack itself. Applications should generally not call these functions or modify these variables.
626
10.22 UDP Microchip TCP/IP Stack Help UDP Stack Members
10.22.2.1
UDPInit Function
File
UDP.h
C void
UDPInit();
Returns
None
Description
Initializes the UDP module. This function initializes all the UDP sockets to the closed state.
Remarks
This function is called only one during lifetime of the application.
Preconditions
None
Section
Function Prototypes
10.22.2.2
UDPProcess Function
File
UDP.h
C
BOOL UDPProcess(
NODE_INFO * remoteNode,
IP_ADDR * localIP,
WORD len
);
Description
This function handles an incoming UDP segment to determine if it is acceptable and should be handed to one of the stack applications for processing.
Preconditions
UDPInit ( see page 627)() has been called an a UDP segment is ready in the MAC buffer.
Parameters
Parameters
remoteNode localIP len
Return Values
Return Values
TRUE
FALSE
Description
The remote node that sent this segment.
The destination IP address for this segment.
Total length of the UDP segment.
Description
A valid packet is waiting and the stack applications should be called to handle it.
The packet was discarded.
627
10.22 UDP Microchip TCP/IP Stack Help UDP Internal Members
10.22.2.3
UDPTask Function
File
UDP.h
C void
UDPTask();
Description
Performs state management and housekeeping for UDP. This is an internal function meant to be called by StackTask() (not a user API).
Remarks
the Ethernet Write pointer location between StackTask() iterations.
Preconditions
None
10.22.3
UDP Internal Members
Functions
Name
FindMatchingSocket ( see page 629)
Description
Matches an incoming UDP segment to a currently active socket.
Macros
Name
Description
Last port number for randomized local port number selection
First port number for randomized local port number selection
Module
Structures
Name
UDP_SOCKET_INFO ( see page 631)
Description
Stores the header of a UDP packet
Stores information about a current UDP socket
Types
Name
Description
Stores a UDP Port Number
Variables
Name
activeUDPSocket ( see page 629)
Description
Indicates which UDP socket is currently active
628
10.22 UDP Microchip TCP/IP Stack Help UDP Internal Members
SocketWithRxData ( see page 630)
Indicates the last socket to which data was written
Indicates which socket has currently received data for this loop
Number of bytes read from this UDP segment
Stores an array of information pertaining to each UDP socket
Number of bytes written to this UDP segment
wGetOffset ( see page 632) Offset from beginning of payload from where data is to be read.
Offset from beginning of payload where data is to be written.
Description
The following functions and variables are designated as internal to the UDP module.
10.22.3.1
activeUDPSocket Variable
File
UDP.c
C
Description
Indicates which UDP socket is currently active
10.22.3.2
FindMatchingSocket Function
File
UDP.c
C static
UDP_SOCKET FindMatchingSocket(
NODE_INFO * remoteNode,
IP_ADDR * localIP
);
Returns
match could be made.
Description
This function attempts to match an incoming UDP segment to a currently active socket for processing.
Preconditions
UDP segment header and IP header have both been retrieved.
Parameters
Parameters
h remoteNode localIP
Description
The UDP header that was received.
IP and MAC of the remote node that sent this segment.
IP address that this segment was destined for.
629
10.22 UDP
Section
Function Prototypes
Microchip TCP/IP Stack Help
10.22.3.3
LastPutSocket Variable
File
UDP.c
C
UDP_SOCKET LastPutSocket = INVALID_UDP_SOCKET;
Description
Indicates the last socket to which data was written
10.22.3.4
LOCAL_UDP_PORT_END_NUMBER Macro
File
UDP.c
C
#define
LOCAL_UDP_PORT_END_NUMBER (8192u)
Description
Last port number for randomized local port number selection
10.22.3.5
LOCAL_UDP_PORT_START_NUMBER Macro
File
UDP.c
C
#define
LOCAL_UDP_PORT_START_NUMBER (4096u)
Description
First port number for randomized local port number selection
10.22.3.6
SocketWithRxData Variable
File
UDP.c
C
UDP_SOCKET SocketWithRxData = INVALID_UDP_SOCKET;
Description
Indicates which socket has currently received data for this loop
UDP Internal Members
630
10.22 UDP Microchip TCP/IP Stack Help
10.22.3.7
UDP_HEADER Structure
File
UDP.h
C typedef struct
{
WORD Length;
WORD Checksum;
} UDP_HEADER;
Members
Members
UDP_PORT SourcePort;
UDP_PORT DestinationPort;
WORD Length;
WORD Checksum;
Description
Stores the header of a UDP packet
Description
Source UDP port
Destination UDP port
Length of data
UDP checksum of the data
10.22.3.8
UDP_PORT Type
File
UDP.h
C typedef
WORD UDP_PORT;
Description
Stores a UDP Port Number
10.22.3.9
UDP_SOCKET_INFO Structure
File
UDP.h
C typedef struct
{
union
{
NODE_INFO remoteNode;
DWORD remoteHost;
} remote;
DWORD retryInterval;
BYTE retryCount;
struct
{
unsigned char
bRemoteHostIsROM : 1;
} flags;
WORD eventTime;
} UDP_SOCKET_INFO;
UDP Internal Members
631
10.22 UDP Microchip TCP/IP Stack Help UDP Internal Members
Members
Members
NODE_INFO remoteNode;
DWORD remoteHost;
UDP_PORT remotePort;
UDP_PORT localPort;
UDP_STATE smState; unsigned char bRemoteHostIsROM : 1;
Description
10 bytes for MAC and IP address
RAM or ROM pointer to a hostname string (ex: "www.microchip.com")
Remote node's UDP port number
Local UDP port number, or INVALID_UDP_PORT ( see page 615) when free
State of this socket
Remote host is stored in ROM
Description
Stores information about a current UDP socket
10.22.3.10
UDPRxCount Variable
File
UDP.c
C
WORD UDPRxCount;
Description
Number of bytes read from this UDP segment
10.22.3.11
UDPSocketInfo Variable
File
UDP.c
C
UDP_SOCKET_INFO UDPSocketInfo[MAX_UDP_SOCKETS];
Description
Stores an array of information pertaining to each UDP socket
10.22.3.12
UDPTxCount Variable
File
UDP.c
C
WORD UDPTxCount;
Description
Number of bytes written to this UDP segment
10.22.3.13
wGetOffset Variable
File
UDP.c
632
10.22 UDP Microchip TCP/IP Stack Help
C
WORD wGetOffset;
Description
Offset from beginning of payload from where data is to be read.
10.22.3.14
wPutOffset Variable
File
UDP.c
C
WORD wPutOffset;
Description
Offset from beginning of payload where data is to be written.
10.22.4
Types
Enumerations
Name
Module
Description
UDP States
10.22.4.1
UDP_STATE Enumeration
File
UDP.h
C typedef enum
{
UDP_DNS_IS_RESOLVED,
UDP_DNS_RESOLVE,
UDP_GATEWAY_SEND_ARP,
UDP_GATEWAY_GET_ARP,
UDP_CLOSED,
UDP_OPENED
} UDP_STATE;
Members
Members
UDP_DNS_IS_RESOLVED
UDP_DNS_RESOLVE
UDP_GATEWAY_SEND_ARP
UDP_GATEWAY_GET_ARP
UDP_CLOSED
Description
UDP States
Description
Special state for UDP client mode sockets
Special state for UDP client mode sockets
Special state for UDP client mode sockets
Special state for UDP client mode sockets
Socket is idle and unallocated
Types
633
Microchip TCP/IP Stack Help 11
11
Wi-Fi API
Modules
Name Description
Wi-Fi Connection Profile ( see page 637) Functions to setup, use, and teardown connection profiles
Wi-Fi Connection Algorithm ( see page
Functions to alter the behavior of the connection process
Functions to manage the connection process
Wi-Fi Connection Manager ( see page
Functions to direct the MRF24WB0M / MRF24WG0M to initiate a site survey
Wi-Fi Tx Power Control ( see page 692)
API to control the transmit (Tx) power of the MRF24WB0M / MRF24WG0M
Wi-Fi Power Save ( see page 695)
Functions to alter the power savings features of the MRF24WB0M /
MRF24WG0M
Wi-Fi Miscellaneous ( see page 705)
Functions for controlling miscellaneous features of the MRF24WB0M /
MRF24WG0M
Description
Feature similarities and differences of MRF24WB0M and MRF24WG0M
MRF24WB0M MRF24WG0M
1 , 2 Mbps
Ad-hoc (OPEN, WEP)
802.11b and 802.11g rates
Ad-hoc (OPEN, WEP)
Infrastructure (OPEN, WEP,
WPA/WPA2)
Infrastructure (OPEN, WEP, WPA/WPA2, WPS)
SoftAP (OPEN, WEP)
Wi-Fi Direct (WPS)
WPA2-Enterprise Security Modes (EAP-PEAP/MSCHAPv2 and EAP-TTLS/MSCHAPv)
Unlike Ethernet, a Wi-Fi 802.11 application needs to initiate a connection to an access point, Wi-Fi Direct or an ad hoc network, before data communications can commence.
The WF_Config.h file has several compile-time constants that can be customized (e.g. MY_DEFAULT_SSID_NAME) as needed.
In order to initiate an connection there is a sequence of steps that should be followed.
directing the WiFi driver about the nature of the connection that will be established. The connection profile defines: a. SSID (name of Access Point) b. Security (open, WEP, WPA, WPA2, WPS-PBC, WPS-PIN, etc.) c. Network type (infrastructure, ad hoc, softAP, Wi-Fi Direct).
The Connection Profile functions are used to create and define an connection profile. These functions all begin with
WF_CP…
2) The connection algorithm must be defined, and applies to all connection profiles. For most applications the defaults will be sufficient. For example, the default connection algorithm channel list for scanning is 1, 6, and 11. However, if, in your application you know the Access Point will always be on channel 6 you could change this setting, thus making the scan process more efficient. Functions pertaining to the connection algorithm all begin with WF_CA…
634
11 Microchip TCP/IP Stack Help
4) After WF_Connect() is called the host application will be notified when the MRF24WB0M / MRF24WG0M has succeeded
the console (if the UART is enabled) that the event occurred. This file can be modified to suit the needs of an application –
The MRF2WB0M / MRF24WG0M demos (under the Demo App, WiFi Console, and WiFi EZ Config demo directories) contain a function, WF_Connect(), in MainDemo.c that executes the above steps and can be referred to as an example of how to initiate a WiFi connection.
Wi-Fi DIRECT (CFG_WF_P2P)
To start up as a Wi-Fi direct group client device, define
• MY_DEFAULT_SSID_NAME as "DIRECT-" which is an unique specifier to identify a Wi-Fi Direct network.
• MY_DEFAULT_CHANNEL LIST as {1, 6, 11} which are specified social channels for Wi-Fi Direct network.
Below describes the host API to the MRF24WB0M / MRF24WG0M on-chip connection manager which creates and maintains Wi-Fi connections. The API is divided into these major sections:
API Section Description
Functions to initialize the host API and MRF24WB0M / MRF24WG0M
Connection Profile
Connection Algorithm
Connection Manager
Scan
Tx Power Control
Power Save
Multicast
Miscellaneous
MRF24WB0M
MRF24WG0M Events
/
Functions to create and maintain one or more connection profiles
Functions to fine tune the connection algorithm
Functions to start and stop an 802.11 connection
Functions to scan for wireless networks
Functions to control the MRF24WB0M / MRF24WG0M Tx power
Functions to save power consumption by the MRF24WB0M / MRF24WG0M
Functions to create multicast filters
Functions to set a custom MAC address, get device information, etc.
Functions to handle events from the MRF24WB0M / MRF24WG0M
SPI
The
WF_Spi.c
file contains functions that the Wi-Fi Driver will use to initialize, send, and receive SPI messages between the host CPU and the MRF24WB0M / MRF24WG0M. To communicate with the MRF24WB0M / MRF24WG0M, which is always an SPI slave, the host CPU SPI controller needs to be configured as follows:
• Mode = 0
• CPOL (clock polarity) = 0
• CPHA (clock phase) = 0
635
11 Microchip TCP/IP Stack Help
• Host CPU set as master
• Clock idles high
• 8-bit transfer length
• Data changes on falling edge
• Data sampled on rising edge
Below is a list of functions in
WF_Spi.c
that must be customized for the specific host CPU architecture:
Function
WF_SpiInit()
WF_SpiTxRx()
WF_SpiEnableChipSelect()
Description
Initializes the host CPU SPI controller for usage by the Wi-Fi driver. Called by the
Wi-Fi driver during initialization.
Transmits and/or receives SPI data from the MRF24WB0M / MRF24WG0M.
Set slave select line on MRF24WB0M / MRF24WG0M low (start SPI transfer).
If SPI bus is shared with any other devices then this function also needs to save the current SPI context and then configure the MRF24WB0M / MRF24WG0M SPI context.
WF_SpiDisableChipSelect() Set slave select line on MRF24WB0M / MRF24WG0M high (end SPI transfer).
If SPI bus is shared with any other devices then this function also needs to restore the SPI context (saved during
WF_SpiEnableChipSelect()
).
External Interrupt
The
WF_Eint.c
file contains functions that the Wi-Fi Driver will use to enable and disable the MRF24WB0M /
MRF24WG0M external interrupt as well as get interrupt status. The functions in this module need to be customized for the specific host CPU architecture.
The MRF24WB0M / MRF24WG0M asserts its EXINT (external interrupt) line (active low) when specific events occur, such as a data message being received. Note that the host CPU has a choice to either configure the EXINT line to generate an actual interrupt, or, it can be polled. Below is a list of the Wi-Fi Driver functions within
WF_Eint.c
that must be customized for the specific Host CPU architecture.
Function
WF_EintInit()
WF_EintEnable()
WF_EintDisable()
WF_EintIsr()
WF_EintIsDisabled()
WFEintHandler()
Description
Configures the interrupt for use and leaves it in a disabled state. Will be called by the
Wi-Fi driver during initialization. If polling the EXINT pin then this function won’t have any work to do except leave the interrupt in a logically disabled state.
Enables the MRF24WB0M / MRF24WG0M external interrupt. If using real interrupts then enable the interrupt. If polling the EXINT pin then this function enables polling of the pin.
Disables the MRF24WB0M / MRF24WG0M external interrupt. If using real interrupts then disable the interrupt. If polling the EXINT pin then this function disables polling of the pin.
This is the interrupt service routine invoked when the EXINT line goes low. It should perform any necessary housekeeping , such as clearing the interrupt. The interrupt must remain disabled until the Wi-Fi Driver calls
WF_EintEnable()
. The Wi-Fi driver function, WFEintHandler() must be called.
Returns true if the external interrupt is disabled, else returns false.
This function does not need to be customized – it is part of the Wi-Fi driver. However, it is added to this list because it must be called each time the MRF24WB0M /
MRF24WG0M interrupt service routine (ISR) occurs.
636
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help
WF_Config.c/h
The WF_Config module (
WF_Config.h
/
WF_Config.c
) is used to control several aspects of the WiFi Driver behavior. Most of the customization of the Wi-Fi module is done from the context of this module.
Removal of Unused Driver Functions
In WFApi.h
there is a block of defines that can be commented out to remove those sections of the Wi-Fi host driver that are not needed by the application. This allows the saving of code and data space.
#define
WF_USE_SCAN_FUNCTIONS
WF_USE_TX_POWER_CONTROL_FUNCTIONS
WF_USE_POWER_SAVE_FUNCTIONS
WF_USE_MULTICAST_FUNCTIONS
WF_USE_INDIVIDUAL_SET_GETS
WF_USE_GROUP_SET_GETS
Controlling Functions
Scan API
Tx power control API
Power save API
Multicast API
Affects all get and set functions, except the following:
WF_CPSetElements ( see page 646)()
WF_CPGetElements ( see page 641)()
WF_CASetElements ( see page 665)()
WF_CAGetElements ( see page 657)()
Affects the following functions:
WF_CPSetElements ( see page 646)()
WF_CPGetElements ( see page 641)()
WF_CASetElements ( see page 665)()
WF_CAGetElements ( see page 657)()
WF_DEBUG
This define enables the
WF_ASSERT
macro in the Wi-Fi driver. Customer code is free to use this macro. The
WF_ASSERT macro can be compiled in or out via the
WF_DEBUG
define. See the comment above the
WF_DEBUG
define in
WF_Customize.h
for details.
WF_CONSOLE
The Wi-Fi driver has a UART console application built in that allows one to type in command lines and has them parsed. If this functionality is not needed than it can be compiled out by commenting out the
WF_CONSOLE
define.
WF_ProcessEvent()
This function is called by the Wi-Fi Driver when an event occurs that the host CPU needs to be notified of. There are several
Wi-Fi connection related events that the application can choose whether to be notified or not. And, there are several events the application will always be notified of.
The function
WF_ProcessEvent ( see page 717)()
can be customized to support desired handling of events.
11.1
Wi-Fi Connection Profile
Module
637
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
Macros
Name
RAW_MGMT_RX_ID ( see page 652)
Description
This is macro RAW_MGMT_RX_ID.
Description
This section describes the API functions related to creating and using connection profiles. At least one connection profile must be created. The connection profile defines elements required by the MRF24WB0M / MRF24WG0M to establish a connection to a Wi-Fi network.
Modifying Connection Profile after Connection is Established
A connection profile can be updated while it is being used for an active connection. However, the updates do not take effect until one of the following occurs:
• Connection is disabled and re-enabled by the host application
• Connection algorithm loses the connection, exhausts all retries, and then reloads the connection profile.
To ensure that connection profile updates take place at a known point in time it is recommended that the host application call
WF_CMDisconnect ( see page 678)()
, update the connection profile, then call
.
11.1.1
Connection Profile Public Members
Functions
Name
WF_CPGetElements ( see page 641)
WF_CPGetNetworkType ( see page 642)
WF_CPGetSecurity ( see page 643)
WF_CPSetElements ( see page 646)
WF_CPSetNetworkType ( see page 646)
Description
Creates a Connection Profile on the MRF24W.
Deletes a Connection Profile on the MRF24W.
Gets the desired Ad Hoc behavior
Gets the BSSID for the specified Connection Profile ID.
Reads the Connection Profile elements for the specified ID.
Retrieves the CP ID bit mask.
Gets the network type for the specified Connection Profile ID.
Gets the security for the specified Connection Profile.
Gets the SSID for the specified Connection Profile ID.
Selects the desired Ad Hoc behavior
Sets the BSSID for the specified Connection Profile ID.
Writes out data for a specific connection profile element.
Sets the network type for the specified Connection Profile ID.
638
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
WF_CPSetSecurity ( see page 647)
WF_CPGetSsidType ( see page 649)
WF_CPSetSsidType ( see page 650)
Sets the security for the specified Connection Profile.
Sets the SSID for the specified Connection Profile ID.
Gets the SSID type for the specified Connection Profile ID.
Sets the SSID type for the specified Connection Profile ID.
Module
Wi-Fi Connection Profile ( see page 637)
Structures
Name
WFCPElementsStruct ( see page 648)
Description
Connection profile elements structure
Description
11.1.1.1
WF_CPCreate Function
File
WFApi.h
C void
WF_CPCreate(
UINT8 * p_CpId
);
Returns
None.
Description
Connection Profile Functions
Requests the MRF24W to create a Connection Profile (CP), assign it an ID, and set all the elements to default values. The
ID returned by this function is used in other connection profile functions. A maximum of 2 Connection Profiles can exist on the MRF24W. Users are encouraged to use 1 profile ID for MRF24W based on v5 stack SW. In v6 stack SW, plan is to have
1 profile ID for MRF24W but stack will be designed to have capability to handle multiple profiles.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_CpId
Description
Pointer to where Connection Profile ID will be written. If function fails, the CP ID will be set to 0xff.
639
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
11.1.1.2
WF_CPDelete Function
File
WFApi.h
C void
WF_CPDelete(
UINT8 CpId
);
Returns
None.
Description
Deletes the specified Connection Profile. If the Connection Profile was in FLASH it will be erased from FLASH.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId
Description
Connection Profile to delete.
11.1.1.3
WF_CPGetAdHocBehavior Function
File
WFApi.h
C void
WF_CPGetAdHocBehavior(
UINT8 CpId,
UINT8 * p_adHocBehavior
);
Returns
None.
Description
Gets the AdHoc behavior within a Connection Profile. Allowable values are:
• WF_ADHOC_CONNECT_THEN_START
• WF_ADHOC_CONNECT_ONLY
• WF_ADHOC_START_ONLY
Remarks
None.
Preconditions
MACInit must be called first.
640
11.1 Wi-Fi Connection Profile
Parameters
Parameters
CpId adHocBehavior
Microchip TCP/IP Stack Help Connection Profile Public Members
Description
Connection Profile ID
Pointer to location of the adhoc behavior value for this connection profile.
11.1.1.4
WF_CPGetBssid Function
File
WFApi.h
C void
WF_CPGetBssid(
UINT8 CpId,
UINT8 * p_bssid
);
Returns
None.
Description
Gets the BSSID element in a Connection Profile.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId p_bssid
Description
Connection Profile ID
Pointer to the BSSID
11.1.1.5
WF_CPGetElements Function
File
WFApi.h
C void
WF_CPGetElements(
UINT8 CpId,
tWFCPElements * p_elements
);
Returns
None.
Description
Gets all Connection Profile elements for the specified CP ID. If the Host CPU does not have enough memory to create a structure of this size then call the individual get functions.
Remarks
None.
641
11.1 Wi-Fi Connection Profile
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId p_elements
Microchip TCP/IP Stack Help Connection Profile Public Members
Description
Connectino Profile ID.
Pointer to Connection Profile elements structure.
11.1.1.6
WF_CPGetIds Function
File
WFApi.h
C void
WF_CPGetIds(
UINT8 * cpIdList
);
Returns
None.
Description
Returns a list of all Connection Profile IDs that have been created on the MRF24W. This is not to be confused with the
Connection Algorithm's connectionProfileList. This function returns a bit mask corresponding to a list of all Connection
Profiles that have been created (whether they are in the connectionProfileList or not). Any Connection Profiles that have been saved to FLASH will be included. Users are encouraged to use 1 profile ID for MRF24W based on v5 stack SW. In v6 stack SW, plan is to have 1 profile ID for MRF24W but stack will be designed to have capability to handle multiple profiles.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_cpIdList
Description
Pointer to value representing the bit mask where each bit index (plus 1) corresponds to a Connection Profile ID that has been created. For example, if this value is 0x03, then Connection Profile IDïs 1 and and 2 have been created.
11.1.1.7
WF_CPGetNetworkType Function
File
WFApi.h
C void
WF_CPGetNetworkType(
UINT8 CpId,
UINT8 * p_networkType
);
Returns
None.
642
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
Description
Gets the Network Type element of the Connection Profile. Allowable values are:
• WF_INFRASTRUCTURE
• WF_ADHOC
• WF_P2P
• WF_SOFT_AP
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId networkType
Description
Connection Profile ID
Type of network to create (infrastructure or adhoc or p2p or softAP)
11.1.1.8
WF_CPGetSecurity Function
File
WFApi.h
C void
WF_CPGetSecurity(
UINT8 CpId,
UINT8 * p_securityType,
UINT8 * p_wepKeyIndex,
UINT8 * p_securityKey,
UINT8 * p_securityKeyLength
);
Returns
None.
Description
Configures security for a Connection Profile.
Security
WF_SECURITY_OPEN
WF_SECURITY_WEP_40
WF_SECURITY_WEP_104
WF_SECURITY_WPA_WITH_KEY
WF_SECURITY_WPA_WITH_PASS_PHRASE
WF_SECURITY_WPA2_WITH_KEY
WF_SECURITY_WPA2_WITH_PASS_PHRASE
WF_SECURITY_WPA_AUTO_WITH_KEY
WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE
WF_SECURITY_WPS_PUSH_BUTTON
WF_SECURITY_WPS_PIN
Key
N/A hex hex hex ascii hex ascii hex ascii
Length
N/A
4, 5 byte keys
4, 13 byte keys
32 bytes
8-63 ascii characters
32 bytes
8-63 ascii characters
32 bytes
8-63 ascii characters
643
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
WF_SECURITY_WPA2_ENTERPRISE
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId securityType wepKeyIndex p_securityKey securityKeyLength
Description
Connection Profile ID
Value corresponding to the security type desired.
Only index 0 is valid. (Applicable for WF_SECURITY_WEP_40 or
WF_SECURITY_WEP_104)
Binary key or passphrase (not used if security is WF_SECURITY_OPEN)
Number of bytes in p_securityKey (not used if security is
WF_SECURITY_OPEN)
11.1.1.9
WF_CPGetSsid Function
File
WFApi.h
C void
WF_CPGetSsid(
UINT8 CpId,
UINT8 * p_ssid,
UINT8 * p_ssidLength
);
Returns
None.
Description
Gets the SSID and SSID Length elements in the Connection Profile.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId p_ssid ssidLength
Description
Connection Profile ID
Pointer to the SSID string
Pumber of bytes in the SSID
11.1.1.10
WF_CPSetAdHocBehavior Function
File
WFApi.h
644
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
C void
WF_CPSetAdHocBehavior(
UINT8 CpId,
UINT8 adHocBehavior
);
Returns
None.
Description
Sets the AdHoc behavior within a Connection Profile. Allowable values are:
• WF_ADHOC_CONNECT_THEN_START
• WF_ADHOC_CONNECT_ONLY
• WF_ADHOC_START_ONLY
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId adHocBehavior
Description
Connection Profile ID
Value of the adhoc behavior for this connection profile.
11.1.1.11
WF_CPSetBssid Function
File
WFApi.h
C void
WF_CPSetBssid(
UINT8 CpId,
UINT8 * p_bssid
);
Returns
None.
Description
Sets the BSSID element in a Connection Profile.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId p_bssid
Description
Connection Profile ID
Pointer to the BSSID
645
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
11.1.1.12
WF_CPSetElements Function
File
WFApi.h
C void
WF_CPSetElements(
UINT8 CpId,
tWFCPElements * p_elements
);
Returns
None.
Description
Sets all Connection Profile elements. If the Host CPU does not have enough memory to create a structure of this size then call the individual set functions.
Remarks
None.
Preconditions
MACInit must be called.
Parameters
Parameters
CpId p_elements
Description
Connectino Profile ID.
Pointer to Connection Profile elements structure.
11.1.1.13
WF_CPSetNetworkType Function
File
WFApi.h
C void
WF_CPSetNetworkType(
UINT8 CpId,
UINT8 networkType
);
Returns
None.
Description
Sets the Network Type element for the Connection Profile. Allowable values are:
• WF_INFRASTRUCTURE
• WF_ADHOC
• WF_P2P
• WF_SOFT_AP
Remarks
None.
646
11.1 Wi-Fi Connection Profile
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId networkType
Microchip TCP/IP Stack Help Connection Profile Public Members
Description
Connection Profile ID
Type of network to create (infrastructure or adhoc or p2p or softAP)
11.1.1.14
WF_CPSetSecurity Function
File
WFApi.h
C void
WF_CPSetSecurity(
UINT8 CpId,
UINT8 securityType,
UINT8 wepKeyIndex,
UINT8 * p_securityKey,
UINT8 securityKeyLength
);
Returns
None.
Description
Configures security for a Connection Profile.
Security
WF_SECURITY_OPEN
WF_SECURITY_WEP_40
WF_SECURITY_WEP_104
WF_SECURITY_WPA_WITH_KEY
WF_SECURITY_WPA_WITH_PASS_PHRASE
WF_SECURITY_WPA2_WITH_KEY
WF_SECURITY_WPA2_WITH_PASS_PHRASE
WF_SECURITY_WPA_AUTO_WITH_KEY
WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE
WF_SECURITY_WPS_PUSH_BUTTON
WF_SECURITY_WPS_PIN
WF_SECURITY_WPA2_ENTERPRISE
Remarks
None.
Preconditions
MACInit must be called first.
Key
N/A hex hex hex ascii hex ascii hex ascii
Length
N/A
4, 5 byte keys
4, 13 byte keys
32 bytes
8-63 ascii characters
32 bytes
8-63 ascii characters
32 bytes
8-63 ascii characters
647
11.1 Wi-Fi Connection Profile
Parameters
Parameters
CpId securityType wepKeyIndex p_securityKey securityKeyLength
Microchip TCP/IP Stack Help Connection Profile Public Members
Description
Connection Profile ID
Value corresponding to the security type desired.
Only index 0 is valid. (Applicable for WF_SECURITY_WEP_40 or
WF_SECURITY_WEP_104)
Binary key or passphrase (not used if security is WF_SECURITY_OPEN)
Number of bytes in p_securityKey (not used if security is
WF_SECURITY_OPEN)
11.1.1.15
WF_CPSetSsid Function
File
WFApi.h
C void
WF_CPSetSsid(
UINT8 CpId,
UINT8 * p_ssid,
UINT8 ssidLength
);
Returns
None.
Description
Sets the SSID and SSID Length elements in the Connection Profile. Note that an Access Point can have either a visible or hidden SSID. If an Access Point uses a hidden SSID then an active scan must be used (see scanType field in the
Connection Algorithm).
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId p_ssid ssidLength
Description
Connection Profile ID
Pointer to the SSID string
Number of bytes in the SSID
11.1.1.16
WFCPElementsStruct Structure
File
WFApi.h
C struct
WFCPElementsStruct {
UINT8 ssid[WF_MAX_SSID_LENGTH];
UINT8 bssid[WF_BSSID_LENGTH];
UINT8 ssidLength;
UINT8 securityType;
UINT8 securityKey[WF_MAX_SECURITY_KEY_LENGTH];
UINT8 securityKeyLength;
648
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Public Members
UINT8 wepDefaultKeyId;
UINT8 networkType;
UINT8 adHocBehavior;
UINT8 hiddenSSID;
UINT8 wepKeyType;
};
Members
Members
UINT8 ssid[WF_MAX_SSID_LENGTH];
UINT8 bssid[WF_BSSID_LENGTH];
UINT8 ssidLength;
Description
SSID, which must be less than or equal to 32 characters. Set to all 0’s if not being used. If ssidLength is 0 this field is ignored. If SSID is not
Default: SSID not used.
Basic Service Set Identifier, always 6 bytes. This is the 48-bit MAC of the SSID. It is an optional field that can be used to specify a specific
SSID if more than one AP exists with the same SSID. This field can also be used in lieu of the SSID.
Set each byte to 0xFF if BSSID is not going to be used. Default:
BSSID not used (all FF’s)
Number of ASCII bytes in ssid. Set to 0 is SSID is not going to be used.
Default: 0
UINT8 securityType; Designates the desired security level for the connection. Choices are:
UINT8 securityKey[WF_MAX_SECURITY_KEY_LENGTH];
Set to NULL if securityType is WF_SECURITY_OPEN. If securityKeyLength is 0 this field is ignored.
UINT8 securityKeyLength;
UINT8 wepDefaultKeyId;
Number of bytes used in the securityKey. Set to 0 if securityType is
WF_SECURITY_OPEN.
This field is only used if securityType is WF_SECURITY_WEP_40 or
WF_SECURITY_WEP_104. This field designates which of the four
WEP keys defined in securityKey to use when connecting to a WiFi network. Only WEP key index (wepDefaultKeyId) 0 is used in RF module FW.
UINT8 networkType;
UINT8 adHocBehavior;
UINT8 hiddenSSID;
UINT8 wepKeyType;
WF_INFRASTRUCTURE / WF_ADHOC / WF_P2P / WF_SOFT_AP
Default: WF_INFRASTRUCTURE
Only applicable if networkType is WF_ADHOC. Configures Adhoc behavior. Choices are:
1 - enable hidden ssid in adhoc mode
0- shared key, 1 - open key
Description
Connection profile elements structure
11.1.1.17
WF_CPGetSsidType Function
File
WFApi.h
C void
WF_CPGetSsidType(
UINT8 CpId,
UINT8 * hidden
);
Returns
None.
649
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help
Description
Gets the SSID type element in the Connection Profile.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId hidden
Description
Connection Profile ID
Pointer to the SSID type
Connection Profile Internal Members
11.1.1.18
WF_CPSetSsidType Function
File
WFApi.h
C void
WF_CPSetSsidType(
UINT8 CpId,
UINT8 hidden
);
Returns
None.
Description
Sets the SSID type element in the Connection Profile. This is valid only when we create AdHoc network.
Remarks
None.
Preconditions
MACInit must be called first.
11.1.2
Connection Profile Internal Members
Functions
Name
LowLevel_CPGetElement ( see page 651)
LowLevel_CPSetElement ( see page 651)
Description
Get an element of the connection profile on the MRF24W.
Set an element of the connection profile on the MRF24W.
Module
Wi-Fi Connection Profile ( see page 637)
Description
650
11.1 Wi-Fi Connection Profile Microchip TCP/IP Stack Help Connection Profile Internal Members
11.1.2.1
LowLevel_CPGetElement Function
File
WFConnectionProfile.c
C static void
LowLevel_CPGetElement(
UINT8 CpId,
UINT8 elementId,
UINT8 * p_elementData,
UINT8 elementDataLength,
UINT8 dataReadAction
);
Returns
None.
Description
All Connection Profile 'Get Element' functions call this function to construct the management message. The caller must fix up any endian issues prior to calling this function.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId elementId p_elementData elementDataLength dataReadAction
Description
Connection Profile ID
Element that is being read
Pointer to where element data will be written
Number of element data bytes that will be read
If TRUE then read data per paramters and free mgmt response buffer. If FALSE then return after response received, do not read any data as the caller will do that, and don't free buffer, as caller will do that as well.
11.1.2.2
LowLevel_CPSetElement Function
File
WFConnectionProfile.c
C static void
LowLevel_CPSetElement(
UINT8 CpId,
UINT8 elementId,
UINT8 * p_elementData,
UINT8 elementDataLength
);
Returns
None.
Description
LOCAL FUNCTION PROTOTYPES
All Connection Profile 'Set Element' functions call this function to construct the management message. The caller must fix up
651
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members any endian issues prior to calling this function.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId elementId p_elementData elementDataLength
Description
Connection Profile ID
Element that is being set
Pointer to element data
Number of bytes pointed to by p_elementData
11.1.3
Macros
Macros
Name
RAW_MGMT_RX_ID ( see page 652)
Description
This is macro RAW_MGMT_RX_ID.
Module
Wi-Fi Connection Profile ( see page 637)
11.1.3.1
RAW_MGMT_RX_ID Macro
File
WFConnectionProfile.c
C
#define
RAW_MGMT_RX_ID RAW_RX_ID
Description
This is macro RAW_MGMT_RX_ID.
11.2
Wi-Fi Connection Algorithm
Module
Description
The connection algorithm is used to fine-tune the MRF24WB0M / MRF24WG0M algorithm used in the connection process.
The connection algorithm can only be changed when the MRF24WB0M / MRF24WG0M is not connected to an 802.11
network.
652
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
11.2.1
Connection Algorithm Public Members
Functions
Name Description
WF_CAGetBeaconTimeout ( see page 654)
Reads the beacon timeout value.
Reads the Connection Algorithm beacon timeout action.
WF_CAGetChannelList ( see page 655)
Gets the channel list.
Not currently supported
WF_CAGetDeauthAction ( see page 656)
Reads the Connection Algorithm deauth action.
Reads all Connection Algorithm elements.
WF_CAGetEventNotificationAction
Reads the Connection Algorithm event notification action.
Gets the listen ( see page 180) interval.
WF_CAGetListenInterval ( see page 658)
WF_CAGetListRetryCount ( see page 659)
Gets the list retry count
WF_CAGetMaxChannelTime ( see page 659)
WF_CAGetMinChannelTime ( see page 660)
WF_CAGetProbeDelay ( see page 660)
Gets the Max Channel Time (in milliseconds)
Gets the current Connection Algorithm minimum channel time.
Gets the Probe Delay (in microseconds)
Gets the RSSI threshold
WF_CAGetScanCount ( see page 661)
Gets the scan count
Gets the Connection Algorithm scan type
Sets the beacon timeout value.
WF_CASetBeaconTimeout ( see page 662)
Action to take if a connection is lost due to a beacon timeout.
Sets the channel list.
WF_CASetChannelList ( see page 663)
WF_CASetDeauthAction ( see page 664)
Not currently supported
Sets the DeauthAction used by the Connection Algorithm.
Writes all Connection Algorithm elements.
WF_CASetEventNotificationAction
Sets the WiFi events that the host wishes to be notified of.
Sets the listen ( see page 180) interval.
WF_CASetListenInterval ( see page 666)
WF_CASetListRetryCount ( see page 667)
Sets the list retry count
653
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
Module
Wi-Fi Connection Algorithm ( see page 652)
Structures
WF_CASetMaxChannelTime ( see page 667)
WF_CASetMinChannelTime ( see page 668)
WF_CASetProbeDelay ( see page 668)
Sets the maximum channel time (in milliseconds)
Sets the minimum channel time (in milliseconds)
Sets the Probe Delay (in microseconds)
Sets the RSSI threshold
WF_CASetScanCount ( see page 669)
Sets the scan count
Sets the Connection Algorith scan type
WF_CAGetDtimInterval ( see page 672)
WF_CASetDtimInterval ( see page 673)
Gets the dtim interval for MRF24WG0MA/B.
Sets the dtim interval for MRF24WG0MA/B.
WF_CAGetBeaconPeriod ( see page 673)
WF_CASetBeaconPeriod ( see page 673)
Retrieves beacon period in Adhoc start mode for MRF24WG0MA/B.
Sets the beacon period in Adhoc start mode for MRF24WG0MA/B
Name
WFCAElementsStruct ( see page 670)
Description
Connection Algorithm Elements
Description
The following functions and variables are available to the stack application.
11.2.1.1
WF_CAGetBeaconTimeout Function
File
WFApi.h
C void
WF_CAGetBeaconTimeout(
UINT8 * p_beaconTimeout
);
Returns
None.
Description
Gets the Beacon Timeout used by the Connection Algorithm.
Value Description
0 No monitoring of the beacon timeout condition. The host will not be notified of this event.
1-255 Number of beacons missed before disconnect event occurs and beaconTimeoutAction occurs. If enabled, host will receive an event message indicating connection temporarily or permanently lost, and if retrying, a connection successful event.
654
11.2 Wi-Fi Connection Algorithm
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_beaconTimeout
Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Pointer where beacon timeout value is written
11.2.1.2
WF_CAGetBeaconTimeoutAction Function
File
WFApi.h
C void
WF_CAGetBeaconTimeoutAction(
UINT8 * p_beaconTimeoutAction
);
Returns
None.
Description
Gets the Beacon Timeout Action used by the Connection Algorithm.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_beaconTimeoutAction will be either
Description
Pointer where returned value is written. The value
• WF_ATTEMPT_TO_RECONNECT
• WF_DO_NOT_ATTEMPT_TO_RECONNECT
11.2.1.3
WF_CAGetChannelList Function
File
WFApi.h
C void
WF_CAGetChannelList(
UINT8 * p_channelList,
UINT8 * p_numChannels
);
Returns
None.
Description
Gets the Channel List used by the Connection Algorithm.
655
11.2 Wi-Fi Connection Algorithm
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_channelList p_numChannels
Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Pointer to where channel list will be returned
Pointer to where number of channels in list will be returned
11.2.1.4
WF_CAGetConnectionProfileList Function
File
WFApi.h
C void
WF_CAGetConnectionProfileList(
UINT8 cpList[WF_CP_LIST_LENGTH]
);
Returns
None
Description
Not currently supported
Remarks
Not currently supported. The list size is always WF_CP_LIST_SIZE.
Preconditions
MACInit must be called first.
Parameters
Parameters
cpList
Description
Array of connection profile ID's used to create CP list
11.2.1.5
WF_CAGetDeauthAction Function
File
WFApi.h
C void
WF_CAGetDeauthAction(
UINT8 * p_deauthAction
);
Returns
None.
Description
Gets the DeauthAction used by the Connection Algorithm.
Remarks
None.
656
11.2 Wi-Fi Connection Algorithm
Preconditions
MACInit must be called first.
Parameters
Parameters
p_deauthAction be either
Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Pointer where returned value is written. The value will
• WF_ATTEMPT_TO_RECONNECT
• WF_DO_NOT_ATTEMPT_TO_RECONNECT
11.2.1.6
WF_CAGetElements Function
File
WFApi.h
C void
WF_CAGetElements(
tWFCAElements * p_elements
);
Returns
None
Description
Sends a message to the MRF24W which requests all the Connection Algorithm elements.
Remarks
None
Preconditions
MACInit must be called first.
Parameters
Parameters
p_elements
Description
Pointer to the output structure (tWFCAElements) where the connection algorithm elements are written.
11.2.1.7
WF_CAGetEventNotificationAction Function
File
WFApi.h
C void
WF_CAGetEventNotificationAction(
UINT8 * p_eventNotificationAction
);
Returns
None.
Description
Gets the Event Notification Action used by the Connection Algorithm. The value read back will be a bit mask that corresponds to the following table:
657
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
Bit Event
0 WF_NOTIFY_CONNECTION_ATTEMPT_SUCCESSFUL
1 WF_NOTIFY_CONNECTION_ATTEMPT_FAILED
2 WF_NOTIFY_CONNECTION_TEMPORARILY_LOST
3 WF_NOTIFY_CONNECTION_PERMANENTLY_LOST
4 WF_NOTIFY_CONNECTION_REESTABLISHED
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_eventNotificationAction
Description
Pointer to where returned value is written.
11.2.1.8
WF_CAGetListenInterval Function
File
WFApi.h
C void
WF_CAGetListenInterval(
UINT16 * p_listenInterval
);
Returns
None.
Description
Gets the Listen Interval used by the Connection Algorithm. This value is measured in 100ms intervals, the default beacon period of APs.
Value Description
1 MRF24W wakes up every 100ms to receive buffered messages.
2
...
MRF24W wakes up every 200ms to receive buffered messages.
...
65535 MRF24W wakes up every 6535.5 seconds (~109 minutes) to receive buffered messages.
Remarks
None.
Preconditions
MACInit must be called first. Only used when PS Poll mode is enabled.
Parameters
Parameters
p_listenInterval
Description
Pointer to where listen ( see page 180) interval is returned
658
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
11.2.1.9
WF_CAGetListRetryCount Function
File
WFApi.h
C void
WF_CAGetListRetryCount(
UINT8 * p_listRetryCount
);
Returns
None
Description
See description in WF_CASetListRetryCount ( see page 667)()
Remarks
None
Preconditions
MACInit must be called first.
Parameters
Parameters
p_listRetryCount
Description
Pointer to where list retry count is written.
11.2.1.10
WF_CAGetMaxChannelTime Function
File
WFApi.h
C void
WF_CAGetMaxChannelTime(
UINT16 * p_minChannelTime
);
Returns
None
Description
Gets the maximum time the connection manager waits for a probe response after sending a probe request.
Remarks
Default is 400ms
Preconditions
MACInit must be called first.
Parameters
Parameters
p_maxChannelTime
Description
Pointer where maximum channel time is written
659
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
11.2.1.11
WF_CAGetMinChannelTime Function
File
WFApi.h
C void
WF_CAGetMinChannelTime(
UINT16 * p_minChannelTime
);
Returns
None
Description
Gets the minimum time the connection manager waits for a probe response after sending a probe request.
Remarks
None
Preconditions
MACInit must be called first.
Parameters
Parameters
p_minChannelTime
Description
Pointer where minimum time to wait for a probe response (in milliseconds) will be written.
11.2.1.12
WF_CAGetProbeDelay Function
File
WFApi.h
C void
WF_CAGetProbeDelay(
UINT16 * p_probeDelay
);
Returns
None
Description
The number of microseconds to delay before transmitting a probe request following the channel change event.
Remarks
Default is 20uS
Preconditions
MACInit must be called first.
Parameters
Parameters
p_probeDelay
Description
Pointer to where probe delay is written
660
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
11.2.1.13
WF_CAGetRssi Function
File
WFApi.h
C void
WF_CAGetRssi(
UINT8 * p_rssi
);
Returns
None
Description
-- this is not the current RSSI of an existing connection. If it is desired to retrieve the current RSSI state then a scan must be performed and the scan result will contain the current RSSI state.
Remarks
Default is 255
Preconditions
MACInit must be called first.
Parameters
Parameters
p_rssi
Description
Pointer to where RSSI value is written
11.2.1.14
WF_CAGetScanCount Function
File
WFApi.h
C void
WF_CAGetScanCount(
UINT8 * p_scanCount
);
Returns
None
Description
The number of times the Connection Manager will scan a channel while attempting to find a particular WiFi network.
Remarks
Default is 1
Preconditions
MACInit must be called first.
Parameters
Parameters
p_scanCount
Description
Pointer to where scan count is written
661
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
11.2.1.15
WF_CAGetScanType Function
File
WFApi.h
C void
WF_CAGetScanType(
UINT8 * p_scanType
);
Returns
None
Description
Reads the current Connection Algorithm scan type. In active scan, STA will transmit probe request frames and AP/routers will respond by transmitting probe response frames. For AP/Router with hidden SSID, active scan is used. In passive scan,
AP/router will continuously transmit beacon frames for every beacon interval (BI), any STAs may/will receive these beacons and know of existence of this AP/router.
Remarks
Active scanning causes the MRF24W to send probe requests. Passive scanning implies the MRF24W only listens for beacons. Default is WF_ACTIVE_SCAN.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_scanType
Description
Pointer where Connection Algorithm scan type is written. Either
WF_ACTIVE_SCAN or WF_PASSIVE_SCAN.
11.2.1.16
WF_CASetBeaconTimeout Function
File
WFApi.h
C void
WF_CASetBeaconTimeout(
UINT8 beaconTimeout
);
Returns
None.
Description
Sets the Beacon Timeout used by the Connection Algorithm.
Value Description
0 No monitoring of the beacon timeout condition. The host will not be notified of this event.
1-255 Number of beacons missed before disconnect event occurs and beaconTimeoutAction occurs. If enabled, host will receive an event message indicating connection temporarily or permanently lost, and if retrying, a connection successful event.
662
11.2 Wi-Fi Connection Algorithm
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
beaconTimeout
Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Number of beacons that can be missed before the action in beaconTimeoutAction is taken.
11.2.1.17
WF_CASetBeaconTimeoutAction Function
File
WFApi.h
C void
WF_CASetBeaconTimeoutAction(
UINT8 beaconTimeoutAction
);
Returns
None.
Description
Sets the Beacon Timeout Action used by the Connection Algorithm.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
beaconTimeoutAction to a beacon timeout. Choices are either
Description
Action to take if a connection is lost due
• WF_ATTEMPT_TO_RECONNECT
• WF_DO_NOT_ATTEMPT_TO_RECONNECT
11.2.1.18
WF_CASetChannelList Function
File
WFApi.h
C void
WF_CASetChannelList(
UINT8 * p_channelList,
UINT8 numChannels
);
Returns
None.
663
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Sets the Channel List used by the Connection Algorithm.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_channelList numChannels
Description
Pointer to channel list.
Number of channels in p_channelList. If set to 0, the MRF24W will use all valid channels for the current regional domain.
11.2.1.19
WF_CASetConnectionProfileList Function
File
WFApi.h
C void
WF_CASetConnectionProfileList(
UINT8 cpList[WF_CP_LIST_LENGTH]
);
Returns
None
Description
Not currently supported
Remarks
Not currently supported. The list size is always WF_CP_LIST_SIZE. The list should start at index 0. Unused entries in the list must be set to 0xff.
Preconditions
MACInit must be called first.
Parameters
Parameters
cpList
Description
Array of connection profile ID's used to create CP list
11.2.1.20
WF_CASetDeauthAction Function
File
WFApi.h
C void
WF_CASetDeauthAction(
UINT8 deauthAction
);
Returns
None.
664
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Action to take if a connection is lost due to receiving a deauthentification message from an AP.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
deauthAction
Allowable values are
Description
Action to take in the event of a deauthentication.
• WF_ATTEMPT_TO_RECONNECT
• WF_DO_NOT_ATTEMPT_TO_RECONNECT
11.2.1.21
WF_CASetElements Function
File
WFApi.h
C void
WF_CASetElements(
tWFCAElements * p_elements
);
Returns
None
Description
Connection Algorithm Functions
Sends a message to the MRF24W which sets all the Connection Algorithm elements.
Remarks
None
Preconditions
MACInit must be called first.
Parameters
Parameters
p_elements
Description
Pointer to the input structure (tWFCAElements) containing the connection algorithm elements.
11.2.1.22
WF_CASetEventNotificationAction Function
File
WFApi.h
C void
WF_CASetEventNotificationAction(
UINT8 eventNotificationAction
);
665
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
Returns
None.
Description
Sets the Event Notification Action used by the Connection Algorithm. The bit mask for the allowable entries is as follows:
Bit Event
0 WF_NOTIFY_CONNECTION_ATTEMPT_SUCCESSFUL
1 WF_NOTIFY_CONNECTION_ATTEMPT_FAILED
2 WF_NOTIFY_CONNECTION_TEMPORARILY_LOST
3 WF_NOTIFY_CONNECTION_PERMANENTLY_LOST
4 WF_NOTIFY_CONNECTION_REESTABLISHED
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
eventNotificationAction
Description
Bit mask indicating which events the host wants to be notifed of.
11.2.1.23
WF_CASetListenInterval Function
File
WFApi.h
C void
WF_CASetListenInterval(
UINT16 listenInterval
);
Returns
None.
Description
default beacon period of APs.
Value Description
1
2
MRF24W wakes up every 100ms to receive buffered messages.
MRF24W wakes up every 200ms to receive buffered messages.
...
...
65535 MRF24W wakes up every 6535.5 seconds (~109 minutes) to receive buffered messages.
Remarks
None.
666
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
Preconditions
MACInit must be called first. Only used when PS Poll mode is enabled.
Parameters
Parameters
listenInterval
Description
Number of 100ms intervals between instances when the MRF24W wakes up to receive buffered messages from the network.
11.2.1.24
WF_CASetListRetryCount Function
File
WFApi.h
C void
WF_CASetListRetryCount(
UINT8 listRetryCount
);
Returns
None
Description
Number of times to cycle through Connection Profile List before giving up on the connection attempt. Since lists are not yet
the current Connection Profile before giving up.
Remarks
None
Preconditions
MACInit must be called first.
Parameters
Parameters
listRetryCount
Description
0 to 254 or WF_RETRY_FOREVER (255)
11.2.1.25
WF_CASetMaxChannelTime Function
File
WFApi.h
C void
WF_CASetMaxChannelTime(
UINT16 minChannelTime
);
Returns
None
Description
The maximum time (in milliseconds) the connection manager will wait for a probe response after sending a probe request. If no probe responses are received in maxChannelTime then the connection manager will go on to the next channel, if any are left to scan, or quit.
667
11.2 Wi-Fi Connection Algorithm
Remarks
Default is 400ms
Preconditions
MACInit must be called first.
Parameters
Parameters
maxChannelTime
Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Maximum time to wait for a probe response (in milliseconds)
11.2.1.26
WF_CASetMinChannelTime Function
File
WFApi.h
C void
WF_CASetMinChannelTime(
UINT16 minChannelTime
);
Returns
None
Description
The minimum time (in milliseconds) the connection manager will wait for a probe response after sending a probe request. If no probe responses are received in minChannelTime then the connection manager will go on to the next channel, if any are left to scan, or quit.
Remarks
Default is 200ms
Preconditions
MACInit must be called first.
Parameters
Parameters
minChannelTime
Description
Minimum time to wait for a probe response (in milliseconds)
11.2.1.27
WF_CASetProbeDelay Function
File
WFApi.h
C void
WF_CASetProbeDelay(
UINT16 probeDelay
);
Returns
None
Description
The number of microseconds to delay before transmitting a probe request following the channel change event.
668
11.2 Wi-Fi Connection Algorithm
Remarks
Default is 20uS
Preconditions
MACInit must be called first.
Parameters
Parameters
probeDelay
Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
Desired probe delay
11.2.1.28
WF_CASetRssi Function
File
WFApi.h
C void
WF_CASetRssi(
UINT8 rssi
);
Returns
None
Description
Specifies the RSSI behavior when connecting. This value is only used if 1) The current Connection Profile has not defined an SSID or BSSID 2) An SSID is defined in the current Connection Profile and multiple access points are discovered with the same SSID.
network if the RSSI is greater than or equal to the specified value 255: Connect to the highest RSSI found
Note that RSSI is a relative value with no units -- it is not correlated to dBm.
Remarks
Default is 255
Preconditions
MACInit must be called first.
Parameters
Parameters
scanCount
Description
Desired scan count
11.2.1.29
WF_CASetScanCount Function
File
WFApi.h
C void
WF_CASetScanCount(
UINT8 scanCount
);
Returns
None
669
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
Description
The number of times the Connection Manager will scan a channel while attempting to find a particular WiFi network.
Remarks
Default is 1
Preconditions
MACInit must be called first.
Parameters
Parameters
scanCount
Description
Desired scan count
11.2.1.30
WF_CASetScanType Function
File
WFApi.h
C void
WF_CASetScanType(
UINT8 scanType
);
Returns
None
Description
Configures the Connection Algorithm for the desired scan type. In active scan, STA will transmit probe request frames and
AP/routers will respond by transmitting probe response frames. For AP/Router with hidden SSID, active scan is used. In passive scan, AP/router will continuously transmit beacon frames for every beacon interval (BI), any STAs may/will receive these beacons and know of existence of this AP/router.
Remarks
Active scanning causes the MRF24W to send probe requests. Passive scanning implies the MRF24W only listens for beacons. Default is WF_ACTIVE_SCAN.
Preconditions
MACInit must be called first.
Parameters
Parameters
scanType
Description
Desired scan type. Either WF_ACTIVE_SCAN or WF_PASSIVE_SCAN.
11.2.1.31
WFCAElementsStruct Structure
File
WFApi.h
C struct
WFCAElementsStruct {
UINT16 listenInterval;
UINT8 scanType;
UINT8 rssi;
UINT8 connectionProfileList[WF_CP_LIST_LENGTH];
UINT8 listRetryCount;
UINT8 eventNotificationAction;
670
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
UINT8 beaconTimeoutAction;
UINT8 deauthAction;
UINT8 channelList[WF_CHANNEL_LIST_LENGTH];
UINT8 numChannelsInList;
UINT8 beaconTimeout;
UINT8 scanCount;
UINT8 pad1;
UINT16 minChannelTime;
UINT16 maxChannelTime;
UINT16 probeDelay;
UINT16 dtimInterval;
UINT16 beaconPrd;
};
Members
Members
UINT16 listenInterval;
UINT8 scanType;
UINT8 rssi;
Description
This parameter is only used when PS Poll mode is enabled. See
WF_PsPollEnable ( see page 699)(). Number of 100ms intervals between
instances when the MRF24W wakes up to received buffered messages from the network. Range is from 1 (100ms) to 6553.5 sec (~109 min).
Note that the 802.11 standard defines the listen ( see page 180) interval
in terms of Beacon Periods, which are typically 100ms. If the MRF24W is communicating to a network with a network that has Beacon Periods that is not 100ms it will round up (or down) as needed to match the actual Beacon
Period as closely as possible.
Important Note: If the listenInterval is modified while connected to a network the MRF24W will automatically reconnect to the network with the new Beacon Period value. This may cause a temporary loss of data packets.
WF_ACTIVE_SCAN (Probe Requests transmitted out) or
WF_PASSIVE_SCAN (listen ( see page 180) only for beacons received)
Default: WF_ACTIVE_SCAN
Specifies RSSI restrictions when connecting. This field is only used if:
1. The Connection Profile has not defined a SSID or BSSID, or
2. An SSID is defined in the Connection Profile and multiple AP’s are discovered with the same SSID.
UINT8 connectionProfileList[WF_CP_LIST_LENGTH];
Note: Connection Profile lists are not yet supported. This array should be set to all FF’s.
UINT8 listRetryCount; This field is used to specify the number of retries for the single connection profile before taking the connection lost action.
Range 1 to 254 or WF_RETRY_FOREVER (255)
Default is 3
UINT8 eventNotificationAction;
UINT8 beaconTimeoutAction;
There are several connection-related events that can occur. The Host has the option to be notified (or not) when some of these events occur. This field controls event notification for connection-related events.
Specifies the action the Connection Manager should take if a Connection is lost due to a Beacon Timeout. If this field is set to
WF_ATTEMPT_TO_RECONNECT then the number of attempts is limited to the value in listRetryCount.
Choices are: WF_ATTEMPT_TO_RECONNECT or
WF_DO_NOT_ATTEMPT_TO_RECONNECT
Default: WF_ATTEMPT_TO_RECONNECT
UINT8 deauthAction; Designates what action the Connection Manager should take if it receives a
Deauthentication message from the AP.
If this field is set to WF_ATTEMPT_TO_RECONNECT then the number of attempts is limited to the value in listRetryCount.
Choices are: WF_ATTEMPT_TO_RECONNECT or
WF_DO_NOT_ATTEMPT_TO_RECONNECT
Default: WF_ATTEMPT_TO_RECONNECT
671
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Public Members
UINT8 channelList[WF_CHANNEL_LIST_LENGTH];
UINT8 numChannelsInList;
UINT8 beaconTimeout;
UINT8 scanCount;
UINT16 minChannelTime;
UINT16 maxChannelTime;
UINT16 probeDelay;
UINT16 dtimInterval;
UINT16 beaconPrd;
Description
Connection Algorithm Elements
List of one or more channels that the MRF24W should utilize when connecting or scanning. If numChannelsInList is set to 0 then this parameter should be set to NULL.
Default: All valid channels for the regional domain of the MRF24W (set at manufacturing).
Number of channels in channelList. If set to 0 then the MRF24W will populate the list with all valid channels for the regional domain.
Default: The number of valid channels for the regional domain of the
MRF24W (set at manufacturing).
Specifies the number of beacons that can be missed before the action described in beaconTimeoutAction is taken.
The number of times to scan a channel while attempting to find a particular access point.
Default: 1
The minimum time (in milliseconds) the connection manager will wait for a probe response after sending a probe request. If no probe responses are received in minChannelTime then the connection manager will go on to the next channel, if any are left to scan, or quit.
Default: 200ms
If a probe response is received within minChannelTime then the connection manager will continue to collect any additional probe responses up to maxChannelTime before going to the next channel in the channelList. Units are in milliseconds.
Default: 400ms
The number of microseconds to delay before transmitting a probe request following the channel change event.
Default: 20us
Default : 4
Default : 100 (ms)
11.2.1.32
WF_CAGetDtimInterval Function
File
WFApi.h
C void
WF_CAGetDtimInterval(
UINT16 * p_dtimInterval
);
Returns
None.
Description
Gets the DTIM Interval used by the Connection Algorithm for MRF24WG0MA/B.
Remarks
None.
Preconditions
MACInit must be called first. Only used when PS Poll mode is enabled.
672
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help
11.2.1.33
WF_CASetDtimInterval Function
File
WFApi.h
C void
WF_CASetDtimInterval(
UINT16 dtimInterval
);
Returns
None.
Description
Sets the dtim interval used by the Connection Algorithm for MRF24WG0MA/B.
Remarks
None.
Preconditions
MACInit must be called first. Only used when PS Poll mode is enabled.
11.2.1.34
WF_CAGetBeaconPeriod Function
File
WFApi.h
C void
WF_CAGetBeaconPeriod(
UINT16 * beaconPeriod
);
Returns
None.
Description
Gets Beacon period in Adhoc start mode for MRF24WG0MA/B.
Remarks
None.
Preconditions
MACInit must be called first.
11.2.1.35
WF_CASetBeaconPeriod Function
File
WFApi.h
C void
WF_CASetBeaconPeriod(
UINT16 beaconPeriod
);
Connection Algorithm Public Members
673
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Internal Members
Returns
None.
Description
Sets the beacon period used by the Connection Algorithm for MRF24WG0MA/B.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
beaconPeriod
Description
beacon period in adhoc start mode by ms resoluation
11.2.2
Connection Algorithm Internal Members
Functions
Name
LowLevel_CAGetElement ( see page 674)
LowLevel_CASetElement ( see page 675)
SetEventNotificationMask ( see page 675)
Description
Get an element of the connection algorithm on the MRF24W.
Set an element of the connection algorithm on the MRF24W.
Sets the event notification mask.
Module
Wi-Fi Connection Algorithm ( see page 652)
Description
The following functions and variables are designated as internal to the module.
11.2.2.1
LowLevel_CAGetElement Function
File
WFConnectionAlgorithm.c
C static void
LowLevel_CAGetElement(
UINT8 elementId,
UINT8 * p_elementData,
UINT8 elementDataLength,
UINT8 dataReadAction
);
Returns
None.
Description
Low-level function to send the appropriate management message to the MRF24W to get the Connection Algorithm element.
674
11.2 Wi-Fi Connection Algorithm Microchip TCP/IP Stack Help Connection Algorithm Internal Members
Remarks
All Connection Algorithm 'Get Element' functions call this function to construct the management message. The caller must fix up any endian issues after getting the data from this function.
Preconditions
MACInit must be called first.
Parameters
Parameters
elementId p_elementData elementDataLength dataReadAction
Description
Element that is being read
Pointer to where element data will be written
Number of element data bytes that will be read
If TRUE then read data per paramters and free mgmt response buffer. If FALSE then return after response received, do not read any data as the caller will do that, and don't free buffer, as caller will do that as well.
11.2.2.2
LowLevel_CASetElement Function
File
WFConnectionAlgorithm.c
C static void
LowLevel_CASetElement(
UINT8 elementId,
UINT8 * p_elementData,
UINT8 elementDataLength
);
Returns
None.
Description
LOCAL FUNCTION PROTOTYPES
Low-level function to send the appropriate management message to the MRF24W to set the Connection Algorithm element.
Remarks
All Connection Algorithm 'Set Element' functions call this function to construct the management message. The caller must fix up any endian issues prior to calling this function.
Preconditions
MACInit must be called first.
Parameters
Parameters
elementId p_elementData elementDataLength
Description
Element that is being set
Pointer to element data
Number of bytes pointed to by p_elementData
11.2.2.3
SetEventNotificationMask Function
File
WFConnectionAlgorithm.c
675
11.3 Wi-Fi Connection Manager Microchip TCP/IP Stack Help
C static void
SetEventNotificationMask(
UINT8 eventNotificationBitMask
);
Returns
None.
Description
Sets the event notification mask for the Connection Algorithm. Allowable values are:
Connection Manager Public Members
Value
0x01
0x02
0x04
0x08
0x10
0x1f
Event
WF_NOTIFY_CONNECTION_ATTEMPT_SUCCESSFUL
WF_NOTIFY_CONNECTION_ATTEMPT_FAILED
WF_NOTIFY_CONNECTION_TEMPORARILY_LOST
WF_NOTIFY_CONNECTION_PERMANENTLY_LOST
WF_NOTIFY_CONNECTION_REESTABLISHED
WF_NOTIFY_ALL_EVENTS
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
eventNotificationBitMask
Description
Bit mask defining which events the host will be notified of.
11.3
Wi-Fi Connection Manager
Module
Description
a network.
11.3.1
Connection Manager Public Members
Functions
Name
WF_CMDisconnect ( see page 678)
Description
Commands the MRF24W to start a connection.
Commands the MRF24W to close any open connections and/or to cease
attempting to connect ( see page 176).
676
11.3 Wi-Fi Connection Manager Microchip TCP/IP Stack Help Connection Manager Public Members
Returns the current connection state. Caution when using
WF_CMGetConnectionState, as it may cause redirection issues when using iPhone iOS6.1, even though redirection on laptop is functional. Users are encouraged to use 1 profile ID for MRF24W based on v5 stack SW. This function is retained for backward compatibility. In v6 stack SW, we are keeping to 1 profile ID for MRF24W and changing stack SW to have capability to handle multiple profile IDs.
WF_CMGetConnectContext ( see page 678)
Retrieves WF connection context for MRF24WG0MA/B
Returns the current connection state.
Module
Wi-Fi Connection Manager ( see page 676)
Description
The following functions and variables are available to the stack application.
11.3.1.1
WF_CMConnect Function
File
WFApi.h
C void
WF_CMConnect(
UINT8 CpId
);
Returns
None.
Description
Connection Manager Functions
can occur as a result of a connection attempt being successful or not.
Note that if the Connection Profile being used has WPA or WPA2 security enabled and is using a passphrase, the connection manager will first calculate the PSK key, and then start the connection process. The key calculation can take up to 30 seconds.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId
Description
If this value is equal to an existing Connection Profile�s ID than only that
Connection Profile will be used to attempt a connection to a WiFi network. If this value is set to WF_CM_CONNECT_USING_LIST then the
connectionProfileList will be used to connect ( see page 176), starting with the
first Connection Profile in the list.
677
11.3 Wi-Fi Connection Manager Microchip TCP/IP Stack Help Connection Manager Public Members
11.3.1.2
WF_CMDisconnect Function
File
WFApi.h
C
UINT16 WF_CMDisconnect();
Returns
Operation results. Success or Failure
Description
Directs the Connection Manager to close any open connection or connection attempt in progress. No further attempts to
connect ( see page 176) are taken until WF_CMConnect ( see page 677)() is called.
Remarks
None.
Preconditions
MACInit must be called.
11.3.1.3
WF_CMGetConnectionState Function
File
WFApi.h
C void
WF_CMGetConnectionState(
UINT8 * p_state,
UINT8 * p_currentCpId
);
Returns
None.
Description
Returns the current connection state.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_state p_currentCpId
Description
Pointer to location where connection state will be written
Pointer to location of current connection profile ID that is being queried.
11.3.1.4
WF_CMGetConnectContext Function
File
WFApi.h
678
11.4 Wi-Fi Scan Microchip TCP/IP Stack Help
C void
WF_CMGetConnectContext(
tWFConnectContext * p_ctx
);
Returns
None.
Description
Retrieve connection context
Retrieves WF connection context for MRF24WG0MA/B
Remarks
None.
Preconditions
MACInit must be called first.
11.3.1.5
WF_CMCheckConnectionState Function
File
WFApi.h
C void
WF_CMCheckConnectionState(
UINT8 * p_state,
UINT8 * p_currentCpId
);
Returns
None.
Description
Returns the current connection state.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_state p_currentCpId
Description
Pointer to location where connection state will be written
Pointer to location of current connection profile ID that is being queried.
11.4
Wi-Fi Scan
Module
Description
If the application already knows the network SSID that it wants to join than it can set up a connection profile with that
679
11.4 Wi-Fi Scan Microchip TCP/IP Stack Help Scan Public Members information and attempt to join the network. However, there are applications that first need to dynamically determine what infrastructure, adhoc or Wi-Fi Direct networks are in the area, and then decide which network to join. The scan API functions are used to gather this information.
There are 2 types of scan operations
• Active Scan
STA will transmit probe request frames and AP/routers will respond by transmitting probe response frames. For AP/Router with hidden SSID, active scan is used.
• Passive Scan
AP/router will continuously transmit beacon frames for every beacon interval (BI), any STAs may/will receive these beacons and know of existence of this AP/router.
11.4.1
Scan Public Members
Functions
Name Description
Commands the MRF24W to start a scan operation. This will generate the
WF_EVENT_SCAN_RESULTS_READY event.
WF_ScanGetResult ( see page 681)
Read scan results back from MRF24W.
Module
Description
The following functions and variables are available to the stack application.
11.4.1.1
WF_Scan Function
File
WFApi.h
C
UINT16 WF_Scan(
UINT8 CpId
);
Returns
Operation results. Success or Failure
Description
Scan Functions
Directs the MRF24W to initiate a scan operation utilizing the input Connection Profile ID. The Host Application will be notified that the scan results are ready when it receives the WF_EVENT_SCAN_RESULTS_READY event. The eventInfo field for this event will contain the number of scan results. Once the scan results are ready they can be retrieved with
WF_ScanGetResult ( see page 681)().
Scan results are retained on the MRF24W until:
1. Calling WF_Scan() again (after scan results returned from previous call).
2. MRF24W reset.
680
11.4 Wi-Fi Scan Microchip TCP/IP Stack Help Scan Public Members
MRF24WB0M & MRF24WG0M support up to max of 60 scan results (SSIDs).
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId
Description
Connection Profile to use. If the CpId is valid then the values from that
Connection Profile will be used for filtering scan results. If the CpId is set to
WF_SCAN_ALL (0xFF) then a default filter will be used.
Valid CpId
• If CP has a defined SSID only scan results with that SSID are retained.
• If CP does not have a defined SSID then all scanned SSID’s will be retained
• Only scan results from Infrastructure or AdHoc networks are retained, depending on the value of networkType in the Connection Profile
• The channel list that is scanned will be determined from channelList in the
Connection Algorithm (which must be defined before calling this function).
CpId is equal to WF_SCAN_ALL
• All scan results are retained (both Infrastructure and Ad Hoc networks).
• All channels within the MRF24W’s regional domain will be scanned.
• No Connection Profiles need to be defined before calling this function.
• The Connection Algorithm does not need to be defined before calling this function.
11.4.1.2
WF_ScanGetResult Function
File
WFApi.h
C void
WF_ScanGetResult(
UINT8 listIndex,
tWFScanResult * p_scanResult
);
Returns
None.
Description
After a scan has completed this function is used to read one or more of the scan results from the MRF24W. The scan results will be written contiguously starting at p_scanResult (see tWFScanResult structure for format of scan result). MRF24WB0M
& MRF24WG0M support up to max of 60 scan results (SSIDs).
Remarks
p_scanResult->rssi contains signal strength RSSI. MRF24WB : RSSI_MAX (200) , RSSI_MIN (106). MRF24WG :
RSSI_MAX (128) , RSSI_MIN (43).
Preconditions
MACInit must be called first. WF_EVENT_SCAN_RESULTS_READY event must have already occurrerd.
681
Microchip TCP/IP Stack Help Wired Equivalent Privacy (WEP) 11.5 Wi-Fi Security
Parameters
Parameters
listIndex p_scanResult
Description
Index (0-based list) of the scan entry to retrieve.
Pointer to location to store the scan result structure
11.5
Wi-Fi Security
Module
Description
This section elaborates on the various security modes supported by MRF24WB0M and MRF24WG0M.
Security modes supported in
• Ad-hoc
OPEN, WEP
• SoftAP
OPEN, WEP
• Infrastructure
OPEN, WEP, WPA/WPA2, WPS
• Wi-Fi Direct
WPS
682
11.5 Wi-Fi Security Microchip TCP/IP Stack Help Wired Equivalent Privacy (WEP)
11.5.1
Wired Equivalent Privacy (WEP)
Functions
Name
WF_CPGetWepKeyType ( see page 684)
Description
Gets the WEP key type for the specified Connection Profile ID.
Returns the value of the active WEP keys to use. Only WEP key index 0 is used in RF module FW.
Set up the WEP key index. Only WEP key index 0 is used in RF module FW.
WF_CPSetWepKeyType ( see page 685)
Sets the WEP key type for the specified Connection Profile ID.
Description
WIRED EQUIVALENT PRIVACY (WEP)
Security loop holes are present and this is not recommend!!!
WEP security modes supported are
• WF_SECURITY_WEP_40
WEP Encryption using 40 bit keys. Also known as WEP 64 keys.
• WF_SECURITY_WEP_104
WEP Encryption using 104 bit keys Also known as WEP 128 keys.
MRF24W only accepts WEP hex keys (MY_DEFAULT_WEP_KEYS_40 or MY_DEFAULT_WEP_KEYS_104) and NOT
passphrase. Some Web sites offer this automatic WEP key generators, whereby WEP keys are generated from ordinary text called a passphrase.
WEP key types supported are
• WF_SECURITY_WEP_OPENKEY
Default
• WF_SECURITY_WEP_SHAREDKEY
Supported by MRF24WG0M.
Supported by MRF24WB0M (RF module FW version 0x1209 and later)
According to 802.11 specifications, WEP can have a total of 4 keys ( or 4 key indices ). However, in commercial products , only 1 key index (0) is really used. As an example, for iOS, Android and even Windows, there is probably no option to choose WEP key index. That implies they are using only 1 WEP key index.
683
11.5 Wi-Fi Security Microchip TCP/IP Stack Help Wired Equivalent Privacy (WEP)
11.5.1.1
WF_CPGetWepKeyType Function
File
WFApi.h
C void
WF_CPGetWepKeyType(
UINT8 CpId,
UINT8 * p_wepKeyType
);
Returns
None.
Description
Gets the WEP key type element for the specified Connection Profile. Allowable values are:
• WF_SECURITY_WEP_SHAREDKEY (0)
• WF_SECURITY_WEP_OPENKEY (1) - Default
Remarks
Before MRF24W is connected to the AP/Router, calling this function will always return WF_SECURITY_WEP_OPENKEY (1) as the default.
Preconditions
MACInit must be called first.
11.5.1.2
WF_CPGetDefaultWepKeyIndex Function
File
WFApi.h
C void
WF_CPGetDefaultWepKeyIndex(
UINT8 CpId,
UINT8 * p_defaultWepKeyIndex
);
Returns
None.
Description
Only applicable if the Connection Profile security type is either WF_SECURITY_WEP_40 or WF_SECURITY_WEP_104.
Since only WEP key index 0 is supported, this function is no longer needed.
Remarks
Note that only WEP key index 0 amongst AP manufacturers is typically used. Using any of the other three keys may be unpredictable from brand to brand.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId p_defaultWepKeyIndex
Description
Connection Profile ID
Pointer to index of WEP key to use.
684
11.5 Wi-Fi Security
No longer supporting 4 WEP key indexes
(0
3).
Microchip TCP/IP Stack Help Wi-Fi Protected Access (WPA/WPA2)
11.5.1.3
WF_CPSetDefaultWepKeyIndex Function
File
WFApi.h
C void
WF_CPSetDefaultWepKeyIndex(
UINT8 CpId,
UINT8 defaultWepKeyIndex
);
Returns
None.
Description
Only applicable if the Connection Profile security type is either WF_SECURITY_WEP_40 or WF_SECURITY_WEP_104.
Since only WEP key index 0 is supported, this function is no longer needed.
Remarks
Note that only WEP key index 0 amongst AP manufacturers is typically used. Using any of the other three keys may be unpredictable from brand to brand.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId defaultWepKeyIndex
Description
Connection Profile ID
Use WEP key index 0. No longer supporting 4 WEP key indexes (0 - 3).
11.5.1.4
WF_CPSetWepKeyType Function
File
WFApi.h
C void
WF_CPSetWepKeyType(
UINT8 CpId,
UINT8 wepKeyType
);
Returns
None.
Description
Sets the WEP key type (WF_SECURITY_WEP_SHAREDKEY or WF_SECURITY_WEP_OPENKEY) for the specified
Connection Profile ID. Default WEP key type is WF_SECURITY_WEP_OPENKEY.
Remarks
None.
Preconditions
MACInit must be called first.
685
11.5 Wi-Fi Security Microchip TCP/IP Stack Help Wi-Fi Protected Access (WPA/WPA2)
11.5.2
Wi-Fi Protected Access (WPA/WPA2)
Functions
Name
WF_CPUpdatePMK ( see page 687)
Description
Updates the PMK element in the connection profile ID retrieved out of 802.1x authentication process
Allow host to convert passphrase to key
This is function pbkdf2_sha1.
Description
Wi-Fi PROTECTED ACCESS (WPA/WPA2)
Refer to the Wi-Fi Protected Access (WPA) Enhanced Security Implementation Based on IEEE P802.11i standard.
Other equivalent WPA/WPA2 terminologies used are WPA - 4 way handshake or EAPOL - 4 way handshake or 802.1X
authentication.
Upon initial connection, after authentication followed by association, WPA/WPA2 EAPOL 4-way handshaking will takes place.
WPA/WPA2 security modes supported are
• WF_SECURITY_WPA_WITH_KEY
WPA-PSK Personal where binary key is given to MRF24W
• WF_SECURITY_WPA_WITH_PASS_PHRASE
WPA-PSK Personal where passphrase is given to MRF24W and it calculates the binary key
• WF_SECURITY_WPA2_WITH_KEY
WPA2-PSK Personal where binary key is given to MRF24W
• WF_SECURITY_WPA2_WITH_PASS_PHRASE
WPA2-PSK Personal where passphrase is given to MRF24W and it calculates the binary key
• WF_SECURITY_WPA_AUTO_WITH_KEY
highest level AP supports (WPA or WPA2)
• WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE
WPA-PSK Personal or WPA2-PSK Personal where passphrase is given to MRF24W and it calculates the binary key and connects at highest level AP supports (WPA or WPA2).
MRF24W can be configured to accept ( see page 174) either binary key or passphrase, through
MY_DEFAULT_WIFI_SECURITY_MODE compile-time definiton. The WPA/WPA2 authentication process involves key derivation from the given passphrase.
Since this key derivation process is computational intensive and requires memory space, options are given
• Host to derive the key from the passphrase
686
11.5 Wi-Fi Security Microchip TCP/IP Stack Help Wi-Fi Protected Access (WPA/WPA2)
In this scenario, MRF24W will generate an event (WF_EVENT_KEY_CALCULATION_REQUEST) to host (eg PIC32) and set g_WpsPassphrase.valid to TRUE. Upon receipt of this event, the host will execute the function
host will call WF_SetPSK ( see page 691)() to pass the converted key to MRF24W.
• MRF24W will handle the entire WPA/WPA2 passphase and then key derivation
MRF24WB0M consumes about ~32 seconds whereas MRF24WG0M will consume about ~25 seconds.
11.5.2.1
WF_CPUpdatePMK Function
File
WFApi.h
C void
WF_CPUpdatePMK(
UINT8 CpId,
UINT8 * pmk
);
Returns
None.
Description
Applicable for MRF24WG0M only. Updates the PMK element in the connection profile ID retrieved out of 802.1x
authentication process. This function is not used in the TCPIP demo apps.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
CpId pmk
Description
Connection Profile ID pairwise master key
11.5.2.2
WF_ConvPassphrase2Key Function
File
WFApi.h
C void
WF_ConvPassphrase2Key(
UINT8 key_len,
UINT8 * key,
UINT8 ssid_len,
UINT8 * ssid
);
Returns
None.
Description
DERIVE_KEY_FROM_PASSPHRASE_IN_HOST and __C32__ must be enabled. This function is called in WPS or WPA or
WPA2 security modes. Convert WPS/WPA/WPA2 passphrase to key. Allows host (eg PIC32) to perform conversion of the
687
11.5 Wi-Fi Security Microchip TCP/IP Stack Help Wi-Fi Protected Setup (WPS) passphrase to the key by itself instead of relying on RF module FW. This is recommended only for PIC microprocessors that has high computational bandwidth and sufficient memory space. As a benchmark, MRF24WB0M will take 32 sec and
MRF24WG0M will take 25 sec for this computation.
Remarks
MRF24W will generate an event (WF_EVENT_KEY_CALCULATION_REQUEST) to PIC32 and set g_WpsPassphrase.valid
to TRUE. Upon receipt of this event, PIC32 will invoke this function WF_ConvPassphrase2Key to convert the passphrase to
MRF24W.
Preconditions
MACInit must be called first.
Parameters
Parameters
key_len key ssid_len ssid
Description
key length passphrase as an input. key as an output ssid length ssid
11.5.2.3
pbkdf2_sha1 Function
File
WFApi.h
C void
pbkdf2_sha1(
const char
* passphrase,
const char
* ssid,
UINT16 ssid_len,
UINT16 iterations,
UINT8 * buf,
UINT16 buflen
);
Description
This is function pbkdf2_sha1.
11.5.3
Wi-Fi Protected Setup (WPS)
Functions
Name
Description
Gets the WPS credentials for the specified Connection Profile ID for
MRF24WG0MA/B.
Allows host to handle WPS WPA/WPA2-PSK passphrase
Sends PSK to module FW in WPS mode.
Description
Wi-Fi PROTECTED SETUP (WPS)
Refer to the Wi-Fi Protected Setup Specification Version 1.0h standard.
688
11.5 Wi-Fi Security Microchip TCP/IP Stack Help Wi-Fi Protected Setup (WPS)
WiFi Protected Setup (WPS) allows users to set up and expand the WiFi networks with security enabled, even if they are not familiar with the underlying technologies or processes involved. For example, users no longer have to know that SSID refers to the network name or WPA2 refers to the security mechanism.
WPS does not support ad hoc networks.
WPS will configure the network name SSID and security key for the AP and WPS client devices on a network. It supports the
WEP / WPA / WPA2 security methods.
2 methods are supported
• WPS-PBC (Push Button Configuration)
buttons on the AP and client device. Users do NOT need to know the SSID of the AP, however the users are required to be within close proximity of the AP to press the push button on the AP.
• WPS-PIN (Personal Information Number)
PIN is provided for each device which joins the network. Enter this PIN on the AP/Router (Registrar) and activate AP
first 7 digits of the PIN. This checksum must be correct, otherwise MRF24WG0M module will reject the PIN code.
To set up WPS-PBC, define
• MY DEFAULT_NETWORK_TYPE as CFG_WF_INFRASTRUCTURE
• MY_DEFAULT_SSID_NAME as ""
• MY_DEFAULT_WIFI_SECURITY_MODE as WF_SECURITY_WPS_PUSH_BUTTON
To set up WPS-PIN, define
• MY DEFAULT_NETWORK_TYPE as CFG_WF_INFRASTRUCTURE
• MY_DEFAULT_SSID_NAME to be the same SSSID as the AP/router
• MY_DEFAULT_WIFI_SECURITY_MODE as WF_SECURITY_WPS_PIN
• MY_DEFAULT_WPS_PIN to be the same as the AP/router PIN.
WPS protocol can be viewed as a security connection method, built upon the existing security modes WPA/WPA2. The protocol encompasses a M1-M8 message exchange process. Therefore additional time is consumed. The WPS specification specifies below:
1. Retransmission timeout = 5 sec
2. Individual message processing timeout = 15 sec
3. Overall timeout for entire protocol to complete = 2 min
To address this lengthy time required every single time the MRF24W is restarted, the function prototype
WF_SaveWPSCredentials() can be invoked. Basically what this function does is to retrieve WPS credentials from MRF24W and store these into global variable AppConfig. In this way, it makes the WPS credentials re-useable and shorten subsequent reconnection time. For an actual product, it is advised to add in a timeout such that the WPS credentials will need to be refreshed or updated periodically.
WPS protocol
The WPS protocol, which encompass WPA/WPA2 authentication process, involves key derivation from the given passphrase. Since this key derivation process is computational intensive and requires memory space, options are given
• Host to derive the key from the passphrase
689
11.5 Wi-Fi Security Microchip TCP/IP Stack Help Wi-Fi Protected Setup (WPS)
MRF24W will generate an event (WF_EVENT_KEY_CALCULATION_REQUEST) to host (eg PIC32) and set
• MRF24W will handle the entire WPA/WPA2 passphase and then key derivation
MRF24WB0M consumes about ~32 seconds whereas MRF24WG0M will consume about ~25 seconds.
Upon initial connection (after authentication followed by association), the subsequent process will take place.
• WPS M1-M8 exchanges
• WPA/WPA2 EAPOL 4-way handshaking
Below shows the WPS protocol
11.5.3.1
WF_CPGetWPSCredentials Function
File
WFApi.h
C void
WF_CPGetWPSCredentials(
UINT8 CpId,
tWFWpsCred * p_cred
);
Returns
None.
Description
Applicable for MRF24WG0M only. Gets the WPS credentials after WPS completed for MRF24WG0MA/B.
Remarks
None.
Preconditions
MACInit must be called first.
690
11.5 Wi-Fi Security
Parameters
Parameters
CpId p_cred
Microchip TCP/IP Stack Help
Description
Connection Profile ID
Pointer to the credentials
WPA2 Enterprise
11.5.3.2
WF_YieldPassphrase2Host Function
File
WFApi.h
C void
WF_YieldPassphrase2Host();
Returns
None.
Description
WPS supporting Functions
DERIVE_KEY_FROM_PASSPHRASE_IN_HOST must be enabled. Applicable for MRF24WG0M only. This function is used only for WF_SECURITY_WPS_PUSH_BUTTON and WF_SECURITY_WPS_PIN security mode. Allows host to convert pass phrase to key in WPS WPA/WPA2-PSK
Remarks
None.
Preconditions
MACInit must be called first.
11.5.3.3
WF_SetPSK Function
File
WFApi.h
C void
WF_SetPSK(
UINT8 * psk
);
Returns
None.
Description
DERIVE_KEY_FROM_PASSPHRASE_IN_HOST must be enabled. Applicable for MRF24WG0M only. Sends PSK to module FW in WPS mode.
Remarks
(WF_EVENT_KEY_CALCULATION_REQUEST) to PIC32 and set g_WpsPassphrase.valid to TRUE. Upon receipt of this
this conversion is completed, PIC32 will call WF_SetPSK to pass the converted key to MRF24W.
Preconditions
MACInit must be called first.
691
11.6 Wi-Fi Tx Power Control Microchip TCP/IP Stack Help Tx Power Control Public Members
11.5.4
WPA2 Enterprise
WPA2 Enterprise
Special approval needs to be submitted to marketing.
Supported by MRF24WG0M only.
RF module FW versions will be even-numbered, such as 0x3108, 0x310a, etc.
Requires MLA v5.42.06 March 2013 release and future releases.
This security mode WPS Enterprise is used in WiFi Console. The security types supported are
• EAP-PEAP/MSCHAPv2
• EAP-TTLS/MSCHAPv2
11.6
Wi-Fi Tx Power Control
Module
Description
The API functions in this section are used to configure the MRF24WB0M / MRF24WG0M transmit (Tx) power control settings.
MRF24WB0M transmit power settings are from -10dBm to +10dBm.
MRF24WG0M transmit power settings are from 0dBm to +18dBm.
11.6.1
Tx Power Control Public Members
Functions
Name
WF_TxPowerGetMinMax ( see page 693)
WF_TxPowerSetMinMax ( see page 693)
WF_TxPowerGetMax ( see page 694)
WF_TxPowerSetMax ( see page 695)
Description
Gets the Tx min and max power on the MRF24WB0MA/B.
Sets the Tx min and max power on the MRF24WB0MA/B.
Retrieves the factory-set max Tx power from the MRF24WB0MA/B and
MRF24WG0MA/B.
Gets the Tx max power on the MRF24WG0MA/B.
Sets the Tx max power on the MRF24WG0MA/B.
Module
Wi-Fi Tx Power Control ( see page 692)
692
11.6 Wi-Fi Tx Power Control Microchip TCP/IP Stack Help
Description
The following functions and variables are available to the stack application.
Tx Power Control Public Members
11.6.1.1
WF_TxPowerGetMinMax Function
File
WFApi.h
C void
WF_TxPowerGetMinMax(
INT8 * p_minTxPower,
INT8 * p_maxTxPower
);
Returns
None.
Description
After initialization the MRF24WB0MA/B max Tx power is determined by a factory-set value. This function can set a different minimum and maximum Tx power levels. However, this function can never set a maximum Tx power greater than the
factory-set value, which can be read via WF_TxPowerGetFactoryMax ( see page 694)().
Remarks
No conversion of units needed, input to MRF24WB0MA/B is in dB.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_minTxPower p_maxTxPower
Description
Pointer to location to write the minTxPower
Pointer to location to write the maxTxPower
11.6.1.2
WF_TxPowerSetMinMax Function
File
WFApi.h
C void
WF_TxPowerSetMinMax(
INT8 minTxPower,
INT8 maxTxPower
);
Returns
None.
Description
After initialization the MRF24WB0MA/B max Tx power is determined by a factory-set value. This function can set a different minimum and maximum Tx power levels. However, this function can never set a maximum Tx power greater than the
factory-set value, which can be read via WF_TxPowerGetFactoryMax ( see page 694)().
Remarks
No conversion of units needed, input to MRF24WB0MA/B is in dB.
693
11.6 Wi-Fi Tx Power Control
Preconditions
MACInit must be called first.
Parameters
Parameters
minTxPower maxTxPower
Microchip TCP/IP Stack Help Tx Power Control Public Members
Description
Desired minTxPower (-10 to 10dB)
Desired maxTxPower (-10 to 10dB)
11.6.1.3
WF_TxPowerGetFactoryMax Function
File
WFApi.h
C void
WF_TxPowerGetFactoryMax(
INT8 * p_factoryMaxTxPower
);
Returns
None.
Description
For MRF24WB, desired maxTxPower (-10 to 10 dBm), in 1dB steps For MRF24WG, desired maxTxPower ( 0 to 18 dBm), in
1dB steps
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_factoryMaxTxPower
Description
for MRF24WB, desired maxTxPower (-10 to 10 dBm), in 1dB steps for
MRF24WG, desired maxTxPower ( 0 to 18 dBm), in 1dB steps
11.6.1.4
WF_TxPowerGetMax Function
File
WFApi.h
C void
WF_TxPowerGetMax(
INT8 * p_maxTxPower
);
Returns
None.
Description
After initialization the MRF24WG0MA/B max Tx power is determined by a factory-set value. This function can set a different maximum Tx power levels. However, this function can never set a maximum Tx power greater than the factory-set value,
which can be read via WF_TxPowerGetFactoryMax ( see page 694)().
694
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help
Remarks
No conversion of units needed, input to MRF24WG0MA/B is in dBm.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_maxTxPower
Description
Pointer to location to write the maxTxPower
11.6.1.5
WF_TxPowerSetMax Function
File
WFApi.h
C void
WF_TxPowerSetMax(
INT8 maxTxPower
);
Returns
None.
Description
Tx Power Control Functions
After initialization the MRF24WG0MA/B max Tx power is determined by a factory-set value. This function can set a different maximum Tx power levels. However, this function can never set a maximum Tx power greater than the factory-set value,
which can be read via WF_TxPowerGetFactoryMax ( see page 694)().
Remarks
No conversion of units needed, input to MRF24WG0MA/B is in dBm.
Preconditions
MACInit must be called first.
Parameters
Parameters
maxTxPower
Description
valid range (0 to 18 dBm)
11.7
Wi-Fi Power Save
Module
Functions
Name
GetAppPowerSaveMode ( see page 701)
SetAppPowerSaveMode ( see page 701)
Description
Returns state of power save mode
Enable or disable power save mode
695
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help
Macros
Name Description
This is macro REG_DISABLE_LOW_POWER_MASK.
Types
Name
702) tWFPwrModeReq ( see page 702)
Description
Enumeration of valid values for WFSetPowerSaveMode()
This is type tWFPwrModeReq.
Variables
Name Description
This is variable g_AppPowerSaveModeEnabled.
g_powerSaveState ( see page 703)
LOCAL GLOBAL VARIABLES
This is variable g_psPollActive.
This is variable g_rxDtim.
This is variable g_sleepNeeded.
704) gRFModuleVer1209orLater ( see page 704)
This is variable gRFModuleVer1209orLater.
Description
The MRF24WB0M / MRF24WG0M supports two power-saving modes – sleep and hibernate.
Mode
Sleep
Hibernate
Description
This mode is used when in PS Poll mode where the MRF24WB0M / MRF24WG0M wakes itself up at periodic intervals to query the network for receive messages buffered by an Access Point.
See listenInterval in the tWFCAElements structure.
When in sleep mode the MRF24WB0M / MRF24WG0M transmitter receiver circuits are turned off along with other circuitry to minimize power consumption.
Sleep mode is entered periodically as a result of the Host CPU enabling PS Poll mode.
This mode effectively turns off the LDO of the MRF24WB0M / MRF24WG0M for maximum power savings. MRF24WB0M / MRF24WG0M state is not retained, and when the MRF24WB0M /
MRF24WG0M is taken out of the Hibernate state it performs a reboot.
Hibernate mode is controlled by toggling the HIBERNATE pin on the MRF24WB0M /
MRF24WG0M module (high to enter hibernate, low to exit).
This mode should be used when the application allows for the MRF24WB0M / MRF24WG0M module to be off for extended periods of time.
Power Save Functions
802.11 chipsets have two well known operational power modes. Active power mode is defined as the radio always on either transmitting or receiving, meaning that when it isn't transmitting then it is trying to receive. Power save mode is defined as operating with the radio turned off when there is nothing to transmit and only turning the radio receiver on when required.
The power save mode is a mode that requires interaction with an Access Point. The access point is notified via a packet from the Station that it is entering into power save mode. As a result the access point is required to buffer any packets that are destined for the Station until the Station announces that it is ready to once again receive packets. The duration that a
Station is allowed to remain in this mode is limited and is typically 10 times the beacon interval of the Access point.
If the host is expecting packets from the network it should operate in Active mode. If however power saving is critical and packets are not expected then the host should consider operating in power save mode. Due to the nature of Access points
696
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help Power Save Public Members not all behaving the same, there is the possibility that an Access point will invalidate a Stations connection if it has not heard from the Station over a given time period. For this reason power save mode should be used with caution.
The 802.11 name for power saving mode is PS-Poll (Power-Save Poll).
11.7.1
Power Save Public Members
Functions
Name
WF_GetPowerSaveState ( see page 697)
WF_HibernateEnable ( see page 698)
WF_PsPollDisable ( see page 698)
WF_PsPollEnable ( see page 699)
Description
Returns current power-save state.
Puts the MRF24W into hibernate mode by setting HIBERNATE pin to HIGH.
Disables PS-Poll mode.
Enables PS Poll mode.
Module
Wi-Fi Power Save ( see page 695)
Description
The following functions and variables are available to the stack application.
11.7.1.1
WF_GetPowerSaveState Function
File
WFApi.h
C void
WF_GetPowerSaveState(
UINT8 * p_powerSaveState
);
Returns
None.
Description
Returns the current MRF24W power save state.
Value
WF_PS_HIBERNATE
WF_PS_PS_POLL_DTIM_ENABLED
WF_PS_PS_POLL_DTIM_DISABLED
WF_PS_POLL_OFF
Remarks
None.
Preconditions
MACInit must be called first.
Definition
MRF24W in hibernate state
MRF24W in PS-Poll mode with DTIM enabled
MRF24W in PS-Poll mode with DTIM disabled
MRF24W is not in any power-save state
697
11.7 Wi-Fi Power Save
Parameters
Parameters
p_powerSaveState
Microchip TCP/IP Stack Help
Description
Pointer to where power state is written
Power Save Public Members
11.7.1.2
WF_HibernateEnable Function
File
WFApi.h
C void
WF_HibernateEnable();
Returns
None.
Description
Enables Hibernate mode on the MRF24W, which effectively turns off the device for maximum power savings. HIBERNATE pin on MRF24W is set to HIGH.
MRF24W state is not maintained when it transitions to hibernate mode. To remove the MRF24W from hibernate mode call
WF_Init().
Remarks
Note that because the MRF24W does not save state, there will be a disconnect between the TCP/IP stack and the
MRF24B0M state. If it is desired by the application to use hibernate, additional measures must be taken to save application state. Then the host should be reset. This will ensure a clean connection between MRF24W and TCP/IP stack
Future versions of the stack might have the ability to save stack context as well, ensuring a clean wake up for the MRF24W without needing a host reset.
Preconditions
MACInit must be called first.
11.7.1.3
WF_PsPollDisable Function
File
WFApi.h
C void
WF_PsPollDisable();
Returns
None.
Description
Power Management Functions
Disables PS Poll mode. The MRF24W will stay active and not go sleep.
Remarks
None.
Preconditions
MACInit must be called first.
698
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help Power Save Internal Members
11.7.1.4
WF_PsPollEnable Function
File
WFApi.h
C void
WF_PsPollEnable(
BOOL rxDtim
);
Returns
None.
Description
Enables PS Poll mode. PS-Poll (Power-Save Poll) is a mode allowing for longer battery life. The MRF24W coordinates with the Access Point to go to sleep and wake up at periodic intervals to check for data messages, which the Access Point will buffer. The listenInterval in the Connection Algorithm defines the sleep interval. By default, PS-Poll mode is disabled.
When PS Poll is enabled, the WF Host Driver will automatically force the MRF24W to wake up each time the Host sends Tx data or a control message to the MRF24W. When the Host message transaction is complete the MRF24W driver will automatically re-enable PS Poll mode.
When the application is likely to experience a high volume of data traffic then PS-Poll mode should be disabled for two reasons:
1. No power savings will be realized in the presence of heavy data traffic.
2. Performance will be impacted adversely as the WiFi Host Driver continually activates and deactivates PS-Poll mode via
SPI messages.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
rxDtim
Description
TRUE listens at the DTIM interval and FALSE listens at the CASetListenInterval
11.7.2
Power Save Internal Members
Functions
Name
SendPowerModeMsg ( see page 700)
SetPowerSaveState ( see page 700)
Description
Send power mode management message to the MRF24W.
Sets the desired power save state of the MRF24W.
Module
Wi-Fi Power Save ( see page 695)
Description
The following functions and variables are designated as internal to the module.
699
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help Functions
11.7.2.1
SendPowerModeMsg Function
File
WFPowerSave.c
C static void
SendPowerModeMsg(
);
Returns
None.
Description
LOCAL FUNCTION PROTOTYPES
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_powerMode
Description
Pointer to tWFPwrModeReq ( see page 702) structure to send to MRF24W.
11.7.2.2
SetPowerSaveState Function
File
WFPowerSave.c
C void
SetPowerSaveState(
UINT8 powerSaveState
);
Returns
None.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
powerSaveState
Description
Value of the power save state desired.
700
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help
11.7.3
Functions
Functions
Name
GetAppPowerSaveMode ( see page 701)
SetAppPowerSaveMode ( see page 701)
Module
Wi-Fi Power Save ( see page 695)
Description
Returns state of power save mode
Enable or disable power save mode
11.7.3.1
GetAppPowerSaveMode Function
File
WFPowerSave.c
C
BOOL GetAppPowerSaveMode();
Returns
None.
Description
Returns state of global variable g_AppPowerSaveModeEnabled ( see page 703)
Remarks
None.
11.7.3.2
SetAppPowerSaveMode Function
File
WFPowerSave.c
C void
SetAppPowerSaveMode(
BOOL state
);
Returns
None.
Description
Remarks
None.
Types
701
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help
11.7.4
Types
Module
Wi-Fi Power Save ( see page 695)
Types
Name
702) tWFPwrModeReq ( see page 702)
Description
Enumeration of valid values for WFSetPowerSaveMode()
This is type tWFPwrModeReq.
11.7.4.1
tWFPsPwrMode Type
File
WFPowerSave.c
C typedef enum
tWFPsPwrMode@1 tWFPsPwrMode;
Description
Enumeration of valid values for WFSetPowerSaveMode()
11.7.4.2
tWFPwrModeReq Type
File
WFPowerSave.c
C typedef struct
pwrModeRequestStruct tWFPwrModeReq;
Description
This is type tWFPwrModeReq.
11.7.5
Variables
Module
Wi-Fi Power Save ( see page 695)
Variables
Name
g_powerSaveState ( see page 703)
Description
This is variable g_AppPowerSaveModeEnabled.
LOCAL GLOBAL VARIABLES
This is variable g_psPollActive.
This is variable g_rxDtim.
Variables
702
11.7 Wi-Fi Power Save Microchip TCP/IP Stack Help
704) gRFModuleVer1209orLater ( see page 704)
This is variable g_sleepNeeded.
This is variable gRFModuleVer1209orLater.
11.7.5.1
g_AppPowerSaveModeEnabled Variable
File
WFPowerSave.c
C
BOOL g_AppPowerSaveModeEnabled = FALSE;
Description
This is variable g_AppPowerSaveModeEnabled.
11.7.5.2
g_powerSaveState Variable
File
WFPowerSave.c
C
UINT8 g_powerSaveState = WF_PS_OFF;
Description
LOCAL GLOBAL VARIABLES
11.7.5.3
g_psPollActive Variable
File
WFPowerSave.c
C
BOOL g_psPollActive = FALSE;
Description
This is variable g_psPollActive.
11.7.5.4
g_rxDtim Variable
File
WFPowerSave.c
C
BOOL g_rxDtim;
Description
This is variable g_rxDtim.
Variables
703
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help
11.7.5.5
g_sleepNeeded Variable
File
WFPowerSave.c
C
BOOL g_sleepNeeded = FALSE;
Description
This is variable g_sleepNeeded.
11.7.5.6
gRFModuleVer1209orLater Variable
File
WFPowerSave.c
C
BOOL gRFModuleVer1209orLater;
Description
This is variable gRFModuleVer1209orLater.
11.7.6
Macros
Macros
Name Description
This is macro REG_DISABLE_LOW_POWER_MASK.
Module
Wi-Fi Power Save ( see page 695)
11.7.6.1
REG_DISABLE_LOW_POWER_MASK Macro
File
WFPowerSave.c
C
#define
REG_DISABLE_LOW_POWER_MASK ((UINT16)(0x00))
Description
This is macro REG_DISABLE_LOW_POWER_MASK.
704
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help
11.8
Wi-Fi Miscellaneous
Module
Description
Wi-Fi Miscellaneous Public Members
11.8.1
Wi-Fi Miscellaneous Public Members
Functions
Name
WF_GetDeviceInfo ( see page 706)
Description
Retrieves WF device information
(MRF24WB0M_DEVICE/MRF24WG0M_DEVICE, romVersion and patchVersion).
Retrieves the MRF24W MAC address
WF_GetMacAddress ( see page 706)
WF_GetMacStats ( see page 707)
WF_GetMultiCastFilter ( see page 707)
WF_GetRegionalDomain ( see page 708)
WF_GetRtsThreshold ( see page 709)
WF_SetMacAddress ( see page 710)
Gets MAC statistics.
Gets a multicast address filter from one of the two multicast filters.
Retrieves the MRF24W Regional domain
Gets the RTS Threshold
Uses a different MAC address for the MRF24W
WF_SetMultiCastFilter ( see page 710)
WF_SetRegionalDomain ( see page 711)
Sets a multicast address filter using one of the two multicast filters.
Enables or disables the MRF24W Regional Domain. For MRF24WG with RF module FW version 0x3106 or earlier, it allows enabling /disabling the Regional
Domain. For MRF24WG with RF module FW version 0x3107 and future releases, this function is NOT supported due to changes in FCC requirements, which does not allow programming of the regional domain.
WF_SetRtsThreshold ( see page 712)
Sets the RTS Threshold.
Forces the module FW to use software filter instead of hardware filter
WF_MulticastSetConfig ( see page 714)
Sets a multicast address filter using one of the two multicast filters.
Can be called to set link down threshold in softAP network type.
Retrieves transmission (tx) mode that indicates transmission rates
Configures 802.11 transmission (Tx) rates
Module
Wi-Fi Miscellaneous ( see page 705)
705
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
Structures
Name
tWFDeviceInfoStruct ( see page 712)
WFMacStatsStruct ( see page 713)
Description
used in WF_GetDeviceInfo ( see page 706)
This is record WFMacStatsStruct.
This is record WFHibernate.
Description
The following functions and variables are available to the stack application.
11.8.1.1
WF_GetDeviceInfo Function
File
WFApi.h
C void
WF_GetDeviceInfo(
tWFDeviceInfo * p_deviceInfo
);
Returns
None.
Description
Version functions
Retrieves RF module information. MRF24WB will have romVersion = 0x12. MRF24WG will have romVersion = 0x30 or 0x31.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_deviceInfo
Description
Pointer where device info will be written
11.8.1.2
WF_GetMacAddress Function
File
WFApi.h
C void
WF_GetMacAddress(
UINT8 * p_mac
);
Returns
None.
Remarks
None.
706
11.8 Wi-Fi Miscellaneous
Preconditions
MACInit must be called first.
Parameters
Parameters
p_mac
Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
Description
Pointer where mac will be written (must point to a 6-byte buffer)
11.8.1.3
WF_GetMacStats Function
File
WFApi.h
C void
WF_GetMacStats(
tWFMacStats * p_macStats
);
Returns
None.
Description
MAC Stats
Returns MAC statistics on number of frames received or transmitted for defined situations such as number of frames transmitted with multicast bit set in destination MAC address. Refer to WFApi.h for data struct tWFMacStats.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_macStats
Description
Pointer to where MAC statistics are written
11.8.1.4
WF_GetMultiCastFilter Function
File
WFApi.h
C void
WF_GetMultiCastFilter(
UINT8 multicastFilterId,
UINT8 multicastAddress[6]
);
Returns
None.
Description
Gets the current state of the specified Multicast Filter.
Normally would call SendGetParamMsg, but this GetParam returns all 6 address filters + 2 more bytes for a total of 48 bytes plus header. So, doing this msg manually to not require a large stack allocation to hold all the data.
Exact format of returned message is:
707
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
[0] -- always mgmt response (2)
[1] -- always WF_GET_PARAM_SUBTYPE (16)
[2] -- result (1 if successful)
[3] -- mac state (not used)
[4] -- data length (length of response data starting at index 6)
[5] -- not used
[6-11] -- Compare Address ( see page 152) 0 address
[12] -- Compare Address ( see page 152) 0 group
[13] -- Compare Address ( see page 152) 0 type
[14-19] -- Compare Address ( see page 152) 1 address
[20] -- Compare Address ( see page 152) 1 group
[21] -- Compare Address ( see page 152) 1 type
[22-27] -- Compare Address ( see page 152) 2 address
[28] -- Compare Address ( see page 152) 2 group
[29] -- Compare Address ( see page 152) 2 type
[30-35] -- Compare Address ( see page 152) 3 address
[36] -- Compare Address ( see page 152) 3 group
[37] -- Compare Address ( see page 152) 3 type
[38-43] -- Compare Address ( see page 152) 4 address
[44] -- Compare Address ( see page 152) 4 group
[45] -- Compare Address ( see page 152) 4 type
[46-51] -- Compare Address ( see page 152) 5 address
[52] -- Compare Address ( see page 152) 5 group
[53] -- Compare Address ( see page 152) 5 type
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
multicastFilterId multicastAddress
Description
WF_MULTICAST_FILTER_1 or WF_MULTICAST_FILTER_2
6-byte address
11.8.1.5
WF_GetRegionalDomain Function
File
WFApi.h
C void
WF_GetRegionalDomain(
UINT8 * p_regionalDomain
);
708
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
Returns
None.
Description
see tWFRegDomain enumerated types
Gets the regional domain on the MRF24W. Allowable values are:
• WF_DOMAIN_FCC
• WF_DOMAIN_IC (MRF24WB)
• WF_DOMAIN_ETSI
• WF_DOMAIN_SPAIN (MRF24WB)
• WF_DOMAIN_FRANCE (MRF24WB)
• WF_DOMAIN_JAPAN_A (MRF24WB)
• WF_DOMAIN_JAPAN_B (MRF24WB)
• WF_DOMAIN_JAPAN (MRF24WG)
• WF_DOMAIN_OTHER (MRF24WG)
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_regionalDomain
Description
Pointer where the regional domain value will be written
11.8.1.6
WF_GetRtsThreshold Function
File
WFApi.h
C void
WF_GetRtsThreshold(
UINT16 * p_rtsThreshold
);
Returns
None.
Description
Gets the RTS/CTS packet size threshold.
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
p_rtsThreshold
Description
Pointer to where RTS threshold is written
709
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
11.8.1.7
WF_SetMacAddress Function
File
WFApi.h
C void
WF_SetMacAddress(
UINT8 * p_mac
);
Returns
None.
Description
MAC Address ( see page 152) Functions
Directs the MRF24W to use the input MAC address instead of its factory-default MAC address. This function does not overwrite the factory default, which is in FLASH memory – it simply tells the MRF24W to use a different MAC.
Remarks
None.
Preconditions
MACInit must be called first. Cannot be called when the MRF24W is in a connected state.
Parameters
Parameters
p_mac
Description
Pointer to 6-byte MAC that will be sent to MRF24W
11.8.1.8
WF_SetMultiCastFilter Function
File
WFApi.h
C void
WF_SetMultiCastFilter(
UINT8 multicastFilterId,
UINT8 multicastAddress[6]
);
Returns
None.
Description
Multicast Functions
If two active multicast filters are set up they are OR’d together – the MRF24WB0M will receive and pass to the Host CPU received packets from either multicast address. The allowable values for the multicast filter are:
• WF_MULTICAST_FILTER_1
• WF_MULTICAST_FILTER_2
By default, both Multicast Filters are inactive.
Remarks
None.
710
11.8 Wi-Fi Miscellaneous
Preconditions
MACInit must be called first.
Parameters
Parameters
multicastFilterId multicastAddress
Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
Description
WF_MULTICAST_FILTER_1 or WF_MULTICAST_FILTER_2
6-byte address (all 0xFF will inactivate the filter)
11.8.1.9
WF_SetRegionalDomain Function
File
WFApi.h
C void
WF_SetRegionalDomain(
UINT8 regionalDomain
);
Returns
None.
Description
see tWFRegDomain enumerated types
(MRF24WG 0x3106 or earlier ) Sets the regional domain on the MRF24WG. Note that this function does not overwrite the factory-set regional domain in FLASH. By default the MRF24W will use the factory-set regional domain. It is invalid to call this function while in a connected state. (MRF24WG 0x3107 and future) Not supported.
Valid values for the regional domain are:
• WF_DOMAIN_FCC
• WF_DOMAIN_IC (MRF24WB)
• WF_DOMAIN_ETSI
• WF_DOMAIN_SPAIN (MRF24WB)
• WF_DOMAIN_FRANCE (MRF24WB)
• WF_DOMAIN_JAPAN_A (MRF24WB)
• WF_DOMAIN_JAPAN_B (MRF24WB)
• WF_DOMAIN_JAPAN (MRF24WG)
• WF_DOMAIN_OTHER (MRF24WG)
Remarks
None.
Preconditions
MACInit must be called first. This function must not be called while in a connected state.
Parameters
Parameters
regionalDomain
Description
Value to set the regional domain to
711
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
11.8.1.10
WF_SetRtsThreshold Function
File
WFApi.h
C void
WF_SetRtsThreshold(
UINT16 rtsThreshold
);
Returns
None.
Description
RTS Threshold Functions
Sets the RTS/CTS packet size threshold for when RTS/CTS frame will be sent. The default is 2347 bytes – the maximum for
802.11. It is recommended that the user leave the default at 2347 until they understand the performance and power ramifications of setting it smaller. Valid values are from 0 to WF_RTS_THRESHOLD_MAX (2347).
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
rtsThreshold
Description
Value of the packet size threshold
11.8.1.11
tWFDeviceInfoStruct Structure
File
WFApi.h
C struct
tWFDeviceInfoStruct {
UINT8 deviceType;
UINT8 romVersion;
UINT8 patchVersion;
};
Members
Members
UINT8 deviceType;
UINT8 romVersion;
UINT8 patchVersion;
Description
used in WF_GetDeviceInfo ( see page 706)
Description
MRF24WB0M_DEVICE or MRF24WG0M_DEVICE
ROM version number
Patch version number
712
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
11.8.1.12
WFMacStatsStruct Structure
File
WFApi.h
C struct
WFMacStatsStruct {
UINT32 MibWEPExcludeCtr;
UINT32 MibTxBytesCtr;
UINT32 MibTxMulticastCtr;
UINT32 MibTxFailedCtr;
UINT32 MibTxRtryCtr;
UINT32 MibTxMultRtryCtr;
UINT32 MibTxSuccessCtr;
UINT32 MibRxDupCtr;
UINT32 MibRxCtsSuccCtr;
UINT32 MibRxCtsFailCtr;
UINT32 MibRxAckFailCtr;
UINT32 MibRxBytesCtr;
UINT32 MibRxFragCtr;
UINT32 MibRxMultCtr;
UINT32 MibRxFCSErrCtr;
UINT32 MibRxWEPUndecryptCtr;
UINT32 MibRxFragAgedCtr;
UINT32 MibRxMICFailureCtr;
};
Members
Members
UINT32 MibWEPExcludeCtr;
UINT32 MibTxBytesCtr;
UINT32 MibTxMulticastCtr;
UINT32 MibTxFailedCtr;
UINT32 MibTxRtryCtr;
UINT32 MibTxMultRtryCtr;
UINT32 MibTxSuccessCtr;
UINT32 MibRxDupCtr;
UINT32 MibRxCtsSuccCtr;
UINT32 MibRxCtsFailCtr;
UINT32 MibRxAckFailCtr;
UINT32 MibRxBytesCtr;
UINT32 MibRxFragCtr;
UINT32 MibRxMultCtr;
UINT32 MibRxFCSErrCtr;
UINT32 MibRxWEPUndecryptCtr;
UINT32 MibRxFragAgedCtr;
UINT32 MibRxMICFailureCtr;
Description
Number of frames received with the Protected Frame subfield of the Frame
Control field set to zero and the value of dot11ExcludeUnencrypted causes that frame to be discarded.
Total number of Tx bytes that have been transmitted
Number of frames successfully transmitted that had the multicast bit set in the destination MAC address.
Number of Tx frames that failed due to the number of transmits exceeding the retry count.
Number of times a transmitted frame needed to be retried
Number of times a frame was successfully transmitted after more than one retransmission.
Number of Tx frames successfully transmitted.
Number of frames received where the Sequence Control field indicates a duplicate.
Number of CTS frames received in response to an RTS frame.
Number of times an RTS frame was not received in response to a CTS frame.
Number of times an Ack was not received in response to a Tx frame.
Total number of Rx bytes received.
Number of successful received frames (management or data)
Number of frames received with the multicast bit set in the destination MAC address.
Number of frames received with an invalid Frame Checksum (FCS).
Number of frames received where the Protected Frame subfield of the Frame
Control Field is set to one and the WEPOn value for the key mapped to the transmitter’s MAC address indicates the frame should not have been encrypted.
Number of times that fragments ‘aged out’, or were not received in the allowable time.
Number of MIC failures that have occurred.
713
11.8 Wi-Fi Miscellaneous
Description
This is record WFMacStatsStruct.
Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
11.8.1.13
WF_EnableSWMultiCastFilter Function
File
WFApi.h
C void
WF_EnableSWMultiCastFilter();
Returns
None.
Description
MRF24WG0MA/B.
Remarks
None.
Preconditions
MACInit must be called first.
11.8.1.14
WF_MulticastSetConfig Function
File
WFApi.h
C void
WF_MulticastSetConfig(
tWFMultiCastConfig * p_config
);
Returns
None.
Description
active multicast filters are set up they are OR’d together – the MRF24W will receive and pass to the Host CPU received packets from either multicast address. The allowable values in p_config are: filterId -- WF_MULTICAST_FILTER_1 or WF_MULTICAST_FILTER_2 action -- WF_MULTICAST_DISABLE_ALL (default) The Multicast Filter discards all received multicast messages – they will not be forwarded to the Host PIC. The remaining fields in this structure are ignored.
WF_MULTICAST_ENABLE_ALL The Multicast Filter forwards all received multicast messages to the Host PIC. The remaining fields in this structure are ignored.
WF_MULTICAST_USE_FILTERS The MAC filter will be used and the remaining fields in this structure configure which
Multicast messages are forwarded to the Host PIC.
macBytes -- Array containing the MAC address to filter on (using the destination address of each incoming 802.11 frame).
Specific bytes with the MAC address can be designated as ‘don’t care’ bytes. See macBitMask. This field in only used if action = WF_MULTICAST_USE_FILTERS.
714
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members macBitMask -- A byte where bits 5:0 correspond to macBytes[5:0]. If the bit is zero then the corresponding MAC byte must be an exact match for the frame to be forwarded to the Host PIC. If the bit is one then the corresponding MAC byte is a ‘don’t care’ and not used in the Multicast filtering process. This field in only used if action = WF_MULTICAST_USE_FILTERS.
By default, both Multicast Filters are inactive.
Remarks
None.
Preconditions
MACInit must be called first.
Example
- Filter on Multicast Address of 01:00:5e:xx:xx:xx where xx are don't care bytes.
p_config->filterId = WF_MULTICAST_FILTER_1
[0] [1] [2] [3] [4] [5] p_config->macBytes[] = 01, 00, 5e, ff, ff, ff (0xff are the don't care bytes) p_config->macBitMask = 0x38 --> bits 5:3 = 1 (don't care on bytes 3,4,5)
--> bits 2:0 = 0 (exact match required on bytes 0,1,2)
11.8.1.15
WF_SetLinkDownThreshold Function
File
WFApi.h
C void
WF_SetLinkDownThreshold(
UINT8 threshold
);
Returns
None.
Description
When MRF24W is configured as a softAP, it will ping the devices to determine whether devices are alive or dead by transmitting consecutive NULL DATA packets. If device is alive, it will transmit ACK back to softAP. If device is dead, softAP will not receive any packets from device. After PARAM_LINK_DOWN_THRESHOLD is reached, softAP considers the device to be dead. To enable this feature, enable SOFTAP_CHECK_LINK_STATUS. This function is only valid with MRF24WG RF module FW version 0x3107 or the later.
Remarks
None.
Preconditions
MACInit must be called first. SOFTAP_CHECK_LINK_STATUS must be enabled.
715
11.8 Wi-Fi Miscellaneous Microchip TCP/IP Stack Help Wi-Fi Miscellaneous Public Members
11.8.1.16
WF_GetTxMode Function
File
WFApi.h
C void
WF_GetTxMode(
UINT8 * mode
);
Returns
None.
Description
Retrieves transmission (tx) mode that indicates transmission rates (802.11b or 802.11g or 802.11 legacy rates)
Remarks
None.
Preconditions
MACInit must be called first.
11.8.1.17
WF_SetTxMode Function
File
WFApi.h
C void
WF_SetTxMode(
UINT8 mode
);
Returns
None.
Description
Configures 802.11 transmission (Tx) rates for 802.11b or 802.11g or 802.11 legacy rates (1-2Mbps)
Remarks
None.
Preconditions
MACInit must be called first.
Parameters
Parameters
mode
Description
Tx rate WF_TXMODE_G_RATES (default) -- will use all 802.11g rates
WF_TXMODE_B_RATES -- will only use 802.11b rates
WF_TXMODE_LEGACY_RATES -- will only use 1 and 2 mbps rates
11.8.1.18
WFHibernate Structure
File
WFApi.h
716
Microchip TCP/IP Stack Help 11.9 WF_ProcessEvent
C struct
WFHibernate {
UINT8 state;
UINT8 wakeup_notice;
};
Description
This is record WFHibernate.
11.9
WF_ProcessEvent
Module
Description
There are several events that can occur on the MRF24WB0M / MRF24WG0M that the host CPU may want to know about.
All MRF24WB0M / MRF24WG0M events go through the
WF_ProcessEvent()
function described in the next section.
Event Processing
The
WF_ProcessEvent()
function is how the host application is notified of events. This function will be called by the Wi-Fi host driver when an event occurs. This function should not be called directly by the host application. This function, located in
WF_Config.c, should be modified by the user as needed. Since this function is called from the WiFi driver there are some restrictions – namely, one cannot call any Wi-Fi driver functions when inside WF_ProcessEvent(). It is recommended that that customer simply set a flag for a specific event and handle it in the main loop. The framework for this function is shown below.
The prototype for this function is: void WF_ProcessEvent(UINT8 event, UINT16 eventInfo, UINT8 *extraInfo)
There are 3 inputs to the function: event eventInfo
*extraInfo
The event that occurred.
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)
Additional information about the event. When DERIVE_KEY_FROM_PASSPHRASE_IN_HOST is enabled. where host will compute the key from the passphrade, this field contains the WPA
Passphrase that will be sent to the host for the computation.
The table below shows possible values that the event and eventInfo parameters can have. Note that event notification of some events can be optionally disabled via:
2. Function WF_CASetEventNotificationAction() ( see page 665).
event
WF_EVENT_CONNECTION_SUCCESSFUL
eventInfo
The connection attempt was successful.
eventInfo:
• Always
WF_NO_ADDITIONAL_INFO
(Optional event)
717
11.9 WF_ProcessEvent Microchip TCP/IP Stack Help
WF_EVENT_CONNECTION_FAILED
The connection attempt failed eventInfo:
• WF_JOIN_FAILURE
•
WF_AUTHENTICATION_FAILURE
•
WF_ASSOCIATION_FAILURE
•
WF_WEP_HANDSHAKE_FAILURE
•
WF_PSK_CALCULATION_FAILURE
•
WF_PSK_HANDSHAKE_FAILURE
•
WF_ADHOC_JOIN_FAILURE
•
WF_SECURITY_MISMATCH_FAILURE
• WF_NO_SUITABLE_AP_FOUND_FAILURE
• WF_RETRY_FOREVER_NOT_SUPPORTED_FAILURE
(Optional event)
WF_EVENT_CONNECTION_TEMPORARILY_LOST An established connection was temporarily lost – the connection algorithm is attempting to reconnect. The eventInfo field indicates why the connection was lost.
eventInfo:
•
WF_BEACON_TIMEOUT
•
WF_DEAUTH_RECEIVED
•
WF_DISASSOCIATE_RECEIVED
(Optional event)
WF_EVENT_CONNECTION_PERMANENTLY_LOST
An established connection was permanently lost – the connection algorithm either ran out of retries or was configured not to retry. The eventInfo field indicates why the connection was lost.
eventInfo:
•
WF_BEACON_TIMEOUT
•
WF_DEAUTH_RECEIVED
•
WF_DISASSOCIATE_RECEIVED
This event can also be generated when
WF_CMDisconnect ( see page 678)()
is called, in which case the eventInfo field has no meaning.
WF_EVENT_CONNECTION_REESTABLISHED
WF_EVENT_SCAN_RESULTS_READY
WF_EVENT_SOFT_AP_EVENT
(Optional event)
A connection that was temporarily lost has been restablished
Always WF_NO_ADDITIONAL_INFO
(Optional event)
The scan request initiated by calling
has completed and results can be read from the MRF24WB0M /
MRF24WG0M.
eventInfo: Number of scan results
Available only for MRF24WG0M (i) RF module FW version 0x3108 and later and (ii) MLA v5.42.06 release or later. Indication of client's connection status, when a client has connected or disconnected or not powered on/active or received deauthentication.
718
11.10 Access Point Compatibility Microchip TCP/IP Stack Help
WF_EVENT_KEY_CALCULATION_REQUEST This event is generated
DERIVE_KEY_FROM_PASSPHRASE_IN_HOST is
when
enabled,
MRF24WG0M will transmit the passphase to the host via the field
*extraInfo. where the host will then compute the passphrase from the
key. Refer to function prototype WF_ConvPassphrase2Key ( see page
12.2 WF_ProcessEvent() Framework
Below is the framework for
WF_ProcessEvent()
. Each case statement should be modified as needed to handle events the application is interested in.
void
WF_ProcessEvent(UINT8 event, UINT16 eventInfo)
{
switch
(event)
{
case
WF_EVENT_CONNECTION_SUCCESSFUL:
/* Application code here */
break
;
case
WF_EVENT_CONNECTION_FAILED:
/* Application code here */
break
;
case
WF_EVENT_CONNECTION_TEMPORARILY_LOST:
/* Application code here */
break
;
case
WF_EVENT_CONNECTION_PERMANENTLY_LOST:
/* Application code here */
break
;
case
WF_EVENT_CONNECTION_REESTABLISHED:
/* Application code here */
break
;
case
WF_EVENT_SCAN_RESULTS_READY:
/* Application code here */
break
;
default
:
WF_ASSERT(FALSE);
break
;
}
}
11.10
Access Point Compatibility
Module
Description
Introduction
The MRF24WB0M / MRF24WG0M has passed through Wi-Fi.org certification testing. Not all routers pass through Wi-Fi.org
certification, and some are pre-configured in Greenfield modes. Further, users can set configurations that severely limit performance or prevent communications. This section is intended to provide an on-going compatibility snapshot among a few of the most popular and market leading access points as well as a larger group of worldwide units. The test results will show the usability of the Microchip Wi-Fi modules operating with the latest release of the Microchip TCPIP stack.
719
11.10 Access Point Compatibility Microchip TCP/IP Stack Help
Wi-Fi Alliance Testing
To carry the Wi-Fi Alliance logo, Wi-Fi products must successfully pass numerous tests, including compatibility testing. Wi-Fi compatibility testing is performed against 4 representative access points, with a subset of tests run against each of the access points. Devices are tested against these access points for characteristics such as connectivity, security, throughput, and a breadth of other specifications. Microchip Wi-Fi modules have successfully passed the Wi-Fi Alliance testing. The report is titled WFA7150 and is available at http://certifications.wi-fi.org/pdf_certificate.php?cid=WFA7150
Additional Wi-Fi Compatibility Testing
Wi-Fi technology is dramatically expanding the reach and applications of the internet to embedded devices. In many cases,
Wi-Fi is new to the markets and applications it is reaching. As a result, Microchip feels it is important to raise the bar on compatibility testing, and education of the developer.
Microchip has thus adopted the Wi-Fi.org test bench for more generic Access Point testing. The goal of these tests is to ensure basic connectivity in multiple non-secure and secure scenarios with a global representation of top selling access points.
Pass Criteria
The following tests are part of the current testing suite and must pass for the Access Point to be considered compatible.
• Following in conditions of no security, WEP40 and WEP104, WPA-PSK (TKIP), WPA2-PSK (AES)
• AP association, Iperf UDP upload/download, Iperf TCP upload/download, DHCP, ICMP ping
In many cases there are other modes that can be run with the Access Points and the user must take caution that if the mode is not listed, then compatibility is not necessarily guaranteed. These modes are usually Greenfield use, modes being deprecated by Wi-Fi.org, or cases of limiting the use of the Access Point for more private networking purposes and not for true Wi-Fi compatibility.
Examples of special modes not necessarily part of the results:
• WPA-PSK(AES) security: WPA-PSK security is defined as using TKIP. This is a mixed mode. This mode works if the AP just auto-detects and does not mix.
• WPA2-PSK (TKIP) security: WPA2-PSK security is defined as using 802.11i with AES. This is a mixed mode. This mode works if the AP just auto-detects and does not mix.
• 802.11g only, 802.11n only, 802.11g/n only: these are private network modes (cutting out mandatory support for 802.11b).
These modes may work if basic rates are limited to 1&2mbps per 802.11.
List of compatible Access Points:
• 2Wire 1701HG
• 2Wire 2701HG-B
• 3COM 3CRWER100-75
• 3COM WL-524
• Actiontec GT704-WG
• Apple Airport Express
• Apple Airport Extreme
• Apple Time Capsule
• Asus RT-N16
• Asus WL530g
720
11.10 Access Point Compatibility
• AirLink AR690W
• Belkin N1
• Belkin F5D7231-4
• Belkin F5D8231-4
• Belkin F7D1301 v1
• Belkin F7D3302 v1
• Belkin F7D5301 v1
• Belkin Surf N300
• Buffalo WHR-G125
• Buffalo WHR-HP-G54
• Buffalo WHR-HP-GN
• Cisco E1000
• Cisco E3000
• Cisco E4200
• Cisco M20
• Cisco Vallet M10
• Corega CG-WLAPGMN
• Corega CG-WLBARGO
• D-Link DI-524
• D-Link DIR-615
• D-Link DIR-655
• D-Link DIR-665
• D-Link DIR-825
• D-Link DIR-855
• D-Link WBR-1310
• D-Link WBR-2310
• Dynex DX-WGRTR G
• Dynex DX-WGRTR v1000
• Level1 WBR-3408
• Linksys WRT150N v1.1
• Linksys WRT310N
• Linksys WRT54G2
• Microsoft MN-700
• Netgear WG103
• Netgear WGR614v9
• Netgear WGT624v2
• Netgear WN2000RPT
• Netgear WN802T v2
• Netgear WNDR3300
• Netgear WNDR3700
• Netgear WNR1000 v2
• Netgear WNR1000 v3
Microchip TCP/IP Stack Help
721
11.11 802.11 AP/Router Configuration
• Netgear WNR200 v3
• Netgear WPN824v2
• Netgear WNR854T
• PCI MZK-W04NU
• Proxim AP-700
• SMC Networks SMCWBR14S-N4
• SMC Networks SMCWBR14T-G
• TP-Link TL-WR340G
• TP-Link TL-WR541G
• TP-Link TL-WR740N
• TP-Link TL-WR741ND
• TP-Link TL-WR841ND
• TP-Link TL-WR941N/D
• Westell B90-327W15-06
• ZyXel P-330W
• ZyXel X550N
*Note Tests Performed:
• Basic association with the AP (no security)
• Association with WEP security
• Association with WPA/WPA2-PSK security
• Ping test validation.
Microchip TCP/IP Stack Help
11.11
802.11 AP/Router Configuration Settings
Module
Description
Tips for Setting up Routers for 802.11b/g Use
The purpose of this section is to describe the settings for the most typical AP configurable parameters to enable compatibility with the Microchip MRF24WB0M / MRF24WG0M devices :
1. DHCP Settings - For DHCP on LAN side (where AP is DHCP server), set Router to Enable DHCP server. Set Client
Lease time to be longer than the typical off time of the station to ensure that the IP address provided doesn’t change each time the station is powered up. If an option for Always Broadcast is present for DHCP setup (broadcasts all DHCP responses to all clients), it should be disabled.
2. Data Rate Settings - Ensure that service rates include 802.11b. 802.11g or 802.11n only rates (green field) should be avoided, but mixed settings are usually acceptable. If a Basic Rate setting is defined, it should be set to 1 and 2MBPS only.
3. SSID Broadcast - Should typically be enabled so that the AP sends beacon frames containing the SSID. If disabled, ensure that Microchip Stack is set for Active Scanning.
4. Channel Selection - For debug purposes, it is typical to use a fixed channel instead of Auto Channel Selection. If a fixed channel has been selected for the MRF24 Station, select the corresponding channel for the AP.
5. Multicast Passthrough - If using multicast features (ZeroConfig for instance) ensure that the Router is configured to enable forwarding of Multicast packets.
722
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help Read back RF module FW version
6. Beacon Interval - Set the value for the time interval between AP beacons, typical is 100msec. For lower power, this can be set to a smaller value, say 30mS, if the DTIM interval is correspondingly increased.
7. RTS Threshold - Set the value for the frame size above which RTS/CTS will be used, typical is 2347.
8. Fragmentation Threshold - Set the value for the frame size above which packets will be fragmented, typical is 2346.
9. DTIM Interval - Set the value for Delivery Traffic Indication Message Interval, typical is 3 if the Beacon Interval is set for
100mSec. For lower power with the MRF24WB0M / MRF24WG0M, if the Beacon Interval is set to 30mS, then the DTIM should be set to 100 to allow 300mS DTIM Interval.
10. WLAN Partition (or AP Isolation)- Prevents AP clients from communicating to each other, typically disabled.
11. WMM Enable - Allows wireless multimedia traffic, disable unless necessary for other AP services.
12. Short Guard Interval (GI) - Lowers the guard interval between frames, disable unless necessary for other AP services.
13. WiFi Protected Setup (WPS) - Enables WPS device discovery, disable unless necessary for other AP services.
14. Frame Burst - Enables higher wireless packet throughput, disable unless necessary for other AP services. This may be called turbo, or other marketing terms.
15. CTS Protection Mode – Improves reliability of 802.11g traffic, disable unless necessary for other AP services.
16. Key Entry – Security can be entered with either a numerical key or an ASCII passphrase. Ensure you enter what the AP expects. If just starting, it is best to have another station like a laptop to validate what the AP is expecting.
11.12
WiFi Troubleshooting Tips
Module
Description
Host Controlled Connection Manager Clarifications
The following clarifications are to be noted for use of the device with Microchip TCPIP Stack versions unless otherwise noted.
11.12.1
Null String ESSID
Null String ESSID
these profile references prior to the attempted connection).
Work around:
When creating a connection profile, verify that the profile number returned is always either 1 or 2. If the returned value is 0,
profile number previously returned from WF_CPCreate ( see page 639)(&cpId) is used.
723
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help SoftAP Network
11.12.2
Read back RF module FW version
RF module FW version
There are 2 methods available.
1. Run WiFi Console standalone CLI command
Type in command getwfver.
The following will be displayed; MRF24W firmware version and Host Driver version.
2. Invoking function prototype WF_GetDeviceInfo ( see page 706)(tWFDeviceInfo *p_deviceInfo)
3 parameters will be returned
• Type (1 for MRF24WB0M_DEVICE and 2 for MRF24WG0M_DEVICE)
• Rom Version (0x12 for MRF24WB0M and 0x30 / 0x31 for MRF24WG0M)
• Patch version
MRF24WG0M RF module FW version
From RF module FW version 0x3107 onwards, FW release will follow this roll-out order
Even Numbered (eg 0x3108, 0x310a, etc)
• Multi-DHCP
• WPA-EAP
• No Wi-Fi Direct
• All other features, including SoftAP supporting max 4 clients
Odd Numbered (eg 3109, 0x310b)
• No multi-DHCP
• No WPA-EAP
• Wi-Fi Direct
• All other features, including SoftAP supporting only 1 client
11.12.3
SoftAP Network
SoftAP mode is only supported by MLA v5.42 July 2012 releases or later.
SoftAP tracking of clients' status (DHCPs.c) is only supported by MLA v5.42.06 Mar 2013 releases or later.
Clients supported in SoftAP Mode
SoftAP mode is only supported by MRF24WG0M RF modules.
For RF module FW version 0x3107, softAP can only support 1 client.
For future RF module FW versions (even-numbered such as 0x3108, 0x310a, etc), softAP can support up to a max of 4 clients.
724
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help SoftAP Network
SoftAP Operations : Support of Max 1 Client Scenario
Once the first client is connected to MRF24WG0M SoftAP, softAP will remember client's MAC address. Only when the client does a disconnect in the 2 scenarios below, softAP will reset the MAC address to NULL. When this happens, another client
can connect ( see page 176) to MRF24WG0M softAP.
Below are 2 scenarios in which a client disconnects from MRF24WG0M SoftAP
Scenario A
Client A does a proper disconnection, that is disassociation & disauthentication frames are sent. MRF24WG0M SoftAP, after
SoftAP.
Scenario B
Client just powers off , in other words, did NOT inform MRF24WG0M SoftAP it is disconnecting.
(SOFTAP_CHECK_LINK_STATUS) To cater to this situation, MRF24WG0M SoftAP will ping STA by transmitting NULL
DATA frames to STA to check whether STA is alive/dead. If STA is alive, it will respond to the NULL DATA frames received by transmitting ACK frames back to softAP. If STA is dead, softAP will not receive any frames from this particular device.
Once the PARAM_LINK_DOWN_THRESHOLD is reached, softAP considers the device to be dead. Refer to function
prototype WF_SetLinkDownThreshold ( see page 715)().
SoftAP Operations : Support of Max 4 Clients Scenario
To know how many clients and their connection status, DHCPs.c has a data struct DHCP_IP_POOL and the variable
DhcpIpPool[] that keeps track of clients connected to softAP, such as client's MAC address, IP address.
typedef struct
{
MAC_ADDR ClientMAC;
IP_ADDR Client_Addr;
BOOL isUsed;
UINT32 Client_Lease_Time;
}DHCP_IP_POOL;
DHCP_IP_POOL DhcpIpPool[MAX_DHCP_CLIENTS_NUMBER];
However, be aware there would be a latency in client's status. For example, a client has disconnected from softAP. But it would take some time before this update in status in reflected in DhcpIpPool[].
Detection of SoftAP's SSID
Certain devices may only support active scan. Based on 802.11 specifications, passive scan is mandatory but active scan is optional.
MRF24WG0M RF module FW version 0x3107 softAP only supports passive scan. Such devices may not be able to detect
MRF24WG0M softAP.
MRF24WG0M RF module FW version 0x3108 and later softAP supports both passive and active scan. If your device is unable to detect MRF24WG0M softAP SSID, check your RF module FW version.
• Why does the software hangs at WF_ProcessEvent ( see page 717)() in line WF_ASSERT(FALSE) when in
softAP network type ?
725
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help Wi-Fi Protected Setup (WPS) Issues
A possible cause could be the handling of WF event WF_EVENT_SOFT_AP_EVENT. This new feature is only available for
MRF24WG0M (i) RF module FW version 0x3108 and later and (ii) MLA v5.42.06 release or later. If you are using RF module
FW version 0x3108 or later and at the same time using prior to MLA v5.42.06 release, MRF24WG0M is generating this
WF_ASSERT(FALSE) ). The corrective action is to port over this event handling in WFEVentHandler.c and
WF_ProcessEvent ( see page 717)() (WiFi EZConfig) from MLA v5.42.06 release or later.
11.12.4
Wi-Fi Protected Setup (WPS) Issues
Wi-Fi Protected Setup (WPS) security connection mode is only supported by MLA v5.42 July 2012 releases or later.
• Why is MRF24WG0M reporting error message "Event: Connection Failed : WF_RECV_DISASSOC :
WF_UNSPECIFIED" when trying to connect ( see page 176) to certain AP/routers in WPS-PBC security
connection modes ?
When running WiFi TCP/IP Demo, the output display shows
*** WiFi TCP/IP Demo ***
Start WiFi Connect
Domain: FCC
MAC: 00 1E C0 08 F1 04
SSID: (none)
Network Type: Infrastructure (using WPS Push Button)
Scan Type: Active Scan
Channel List: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Retry Count: Retry Forever
Beacon Timeout: 40
Security: WPS push button method
Power Save: Disabled
New IP Address ( see page 152): 169.254.1.1
Event: Connection Failed : WF_RECV_DISASSOC : WF_UNSPECIFIED
A wireless capture revealed that some AP/routers is transmitting disassociation frames instead of deauthentication frames during WPS process. This behavior is not according to 802.11 specifications and thereby causing WPS to dysfunction. RF module FW (from 0x3108 onwards) was modified to handle this erroneous case.
AP/router is in WPA/WPA2 security mode?
Refer to Wi-Fi Protected Setup Specification Version 1.0h standard.
WPS protocol is built on top of the WPA/WPA2 EAPOL 4-way handshaking process and there are additional process for
WPS. Time allowed for entire WPS protocol is 2 min.
The specifications listed the below parameters
726
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help
1. Retransmission timeout = 5 sec
2. Individual message processing timeout = 15 sec
3. Overall timeout for entire protocol to complete = 2 min
Network Switch or Change
• What is needed to see the WPS frame exchanges in a wireless sniffer capture?
Either click on <Protocol> field and scroll down until this starts with the alphabet "E..." or in the <Filter:> field, type in "eapol".
• What is special about the PIN selected for WPS-PIN? Can this PIN be randomly selected by the user?
The 8 digit PIN is NOT randomly generated. The last digit is the checksum of first 7 digits of the PIN. If this checksum is wrong, MRF24WG0M module will reject this PIN code.
11.12.5
Network Switch or Change
Network Switch or Change
WiFi EZConfig is a good demo reference for handling network switch.
In WiFi EZConfig, the function prototype WFEasyConfigProcess() is called to execute a network change.
MRF24W is put into Hibernate mode, which implies a reset operation, whereby the LDO is turned off.
Old connection profile is deleted and new connection profile is created. New parameters, linked to selected network, are configured into new profile. Then exit out of Hibernate mode.
The recommend sequences are
1. Disconnect from current network by invoking WF_CMDisconnect ( see page 678)()
2. Delete the profile by invoking WF_CPDelete ( see page 640)()
3. Create new profile by invoking WF_CPCreate ( see page 639)()
4. Set up parameters for this new profile such as setting SSID, Wi-Fi security, network type.
5. Enter Hibernate mode by setting WF_hibernate.state = WF_HB_ENTER_SLEEP and WF_hibernate.wakeup_notice =
FALSE
6. Have a short time delay such as DelayMs(50)
727
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help
7. Exit from Hibernate mode by setting WF_hibernate.wakeup_notice = TRUE
Management Scan Message Conflict
11.12.6
Hibernate Mode
Hibernate Mode
Hibernate mode is used during network switch or change.
Ensure definition WF_USE_POWER_SAVE_FUNCTIONS is enabled.
Within the main() loop, StackTask() will call MACProcess(). It will then invoke CheckHibernate(), which executes/handles hibernate mode based on WF_hibernate.state and WF_hibernate.wakeup_notice.
To enter into Hibernate mode, the following settings are required
• WF_hibernate.state = WF_HB_ENTER_SLEEP
• WF_hibernate.wakeup_notice = FALSE
To exit from Hibernate mode, the following settings are required
• WF_hibernate.wakeup_notice = TRUE
11.12.7
Management Scan Message Conflict
Management scan message conflict
Management messages must always return successful or it causes an assert in the host driver. An unsuccessful management message can occur when the connection retry is enabled (MY_DEFAULT_LIST_RETRY_COUNT>0) causing
command is sent.
Work around:
scan retry” and “no de-authorization action”.
a. To disable Scan Retry
WF_CASetListRetryCount ( see page 667)(MY_DEFAULT_LIST_RETRY_COUNT);
should be 0 b. To disable De-authorization action
WF_CASetDeauthAction ( see page 664)(WF_DO_NOT_ATTEMPT_TO_RECONNECT);
c. To disable De-authentication action
WF_CASetBeaconTimeoutAction ( see page 663)(WF DO NOT ATTEMPT TO RECONNECT);
d. Use “Connect” only on “permanent loss” or “connection failure”.
728
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help Shorter Scan or Connection Duration
i. If the return state is WF_CSTATE_NOT_CONNECTED (or WF_CSTATE_CONNECTION_PERMANENTLY_LOST), then this means firmware is in IDLE, so host can issue host scan safely ii. If the return state is WF_CSTATE_CONNECTED_INFRASTRUCTURE, then this means firmware is in CONNECTED. In this case a scan command can be issued but a watchdog timer must be used to time for conflict. Also, ensure the management timer is set for at least 0.4seconds per channel scanned to prevent queued Tx buffer requests from timing out.
iii. If return state is WF_CSTATE_CONNECTION_IN_PROGRESS ( or WF_CSTATE_RECONNECTION_IN_PROGRESS), then this means firmware is in the middle of connection process and a scan must not be initiated.
f. If “Disconnect” function is desired, a watchdog timer needs to be used to address the case where a conflict occurs with an over the air disassociate or deauthorize.
g. For watchdog timing, advised timing is 2x the management packet timeout (that is, use 4seconds unless the management timeout has been increased).
idle, etc.) then you can use MY_DEFAULT_LIST_RETRY_COUNT>0 or retry forever
176)” API. Do not use “Disconnect”.
a. If “Disconnect” function is desired, a watchdog timer needs to be used to address the case where a conflict occurs with an over the air disassociate or deauthorize.
11.12.8
Maximum Scan Results
Maximum Scan Results Supported
Both MRF24WB0M and MRF24WG0M support up to a maximum of 60 scan results.
11.12.9
Shorter Scan or Connection Duration
Scan or Connection Duration
1. Channel selection
Within FCC domain, there are 11 channels.
Channel 1, 6, 11 overlaps and are designated social channels. The longer the scan channel list, the longer will be the scan and connection duration.
To scan all channel
• #define MY_DEFAULT_CHANNEL_LIST {}
To scan selected channels
729
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help
• #define MY_DEFAULT_CHANNEL_LIST {1,6,11}
2. Delay timing
Within the stack software, there are numerous delays added in.
These selected delay time may be optimized or changed to use shorter delay time.
Scan Operation and Scan Results
Example:
In WFEasyConfigProcess(), when softAP enters Hibernate mode, a delay is executed before exiting Hibernate mode.
DelayMs(50); // SOFTAP_ZEROCONF_SUPPORT. Timing reduced from 200 to 50.
Delay timing was originally set to 200msec and then optimized to 50msec.
The delay timing has not been tested on actual products and are just recommended values.
11.12.10
Scan Operation and Scan Results
Scan operation and scan result
Refer to WiFi EZConfig demo for example on how scanning operation is initiated and how scan results are displayed.
Use function prototype WF_Scan ( see page 680)() to invoke a scan operation.
When the scan results are ready, a WF_EVENT_SCAN_RESULTS_READY event will be generated.
MRF24WG0M.
Refer to data struct tWFScanResult (WFApi.h)
Each scan result returned by MRF24WB0M / MRF24WG0M RF module will contain
• bssid (Network BSSID value)
• ssid (Network SSID value)
• Access point configuration information such as security mode (WPA2, WPA, WEP, OPEN)
For WEP security mode, the scan results will NOT indicate whether it is WF_SECURITY_WEP_SHAREDKEY or
WF_SECURITY_WEP_OPENKEY. Referring to 802.11 specifications, the beacon itself does not indicate this difference.
The scan results reflect whatever information is contained in the beacons or probe responses.
• Access point beacon interval
• atimWindow (Applicable only for infrastructure network)
• List of network basic rates and number of valid rates in basic rates
• RSSI (Signal strength of received beacon or probe response frames)
• DtimPeriod
• bssType (WF_INFRASTRUCTURE, WF_ADHOC)
• channel (channel number in which beacon or probe response frame is received in)
• ssidLen (Length of SSID)
Remember scan results are retained on the MRF24W until:
1. Calling WF_Scan ( see page 680)() again (after scan results returned from previous call).
730
11.12 WiFi Troubleshooting Tips
2. Resetting MRF24W.
Microchip TCP/IP Stack Help Error Messages And Possible Causes
Scan Results Showing Multiple Copies of the Same SSID
If the same SSID is detected on different channels, the scan results may seem to show duplicate scan results. In reality, the scan results are showing the same SSID but on different channels. For example, SSID "MCHP_Network" is detected on channel 1, 6 and 11. Therefore the scan results will display among the scan results 3 copies of SSID "MCHP_Network".
AP/Routers With Hidden SSID
If an Access Point uses a hidden SSID, then an active scan must be used (see scanType field in the Connection Algorithm).
In active scan, MRF24W will transmit a probe request frame and the AP with the hidden SSID will respond by transmitting a probe response frame.
Scan Cache
If necessary, a scan cache can be created such that scan results are retrieved and stored.
As an example, in WiFi EZConfig in SoftAP mode, upon power on reset, a scan operation is invoked and scan results are retrieved from MRF24WG0M and stored into global array (tWFScanResult preScanResult[50]).
After this, wifi startup in softAP mode is initiated via function prototype WF_Connect(). Within WF_Connect(), there are embedded scan operation, which will cause the scan results to be reset to default values.
11.12.11
MRF24WB0M Compatibility with AP/router
MRF24WB0M Compatibility With AP/Routers
MRF24WB0M supports only legacy 802.11b rates of 1Mbps and 2Mbps.
To ensure compatibility with MRF24WB0M,
• iOS and Android FW releases need to support 1 and 2 Mbps
• APs/ routers need to support 1 and 2 Mbps
Recommended configurations on APs/Routers settings
• Set AP/router basic rate to 1-2 Mbps
• Set AP/router channel settings to defined social channels such as channel 1, 6 or 11.
If iOS, Android FW releases and AP/routers do not support 1 and 2 Mbps, customers are encouraged to feedback to the manufacturers or developers.
MRF24WB0M is best suited for captive networks, whereby the surrounding wireless networks are under control by the users.
In applications where the surrounding wireless networks are unknown and constantly changing, the MRF24WG0M is highly recommended over the MRF24WB0M.
11.12.12
Error Messages And Possible Causes
• During scanning, the web browser reported error message "Command failed, connection to development board
was lost".
731
11.12 WiFi Troubleshooting Tips Microchip TCP/IP Stack Help Error Messages And Possible Causes
This is not a bug because when you click the "OK" button in the message box, it will continue to work correctly. Above timeout error message happens when you choose to scan ALL channels. If you elect to scan only 2-3 channels, the scan duration will be much faster and the web browser is unlikely to timeout.
A possible solution is to increase the timeout setting in mchp.js
Eg \EasyConfigWebPages\javascript\mchp.js
var timeOutMS = 5000; //ms
• Scan results seem to display 1 SSID less. For example, there are 10 scan results but only 9 scan results are
displayed.
If the scan result yields 10 scan results, our MRF24W + PIC development board will send 10 scan results to the webpage.
However, the webpage will display only 9 scan results and drop its own SSID (scan result). As an example, the development board and laptop are using an AP named "test", then the webpage will not display SSID "test" among the displayed scan results.
• Why is my device not displaying MRF24WG0M softAP SSID in the scan results?
There are 2 possible reasons.
(a) Hidden SSID
(b) The device is only supporting active scan. MRF24WG0M RF module FW version 0x3107 only supports softAP with passive scan. From MRF24WG0M RF module FW version 0x3108 and future releases, softAP supports both active and passive scan. Check that your MRF24WG0M RF module FW version is 0x3108 and later.
732
12
_
_checkIpSrvrResponse variable 206
_IsSNMPv3ValidStructure function 379
_Snmpv3IsValidAuthStructure function 379
_Snmpv3IsValidInt function 380
_TFTP_ACCESS_ERROR enumeration 592
_TFTP_FILE_MODE enumeration 592
_TFTPSendFileName function 603
_TFTPSendROMFileName function 604
_updateIpSrvrResponse variable 206
8
Index
802.11 AP/Router Configuration Settings 722
A
Access Point Compatibility 719
AccessCtrlSubSysIsAccessAllowed structure 408
Accessing the Demo Application 80
Microchip TCP/IP Stack Help
arp_app_callbacks structure 166
ARPDeRegisterCallbacks function 164
ARPRegisterCallbacks function 165
AUTH_LOCALIZED_PASSWORD_KEY_LEN macro 439
authKey_iPad variable 426 authKey_oPad variable 426 authoritativeSnmpEngineBoots variable 426
authoritativeSnmpEngineTime variable 427
a
12
B
BerkeleySocketInit function 186
BSD Wrapper Internal Members 187
BSD Wrapper Public Members 173
btohexa_high function 220 btohexa_low function 220
C
CalculateFinishedHash function 487
COMMUNITY_TYPE enumeration 334
Configure your WiFi Access Point 77
Connection Algorithm Internal Members 674
Connection Algorithm Public Members 653
Connection Manager Public Members 676
Connection Profile Internal Members 650
Connection Profile Public Members 638
Microchip TCP/IP Stack Help
D
DATA_TYPE_TABLE_SIZE macro 351 dataTypeTable variable 351
DDNSGetLastStatus function 202
ddnsServiceHosts variable 205 ddnsServicePorts variable 205
dispatcherProcessPdu structure 409 dispatcherStatusInfo structure 409
dispathcerReturnResponsePdu structure 410
b
12
Dynamic DNS Internal Members 204
Dynamic DNS Public Members 198
E
Error Messages And Possible Causes 731
Explorer 16 and PIC32 Starter Kit 73
F
FindMatchingSocket function 564, 629
FindOIDsFromSnmpV3Request function 381
FindOIDsInRequest function 351
FindROMEmailAddress function 317
Flag_ImageUpdate_running variable 98
Microchip TCP/IP Stack Help
FormatNetBIOSName function 224
G
GenerateHashRounds function 488
GenerateRandomDWORD function 225
GenerateSessionKeys function 488
Generating Server Certificates 469
GENERIC_TRAP_NOTIFICATION_TYPE enumeration 333
GetAppPowerSaveMode function 701
GetOIDStringByAddr function 368
getSnmpV2GenTrapOid function 381
gGenericTrapNotification variable 336 gOIDCorrespondingSnmpMibID variable 336
gRFModuleVer1209orLater variable 704
c
12 Microchip TCP/IP Stack Help
gSnmpNonMibRecInfo variable 121
gSnmpV3InPduWholeMsgBuf variable 427
gSNMPV3TrapSecurityLevel variable 430 gSnmpv3UserDBIndex variable 430
gSnmpv3UserSecurityName variable 121
gSpecificTrapNotification variable 336
gUsmStatsEngineID variable 430
H
HandlePossibleTCPDisconnection function 188
Hash Table Filter Entry Calculator 67
HTTP_FILE_TYPE enumeration 258
HTTP_IO_RESULT enumeration 246
HTTP_MIN_CALLBACK_FREE macro 259
HTTP_READ_STATUS enumeration 246
httpFileExtensions variable 261
d
12
HTTPHeaderParseAuthorization function 261
HTTPHeaderParseContentLength function 262
HTTPHeaderParseCookie function 262
HTTPHeaderParseLookup function 263
HTTPPostDDNSConfig function 96
HTTPPostSNMPCommunity function 96
HTTPPrint_varname function 251
HTTPReadPostValue function 253
HTTPRequestHeaders variable 266
HTTPResponseHeaders variable 266
Microchip TCP/IP Stack Help
I
ICMPSendPingToHost function 270
ICMPSendPingToHostROM function 271
ICMPSendPingToHostROM macro 272
ImageUpdate_Checksum variable 99
incomingPdu variable 431 incomingSnmpPDUmsgID variable 431
INOUT_SNMP_PDU enumeration 417
e
12
IS_SNMPV3_AUTH_STRUCTURE macro 440
IsSNMPv3ValidStructure function 383
L
Microchip TCP/IP Stack Help
LowLevel_CPGetElement function 651
LowLevel_CPSetElement function 651
leftRotateDWORD function 226 leftRotateDWORD macro 226
LOCAL_PORT_END_NUMBER macro 566
LOCAL_PORT_START_NUMBER macro 566
LOCAL_UDP_PORT_END_NUMBER macro 630
LOCAL_UDP_PORT_START_NUMBER macro 630
LowLevel_CAGetElement function 674
LowLevel_CASetElement function 675
M
Management Scan Message Conflict 728
MAX_TELNET_CONNECTIONS macro 578
MAX_TRY_TO_SEND_TRAP macro 121
md5LocalizedAuthKey variable 432
Microchip TCP/IP Discoverer 67
MPFS_SEEK_MODE enumeration 278
MPFS_WRITE_PAGE_SIZE macro 292
f
12
MRF24WB0M Compatibility with AP/router 731
MSG_AUTHORITATIVE_HEADER_LEN macro 440
MSGGLOBAL_HEADER_LEN macro 440
MsgProcModPrepareDataElements structure 411
MsgProcModPrepareOutgoingMessage structure 412
MsgProcModPrepareResponseMessage structure 412
msgSecrtyParamLenOffset variable 432
N
Microchip TCP/IP Stack Help
NOTIFY_COMMUNITY_LEN macro 344
NTP_FAST_QUERY_INTERVAL macro 466
O
P
Performance Test Internal Members 300
Performance Test Stack Members 298
Power Save Internal Members 699
PRIV_LOCALIZED_PASSWORD_KEY_LEN macro 441
ProcessGetBulkVar function 383
g
12
ProcessGetNextVar function 384
ProcessGetSetHeader function 372
processResponsePdu structure 413
ProcessSnmpv3MsgData function 385
R
Read back RF module FW version 724
ReadProgramMemory function 293
REBOOT_SAME_SUBNET_ONLY macro 323
REG_DISABLE_LOW_POWER_MASK macro 704
registerContextEngineID structure 422
REPORT_FLAG_AND_SECURITY_LEVEL_FLAGS enumeration 417
RESERVED_HTTP_MEMORY macro 268
Microchip TCP/IP Stack Help
ROMStringToIPAddress function 227
ROMStringToIPAddress macro 228
S
Scan Operation and Scan Results 730
securityPrimitivesOfIncomingPdu variable 432
SecuritySysGenerateRequestMsg structure 414
SecuritySysGenerateResponseMsg structure 415
SecuritySysProcessIncomingMsg structure 418
SENDTCP_RESET_TIMERS macro 568
SetAppPowerSaveMode function 701
SetEventNotificationMask function 675
SetPowerSaveState function 700
sha1LocalizedAuthKey variable 433
Shorter Scan or Connection Duration 729
SM_SSL_RX_SERVER_HELLO enumeration 496
h
12
SMTP Client Internal Members 315
SMTP Client Long Message Example 303
SMTP Client Public Members 305
SMTP Client Short Message Example 302
SMTP_SERVER_REPLY_TIMEOUT macro 319
Microchip TCP/IP Stack Help
SNMP_COMMUNITY_MAX_LEN macro 342
SNMP_ENGINE_MAX_MSG_SIZE macro 441
SNMP_ENGNID_OCTET_IDENTIFIER_VAL enumeration 419
SNMP_ERR_STATUS enumeration 361
SNMP_MAX_NON_REC_ID_OID macro 122
SNMP_MAX_OID_LEN_MEM_USE macro 442
SNMP_NOTIFY_INFO structure 363
SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE macro
SNMPCheckIfPvtMibObjRequested function 375
i
12 Microchip TCP/IP Stack Help
SNMPGetExactIndex function 386
SNMPIdRecrdValidation function 386
SNMPIsNotifyReady function 339
SNMPIsValidSetLen function 387
snmpMsgBufSeekPos variable 435
SNMPNONMIBRECDINFO structure 419
SNMPNotifyPrepare function 340
snmpReqVarErrStatus variable 366
snmpResponseSecurityFlag variable 437
snmpSecurityLevel variable 437
SNMPV3_AUTH_LOCALIZED_PASSWORD_KEY_LEN_ME
SNMPV3_HMAC_HASH_TYPE enumeration 419
SNMPV3_MSG_AUTH_SEC_PARAM_RESULT enumeration
SNMPV3_MSG_PRIV_SEC_PARAM_RESULT enumeration
SNMPV3_PRIV_LOCALIZED_PASSWORD_KEY_LEN_MEM
SNMPV3_PRIV_PROT_TYPE enumeration 420
SNMPV3_REQUEST_WHOLEMSG structure 421
SNMPV3_RESPONSE_WHOLEMSG structure 421
SNMPV3_USER_SECURITY_NAME_LEN_MEM_USE macro 443
snmpV3AesDecryptInitVector variable 437
Snmpv3AESDecryptRxedScopedPdu function 388
snmpV3AesEncryptInitVector variable 437
Snmpv3AESEncryptResponseScopedPdu function 388
Snmpv3AuthenticateRxedPduForDataIntegrity function 389
Snmpv3AuthenticateTxPduForDataIntegrity function 389
Snmpv3AuthKeyZeroing2HmacBufLen64 function 390
Snmpv3CmprTrapSecNameAndSecLvlWithUSMDb function
Snmpv3ComputeHMACIpadOpadForAuthLoclzedKey function 391
Snmpv3ComputeHmacMD5Digest function 392
Snmpv3ComputeHmacShaDigest function 393
Snmpv3ComputeMd5HmacCode function 393
Snmpv3ComputeShaHmacCode function 394
snmpV3EngnUserDataBase structure 421
Snmpv3FormulateEngineID function 394
Snmpv3FreeDynAllocMem function 395
Snmpv3GetAuthEngineTime function 395
Snmpv3GetBufferData function 396
Snmpv3GetSecurityLevel function 396
Snmpv3GetTrapSecurityLevel function 397
Snmpv3InitializeUserDataBase function 398
Snmpv3IsValidAuthStructure function 398
SNMPV3MSG_AUTHENTICATION_FAIL macro 444
SNMPV3MSG_AUTHENTICATION_SUCCESS macro 444
Snmpv3MsgProcessingModelProcessPDU function 399
j
12
Snmpv3Pswd2LocalizedAuthKeyMD5Hashing function 400
Snmpv3Pswd2LocalizedAuthKeySHAHashing function 401
Snmpv3ScopedPduProcessing function 402
Snmpv3SetErrorStatus function 402
snmpV3TrapConfigDataBase structure 422
Snmpv3TrapScopedpdu function 403
snmpV3UserDataBase variable 437
Snmpv3UserSecurityModelProcessPDU function 404
Snmpv3UsmAesEncryptDecryptInitVector function 404
Snmpv3UsmOutMsgAuthenticationParam function 405
Snmpv3USMOutMsgPrivParam function 405
Snmpv3UsmSnmpEngnAuthPrivPswdLocalization function
Snmpv3ValidateEngineId function 406
Snmpv3ValidateSecNameAndSecLvl function 406
Snmpv3ValidateSecurityName function 407
SNMPValidateCommunity function 341
SNTP Client Internal Members 463
SNTP Client Public Members 462
SNTPGetUTCSeconds function 462
SOCK_STREAM macro 183 sockaddr structure 183
SOCKADDR type 184 sockaddr_in structure 184
SOCKET_CNXN_IN_PROGRESS macro 185
Microchip TCP/IP Stack Help
SSL_ALERT_LEVEL enumeration 496
SSL_BASE_BUFFER_ADDR macro 497
SSL_BASE_SESSION_ADDR macro 498
SSL_CHANGE_CIPHER_SPEC macro 499
SSL_MIN_SESSION_LIFETIME macro 481
SSL_RSA_EXPORT_WITH_ARCFOUR_40_MD5 macro 502
SSL_RSA_LIFETIME_EXTENSION macro 482
SSL_RSA_WITH_ARCFOUR_128_MD5 macro 502
SSL_SESSION_STUB structure 504
SSL_SESSION_TYPE enumeration 504
k
12 Microchip TCP/IP Stack Help
SSL_SUPPLEMENTARY_DATA_TYPES enumeration 475
SSLFinishPartialRecord macro 508
SSLFlushPartialRecord macro 509 sslHash variable 509
SSLHashFree function 510 sslHashID variable 510
sslKeys variable 511 sslKeysID variable 511
SSLRSAOperation function 513 sslRSAStubID variable 513
SSLRxAntiqueClientHello function 514
SSLRxClientKeyExchange function 516
SSLRxServerCertificate function 518
sslSession variable 519 sslSessionID variable 519
SSLSessionMatchID function 519
SSLSessionMatchIP function 520
SSLSessionUpdated macro 522 sslSessionUpdated variable 522
SSLStartPartialRecord function 522
SSLTxClientKeyExchange function 526
SSLTxServerCertificate function 528
SSLTxServerHelloDone function 529
statusInformation structure 422
STD_BASED_SNMP_MESSAGE_PROCESSING_MODEL enumeration 423
STD_BASED_SNMP_SECURITY_MODEL enumeration 423
STD_BASED_SNMPV3_SECURITY_LEVEL enumeration 423
strAuthenticated variable 581 strDisplay variable 581 strGoodBye variable 581
StringToIPAddress function 229
l
12
T
TCP/IP Configuration Wizard 64
TCP_ADJUST_GIVE_REST_TO_RX macro 534
TCP_ADJUST_GIVE_REST_TO_TX macro 534
TCP_ADJUST_PRESERVE_RX macro 534
TCP_ADJUST_PRESERVE_TX macro 534
TCP_AUTO_TRANSMIT_TIMEOUT_VAL macro 570
TCP_CLOSE_WAIT_TIMEOUT macro 570
TCP_DELAYED_ACK_TIMEOUT macro 570
TCP_FIN_WAIT_2_TIMEOUT macro 571
TCP_KEEP_ALIVE_TIMEOUT macro 572
TCP_MAX_UNACKED_KEEP_ALIVES macro 573
Microchip TCP/IP Stack Help
TCP_OPTIMIZE_FOR_SIZE macro 573
TCP_OPTIONS_END_OF_LIST macro 574
TCP_OPTIONS_MAX_SEG_SIZE macro 574
TCP_START_TIMEOUT_VAL macro 575
TCP_SYN_QUEUE_MAX_ENTRIES macro 576
TCP_SYN_QUEUE_TIMEOUT macro 576
TCP_WINDOW_UPDATE_TIMEOUT_VAL macro 570
TCPAddSSLListener function 472
TCPAdjustFIFOSize function 536
TCPFindROMArrayEx function 541
TCPIP Demo App Features by Hardware Platform 88
m
12
TCPPerformanceTask function 299
TCPRequestSSLMessage function 478
TCPRXPerformanceTask function 300
TCPSSLGetPendingTxSize function 478
TCPSSLHandleIncoming function 479
TCPSSLHandshakeComplete function 479
TCPSSLInPlaceMACEncrypt function 480
TCPSSLIsHandshaking function 473
TCPSSLPutRecordHeader function 480
TCPStartSSLClient function 473
TCPStartSSLClientEx function 561
TCPStartSSLServer function 481
TCPTXPerformanceTask function 301
TFTP_ACCESS_ERROR enumeration 592
TFTP_ARP_TIMEOUT_VAL macro 598
Microchip TCP/IP Stack Help
TFTP_CHUNK_DESCRIPTOR structure 595
TFTP_END_OF_FILE enumeration member 593
TFTP_ERROR enumeration member 593
TFTP_ERROR_ACCESS_VIOLATION enumeration member
TFTP_ERROR_DISK_FULL enumeration member 592
TFTP_ERROR_FILE_EXISTS enumeration member 592
TFTP_ERROR_FILE_NOT_FOUND enumeration member
TFTP_ERROR_INVALID_OPERATION enumeration member
TFTP_ERROR_NO_SUCH_USE enumeration member 592
TFTP_ERROR_NOT_DEFINED enumeration member 592
TFTP_ERROR_UNKNOWN_TID enumeration member 592
TFTP_FILE_MODE enumeration 592
TFTP_FILE_MODE_READ enumeration member 592
TFTP_FILE_MODE_WRITE enumeration member 592
TFTP_GET_TIMEOUT_VAL macro 599
TFTP_NOT_READY enumeration member 593
TFTP_OK enumeration member 593
TFTP_RETRY enumeration member 593
TFTP_TIMEOUT enumeration member 593
TFTP_UPLOAD_COMPLETE macro 596
TFTP_UPLOAD_CONNECT_TIMEOUT macro 596
TFTP_UPLOAD_HOST_RESOLVE_TIMEOUT macro 597
TFTP_UPLOAD_RESOLVE_HOST macro 597
TFTP_UPLOAD_SEND_DATA macro 597
TFTP_UPLOAD_SEND_FILENAME macro 597
TFTP_UPLOAD_SERVER_ERROR macro 597
TFTP_UPLOAD_WAIT_FOR_CLOSURE macro 598
TFTPGetUploadStatus function 593
n
12 Microchip TCP/IP Stack Help
TFTPUploadFragmentedRAMFileToHost function 594
TFTPUploadRAMFileToHost function 595
TickConvertToMilliseconds function 608
TRAP_COMMUNITY_MAX_LEN macro 343
tWFDeviceInfoStruct structure 712
tWFPsPwrMode type 702 tWFPwrModeReq type 702
Tx Power Control Public Members 692
U
UDPPerformanceTask function 299
o
12 Microchip TCP/IP Stack Help
unregisterContextEngineID structure 416
uploadChunkDescriptor variable 605 uploadChunkDescriptorForRetransmit variable 605
Uploading Pre-built MPFS2 Images 65
USER_SECURITY_NAME_LEN macro 444
USM_SECURITY_LEVEL enumeration 424
V
VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE enumeration 333
vUploadFilename variable 605 vUploadRemoteHost variable 605
W
WF_CAGetBeaconPeriod function 673
WF_CAGetBeaconTimeout function 654
WF_CAGetBeaconTimeoutAction function 655
WF_CAGetChannelList function 655
WF_CAGetConnectionProfileList function 656
WF_CAGetDeauthAction function 656
WF_CAGetDtimInterval function 672
WF_CAGetEventNotificationAction function 657
WF_CAGetListenInterval function 658
WF_CAGetListRetryCount function 659
WF_CAGetMaxChannelTime function 659
WF_CAGetMinChannelTime function 660
WF_CAGetProbeDelay function 660
WF_CAGetScanCount function 661
WF_CASetBeaconPeriod function 673
WF_CASetBeaconTimeout function 662
WF_CASetBeaconTimeoutAction function 663
WF_CASetChannelList function 663
WF_CASetConnectionProfileList function 664
WF_CASetDeauthAction function 664
WF_CASetDtimInterval function 673
WF_CASetEventNotificationAction function 665
WF_CASetListenInterval function 666
WF_CASetListRetryCount function 667
WF_CASetMaxChannelTime function 667
WF_CASetMinChannelTime function 668
WF_CASetProbeDelay function 668
WF_CASetScanCount function 669
WF_CMCheckConnectionState function 679
WF_CMGetConnectContext function 678
WF_CMGetConnectionState function 678
WF_ConvPassphrase2Key function 687
WF_CPGetAdHocBehavior function 640
WF_CPGetDefaultWepKeyIndex function 684
WF_CPGetNetworkType function 642
WF_CPGetWepKeyType function 684
WF_CPGetWPSCredentials function 690
WF_CPSetAdHocBehavior function 644
WF_CPSetDefaultWepKeyIndex function 685
WF_CPSetNetworkType function 646
p
12
WF_CPSetWepKeyType function 685
WF_EnableSWMultiCastFilter function 714
WF_GetMultiCastFilter function 707
WF_GetPowerSaveState function 697
WF_GetRegionalDomain function 708
WF_GetRtsThreshold function 709
WF_HibernateEnable function 698
WF_MulticastSetConfig function 714
WF_SetLinkDownThreshold function 715
WF_SetMultiCastFilter function 710
WF_SetRegionalDomain function 711
WF_SetRtsThreshold function 712
WF_TxPowerGetFactoryMax function 694
WF_TxPowerGetMinMax function 693
WF_TxPowerSetMinMax function 693
WF_YieldPassphrase2Host function 691
WFCAElementsStruct structure 670
WFCPElementsStruct structure 648
WFMacStatsStruct structure 713
wICMPSequenceNumber variable 276
Wi-Fi Connection Algorithm 652
Microchip TCP/IP Stack Help
Wi-Fi Miscellaneous Public Members 705
Wi-Fi Protected Access (WPA/WPA2) 686
Wi-Fi Protected Setup (WPS) 688
Wi-Fi Protected Setup (WPS) Issues 726
Wired Equivalent Privacy (WEP) 683
wUploadChunkOffset variable 606 wUploadChunkOffsetForRetransmit variable 606
Z
Zero Configuration (ZeroConf) 123
q
İndir
Reklam