]> git.sur5r.net Git - freertos/blob - FreeRTOS-Labs/Demo/Common/Utilities/UDPLoggingPrintf.c
Add the Labs projects provided in the V10.2.1_191129 zip file.
[freertos] / FreeRTOS-Labs / Demo / Common / Utilities / UDPLoggingPrintf.c
1 /*\r
2     FreeRTOS V9.0.0 - 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  * Logging utility that allows FreeRTOS tasks to log to a UDP port.\r
72  *\r
73  * Logging print calls generate messages that are buffered in a stream buffer.\r
74  * A background task then retrieves messages from the stream buffer and sends\r
75  * them to a UDP port.\r
76  */\r
77 \r
78 /* Standard includes. */\r
79 #include <stdio.h>\r
80 #include <string.h>\r
81 #include <stdlib.h>\r
82 #include <limits.h>\r
83 \r
84 /* Scheduler include files. */\r
85 #include "FreeRTOS.h"\r
86 #include "task.h"\r
87 #include "semphr.h"\r
88 \r
89 /* FreeRTOS+TCP includes. */\r
90 #include "FreeRTOS_IP.h"\r
91 #include "FreeRTOS_Sockets.h"\r
92 #include "FreeRTOS_tcp_server.h"\r
93 #include "FreeRTOS_Stream_Buffer.h"\r
94 #include "FreeRTOS_DHCP.h"\r
95 #include "NetworkInterface.h"\r
96 \r
97 /* Demo includes. */\r
98 #include "hr_gettime.h"\r
99 #include "UDPLoggingPrintf.h"\r
100 \r
101 /* Set to 1 to end each line with \r\n, or 0 for just \n. */\r
102 #ifndef configUDP_LOGGING_NEEDS_CR_LF\r
103         #define configUDP_LOGGING_NEEDS_CR_LF  ( 0 )\r
104 #endif\r
105 \r
106 /* The maximum string length for each logged message. */\r
107 #ifndef configUDP_LOGGING_STRING_LENGTH\r
108         #define configUDP_LOGGING_STRING_LENGTH ( 200 )\r
109 #endif\r
110 \r
111 /* The maximum number of messages that can be buffered at any one time. */\r
112 #ifndef configUDP_LOGGING_MAX_MESSAGES_IN_BUFFER\r
113         #define configUDP_LOGGING_MAX_MESSAGES_IN_BUFFER        ( 30 )\r
114 #endif\r
115 \r
116 #ifndef configUDP_LOGGING_TASK_STACK_SIZE\r
117         #define configUDP_LOGGING_TASK_STACK_SIZE       ( 512 )\r
118 #endif\r
119 \r
120 #ifndef configUDP_LOGGING_TASK_PRIORITY\r
121         #define configUDP_LOGGING_TASK_PRIORITY         ( tskIDLE_PRIORITY + 2 )\r
122 #endif\r
123 \r
124 /* configUDP_LOGGING_PORT_REMOTE is the port number to which the logging\r
125 will be sent. */\r
126 #ifndef configUDP_LOGGING_PORT_REMOTE\r
127         #error configUDP_LOGGING_PORT_REMOTE must be defined in FreeRTOSconfig.h to use UDP logging\r
128 #endif\r
129 \r
130 /* configUDP_LOGGING_PORT_LOCAL is the port number to which the\r
131 socket will be bound. It is possible to send messages to\r
132 this socket. */\r
133 #ifndef configUDP_LOGGING_PORT_LOCAL\r
134         /* If not defined, the UDP socket will be bound to a random port number.\r
135         If you want to use a specific port number, please define so in FreeRTOSconfig.h */\r
136         #define configUDP_LOGGING_PORT_LOCAL 0\r
137 #endif\r
138 \r
139 /* The logging task's block time.  This is used as the UDP socket's send block\r
140 time, and the maximum time the logging task will spend in the Blocked state\r
141 waiting to be notified of a new message to send before manually looking for a\r
142 message. */\r
143 #ifndef logUDP_LOGGING_BLOCK_TIME_MS\r
144         #define logUDP_LOGGING_BLOCK_TIME_MS    ( 1000ul )\r
145 #endif\r
146 \r
147 /* Log messages are cached in a stream buffer.  The stream buffer's storage\r
148 area is dimensioned to contain the maximum number of strings of the maximum\r
149 string length. */\r
150 #define logMESSAGE_BUFFER_SIZE_BYTES  ( ( configUDP_LOGGING_STRING_LENGTH ) * ( configUDP_LOGGING_MAX_MESSAGES_IN_BUFFER ) )\r
151 \r
152 /* Ascii characters used in this file. */\r
153 #define logASCII_CR                     ( 13 )\r
154 #define logASCII_NL                             ( 10 )\r
155 \r
156 #ifndef iptraceUDP_LOGGING_TASK_STARTING\r
157         /* This macro will be called once when the UDP logging task is starting up. */\r
158         #define iptraceUDP_LOGGING_TASK_STARTING()      do { } while( 0 )\r
159 #endif\r
160 /*-----------------------------------------------------------*/\r
161 \r
162 /*\r
163  * Called automatically to create the stream buffer.\r
164  */\r
165 static BaseType_t prvInitialiseLogging( void );\r
166 \r
167 /*\r
168  * The task that reads messages from the stream buffer and sends them to the\r
169  * UDP port.\r
170  */\r
171 static void prvLoggingTask( void *pvParameters );\r
172 \r
173 /*\r
174  * Obtain a message from the stream buffer.\r
175  */\r
176 static size_t prvGetMessageFromStreamBuffer( char *pcBuffer, size_t xBufferLength );\r
177 \r
178 /*\r
179  * Generate a formatted string and add it to the stream buffer ready for the\r
180  * logging task to transmit.\r
181  */\r
182 static size_t prvBufferFormattedString( const char *pcFormatString, va_list xArgs );\r
183 \r
184 /*-----------------------------------------------------------*/\r
185 \r
186 /* Is this structure used anywhere? */\r
187 typedef struct LogStruct\r
188 {\r
189         size_t xLength;\r
190 \r
191         #if LOGBUF_SHOW_US\r
192                 uint64_t ullLogTime;\r
193         #else\r
194                 uint32_t ulLogTime;\r
195         #endif\r
196         uint32_t ulPriority;\r
197 \r
198 } LogStruct_t;\r
199 \r
200 typedef struct LogUnit_t\r
201 {\r
202         LogStruct_t xHeader;\r
203         char cMessage[ configUDP_LOGGING_STRING_LENGTH ];\r
204 \r
205 } LogUnit_t;\r
206 \r
207 static LogUnit_t xLogEntry;\r
208 static StreamBuffer_t *pxStreamBuffer = NULL;\r
209 static TaskHandle_t xLoggingTask = NULL;\r
210 static xSocket_t xUDPLoggingSocket = FREERTOS_INVALID_SOCKET;\r
211 \r
212 /*-----------------------------------------------------------*/\r
213 \r
214 static BaseType_t prvInitialiseLogging( void )\r
215 {\r
216 size_t xSize;\r
217 static BaseType_t xLoggingInitialised = pdFALSE;\r
218 \r
219         if( xLoggingInitialised == pdFALSE )\r
220         {\r
221                 /* Don't attempt to log unless the scheduler is running. */\r
222                 if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )\r
223                 {\r
224                         /* Create a stream buffer large enough for the maximum number of\r
225                         bytes + 1. */ /*_RB_ Why is the size of pxStreamBuffer->ucArray\r
226                         subtracted here? */\r
227                         xSize = sizeof( StreamBuffer_t ) - sizeof( pxStreamBuffer->ucArray ) + logMESSAGE_BUFFER_SIZE_BYTES + 1;\r
228                         pxStreamBuffer = pvPortMalloc( xSize );\r
229 \r
230                         if( pxStreamBuffer != NULL )\r
231                         {\r
232                                 memset( pxStreamBuffer, '\0', xSize );\r
233                                 pxStreamBuffer->LENGTH = logMESSAGE_BUFFER_SIZE_BYTES + 1;\r
234 \r
235                                 xLoggingInitialised = pdTRUE;\r
236                         }\r
237                 }\r
238         }\r
239 \r
240         return xLoggingInitialised;\r
241 }\r
242 /*-----------------------------------------------------------*/\r
243 \r
244 static size_t prvGetMessageFromStreamBuffer( char* pcBuffer, size_t xBufferLength )\r
245 {\r
246 size_t uxLength;\r
247 size_t xMessageLength = 0;\r
248 \r
249         if( pxStreamBuffer != NULL )\r
250         {\r
251                 /* Is there data in the stream buffer? */\r
252                 uxLength = uxStreamBufferGetSize( pxStreamBuffer );\r
253                 if( uxLength > sizeof( size_t ) )\r
254                 {\r
255                         /* Avoid concurrent access to the buffer. */\r
256                         vTaskSuspendAll();\r
257                         {\r
258                                 /* Every message is stored as a length followed by the string.\r
259                                 Obtain the length of the data first. */\r
260                                 uxStreamBufferGet( pxStreamBuffer, 0, ( uint8_t * ) &xMessageLength, sizeof( xMessageLength ), pdFALSE );\r
261 \r
262                                 if( xBufferLength < xMessageLength )\r
263                                 {\r
264                                         /* The 'pcBuffer' provided by the caller is too small.  Load\r
265                                         the message first into 'xLogEntry.message', and then copy\r
266                                         as much as possible to 'pcBuffer'. */\r
267                                         uxStreamBufferGet( pxStreamBuffer, 0, ( uint8_t * ) xLogEntry.cMessage, xMessageLength, pdFALSE );\r
268                                         memcpy( pcBuffer, xLogEntry.cMessage, xBufferLength );\r
269                                         xMessageLength = xBufferLength;\r
270 \r
271                                         /* Terminate the string at the very end of the buffer. */\r
272                                         pcBuffer[ xBufferLength - 1 ] = 0x00;\r
273                                 }\r
274                                 else\r
275                                 {\r
276                                         /* The 'pcBuffer' provided by the caller is big enough. */\r
277                                         uxStreamBufferGet( pxStreamBuffer, 0, ( uint8_t * ) pcBuffer, xMessageLength, pdFALSE );\r
278 \r
279                                         /* Terminate the string after the string's last character. */\r
280                                         pcBuffer[ xMessageLength ] = 0x00;\r
281                                 }\r
282                         }\r
283                         xTaskResumeAll();\r
284                 }\r
285         }\r
286 \r
287         return xMessageLength;\r
288 }\r
289 /*-----------------------------------------------------------*/\r
290 \r
291 static size_t prvBufferFormattedString( const char *pcFormatString, va_list xArgs )\r
292 {\r
293 size_t xLength, xSpace;\r
294 uint64_t ullCurrentTime;\r
295 uint32_t ulSeconds, ulMilliSeconds, ulMicroSeconds;\r
296 \r
297         /* Sanity check. */\r
298         configASSERT( pxStreamBuffer );\r
299 \r
300         vTaskSuspendAll();\r
301         {\r
302                 ullCurrentTime = ullGetHighResolutionTime();\r
303                 ulSeconds = ( uint32_t ) ( ullCurrentTime / 1000000ull );\r
304                 ullCurrentTime = ullCurrentTime % 1000000ull;\r
305                 ulMilliSeconds = ( uint32_t ) ( ullCurrentTime / 1000ull );\r
306                 ulMicroSeconds = ( uint32_t ) ( ullCurrentTime % 1000ull );\r
307 \r
308                 xLength = ( size_t ) snprintf( xLogEntry.cMessage, sizeof( xLogEntry.cMessage ), "%4u.%03u.%03u [%-10s] ",\r
309                         ( unsigned int ) ulSeconds, ( unsigned int ) ulMilliSeconds, ( unsigned int ) ulMicroSeconds, pcTaskGetTaskName( NULL ) );\r
310                 xLength += ( size_t ) vsnprintf( xLogEntry.cMessage + xLength, sizeof( xLogEntry.cMessage ) - xLength, pcFormatString, xArgs );\r
311 \r
312                 xSpace = uxStreamBufferGetSpace( pxStreamBuffer );\r
313 \r
314                 if( xSpace > ( xLength + sizeof( BaseType_t ) ) )\r
315                 {\r
316                         uxStreamBufferAdd( pxStreamBuffer, 0, ( const uint8_t * ) &xLength, sizeof( xLength ) );\r
317                         uxStreamBufferAdd( pxStreamBuffer, 0, ( const uint8_t * ) ( xLogEntry.cMessage ), xLength );\r
318                 }\r
319         }\r
320         xTaskResumeAll();\r
321 \r
322         if( xLoggingTask != NULL )\r
323         {\r
324                 /* Unblock the logging task so it can output the message. */\r
325                 xTaskNotifyGive( xLoggingTask );\r
326         }\r
327 \r
328         return xLength;\r
329 }\r
330 /*-----------------------------------------------------------*/\r
331 \r
332 int lUDPLoggingPrintf( const char *pcFormatString, ... )\r
333 {\r
334 size_t xLength;\r
335 \r
336         if( prvInitialiseLogging() != pdFALSE )\r
337         {\r
338                 va_list args;\r
339                 va_start (args, pcFormatString);\r
340                 xLength = prvBufferFormattedString (pcFormatString, args);\r
341                 va_end (args);\r
342         }\r
343         else\r
344         {\r
345                 xLength = 0;\r
346         }\r
347 \r
348         return ( int ) xLength;\r
349 }\r
350 /*-----------------------------------------------------------*/\r
351 \r
352 void vUDPLoggingTaskCreate( void )\r
353 {\r
354         /* Start a task which will send out the logging lines to a UDP address. */\r
355         xTaskCreate( prvLoggingTask, "LogTask", configUDP_LOGGING_TASK_STACK_SIZE, NULL, configUDP_LOGGING_TASK_PRIORITY, &xLoggingTask );\r
356 }\r
357 /*-----------------------------------------------------------*/\r
358 \r
359 xSocket_t xLoggingGetSocket( void )\r
360 {\r
361 xSocket_t xReturn;\r
362 \r
363         if( ( xUDPLoggingSocket != NULL ) && ( xUDPLoggingSocket != FREERTOS_INVALID_SOCKET ) )\r
364         {\r
365                 xReturn = xUDPLoggingSocket;\r
366         }\r
367         else\r
368         {\r
369                 xReturn = NULL;\r
370         }\r
371 \r
372         return xReturn;\r
373 }\r
374 /*-----------------------------------------------------------*/\r
375 \r
376 void prvLoggingTask( void *pvParameters )\r
377 {\r
378 TickType_t xBlockingTime = pdMS_TO_TICKS( logUDP_LOGGING_BLOCK_TIME_MS );\r
379 struct freertos_sockaddr xLocalAddress, xRemoteAddress;\r
380 BaseType_t xSendTimeOut;\r
381 int32_t lLines;\r
382 size_t xCount;\r
383 static char cLoggingLine[ configUDP_LOGGING_STRING_LENGTH ];\r
384 const TickType_t xResolveDelay = pdMS_TO_TICKS( ( TickType_t ) 250 );\r
385 \r
386         /* Prevent compiler warnings about unused parameters. */\r
387         ( void ) pvParameters;\r
388 \r
389         /* A possibility to set some additional task properties. */\r
390         iptraceUDP_LOGGING_TASK_STARTING();\r
391 \r
392         xRemoteAddress.sin_port = FreeRTOS_htons( configUDP_LOGGING_PORT_REMOTE );\r
393         #if defined( configUDP_LOGGING_ADDR0 )\r
394         {\r
395                 /* Use a fixed address to where the logging will be sent. */\r
396                 xRemoteAddress.sin_addr = FreeRTOS_inet_addr_quick( configUDP_LOGGING_ADDR0,\r
397                                                                                                                         configUDP_LOGGING_ADDR1,\r
398                                                                                                                         configUDP_LOGGING_ADDR2,\r
399                                                                                                                         configUDP_LOGGING_ADDR3 );\r
400         }\r
401         #else\r
402         {\r
403                 /* The logging will be broadcasted on the local broadcasting\r
404                 address, such as 192.168.0.255 */\r
405                 xRemoteAddress.sin_addr = FreeRTOS_GetIPAddress() | ~( FreeRTOS_GetNetmask() );\r
406         }\r
407         #endif\r
408 \r
409         /* Loop until a socket is created. */\r
410         do\r
411         {\r
412                 vTaskDelay( xBlockingTime );\r
413                 xUDPLoggingSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
414         } while( xUDPLoggingSocket == FREERTOS_INVALID_SOCKET );\r
415 \r
416         xLocalAddress.sin_port = FreeRTOS_htons( configUDP_LOGGING_PORT_LOCAL );\r
417         xLocalAddress.sin_addr = FreeRTOS_GetIPAddress();\r
418 \r
419         FreeRTOS_bind( xUDPLoggingSocket, &xLocalAddress, sizeof( xLocalAddress ) );\r
420 \r
421         xSendTimeOut = xBlockingTime;\r
422         FreeRTOS_setsockopt( xUDPLoggingSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xSendTimeOut ) );\r
423 \r
424         /* Send a dummy message to resolve the IP address before sending the logging \r
425         messages. */\r
426         snprintf( cLoggingLine, configUDP_LOGGING_STRING_LENGTH, "Logging Probe\n" );\r
427         FreeRTOS_sendto( xUDPLoggingSocket, ( void * ) cLoggingLine, strlen( cLoggingLine ), 0, &xRemoteAddress, sizeof( xRemoteAddress ) );\r
428         vTaskDelay( xResolveDelay );\r
429 \r
430         for( ;; )\r
431         {\r
432                 /* Wait for another message to be placed into the stream buffer. */\r
433                 ulTaskNotifyTake( pdTRUE, xBlockingTime );\r
434 \r
435                 if( xGetPhyLinkStatus() != pdFALSE )\r
436                 {\r
437                         /* Check for messages in the buffer. */\r
438                         for( lLines = 0; lLines < configUDP_LOGGING_MAX_MESSAGES_IN_BUFFER; lLines++ )\r
439                         {\r
440                                 xCount = prvGetMessageFromStreamBuffer ( cLoggingLine, sizeof( cLoggingLine ) );\r
441 \r
442                                 if( xCount <= 0 )\r
443                                 {\r
444                                         break;\r
445                                 }\r
446 \r
447                                 #if( configUDP_LOGGING_NEEDS_CR_LF != 0 )\r
448                                 {\r
449                                 char *pcTarget;\r
450                                 const char *pcSource;\r
451 \r
452                                         /* Within the code, a single "\n" is used to denote     a\r
453                                         newline.  If 'configUDP_LOGGING_NEEDS_CR_LF' is defined as non-zero,\r
454                                         every "\n" will be translated into a "\r\n". */\r
455                                         pcTarget = cLoggingLine;\r
456                                         pcSource = cLoggingLine;\r
457 \r
458                                         while( ( *pcSource != 0x00 ) && ( pcSource < ( cLoggingLine + xCount ) ) )\r
459                                         {\r
460                                                 *pcTarget = *pcSource;\r
461 \r
462                                                 if( ( ( pcSource == cLoggingLine ) || ( pcSource[ -1 ] != logASCII_CR ) ) && ( pcSource[ 0 ] == logASCII_NL ) )\r
463                                                 {\r
464                                                         pcTarget[ 0 ] = logASCII_CR;\r
465                                                         pcTarget[ 1 ] = logASCII_NL;\r
466 \r
467                                                         if( xCount < ( sizeof( cLoggingLine ) - 1 ) )\r
468                                                         {\r
469                                                                 xCount++;\r
470                                                                 pcTarget++;\r
471                                                         }\r
472                                                 }\r
473 \r
474                                                 pcTarget++;\r
475                                                 pcSource++;\r
476                                         }\r
477                                 }\r
478                                 #endif\r
479 \r
480                                 FreeRTOS_sendto( xUDPLoggingSocket, ( void * ) cLoggingLine, xCount, 0, &xRemoteAddress, sizeof( xRemoteAddress ) );\r
481                         }\r
482                 }\r
483         }\r
484 }\r
485 /*-----------------------------------------------------------*/\r
486 \r
487 void vUDPLoggingFlush( void )\r
488 {\r
489 const TickType_t xDelay = pdMS_TO_TICKS( 20UL );\r
490 \r
491         /* In some situations a lot of logging is produced deliberately in which\r
492         case vUDPLoggingFlush() can be called to prevent the buffer overflowing. */\r
493         if( xLoggingTask != NULL )\r
494         {\r
495                 /* Unblock the logging task so it can output the message. */\r
496                 xTaskNotifyGive( xLoggingTask );\r
497         }\r
498 \r
499         /* Allow the low priority logging task a chance to clear the buffer. */\r
500         vTaskDelay( pdMS_TO_TICKS( xDelay ) );\r
501 }\r
502 \r