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