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