]> begriffs open source - cmsis-freertos/blob - Demo/WizNET_DEMO_GCC_ARM7/TCP.c
Update cmsis_os2.c
[cmsis-freertos] / Demo / WizNET_DEMO_GCC_ARM7 / TCP.c
1 /*
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
3     All rights reserved
4
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
6
7     This file is part of the FreeRTOS distribution.
8
9     FreeRTOS is free software; you can redistribute it and/or modify it under
10     the terms of the GNU General Public License (version 2) as published by the
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
12
13     ***************************************************************************
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<
16     >>!   obliged to provide the source code for proprietary components     !<<
17     >>!   outside of the FreeRTOS kernel.                                   !<<
18     ***************************************************************************
19
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following
23     link: http://www.freertos.org/a00114.html
24
25     ***************************************************************************
26      *                                                                       *
27      *    FreeRTOS provides completely free yet professionally developed,    *
28      *    robust, strictly quality controlled, supported, and cross          *
29      *    platform software that is more than just the market leader, it     *
30      *    is the industry's de facto standard.                               *
31      *                                                                       *
32      *    Help yourself get started quickly while simultaneously helping     *
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *
34      *    tutorial book, reference manual, or both:                          *
35      *    http://www.FreeRTOS.org/Documentation                              *
36      *                                                                       *
37     ***************************************************************************
38
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
40     the FAQ page "My application does not run, what could be wrong?".  Have you
41     defined configASSERT()?
42
43     http://www.FreeRTOS.org/support - In return for receiving this top quality
44     embedded software for free we request you assist our global community by
45     participating in the support forum.
46
47     http://www.FreeRTOS.org/training - Investing in training allows your team to
48     be as productive as possible as early as possible.  Now you can receive
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
50     Ltd, and the world's leading authority on the world's leading RTOS.
51
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.
55
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
58
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
61     licenses offer ticketed support, indemnification and commercial middleware.
62
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety
64     engineered and independently SIL3 certified version for use in safety and
65     mission critical applications that require provable dependability.
66
67     1 tab == 4 spaces!
68 */
69
70 /*
71         Changes from V3.2.3
72         
73         + Modified char* types to compile without warning when using GCC V4.0.1.
74         + Corrected the address to which the MAC address is written.  Thanks to
75           Bill Knight for this correction.
76
77         Changes from V3.2.4
78
79         + Changed the default MAC address to something more realistic.
80
81 */
82
83 /* Standard includes. */
84 #include <stdlib.h>
85 #include <string.h>
86
87 /* Scheduler include files. */
88 #include "FreeRTOS.h"
89 #include "task.h"
90 #include "semphr.h"
91 #include "tcp.h"
92 #include "serial.h"
93
94 /* Application includes. */
95 #include "i2c.h"
96 #include "html_pages.h"
97
98 /*-----------------------------------------------------------*/
99
100 /* Hardwired i2c address of the WIZNet device. */
101 #define tcpDEVICE_ADDRESS                               ( ( unsigned char ) 0x00 )
102
103 /* Constants used to configure the Tx and Rx buffer sizes within the WIZnet
104 device. */
105 #define tcp8K_RX                                                ( ( unsigned char ) 0x03 )
106 #define tcp8K_TX                                                ( ( unsigned char ) 0x03 )
107
108 /* Constants used to generate the WIZnet internal buffer addresses. */
109 #define tcpSINGLE_SOCKET_ADDR_MASK              ( ( unsigned long ) 0x1fff )
110 #define tcpSINGLE_SOCKET_ADDR_OFFSET    ( ( unsigned long ) 0x4000 )
111
112 /* Bit definitions of the commands that can be sent to the command register. */
113 #define tcpRESET_CMD                                    ( ( unsigned char ) 0x80 )
114 #define tcpSYS_INIT_CMD                                 ( ( unsigned char ) 0x01 )
115 #define tcpSOCK_STREAM                                  ( ( unsigned char ) 0x01 )
116 #define tcpSOCK_INIT                                    ( ( unsigned char ) 0x02 )
117 #define tcpLISTEN_CMD                                   ( ( unsigned char ) 0x08 )
118 #define tcpRECEIVE_CMD                                  ( ( unsigned char ) 0x40 )
119 #define tcpDISCONNECT_CMD                               ( ( unsigned char ) 0x10 )
120 #define tcpSEND_CMD                                             ( ( unsigned char ) 0x20 )
121
122 /* Constants required to handle the interrupts. */
123 #define tcpCLEAR_EINT0                                  ( 1 )
124 #define i2cCLEAR_ALL_INTERRUPTS                 ( ( unsigned char ) 0xff )
125 #define i2cCHANNEL_0_ISR_ENABLE                 ( ( unsigned char ) 0x01 )
126 #define i2cCHANNEL_0_ISR_DISABLE                ( ( unsigned char ) 0x00 )
127 #define tcpWAKE_ON_EINT0                                ( 1 )
128 #define tcpENABLE_EINT0_FUNCTION                ( ( unsigned long ) 0x01 )
129 #define tcpEINT0_VIC_CHANNEL_BIT                ( ( unsigned long ) 0x4000 )
130 #define tcpEINT0_VIC_CHANNEL                    ( ( unsigned long ) 14 )
131 #define tcpEINT0_VIC_ENABLE                             ( ( unsigned long ) 0x0020 )
132
133 /* Various delays used in the driver. */
134 #define tcpRESET_DELAY                                  ( ( TickType_t ) 16 / portTICK_PERIOD_MS )
135 #define tcpINIT_DELAY                                   ( ( TickType_t ) 500 / portTICK_PERIOD_MS  )
136 #define tcpLONG_DELAY                                   ( ( TickType_t ) 500 / portTICK_PERIOD_MS  )
137 #define tcpSHORT_DELAY                                  ( ( TickType_t ) 5 / portTICK_PERIOD_MS )
138 #define tcpCONNECTION_WAIT_DELAY                ( ( TickType_t ) 100 / portTICK_PERIOD_MS )
139 #define tcpNO_DELAY                                             ( ( TickType_t ) 0 )
140
141 /* Length of the data to read for various register reads. */
142 #define tcpSTATUS_READ_LEN                              ( ( unsigned long ) 1 )
143 #define tcpSHADOW_READ_LEN                              ( ( unsigned long ) 1 )
144         
145 /* Register addresses within the WIZnet device. */
146 #define tcpCOMMAND_REG                                  ( ( unsigned short ) 0x0000 )
147 #define tcpGATEWAY_ADDR_REG                             ( ( unsigned short ) 0x0080 )
148 #define tcpSUBNET_MASK_REG                              ( ( unsigned short ) 0x0084 )
149 #define tcpSOURCE_HA_REG                                ( ( unsigned short ) 0x0088 )
150 #define tpcSOURCE_IP_REG                                ( ( unsigned short ) 0x008E )
151 #define tpcSOCKET_OPT_REG                               ( ( unsigned short ) 0x00A1 )
152 #define tcpSOURCE_PORT_REG                              ( ( unsigned short ) 0x00AE )
153 #define tcpTX_WRITE_POINTER_REG                 ( ( unsigned short ) 0x0040 )
154 #define tcpTX_READ_POINTER_REG                  ( ( unsigned short ) 0x0044 )
155 #define tcpTX_ACK_POINTER_REG                   ( ( unsigned short ) 0x0018 )
156 #define tcpTX_MEM_SIZE_REG                              ( ( unsigned short ) 0x0096 )
157 #define tcpRX_MEM_SIZE_REG                              ( ( unsigned short ) 0x0095 )
158 #define tcpINTERRUPT_STATUS_REG                 ( ( unsigned short ) 0x0004 )
159 #define tcpTX_WRITE_SHADOW_REG                  ( ( unsigned short ) 0x01F0 )
160 #define tcpTX_ACK_SHADOW_REG                    ( ( unsigned short ) 0x01E2 )
161 #define tcpISR_MASK_REG                                 ( ( unsigned short ) 0x0009 )
162 #define tcpINTERRUPT_REG                                ( ( unsigned short ) 0x0008 )
163 #define tcpSOCKET_STATE_REG                             ( ( unsigned short ) 0x00a0 )
164
165 /* Constants required for hardware setup. */
166 #define tcpRESET_ACTIVE_LOW                     ( ( unsigned long ) 0x20 )
167 #define tcpRESET_ACTIVE_HIGH                    ( ( unsigned long ) 0x10 )
168
169 /* Constants defining the source of the WIZnet ISR. */
170 #define tcpISR_SYS_INIT                                 ( ( unsigned char ) 0x01 )
171 #define tcpISR_SOCKET_INIT                              ( ( unsigned char ) 0x02 )
172 #define tcpISR_ESTABLISHED                              ( ( unsigned char ) 0x04 )
173 #define tcpISR_CLOSED                                   ( ( unsigned char ) 0x08 )
174 #define tcpISR_TIMEOUT                                  ( ( unsigned char ) 0x10 )
175 #define tcpISR_TX_COMPLETE                              ( ( unsigned char ) 0x20 )
176 #define tcpISR_RX_COMPLETE                              ( ( unsigned char ) 0x40 )
177
178 /* Constants defining the socket status bits. */
179 #define tcpSTATUS_ESTABLISHED                   ( ( unsigned char ) 0x06 )
180 #define tcpSTATUS_LISTEN                                ( ( unsigned char ) 0x02 )
181
182 /* Misc constants. */
183 #define tcpNO_STATUS_BITS                               ( ( unsigned char ) 0x00 )
184 #define i2cNO_ADDR_REQUIRED                             ( ( unsigned short ) 0x0000 )
185 #define i2cNO_DATA_REQUIRED                             ( 0x0000 )
186 #define tcpISR_QUEUE_LENGTH                             ( ( unsigned portBASE_TYPE ) 10 )
187 #define tcpISR_QUEUE_ITEM_SIZE                  ( ( unsigned portBASE_TYPE ) 0 )
188 #define tcpBUFFER_LEN                                   ( 4 * 1024 )
189 #define tcpMAX_REGISTER_LEN                             ( 4 )
190 #define tcpMAX_ATTEMPTS_TO_CHECK_BUFFER ( 6 )
191 #define tcpMAX_NON_LISTEN_STAUS_READS   ( 5 )
192
193 /* Message definitions.  The IP address, MAC address, gateway address, etc.
194 is set here! */
195 const unsigned char const ucDataGAR[]                           = { 172, 25, 218, 3 };  /* Gateway address. */
196 const unsigned char const ucDataMSR[]                           = { 255, 255, 255, 0 }; /* Subnet mask.         */
197 const unsigned char const ucDataSIPR[]                          = { 172, 25, 218, 201 };/* IP address.          */
198 const unsigned char const ucDataSHAR[]                          = { 00, 23, 30, 41, 15, 26 }; /* MAC address - DO NOT USE THIS ON A PUBLIC NETWORK! */
199
200 /* Other fixed messages. */
201 const unsigned char const ucDataReset[]                         = { tcpRESET_CMD }; 
202 const unsigned char const ucDataInit[]                          = { tcpSYS_INIT_CMD }; 
203 const unsigned char const ucDataProtocol[]                      = { tcpSOCK_STREAM };
204 const unsigned char const ucDataPort[]                          = { 0xBA, 0xCC };
205 const unsigned char const ucDataSockInit[]                      = { tcpSOCK_INIT };
206 const unsigned char const ucDataTxWritePointer[]        = { 0x11, 0x22, 0x00, 0x00 };
207 const unsigned char const ucDataTxAckPointer[]          = { 0x11, 0x22, 0x00, 0x00 };
208 const unsigned char const ucDataTxReadPointer[]         = { 0x11, 0x22, 0x00, 0x00 };
209 const unsigned char const ucDataListen[]                        = { tcpLISTEN_CMD };
210 const unsigned char const ucDataReceiveCmd[]            = { tcpRECEIVE_CMD };
211 const unsigned char const ucDataSetTxBufSize[]          = { tcp8K_TX };
212 const unsigned char const ucDataSetRxBufSize[]          = { tcp8K_RX };
213 const unsigned char const ucDataSend[]                          = { tcpSEND_CMD };
214 const unsigned char const ucDataDisconnect[]            = { tcpDISCONNECT_CMD };
215 const unsigned char const ucDataEnableISR[]                     = { i2cCHANNEL_0_ISR_ENABLE };
216 const unsigned char const ucDataDisableISR[]            = { i2cCHANNEL_0_ISR_DISABLE };
217 const unsigned char const ucDataClearInterrupt[]        = { i2cCLEAR_ALL_INTERRUPTS };
218
219 static SemaphoreHandle_t xMessageComplete = NULL;
220 QueueHandle_t xTCPISRQueue = NULL;
221
222 /* Dynamically generate and send an html page. */
223 static void prvSendSamplePage( void );
224
225 /* Read a register from the WIZnet device via the i2c interface. */
226 static void prvReadRegister( unsigned char *pucDestination, unsigned short usAddress, unsigned long ulLength );
227
228 /* Send the entire Tx buffer (the Tx buffer within the WIZnet device). */
229 static void prvFlushBuffer( unsigned long ulTxAddress );
230
231 /* Write a string to the WIZnet Tx buffer. */
232 static void prvWriteString( const char * const pucTxBuffer, long lTxLen, unsigned long *pulTxAddress );
233
234 /* Convert a number to a string. */
235 void ultoa( unsigned long ulVal, char *pcBuffer, long lIgnore );
236
237 /*-----------------------------------------------------------*/
238
239 void ultoa( unsigned long ulVal, char *pcBuffer, long lIgnore )
240 {
241 unsigned long lNibble;
242 long lIndex;
243
244         /* Simple routine to convert an unsigned long value into a string in hex 
245         format. */
246
247         /* For each nibble in the number we are converting. */
248         for( lIndex = 0; lIndex < ( sizeof( ulVal ) * 2 ); lIndex++ )
249         {
250                 /* Take the top four bits of the number. */
251                 lNibble = ( ulVal >> 28 );
252
253                 /* We are converting it to a hex string, so is the number in the range
254                 0-10 or A-F? */
255                 if( lNibble < 10 )
256                 {
257                         pcBuffer[ lIndex ] = '0' + lNibble;
258                 }
259                 else
260                 {
261                         lNibble -= 10;
262                         pcBuffer[ lIndex ] = 'A' + lNibble;
263                 }
264
265                 /* Shift off the top nibble so we use the next nibble next time around. */
266                 ulVal <<= 4;
267         }       
268
269         /* Mark the end of the string with a null terminator. */
270         pcBuffer[ lIndex ] = 0x00;
271 }
272 /*-----------------------------------------------------------*/
273
274 static void prvReadRegister( unsigned char *pucDestination, unsigned short usAddress, unsigned long ulLength )
275 {
276 unsigned char ucRxBuffer[ tcpMAX_REGISTER_LEN ];
277
278         /* Read a register value from the WIZnet device. */
279
280         /* First write out the address of the register we want to read. */
281         i2cMessage( ucRxBuffer, i2cNO_DATA_REQUIRED, tcpDEVICE_ADDRESS, usAddress, i2cWRITE, NULL, portMAX_DELAY );
282         
283         /* Then read back from that address. */
284         i2cMessage( ( unsigned char * ) pucDestination, ulLength, tcpDEVICE_ADDRESS, i2cNO_ADDR_REQUIRED, i2cREAD, xMessageComplete, portMAX_DELAY );
285
286         /* I2C messages are queued so use the semaphore to wait for the read to 
287         complete - otherwise we will leave this function before the I2C 
288         transactions have completed. */
289         xSemaphoreTake( xMessageComplete, tcpLONG_DELAY );
290 }
291 /*-----------------------------------------------------------*/
292
293 void vTCPHardReset( void )
294 {
295         /* Physical reset of the WIZnet device by using the GPIO lines to hold the 
296         WIZnet reset lines active for a few milliseconds. */
297
298         /* Make sure the interrupt from the WIZnet is disabled. */
299         VICIntEnClear |= tcpEINT0_VIC_CHANNEL_BIT;
300
301         /* If xMessageComplete is NULL then this is the first time that this 
302         function has been called and the queue and semaphore used in this file
303         have not yet been created. */
304         if( xMessageComplete == NULL )
305         {
306                 /* Create and obtain the semaphore used when we want to wait for an i2c
307                 message to be completed. */
308                 vSemaphoreCreateBinary( xMessageComplete );
309                 xSemaphoreTake( xMessageComplete, tcpNO_DELAY );
310
311                 /* Create the queue used to communicate between the WIZnet and TCP tasks. */
312                 xTCPISRQueue = xQueueCreate( tcpISR_QUEUE_LENGTH, tcpISR_QUEUE_ITEM_SIZE );
313         }
314
315         /* Use the GPIO to reset the network hardware. */
316         GPIO_IOCLR = tcpRESET_ACTIVE_LOW;
317         GPIO_IOSET = tcpRESET_ACTIVE_HIGH;
318
319         /* Delay with the network hardware in reset for a short while. */
320         vTaskDelay( tcpRESET_DELAY );
321
322         GPIO_IOCLR = tcpRESET_ACTIVE_HIGH;
323         GPIO_IOSET = tcpRESET_ACTIVE_LOW;
324
325         vTaskDelay( tcpINIT_DELAY );
326
327         /* Setup the EINT0 to interrupt on required events from the WIZnet device.
328         First enable the EINT0 function of the pin. */
329         PCB_PINSEL1 |= tcpENABLE_EINT0_FUNCTION;
330         
331         /* We want the TCP comms to wake us from power save. */
332         SCB_EXTWAKE = tcpWAKE_ON_EINT0;
333
334         /* Install the ISR into the VIC - but don't enable it yet! */
335         portENTER_CRITICAL();
336         {
337                 extern void ( vEINT0_ISR_Wrapper )( void );
338
339                 VICIntSelect &= ~( tcpEINT0_VIC_CHANNEL_BIT );
340                 VICVectAddr3 = ( long ) vEINT0_ISR_Wrapper;
341
342                 VICVectCntl3 = tcpEINT0_VIC_CHANNEL | tcpEINT0_VIC_ENABLE;
343         }
344         portEXIT_CRITICAL();
345
346         /* Enable interrupts in the WIZnet itself. */
347         i2cMessage( ucDataEnableISR, sizeof( ucDataEnableISR ), tcpDEVICE_ADDRESS, tcpISR_MASK_REG, i2cWRITE, NULL, portMAX_DELAY );
348
349         vTaskDelay( tcpLONG_DELAY );
350 }
351 /*-----------------------------------------------------------*/
352
353 long lTCPSoftReset( void )
354 {
355 unsigned char ucStatus;
356 extern volatile long lTransactionCompleted;
357
358         /* Send a message to the WIZnet device to tell it set all it's registers
359         back to their default states.  Then setup the WIZnet device as required. */
360
361         /* Reset the internal WIZnet registers. */
362         i2cMessage( ucDataReset,        sizeof( ucDataReset ),  tcpDEVICE_ADDRESS, tcpCOMMAND_REG, i2cWRITE, NULL, portMAX_DELAY );
363
364         /* Now we can configure the protocol.   Here the MAC address, gateway 
365         address, subnet mask and IP address are configured. */
366         i2cMessage( ucDataSHAR,         sizeof( ucDataSHAR ),   tcpDEVICE_ADDRESS, tcpSOURCE_HA_REG, i2cWRITE, NULL, portMAX_DELAY );
367         i2cMessage( ucDataGAR,          sizeof( ucDataGAR ),    tcpDEVICE_ADDRESS, tcpGATEWAY_ADDR_REG, i2cWRITE, NULL, portMAX_DELAY );
368         i2cMessage( ucDataMSR,          sizeof( ucDataMSR ),    tcpDEVICE_ADDRESS, tcpSUBNET_MASK_REG,  i2cWRITE, NULL, portMAX_DELAY );
369         i2cMessage( ucDataSIPR,         sizeof( ucDataSIPR ),   tcpDEVICE_ADDRESS, tpcSOURCE_IP_REG,    i2cWRITE, NULL, portMAX_DELAY );
370         
371         /* Next the memory buffers are configured to give all the WIZnet internal
372         memory over to a single socket.  This gives the socket the maximum internal
373         Tx and Rx buffer space. */
374         i2cMessage( ucDataSetTxBufSize, sizeof( ucDataSetTxBufSize ), tcpDEVICE_ADDRESS, tcpTX_MEM_SIZE_REG, i2cWRITE, NULL, portMAX_DELAY );
375         i2cMessage( ucDataSetRxBufSize, sizeof( ucDataSetRxBufSize ), tcpDEVICE_ADDRESS, tcpRX_MEM_SIZE_REG, i2cWRITE, NULL, portMAX_DELAY );
376
377         /* Send the sys init command so the above parameters take effect. */
378         i2cMessage( ucDataInit,         sizeof( ucDataInit ),   tcpDEVICE_ADDRESS, tcpCOMMAND_REG, i2cWRITE, NULL, portMAX_DELAY );
379
380         /* Seems to like a little wait here. */
381         vTaskDelay( tcpINIT_DELAY );
382
383         /* Read back the status to ensure the system initialised ok. */
384         prvReadRegister( &ucStatus, tcpINTERRUPT_STATUS_REG, tcpSTATUS_READ_LEN );
385
386         /* We should find that the sys init was successful. */
387         if( ucStatus != tcpISR_SYS_INIT )
388         {
389                 return ( long ) pdFAIL;
390         }
391
392         /* No i2c errors yet. */
393         portENTER_CRITICAL();
394                 lTransactionCompleted = pdTRUE;
395         portEXIT_CRITICAL();
396
397         return ( long ) pdPASS;
398 }
399 /*-----------------------------------------------------------*/
400
401 long lTCPCreateSocket( void )
402 {
403 unsigned char ucStatus;
404
405         /* Create and configure a socket. */
406
407         /* Setup and init the socket.  Here the port number is set and the socket
408         is initialised. */
409         i2cMessage( ucDataProtocol, sizeof( ucDataProtocol),tcpDEVICE_ADDRESS, tpcSOCKET_OPT_REG, i2cWRITE, NULL, portMAX_DELAY );
410         i2cMessage( ucDataPort,         sizeof( ucDataPort),    tcpDEVICE_ADDRESS, tcpSOURCE_PORT_REG, i2cWRITE, NULL, portMAX_DELAY );
411         i2cMessage( ucDataSockInit, sizeof( ucDataSockInit),tcpDEVICE_ADDRESS, tcpCOMMAND_REG, i2cWRITE, xMessageComplete, portMAX_DELAY );
412
413         /* Wait for the Init command to be sent. */
414         if( !xSemaphoreTake( xMessageComplete, tcpLONG_DELAY ) )
415         {
416                 /* For some reason the message was not transmitted within our block
417                 period. */
418                 return ( long ) pdFAIL;
419         }
420
421         /* Allow the socket to initialise. */
422         vTaskDelay( tcpINIT_DELAY );
423
424         /* Read back the status to ensure the socket initialised ok. */
425         prvReadRegister( &ucStatus, tcpINTERRUPT_STATUS_REG, tcpSTATUS_READ_LEN );
426         
427         /* We should find that the socket init was successful. */
428         if( ucStatus != tcpISR_SOCKET_INIT )
429         {
430                 return ( long ) pdFAIL;
431         }
432
433
434         /* Setup the Tx pointer registers to indicate that the Tx buffer is empty. */
435         i2cMessage( ucDataTxReadPointer, sizeof( ucDataTxReadPointer ), tcpDEVICE_ADDRESS, tcpTX_READ_POINTER_REG, i2cWRITE, NULL, portMAX_DELAY );
436         vTaskDelay( tcpSHORT_DELAY );
437         i2cMessage( ucDataTxWritePointer, sizeof( ucDataTxWritePointer ), tcpDEVICE_ADDRESS, tcpTX_WRITE_POINTER_REG, i2cWRITE, NULL, portMAX_DELAY );
438         vTaskDelay( tcpSHORT_DELAY );
439         i2cMessage( ucDataTxAckPointer,   sizeof( ucDataTxAckPointer ),   tcpDEVICE_ADDRESS, tcpTX_ACK_POINTER_REG, i2cWRITE, NULL, portMAX_DELAY );
440         vTaskDelay( tcpSHORT_DELAY );
441
442         return ( long ) pdPASS;
443 }
444 /*-----------------------------------------------------------*/
445
446 void vTCPListen( void )
447 {
448 unsigned char ucISR;
449
450         /* Start a passive listen on the socket. */
451
452         /* Enable interrupts in the WizNet device after ensuring none are 
453         currently pending. */
454         while( SCB_EXTINT & tcpCLEAR_EINT0 )
455         {
456                 /* The WIZnet device is still asserting and interrupt so tell it to 
457                 clear. */
458                 i2cMessage( ucDataClearInterrupt, sizeof( ucDataClearInterrupt ), tcpDEVICE_ADDRESS, tcpINTERRUPT_REG, i2cWRITE, xMessageComplete, portMAX_DELAY );
459                 xSemaphoreTake( xMessageComplete, tcpLONG_DELAY );
460
461                 vTaskDelay( 1 );
462                 SCB_EXTINT = tcpCLEAR_EINT0;
463         }
464
465         while( xQueueReceive( xTCPISRQueue, &ucISR, tcpNO_DELAY ) )
466         {
467                 /* Just clearing the queue used by the ISR routine to tell this task
468                 that the WIZnet device needs attention. */
469         }
470
471         /* Now all the pending interrupts have been cleared we can enable the 
472         processor interrupts. */
473         VICIntEnable |= tcpEINT0_VIC_CHANNEL_BIT;
474
475         /* Then start listening for incoming connections. */
476         i2cMessage( ucDataListen, sizeof( ucDataListen ), tcpDEVICE_ADDRESS, tcpCOMMAND_REG, i2cWRITE, NULL, portMAX_DELAY );
477 }
478 /*-----------------------------------------------------------*/
479
480 long lProcessConnection( void )
481 {
482 unsigned char ucISR, ucState, ucLastState = 2, ucShadow;
483 extern volatile long lTransactionCompleted;
484 long lSameStateCount = 0, lDataSent = pdFALSE;
485 unsigned long ulWritePointer, ulAckPointer;
486
487         /* No I2C errors can yet have occurred. */
488         portENTER_CRITICAL();
489                 lTransactionCompleted = pdTRUE;
490         portEXIT_CRITICAL();
491
492         /* Keep looping - processing interrupts, until we have completed a 
493         transaction.   This uses the WIZnet in it's simplest form.  The socket
494         accepts a connection - we process the connection - then close the socket.
495         We then go back to reinitialise everything and start again. */
496         while( lTransactionCompleted == pdTRUE )
497         {
498                 /* Wait for a message on the queue from the WIZnet ISR.  When the 
499                 WIZnet device asserts an interrupt the ISR simply posts a message
500                 onto this queue to wake this task. */
501                 if( xQueueReceive( xTCPISRQueue, &ucISR, tcpCONNECTION_WAIT_DELAY ) )
502                 {
503                         /* The ISR posted a message on this queue to tell us that the
504                         WIZnet device asserted an interrupt.  The ISR cannot process
505                         an I2C message so cannot tell us what caused the interrupt so
506                         we have to query the device here.  This task is the highest
507                         priority in the system so will run immediately following the ISR. */
508                         prvReadRegister( &ucISR, tcpINTERRUPT_STATUS_REG, tcpSTATUS_READ_LEN );
509
510                         /* Once we have read what caused the ISR we can clear the interrupt
511                         in the WIZnet. */
512                         i2cMessage( ucDataClearInterrupt, sizeof( ucDataClearInterrupt ), tcpDEVICE_ADDRESS, tcpINTERRUPT_REG, i2cWRITE, NULL, portMAX_DELAY );
513
514                         /* Now we can clear the processor interrupt and re-enable ready for
515                         the next. */
516                         SCB_EXTINT = tcpCLEAR_EINT0;
517                         VICIntEnable |= tcpEINT0_VIC_CHANNEL_BIT;
518         
519                         /* Process the interrupt ... */
520
521                         if( ucISR & tcpISR_ESTABLISHED )
522                         {
523                                 /* A connection has been established - respond by sending
524                                 a receive command. */
525                                 i2cMessage( ucDataReceiveCmd, sizeof( ucDataReceiveCmd ), tcpDEVICE_ADDRESS, tcpCOMMAND_REG, i2cWRITE, NULL, portMAX_DELAY );
526                         }
527                 
528                         if( ucISR & tcpISR_RX_COMPLETE )
529                         {
530                                 /* We message has been received.  This will be an HTTP get 
531                                 command.  We only have one page to send so just send it without
532                                 regard to what the actual requested page was. */
533                                 prvSendSamplePage();
534                         }
535                 
536                         if( ucISR & tcpISR_TX_COMPLETE )
537                         {
538                                 /* We have a TX complete interrupt - which oddly does not 
539                                 indicate that the message being sent is complete so we cannot
540                                 yet close the socket.  Instead we read the position of the Tx
541                                 pointer within the WIZnet device so we know how much data it
542                                 has to send.  Later we will read the ack pointer and compare 
543                                 this to the Tx pointer to ascertain whether the transmission 
544                                 has completed. */
545
546                                 /* First read the shadow register. */
547                                 prvReadRegister( &ucShadow, tcpTX_WRITE_SHADOW_REG, tcpSHADOW_READ_LEN );
548                         
549                                 /* Now a short delay is required. */
550                                 vTaskDelay( tcpSHORT_DELAY );
551
552                                 /* Then we can read the real register. */
553                                 prvReadRegister( ( unsigned char * ) &ulWritePointer, tcpTX_WRITE_POINTER_REG, sizeof( ulWritePointer ) );
554
555                                 /* We cannot do anything more here but need to remember that 
556                                 this interrupt has occurred. */
557                                 lDataSent = pdTRUE;
558                         }
559                 
560                         if( ucISR & tcpISR_CLOSED )
561                         {
562                                 /* The socket has been closed so we can leave this function. */
563                                 lTransactionCompleted = pdFALSE;
564                         }
565                 }
566                 else
567                 {
568                         /* We have not received an interrupt from the WIZnet device for a 
569                         while.  Read the socket status and check that everything is as
570                         expected. */
571                         prvReadRegister( &ucState, tcpSOCKET_STATE_REG, tcpSTATUS_READ_LEN );
572                         
573                         if( ( ucState == tcpSTATUS_ESTABLISHED ) && ( lDataSent > 0 ) ) 
574                         {
575                                 /* The socket is established and we have already received a Tx
576                                 end interrupt.  We must therefore be waiting for the Tx buffer
577                                 inside the WIZnet device to be empty before we can close the
578                                 socket. 
579
580                                 Read the Ack pointer register to see if it has caught up with
581                                 the Tx pointer register.  First we have to read the shadow 
582                                 register. */
583                                 prvReadRegister( &ucShadow, tcpTX_ACK_SHADOW_REG, tcpSHADOW_READ_LEN );
584                                 vTaskDelay( tcpSHORT_DELAY );
585                                 prvReadRegister( ( unsigned char * ) &ulAckPointer, tcpTX_ACK_POINTER_REG, sizeof( ulWritePointer ) );
586
587                                 if( ulAckPointer == ulWritePointer )
588                                 {
589                                         /* The Ack and write pointer are now equal and we can 
590                                         safely close the socket. */
591                                         i2cMessage( ucDataDisconnect, sizeof( ucDataDisconnect ), tcpDEVICE_ADDRESS, tcpCOMMAND_REG, i2cWRITE, NULL, portMAX_DELAY );
592                                 }
593                                 else
594                                 {
595                                         /* Keep a count of how many times we encounter the Tx
596                                         buffer still containing data. */
597                                         lDataSent++;
598                                         if( lDataSent > tcpMAX_ATTEMPTS_TO_CHECK_BUFFER )
599                                         {
600                                                 /* Assume we cannot complete sending the data and 
601                                                 therefore cannot safely close the socket.  Start over. */
602                                                 vTCPHardReset();
603                                                 lTransactionCompleted = pdFALSE;
604                                         }
605                                 }
606                         }
607                         else if( ucState != tcpSTATUS_LISTEN )
608                         {
609                                 /* If we have not yet received a Tx end interrupt we would only 
610                                 ever expect to find the socket still listening for any 
611                                 sustained period. */
612                                 if( ucState == ucLastState )
613                                 {
614                                         lSameStateCount++;
615                                         if( lSameStateCount > tcpMAX_NON_LISTEN_STAUS_READS )
616                                         {                                               
617                                                 /* We are persistently in an unexpected state.  Assume
618                                                 we cannot safely close the socket and start over. */
619                                                 vTCPHardReset();
620                                                 lTransactionCompleted = pdFALSE;
621                                         }
622                                 }
623                         }
624                         else
625                         {
626                                 /* We are in the listen state so are happy that everything
627                                 is as expected. */
628                                 lSameStateCount = 0;
629                         }
630
631                         /* Remember what state we are in this time around so we can check
632                         for a persistence on an unexpected state. */
633                         ucLastState = ucState;
634                 }
635         }
636
637         /* We are going to reinitialise the WIZnet device so do not want our 
638         interrupts from the WIZnet to be processed. */
639         VICIntEnClear |= tcpEINT0_VIC_CHANNEL_BIT;
640         return lTransactionCompleted;
641 }
642 /*-----------------------------------------------------------*/
643
644 static void prvWriteString( const char * const pucTxBuffer, long lTxLen, unsigned long *pulTxAddress )
645 {
646 unsigned long ulSendAddress;
647
648         /* Send a string to the Tx buffer internal to the WIZnet device. */
649
650         /* Calculate the address to which we are going to write in the buffer. */
651         ulSendAddress = ( *pulTxAddress & tcpSINGLE_SOCKET_ADDR_MASK ) + tcpSINGLE_SOCKET_ADDR_OFFSET;
652
653         /* Send the buffer to the calculated address.  Use the semaphore so we
654         can wait until the entire message has been transferred. */
655         i2cMessage( ( unsigned char * ) pucTxBuffer, lTxLen, tcpDEVICE_ADDRESS, ( unsigned short ) ulSendAddress, i2cWRITE, xMessageComplete, portMAX_DELAY );
656
657         /* Wait until the semaphore indicates that the message has been transferred. */
658         if( !xSemaphoreTake( xMessageComplete, tcpLONG_DELAY ) )
659         {
660                 return;
661         }
662
663         /* Return the new address of the end of the buffer (within the WIZnet 
664         device). */
665         *pulTxAddress += ( unsigned long ) lTxLen;
666 }
667 /*-----------------------------------------------------------*/
668
669 static void prvFlushBuffer( unsigned long ulTxAddress )
670 {
671 unsigned char ucTxBuffer[ tcpMAX_REGISTER_LEN ];
672
673         /* We have written some data to the Tx buffer internal to the WIZnet
674         device.  Now we update the Tx pointer inside the WIZnet then send a
675         Send command - which causes     the data up to the new Tx pointer to be 
676         transmitted. */
677
678         /* Make sure endieness is correct for transmission. */
679         ulTxAddress = htonl( ulTxAddress );
680
681         /* Place the new Tx pointer in the string to be transmitted. */
682         ucTxBuffer[ 0 ] = ( unsigned char ) ( ulTxAddress & 0xff );
683         ulTxAddress >>= 8;
684         ucTxBuffer[ 1 ] = ( unsigned char ) ( ulTxAddress & 0xff );
685         ulTxAddress >>= 8;
686         ucTxBuffer[ 2 ] = ( unsigned char ) ( ulTxAddress & 0xff );
687         ulTxAddress >>= 8;
688         ucTxBuffer[ 3 ] = ( unsigned char ) ( ulTxAddress & 0xff );
689         ulTxAddress >>= 8;
690
691         /* And send it to the WIZnet device. */
692         i2cMessage( ucTxBuffer, sizeof( ulTxAddress ), tcpDEVICE_ADDRESS, tcpTX_WRITE_POINTER_REG, i2cWRITE, xMessageComplete, portMAX_DELAY );
693
694         if( !xSemaphoreTake( xMessageComplete, tcpLONG_DELAY ) )
695         {
696                 return;
697         }
698
699         vTaskDelay( tcpSHORT_DELAY );
700
701         /* Transmit! */
702         i2cMessage( ucDataSend, sizeof( ucDataSend ), tcpDEVICE_ADDRESS, tcpCOMMAND_REG, i2cWRITE, xMessageComplete, portMAX_DELAY );
703
704         if( !xSemaphoreTake( xMessageComplete, tcpLONG_DELAY ) )
705         {
706                 return;
707         }
708 }
709 /*-----------------------------------------------------------*/
710
711 static void prvSendSamplePage( void )
712 {
713 extern long lErrorInTask;
714 unsigned long ulTxAddress;
715 unsigned char ucShadow;
716 long lIndex;
717 static unsigned long ulRefreshCount = 0x00;
718 static char cPageBuffer[ tcpBUFFER_LEN ];
719
720
721         /* This function just generates a sample page of HTML which gets
722         sent each time a client attaches to the socket.  The page is created
723         from two fixed strings (cSamplePageFirstPart and cSamplePageSecondPart)
724         with a bit of dynamically generated data in the middle. */
725
726         /* We need to know the address to which the html string should be sent
727         in the WIZnet Tx buffer.  First read the shadow register. */
728         prvReadRegister( &ucShadow, tcpTX_WRITE_SHADOW_REG, tcpSHADOW_READ_LEN );
729
730         /* Now a short delay is required. */
731         vTaskDelay( tcpSHORT_DELAY );
732
733         /* Now we can read the real pointer value. */
734         prvReadRegister( ( unsigned char * ) &ulTxAddress, tcpTX_WRITE_POINTER_REG, sizeof( ulTxAddress ) );
735
736         /* Make sure endieness is correct. */
737         ulTxAddress = htonl( ulTxAddress );
738
739         /* Send the start of the page. */
740         prvWriteString( cSamplePageFirstPart, strlen( cSamplePageFirstPart ), &ulTxAddress );
741
742         /* Generate a bit of dynamic data and place it in the buffer ready to be
743         transmitted. */
744         strcpy( cPageBuffer, "<BR>Number of ticks since boot = 0x" );
745         lIndex = strlen( cPageBuffer );
746         ultoa( xTaskGetTickCount(), &( cPageBuffer[ lIndex ] ), 0 );
747         strcat( cPageBuffer, "<br>Number of tasks executing = ");
748         lIndex = strlen( cPageBuffer );
749         ultoa( ( unsigned long ) uxTaskGetNumberOfTasks(), &( cPageBuffer[ lIndex ] ), 0 );
750         strcat( cPageBuffer, "<br>IO port 0 state (used by flash tasks) = 0x" );
751         lIndex = strlen( cPageBuffer );
752         ultoa( ( unsigned long ) GPIO0_IOPIN, &( cPageBuffer[ lIndex ] ), 0 );
753         strcat( cPageBuffer, "<br>Refresh = 0x" );
754         lIndex = strlen( cPageBuffer );
755         ultoa( ( unsigned long ) ulRefreshCount, &( cPageBuffer[ lIndex ] ), 0 );
756         
757         if( lErrorInTask )
758         {
759                 strcat( cPageBuffer, "<p>An error has occurred in at least one task." );
760         }
761         else
762         {
763                 strcat( cPageBuffer, "<p>All tasks executing without error." );         
764         }
765
766         ulRefreshCount++;
767
768         /* Send the dynamically generated string. */
769         prvWriteString( cPageBuffer, strlen( cPageBuffer ), &ulTxAddress );
770
771         /* Finish the page. */
772         prvWriteString( cSamplePageSecondPart, strlen( cSamplePageSecondPart ), &ulTxAddress );
773
774         /* Tell the WIZnet to send the data we have just written to its Tx buffer. */
775         prvFlushBuffer( ulTxAddress );
776 }
777