You are on page 1of 15

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.


Top: „Flexgate III“ (ED2)
Bottom right: "FlexGate II" from Elektor (MSC1210)
Bottom left: "FlexGate I " (C515).
Top right: LCD connected over I²C
Right: As seen from a browser

Using the FlexGate TCP/IP-Stack

This document describes how to use the FlexGate TCP/IP V2.0 Stack. The first part is a little tutorial
for the included examples (a small webserver with dynamic data and a simple Send-Mail client). The
second part is a reference of the available functions.

Using the FlexGate TCP/IP-Stack is very easy. For a simple webserver you will require only very little
knowledge about the underlying hard- and software. Because the software is highly scalable, it will run
on many 8051 cores, the only requirements are a minimum of about 8-16 kB memory for code storage
and about 512 Bytes or more of XRAM (external or on-chip). For a webserver (that must be able to
maintain several connections simultaneously, about 1kB of XRAM is a good starting point).

The text is not intended as a brief introduction to the Internet protocol and its mechanisms. And it will
not give a detailed explanation of HTML. Many good books are available about these topics (see
'Literature' at the end of the document. A very good book about the protocols is the "TCP/IP Illustrated
Volume 1".

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

To learn more about the required uC/51 compiler and its related tools, please read the "uC/51 User's
Manual" (included in the uC/51 distribution) first.

Please note: Additional documentation about the FlexGate modules and the FlexGate TCP/IP-Stack
will be available soon: Currently several authors are preparing books. Some will be available in
English and/or German. If you subscribe to our newsletter, we will keep you informed! We are always
interested in user projects. If you have realised any interesting projects, do not hesitate to contact us!

The TCP/IP-Stack was originally developed on a FlexGate I module (picture above). The FlexGate I
has the advantage, that software can be downloaded either to XRAM (32 kB available) or into the
512kB Flash. So it is very convenient as a development platform (as well as for mass production). The
FlexGate I is based on a C515 CPU (from Infineon). It contains several (mostly bi-directional)
additional Ports (P0 - P6), a fast 8-10 bit A/D-converter, ...

The FlexGate I is also software compatible to our other boards MINI535 (and the older Flash_M1,

The Ethernet driver is currently available for three platforms, depending on an external macro
definition from the project's make file.

{ The FlexGate I - as described: The ideal development platform, requires the definition
'FLEXGATE' ('-dFLEXGATE' in the MAKE-File).

{ The FlexGate II (or ElmFlex) as published by Elektor magazine in the 7/8 issue 2004: A
MSC1210 CPU with seperate LAN board (you can find more infos (and schematics) about this
board in the directory '...\src\msc1210\elmet.pdf'.

The MSC1210 is a High-Speed 8051 core (4 cycles/Inst.) from Texas Instruments. It offers a
high resolution 24 bit 8-channel A/D converter, a ultra-stable voltage-reference and 1kB of
on-chip XRAM und up to 32kB of Flash memory. This is the ideal platform for Internet based
measurement systems. The ElmFlex requires the definition 'ELMET' ('-dELMET' in the

Please note: there is an additional application note available from Texas Instruments
(, SBAA114).

{ The FlexGate III (or ED2Flex): A low-cost board, based on the ATMEL AT89C51ED2 CPU
with 64 kB on-chip-flash and 1.7 kB XRAM. This board is a two chip minimal solution with an
optional LCD. The ED2 runs with 6 cycles/Inst. Software to this board can be downloaded
over its RS232 port, by using ATMEL's FLIP-software. More details can be found in the
directory '..\src\ed2\', which will be included since the V1.20.02 distribution of the uC/51.
Requires the definition 'ED2FLEX' ('-dED2FLEX' in the MAKE-File).

Quick tutorial: A webserver

This tutorial assumes, that you have a ready-to-run assembled FlexGate I, mounted on the
Starter-Kit-Carrier board, as described in the '...\src\flexgate\src\flexgate_hw.pdf'. For other FlexGate
modules the steps are similar.

Please note: The FlexGate I is able to run most of the other demos that come with the uC/51 compiler
and do not require Ethernet or LAN!

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

1. Connect LAN, RS232 (if possible use COM1, else any other COM) and power (7.5-9V). The LAN
cable must be connected to an Ethernet Hub, which is capable of running 10 MBit or 100/10 MBit.

2. Now the RED LED on the FlexGate module will blink: first fast, then a little bit slower.

3. Press the RESET button on the Carrier board as a test, this will repeat the blinking sequence.

4. Now start 'MakeWiz' and open the MAKE File '...\src\flexgate\fg1_http.mak'. The most convenient
way is to use the new JFE Editor. For this a Workspace File must be generated: To enable the
"Save-Button" any (unimportant) change must be made, like inserting a space character in the
'Project Remarks'. Now check the 'Write JFE-Workspace File' box and press "Save Changes". You
can see the required definition of the Macro "FLEXGATE" in the C-Compiler tab.
Because the C515 exists in different versions (but the only important difference is the
A/D-converter), the second definition defines the CPU version. Currently 'AD_C515' and
'ADC515C' are supported. For more details refer to the source code of the A/D-driver in
'...\src\c515\ad535.c'. The CPU type can also be found on the label of the bag the FlexGate module
was shipped in. If a wrong CPU is selected, the software will run anyway, but measure incorrect

5. Now the JFE should be started, open the newly written Workspace.

6. For correct setup each node in an Ethernet, running TCP/IP must have a unique IP address (often
just called 'IP', do not mess with the 'IP' that stands for 'Internet-Protocol'). Larger systems (like
PCs) often get them dynamically from network routers. This was omitted for the FlexGate
TCP/IP-Stack. Here the user must select the IP manually, the preset is Internally
IPs are 32bit numbers. A macro named 'COMPOSE_IP' helps in converting the human readable
format to a 32 bit number. The own IP is stored in a variable called 'my_ip'. It must be initialised
first. Then the 'Init_net()' must be called to initialise the TCP/IP subsystem.

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

Please note: Any node in an Ethernet must have a different IP (=logical address) and a different MAC
(= physical address). For the FlexGate TCP/IP-Stack the MAC is dynamically generated out of the IP.

1. Then the project can be compiled with the MAKE-Button. Although the demo version normally
does only allow 8 kB of code, the uC/51 will encrypt files that contain more code or allow larger
code sizes under special conditions. Encrypted files can only be used on boards from us, like the
FlexGate I.

For the FlexGate I this means: You can write programs up to 32kB for download into
XRAM, and up to 64kB for download into Flash.

If the uC/51 compiler detects, that the target system is a FlexGate II (with the MSC1210
CPU) it will automatically allow up to 16 kB code, for download with the original
downloader from Texas Instruments.

2. Now press 'DL.BAT'. This batchfile (which is already included in the uC/51 distribution) will start
the 'FlashMon' and transfer the generated 'FG1_HTTP.BIN' into the Flexgate's RAM. The used
COM-port is taken from 'FlashMon's INI-File. To start the webserver, press <F9> (the 'Shoe'). The
'FlashMon must display the uper half (down to '*** MINI WEBSERVER ***') of the following

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

3. Now the YELLOW LED ('Link') on the FlexGate I should be lit, and (if the connected
Ethernet-Hub supports this) another LED on the Hub will be lit. This shows, that the FlexGate is
now physically connected to the Ethernet. The RED LED should continue blinking.

4. As a very first connection test, try to send a 'PING' to the FlexGate I. 'PING' is one of the standard
Internet protocols. It does nothing else than sending some data, which must be echoed by the
receiver: Open a command window and type:

ping (or whatever your selected IP is).

The result should look like:

reply from bytes=32 time=3ms TTL=64

reply from bytes=32 time=2ms TTL=64
reply from bytes=32 time=3ms TTL=64
reply from bytes=32 time=4ms TTL=64
4 packets sent, 0 lost, average time 3ms

After each sent 'PING' request the GREEN LED ('Activity') on the Flexgate I must flicker.

5. If everything was ok, you could now try to access the FlexGate I with your standard Internet
browser. Start your browser and enter as URL:

6. Now you should be able to retrieve the HTML-pages from the FlexGate! In the upper image
('FlashMon') the 'Form Demo' was requested and 'SENT' was pressed:

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

The form.... ... and the result.

7. Congratulations! Your FlexGate I webserver is running!

8. As you might have already recognised: The reply was generated dynamically from the FlexGate
TCP/IP-Stack (the passed information was displayed in the FlashMon image).

But most of the time, the FlexGate can act like a "regular microcontroller":
- controlling or measuring something
- serving as a RS485<->Internet-Gateway
- etc...

9. Currently the downloaded binary was transfered into XRAM. To transfer a binary file into the
(nonvolatile) Flash, select $0000 as code start and $8000 as XRAM start (with 'MakeWiz' in the
MAKE-File). To download, use the menu item 'Toolbox' in Flashmon. Please note, that a Flash can
only be cleared in whole 64kB Blocks.

10. A closer look at the source code will follow later.

Hint: You don't have to exit the FlashMon after the binaries have been recompiled! The FlashMon will
automatically recognise any new version and will ask, if it should be downloaded:

Other projects
There is another project included as a demo for the FlexGate I. It is a simple SMTP client. SMTP is a
standard protocol to send e-mails: '...\src\flexgate\fg1_smtp.mak'. The process of sending the mail itself
is quite simple. The most difficult thing is the login procedure. Most Internet-Service-Providers use the
SMTP-AUTH login. This system requires the transmission of a 'BASE64' coded password. We will add
other demos soon, as well as a more flexible e-mail demo.

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

The included sourcecodes access a predefined mailbox and receiver (=

Please change the settings in the sourcecodes to an own mailbox, before using it!

NET.H - Setting up the FlexGate TCP/IP-Stack's options

Whereas the webserver was a simple server, that only sends 'replies' on 'requests', the SMTP
additionally requires the ability for 'active opening' a connection. To keep the generated code size
small, the file 'NET.H' contains several switches and Settings. If you have multiple projects, that use the
FlexGate TCP/IP-Stack in different settings, it could be a good idea to copy the required contents from
'...\src\flexgate\tcpip' to a local directory, or, if code and memory size is not crucial, select the maximum
options in 'NET.H'

The stack is completely located in '..\SRC\FLEXGATE\TCPIP\*.*'. The only file that must be regarded
is 'NET.H': this file contains definitions for scaling the stack. This is the only part of the file, that is
intended for user changes:

* OPTION DEFs for this Stack (Change for your needs)

//#define DEBUG_REC // if defined: Record Send/received Frames

//#define USE_UDP // If defined: UDP-Support added
//#define USE_TCP_CLIENT // If defined: TCP-Client (Active open, Active ARP)

// RX-Buffer (only one)

#define MAX_RX 100 // May be up to 1400-1500 Bytes, use at least 100 Bytes

// TX-Buffers (>=1)
#define MAX_TX 100 // Transmition Buffer Size, may be up to 1400-1500 Bytes

// No. of sockets (should be >= TX_BUFFERS, 1-8 recom.)

#define MAX_SOCK 4 // Maximum No. of Sockets
#define TX_BUFFERS 4 // Recommended: 3 to 3*MAX_SOCK

{ The first option ('DEBUG_REC') keeps a list of the transmitted and received data. This is only
for debugging and maintenance. If interested: read the comment in 'NET.C'.

{ The option 'USE_UDP' will add the UDP-Protocol to the stack. UDP is a non-connection
based mechanism to transmit single packages of data at a high speed. There is (in conjunction
to TCP) no guarantee, that a UDP package has or will receive the addressee. On the other side,
if offers the ability of broadcast transmissions, that will be received by each node in the

One application, where broadcast UDP could be used, might be a time server: One node in the
network, which has a precise clock, will send periodically (like once each minute) 'his' time, so
that all other could synchronise themselves. If a client misses a packet, it will surely get one of
the next.

Another - more complex - application could be a DMX512 transmission system: DMX512 is a

protocol used for lighting application (theatre, disco, studio, ...). DMX512 consists of a stream
of blocks of 512 bytes size. Each of the 512 bytes represents one (possible) channel, which can
have any value between 0 (== 0%) and 255 (==100%). Up to 40 of these blocks are transferred
in one second, so if a byte within a block gets corrupt, probably a correct value will arrive only
a few msec. later.

Ethernet could be an ideal transportation medium for DMX512, because the DMX512 sender
is mostly a PC, modern switching hubs will keep the network traffic low and Ethernet
infrastructure (like wireless IEE802 bridges, routers, cheap cables, ...) could be used.... But this

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

is just an idea...

{ The last option 'USE_TCP_CLIENT' might be the most interesting: A TCP-connection could
be established in two modes:

- Passive mode (or Server mode): A client must initiate the opening sequence. Like for a
webserver, the connection is initiated by the browser.

- Active mode (or Client (and Server) mode): This allows initiating the opening sequence from
both sides. Like for an E-Mail client, which must be able to initiate a TCP-connection with
the E-Mail server. The Active mode will produce slightly more code (abt. 0.8-1kB).

Important: the Active mode requires to additional IP addresses:

- the 'subnet_ip': this is a mask, that is required to decide, if a given IP is from within the
local Ethernet, or if it is from 'outside'. This is done by an logical XOR of 'my_ip' and the
remote IP. The result is ANDed with the 'subnet_ip'. If the result is not zero, the destination is
'outside'. In that case all data must be sent to the 'gateway_ip':

- the 'gateway_ip': This is the router's IP. A router connects the local Ethernet with the 'far'

For a simple webserver non of the first three options is required!

To keep the required RAM ('movx' accessible) low, only a small number of buffers is available.
'MAX_SOCK' defines the maximum number of simultaneous active TCP/IP connections. The FlexGate
webserver forces an immediate closing after a a page is transmitted, so 4 sockets is more than enough.
If only a single connection at one time is required, set t'MAX_SOCK' to 1.

If you have a large RAM (like on the FlexGate I module), you may set the buffer size ('MAX_RX' and
'MAX_TX') to larger values. But with the shown options, 1kB of RAM will be sufficient.

The number of 'TX_BUFFERS' is often a compromise. Ideal would be to set 'TX_BUFFERS' to

'MAX_SOCK * 3'. But often RAM is rare, so we recommend to choose a value between 'MAX_SOCK'
and 'MAX_SOCK * 3'.

It should be regarded, that embedded graphics in HTML code may require more than one socket, even
if only one page is generated. It should also be mentioned, that the small RAM of the CS8900A can
only buffer a small number of Ethernet data frames. Although TCP's retransmission mechanisms will
catch this, it will increase the overall transmission time of a page.

A closer look at dynamic HTML

As you might have recognised, the webserver project includes HTML-templates. You can open these
files (like the 'FORM.HTML') directly with a standard browser. We recommend to maintain your
HTML-templates with a text based HTML-Editor. There are many available across the Internet.
Generating HTML-templates with a WYSIWYG-Editor is not recommended, because these tools
usually include a lot of (unwanted) overhead... But try your own!

Generating dynamic HTML pages

Generating dynamic HTML pages is the most important feature of an embedded webserver. Because
the FlexGate TCP/IP stack comes with its own ANSI C Compiler, it offers a very unique feature: C
Variables can be included in HTML code by name. This is an example of a very simple HTML page:
<title>Dynamic HTML</title>

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

Hello @adr. @name!<br><br>

The tag for dynamic variables is the '@'. Hence 'adr' and 'name' are C variables (strings). They could be
defined in the corresponding C file as:

char adr[5]; // will be automatically located in xdata

char name[50]; // and must be a global variable!

If the FlexGate webserver driver encounters a tagged variable, it will simply include the variable's
content in the generated HTML code. If 'adr[]' might equal "Mr" and 'name[]' is "Wickenhaeuser", the
HTML will be "Hello Mr. Wickenhaeuser".

There is no other limit in the number of available variables, than the CPU's RAM ('movx' accessible). It
is important, that the reserved space for the variable must be large enough and that the terminating '\0'
byte of a C string counts 1 byte. Like 'adr[]' must not hold longer strings than 'Mrs.' as an example.

The contents of the strings can be altered or assigned with all standard C functions like 'sprintf()' or
'strcpy()'. The application is responsible for setting up the required variables.

This document will not go into any deeper description of HTML, many good and easy-to-read books
are available in almost every bookshop. Because the tagged C variables will appear as pure text, if
opened in 'raw' state with a standard Webbrowser, developing HTML pages for the FlexGate TCP/IP
Stack is very easy.

Hint: It is even possible to include advanced features like Java-Script or 'URL-attached' session
management (like possible in PHP, which is another Internet scripting language).

Hint: It is no problem to include even Java-Script in FlexGate HTML-pages. With this nice effects or
pre-processing is possible!

As mentioned before, it is possible to include graphics (GIF and JPEG) in FlexGate dynamic pages:

<img src="logo.gif">

or as a dynamic version:
<img src=@dyn_graf>

Hint: moving graphics to other webservers will save a lot of (precious) memory. In this case a
reference to a graphics would look like '<img src="">'.

Receiving input
The FlexGate webserver supports 'URL-attached' argument passing, which is equal to the
'GET'-method used in HTML forms. As mentioned, the HTML related background about forms can be
found in any good HTML book.

The webserver supports only variables name 'a1' to 'a255' or 'A1' to 'A255'. A webserver's functions will
retrieve the number of such an argument or zero, another function will retrieve a pointer to the
argument's value. By looking into the example sourcecodes, the mechanism will become obvious.

If a URL request is too long (longer than 'MAX_RX' from 'NET.H', the webserver will ignore the
request to prevent a buffer overflow.

WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

The 'main()'-function
The 'main()'-function is located in '...\src\flexgate\fg1_http.c'.

'my_ip' is the stack's variable that is holding the local IP. After the function 'init_net()' has been called,
the sockets that can be used for HTML must be initialised (some sockets may be reserved for other type
of connections, like E-Mail, Telnet, UDP; a closer description will be published in the additional

// Enable ALL (or less) Sockets as General Server HTTP at port 80


'MAX_SOCK' is defined in 'NET.H' (see previous paragraph), 'SOCKET_SETUP' is a macro from

'NET.H'. It should be mentioned, that the FlexGate TCP/IP Stack monitors all sockets for time outs:
dead or stalled connections will be released after a certain time.

Now the program will stay in an endless loop, that must periodically call the function

If nothing has happened, 'poll_webserver()' will return 0. In any other cases, the result (or 'event') will
contain a code in its highbyte and (optionally) the number of the socket in its lowbyte. There are much
more events than required for a webserver. Here only two events are needed:


The last one appears about twice a second and will do nothing than toggle the RED LED. The other
event shows, that a HTML page was requested. If this event is not processed, a default page containing
the text "Page not found" will be sent. In this application at first the name of the requested page is

Because there are only a few pages on the webserver, only the first letter is used for distinction, what is
a convenient and fast way. Each page might require filling out some variables...

In the demo there is only one page that may get input: 'reply.html' (called from 'form.html' if 'SUBMIT'
was pressed). A simple loop scans the arguments, until no more arguments are found. Arguments 'A1' to
'A3' hold the variables. This is the requested URL:

It is important, that URL arguments that are copied to C variables never exceed the reserved space. It
should never be only relied to any size limits in the corresponding HTML forms! Functions like
'strlen()' could be used for verification.

User Tasks
In this demo application no user task is required. But in most cases the webserver is not the primary
task of the application.

In cases where an additional user task is required, some things should be noted:

{ Only if 'poll_webserver()' returns 0 the user task should be called.

{ The user task should be kept as short as possible. Although the CS8900A has some on chip
RAM, it will buffer only a certain number of Ethernet frames. As a raw recommendation, the
user task should not run longer than 10-100 msec.
{ Often it is possible (and also technically more elegant) to use a software state machine for more
complex user tasks, that splits an algorithm into small pieces.

- 10 -
WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

FlexGate TCP/IP-Stack Reference

This paragraph will show all functions/data that might be important for the user. All sourcecodes,
(except the 'User's application') is located in '...\src\flexgate\tcpip'.

The layer model

User's application
NETUTIL.C - Toolbox
(CRC, fast Copy, ...)

BASE64.C (optional)

WEB_SERV.C - Webserver
= Call
NET.C - TCP/IP/ICMP poll_net()

CS8900.C - Ethernet-driver


The basic access to the (physical) network is encapsulated in 'CS8900.C'.

'NET.C' will handle all Internet-Protocol related actions. If applicable, it passes an 'EVENT_xxx' to the
calling layer (a list of all event definitions ('EVENT_xxx') is in 'NET.H'). So the calling layer might
receive much more events than required. They can be ignored safely. To retrieve events, periodically
the function 'poll_net()' must be called.

The 'WEB_SERV.C' retrieves its events from 'NET.C' (by calling 'poll_net()'). It filters out all
Webserver based events (this means all TCP-events for Port 80). If a HTML-page was requested, an
'EVENT_HTTP_REQEST' is generated and the User's application may:
1. Retrieve the page's name and optional arguments

2. Initialise dynamic data for the reply

3. Tell 'WEB_SERV.C' the name of the HTML-template for the reply

All other work (generating the page, transferring it to the receiver, manage optional retransmission,
timeouts, dead connections, closing the connection) is done by 'WEB_SERV.C' in the background later.

The User's application must periodically call 'poll_webserver()'. Of course, if a webserver must not be
implemented for the application, the User must directly call 'poll_net()' instead.

The 'BASE64.C' module is optionally needed. It is not required for a pure Webserver, but the login
procedure ('AUTH-LOGIN') for 'SMTP' (for sending e-mail) and the transmission of e-mail
attachments will require BASE64-coding. For details refer to RFC2045.

'NETUTIL.C' includes some necessary toolbox-functions (like fast XRAM-to-XRAM-copy, CRC

processing, ...).

- 11 -
WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

Function reference
Only information and functions that might be used externally are listed. For details refer to the
sourcecodes directly.

The webserver is an optional layer on top of 'NET.C'. It filters all TCP-connections with destination
port 80 (what is the standard for HTTP access). This is done by the function 'poll_webserver()' that
must be called periodically, and that calls 'poll_net()'. Unhandled events are passed to the called. For
HTTP-requests, an 'EVENT_HTTP_REQUEST' is generated, as stated previously.

uint poll_webserver(void);

Will give 0 or an 'EVENT_xx'. For 'EVENT_HTTP_REQUEST' the socket is coded in the low-byte.

xdata uchar * webpage_name(void);

Will retrieve a pointer to the requested URL ('\0' terminated). As a recommendation: using pages with
different first letter is the most easy way.

uchar url_getarg_no(void);

A function to scan the URL for arguments. The arguments must have the name 'a1' to 'a255' or 'A1' to
'A255'. All other arguments wil return 0, else the number or the argument is returned.

xdata uchar *url_getarg_str(void);

For any valid argument, this function returns the value string. It is allowed to use an empty string as an

void webpage_bind(uchar sock, code unsigned char *pd);

Sets the reply to the HTTP-request to a HTML-template, stored in code memory. Else a page
containigng the text "page not found" will be generated.


The BASE64 coding is required for e-mail applications and e-mail (SMTP-AUTH) login: E-mails are
normally treated as text during transmission. To omit conflicts for binary data (attachments) and to hide
the transmitted password, these are BASE64 coded. The system is easy: 3 binary bytes (24 bits) are
mapped to 4 digits (each containing 6 bits of information). Hence that is the name (2^6 equals 64).

If an input has characters left (like 1 or 2 characters), the result is padded with special chars.

xdata uchar* b64_code(uchar* src, xdata uchar *dst, uchar len)

This function converts a (far) string in its BASE64 pendant (without '\0' terminator). Source may be in
any 8051 memory, the result string must be in XDATA.

{ Definition of all required IPs (depending on the Options in 'NET.H')
{ Definition of the 'Sockets' (one socket per (simultaneous open) TCP/UDP connection)
{ Definitions of other global variables ('rx_len', ...)
{ Definition of the 'EVENT_xxx'

- 12 -
WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

{ Macros for 'COMPOSE_IP' and 'SOCKET_SETUP'

{ Debug functions

void send_request_ARP(unsigned long ipl);

This function sends an 'ARP' request. ARP is used to get the MAC for a given IP. This function is
indirectly needed for active opening a TCP/IP connection, The parameter 'ipl' can be passed as the 'long
int' part from an IP, made with 'COMPOSE_IP'. The global 'remote_ip' could be used as an temporary
parameter. The result (if any arrived) will appear as a 'EVENT_ARP_xxx'.

void send_udp(xdata char* , uint len,xdata MAC *pmac,unsigned long

rem_ipl,uint sport, uint dport);

To send an UDP-packet (USE_UDP must be enabled in 'NET.H'), a pointer to the Data, size of the
packet, the receiver's MAC (use FF FF FF FF FF for broadcast), source and destination port are
passed. Please note: UDP-Sockets can be opened only for receiving data. Because sending UDP
requires no external context, the data are sent directly (from XRAM). There is no buffer that must be

xdata uchar* allocate_tx_buf(void);

Prior to sending TCP data, a buffer must be allocated. All buffer are in XRAM of size 'MAX_TX'. If no
buffer is available, 0 is returned.

uint send_socket_tcp(uchar sock, xdata uchar* pbuf, uint datalen);

This function sends a packet of TCP-data for a given socket. the socket must be open and initialised.
The function will return immediatelly. The result is 0 for success or an 'EVENT_xxx' in case of an
error. It should be checked if a sending is allowed by a call to 'notready_socket_tcp()' first.

uint notready_socket_tcp(uchar sock, uchar flag);

Each socket buffers the data to sent. There are two situations: 1.) There are already some data under
transmission, but still more data could be added, 2.) All data are sent and have been acknowledged by
the receiver. No more pending transmission. The 'flag' differentiates these conditions: for 1.) use
'RDY_4_TX', for 2.) use 'RDY_4_CLOSE'. If the condition asserts, the result is 0.

uint stringsend_socket_tcp(uchar sock, far char* pdata);

A string can be located in any of the 8051 memory spaces (Code, XRAM, IRAM, DRAM). Because a
string is always terminated by a '\0', the length is not required. Also no allocation of a buffer is
required. If the socket is not ready the function will simply return an 'EVENT_xxx', success returns a 0.

uint close_socket_tcp(uchar sock);

For an active closure of an open socket. Check prior to closing, if the socket is ready by
'notready_socket_tcp(sock,RDY_4_CLOSE)', else the closing will fail (result 0 on success). Please
note that the FlexGate TCP/IP-Stack will close dead connections or fully transmitted HTMP-pages
automatically, also the receiver could close a socket, what would result in an 'EVENT_xxx'.

uint open_socket_tcp(uchar sock,unsigned long remote_ipl,

unsigned int remote_port);

Active opening of a socket requires the option 'USE_TCP_CLIENT' in 'NET.H' set!

Opening a socket is a 3-step process: 1.) The socket data must be initialised (select the socket type
('SOCKET_TCP') a local port (any from 1..65535), set socket flags to 'FLAG_ACTIVE_OPEN'). This
is best done with the macro 'SOCEKT_SETUP'. 2.) The remote IP must be defined. For this the macro

- 13 -
WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

'COMPOSE_IP' with 'remote_ip' as a temporary might be used. 3.) Now 'open_socket_tcp()' might be
called. For success it will return 0.

As a good starting point the demo '...\src\flexgate\fg1_smtp.c' can be used. Because there are many
possibilities that could close a socket, it is easier to monitor the socket's internal state
('uc_socket[].state') for the state 'TCP_CLOSED' (== 0), than to catch all 'EVENT_xxx'.

If the connection is established, the poll-functions ('poll_net()' or 'poll_webersver'()' will return an

'EVENT_TCP_DATARECEIVED'. with a size of 0 (found in 'rcv_len') or more.

uint poll_net(void);

This function keeps the FlexGate TCP/IP-Stack alive. As already stated, it must be called periodically -
either directly by the user or implicit through the 'WEB_SERV.C'. If nothing has happened (as it will be
for most of the times) it will return 0. In all other cases an 'EVENT_xxx' will be the result. Some
TCP-related events have the socket number coded in the low-byte. All 'EVENT_xxx' are coded in the
high-byte. Most events can be ignored, only a few will normally be used:

{ EVENT_HTTP_REQUEST : 'WEB_SERV.C' Received a request for a HTML-page

{ EVENT_SOCKET_IDLETIMER : About twice a second...
{ EVENT_TCP_DATARECEIVED: TCP data received. Data ('rcv_len', in 'rcv_buf[]').
{ EVENT_UDP_DATARECEIVED: UDP data received. Data ('rcv_len', in 'rcv_buf[]').

Please note: the received data must be processed immediately, because the next call to 'poll_net()' could
overwrite it! For more information about the events, read the comments in 'NET.C/H'.

uchar Init_net(void);

This initialises the Flexgate TCP/IP-Stack. First the IP ('my_ip') is mapped to a unique MAC, then the
CS8900A is (re-)initialised and then a IRQ, that generated the 'EVENT_SOCKET_IDLETIMER'
with an additional software counter.

It is possible to change 'my_ip' and then to call 'Init_net()' again. The function will need about 0.2 sec.
On success 0 is returned.

Here several utility functions (like IP checksums) are included. There is only one, that might be used
for user applications:

void xram_fast_copy(xdata uchar* src,xdata uchar* dest,uint size);

This is a optimised functions to copy memory blocks (non overlaying!) in the XRAM.

This sourcecode is responsible for accessing the physical Ethernet. The user should not make any
changes. In this sourcecode the macro, that defines the board type is required for the correct access to
the CS8900A.

There is only one function, that might be useful:

void Led_8900(char ns)

Will determine the behaviour of the YELLOW LED: ns=0: always OFF, ns=1: always ON, else:
function as 'Link indicator' for the Ethernet.

- 14 -
WWW.WICKENHAEUSER.COM - ‘FlexGate TCP/IP Stack V2.0’ 10.05.2005

1. TCP/IP Illustrated Volume 1: The Protocols by W. Richard Stevens, Addison-Wesley, 1994. A
comprehensive description of the TCP/IP protocols

2. RFC791 Internet Protocol by J. Postel

RFC792 Internet Control Message Protocol by J. Postel
RFC793 Transmission Control Protocol by J. Postel

The RFC's ('Request for comments') describe the standards. Available form several Internet
locations (search for 'RFC79x').

3. TCP/IP Lean by J. Bentham, CMP Books, 2.nd Edition 2002

4. Building a Complete Webserver on the MSC121x Using FlexGateTM Technology (Application note
SBAA114, available for download from Texas Instruments,

- 15 -