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