2 FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
\r
5 VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
\r
7 This file is part of the FreeRTOS distribution.
\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
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
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
25 ***************************************************************************
\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
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
37 ***************************************************************************
\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
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
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
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
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
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
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
71 * Logging utility that allows FreeRTOS tasks to log to a UDP port, stdout, and
\r
72 * disk file without making any Win32 system calls themselves.
\r
74 * Messages logged to a UDP port are sent directly (using FreeRTOS+TCP), but as
\r
75 * FreeRTOS tasks cannot make Win32 system calls messages sent to stdout or a
\r
76 * disk file are sent via a stream buffer to a Win32 thread which then performs
\r
77 * the actual output.
\r
80 /* Standard includes. */
\r
87 /* FreeRTOS includes. */
\r
88 #include <FreeRTOS.h>
\r
91 /* FreeRTOS+TCP includes. */
\r
92 #include "FreeRTOS_IP.h"
\r
93 #include "FreeRTOS_Sockets.h"
\r
94 #include "FreeRTOS_Stream_Buffer.h"
\r
96 /* Demo includes. */
\r
97 #include "demo_logging.h"
\r
99 /*-----------------------------------------------------------*/
\r
101 /* The maximum size to which the log file may grow, before being renamed
\r
103 #define dlLOGGING_FILE_SIZE ( 40ul * 1024ul * 1024ul )
\r
105 /* Dimensions the arrays into which print messages are created. */
\r
106 #define dlMAX_PRINT_STRING_LENGTH 255
\r
108 /* The size of the stream buffer used to pass messages from FreeRTOS tasks to
\r
109 the Win32 thread that is responsible for making any Win32 system calls that are
\r
110 necessary for the selected logging method. */
\r
111 #define dlLOGGING_STREAM_BUFFER_SIZE 32768
\r
113 /* A block time of zero simply means don't block. */
\r
114 #define dlDONT_BLOCK 0
\r
116 /*-----------------------------------------------------------*/
\r
119 * Called from vLoggingInit() to start a new disk log file.
\r
121 static void prvFileLoggingInit( void );
\r
124 * Attempt to write a message to the file.
\r
126 static void prvLogToFile( const char *pcMessage, size_t xLength );
\r
129 * Simply close the logging file, if it is open.
\r
131 static void prvFileClose( void );
\r
134 * Before the scheduler is started this function is called directly. After the
\r
135 * scheduler has started it is called from the Windows thread dedicated to
\r
136 * outputting log messages. Only the windows thread actually performs the
\r
137 * writing so as not to disrupt the simulation by making Windows system calls
\r
138 * from FreeRTOS tasks.
\r
140 static void prvLoggingFlushBuffer( void );
\r
143 * The windows thread that performs the actual writing of messages that require
\r
144 * Win32 system calls. Only the windows thread can make system calls so as not
\r
145 * to disrupt the simulation by making Windows calls from FreeRTOS tasks.
\r
147 static DWORD WINAPI prvWin32LoggingThread( void *pvParam );
\r
150 * Creates the socket to which UDP messages are sent. This function is not
\r
151 * called directly to prevent the print socket being created from within the IP
\r
152 * task - which could result in a deadlock. Instead the function call is
\r
153 * deferred to run in the RTOS daemon task - hence it prototype.
\r
155 static void prvCreatePrintSocket( void *pvParameter1, uint32_t ulParameter2 );
\r
157 /*-----------------------------------------------------------*/
\r
159 /* Windows event used to wake the Win32 thread which performs any logging that
\r
160 needs Win32 system calls. */
\r
161 static void *pvLoggingThreadEvent = NULL;
\r
163 /* Stores the selected logging targets passed in as parameters to the
\r
164 vLoggingInit() function. */
\r
165 BaseType_t xStdoutLoggingUsed = pdFALSE, xDiskFileLoggingUsed = pdFALSE, xUDPLoggingUsed = pdFALSE;
\r
167 /* Circular buffer used to pass messages from the FreeRTOS tasks to the Win32
\r
168 thread that is responsible for making Win32 calls (when stdout or a disk log is
\r
170 static StreamBuffer_t *xLogStreamBuffer = NULL;
\r
172 /* Handle to the file used for logging. This is left open while there are
\r
173 messages waiting to be logged, then closed again in between logs. */
\r
174 static FILE *pxLoggingFileHandle = NULL;
\r
176 /* When true prints are performed directly. After start up xDirectPrint is set
\r
177 to pdFALSE - at which time prints that require Win32 system calls are done by
\r
178 the Win32 thread responsible for logging. */
\r
179 BaseType_t xDirectPrint = pdTRUE;
\r
181 /* File names for the in use and complete (full) log files. */
\r
182 static const char *pcLogFileName = "RTOSDemo.log";
\r
183 static const char *pcFullLogFileName = "RTOSDemo.ful";
\r
185 /* Keep the current file size in a variable, as an optimisation. */
\r
186 static size_t ulSizeOfLoggingFile = 0ul;
\r
188 /* The UDP socket and address on/to which print messages are sent. */
\r
189 Socket_t xPrintSocket = FREERTOS_INVALID_SOCKET;
\r
190 struct freertos_sockaddr xPrintUDPAddress;
\r
192 /*-----------------------------------------------------------*/
\r
194 void vLoggingInit( BaseType_t xLogToStdout, BaseType_t xLogToFile, BaseType_t xLogToUDP, uint32_t ulRemoteIPAddress, uint16_t usRemotePort )
\r
196 /* Can only be called before the scheduler has started. */
\r
197 configASSERT( xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED );
\r
199 #if( ( ipconfigHAS_DEBUG_PRINTF == 1 ) || ( ipconfigHAS_PRINTF == 1 ) )
\r
201 HANDLE Win32Thread;
\r
203 /* Record which output methods are to be used. */
\r
204 xStdoutLoggingUsed = xLogToStdout;
\r
205 xDiskFileLoggingUsed = xLogToFile;
\r
206 xUDPLoggingUsed = xLogToUDP;
\r
208 /* If a disk file is used then initialise it now. */
\r
209 if( xDiskFileLoggingUsed != pdFALSE )
\r
211 prvFileLoggingInit();
\r
214 /* If UDP logging is used then store the address to which the log data
\r
215 will be sent - but don't create the socket yet because the network is
\r
216 not initialised. */
\r
217 if( xUDPLoggingUsed != pdFALSE )
\r
219 /* Set the address to which the print messages are sent. */
\r
220 xPrintUDPAddress.sin_port = FreeRTOS_htons( usRemotePort );
\r
221 xPrintUDPAddress.sin_addr = ulRemoteIPAddress;
\r
224 /* If a disk file or stdout are to be used then Win32 system calls will
\r
225 have to be made. Such system calls cannot be made from FreeRTOS tasks
\r
226 so create a stream buffer to pass the messages to a Win32 thread, then
\r
227 create the thread itself, along with a Win32 event that can be used to
\r
228 unblock the thread. */
\r
229 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) )
\r
231 /* Create the buffer. */
\r
232 xLogStreamBuffer = ( StreamBuffer_t * ) malloc( sizeof( *xLogStreamBuffer ) - sizeof( xLogStreamBuffer->ucArray ) + dlLOGGING_STREAM_BUFFER_SIZE + 1 );
\r
233 configASSERT( xLogStreamBuffer );
\r
234 memset( xLogStreamBuffer, '\0', sizeof( *xLogStreamBuffer ) - sizeof( xLogStreamBuffer->ucArray ) );
\r
235 xLogStreamBuffer->LENGTH = dlLOGGING_STREAM_BUFFER_SIZE + 1;
\r
237 /* Create the Windows event. */
\r
238 pvLoggingThreadEvent = CreateEvent( NULL, FALSE, TRUE, "StdoutLoggingEvent" );
\r
240 /* Create the thread itself. */
\r
241 Win32Thread = CreateThread(
\r
242 NULL, /* Pointer to thread security attributes. */
\r
243 0, /* Initial thread stack size, in bytes. */
\r
244 prvWin32LoggingThread, /* Pointer to thread function. */
\r
245 NULL, /* Argument for new thread. */
\r
246 0, /* Creation flags. */
\r
249 /* Use the cores that are not used by the FreeRTOS tasks. */
\r
250 SetThreadAffinityMask( Win32Thread, ~0x01u );
\r
251 SetThreadPriorityBoost( Win32Thread, TRUE );
\r
252 SetThreadPriority( Win32Thread, THREAD_PRIORITY_IDLE );
\r
257 /* FreeRTOSIPConfig is set such that no print messages will be output.
\r
258 Avoid compiler warnings about unused parameters. */
\r
259 ( void ) xLogToStdout;
\r
260 ( void ) xLogToFile;
\r
261 ( void ) xLogToUDP;
\r
262 ( void ) usRemotePort;
\r
263 ( void ) ulRemoteIPAddress;
\r
265 #endif /* ( ipconfigHAS_DEBUG_PRINTF == 1 ) || ( ipconfigHAS_PRINTF == 1 ) */
\r
267 /*-----------------------------------------------------------*/
\r
269 static void prvCreatePrintSocket( void *pvParameter1, uint32_t ulParameter2 )
\r
271 static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 0 );
\r
274 /* The function prototype is that of a deferred function, but the parameters
\r
275 are not actually used. */
\r
276 ( void ) pvParameter1;
\r
277 ( void ) ulParameter2;
\r
279 xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
\r
281 if( xSocket != FREERTOS_INVALID_SOCKET )
\r
283 /* FreeRTOS+TCP decides which port to bind to. */
\r
284 FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xSendTimeOut ) );
\r
285 FreeRTOS_bind( xSocket, NULL, 0 );
\r
287 /* Now the socket is bound it can be assigned to the print socket. */
\r
288 xPrintSocket = xSocket;
\r
291 /*-----------------------------------------------------------*/
\r
293 void vLoggingPrintf( const char *pcFormat, ... )
\r
295 char cPrintString[ dlMAX_PRINT_STRING_LENGTH ];
\r
296 char cOutputString[ dlMAX_PRINT_STRING_LENGTH ];
\r
297 char *pcSource, *pcTarget, *pcBegin;
\r
298 size_t xLength, xLength2, rc;
\r
299 static BaseType_t xMessageNumber = 0;
\r
301 uint32_t ulIPAddress;
\r
302 const char *pcTaskName;
\r
303 const char *pcNoTask = "None";
\r
304 int iOriginalPriority;
\r
305 HANDLE xCurrentTask;
\r
308 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) || ( xUDPLoggingUsed != pdFALSE ) )
\r
310 /* There are a variable number of parameters. */
\r
311 va_start( args, pcFormat );
\r
313 /* Additional info to place at the start of the log. */
\r
314 if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
\r
316 pcTaskName = pcTaskGetName( NULL );
\r
320 pcTaskName = pcNoTask;
\r
323 if( strcmp( pcFormat, "\n" ) != 0 )
\r
325 xLength = snprintf( cPrintString, dlMAX_PRINT_STRING_LENGTH, "%lu %lu [%s] ",
\r
327 ( unsigned long ) xTaskGetTickCount(),
\r
333 memset( cPrintString, 0x00, dlMAX_PRINT_STRING_LENGTH );
\r
336 xLength2 = vsnprintf( cPrintString + xLength, dlMAX_PRINT_STRING_LENGTH - xLength, pcFormat, args );
\r
341 xLength2 = sizeof( cPrintString ) - 1 - xLength;
\r
342 cPrintString[ sizeof( cPrintString ) - 1 ] = '\0';
\r
345 xLength += xLength2;
\r
348 /* For ease of viewing, copy the string into another buffer, converting
\r
349 IP addresses to dot notation on the way. */
\r
350 pcSource = cPrintString;
\r
351 pcTarget = cOutputString;
\r
353 while( ( *pcSource ) != '\0' )
\r
355 *pcTarget = *pcSource;
\r
359 /* Look forward for an IP address denoted by 'ip'. */
\r
360 if( ( isxdigit( pcSource[ 0 ] ) != pdFALSE ) && ( pcSource[ 1 ] == 'i' ) && ( pcSource[ 2 ] == 'p' ) )
\r
362 *pcTarget = *pcSource;
\r
365 pcBegin = pcTarget - 8;
\r
367 while( ( pcTarget > pcBegin ) && ( isxdigit( pcTarget[ -1 ] ) != pdFALSE ) )
\r
372 sscanf( pcTarget, "%8X", &ulIPAddress );
\r
373 rc = sprintf( pcTarget, "%lu.%lu.%lu.%lu",
\r
374 ( unsigned long ) ( ulIPAddress >> 24UL ),
\r
375 ( unsigned long ) ( (ulIPAddress >> 16UL) & 0xffUL ),
\r
376 ( unsigned long ) ( (ulIPAddress >> 8UL) & 0xffUL ),
\r
377 ( unsigned long ) ( ulIPAddress & 0xffUL ) );
\r
379 pcSource += 3; /* skip "<n>ip" */
\r
383 /* How far through the buffer was written? */
\r
384 xLength = ( BaseType_t ) ( pcTarget - cOutputString );
\r
386 /* If the message is to be logged to a UDP port then it can be sent directly
\r
387 because it only uses FreeRTOS function (not Win32 functions). */
\r
388 if( xUDPLoggingUsed != pdFALSE )
\r
390 if( ( xPrintSocket == FREERTOS_INVALID_SOCKET ) && ( FreeRTOS_IsNetworkUp() != pdFALSE ) )
\r
392 /* Create and bind the socket to which print messages are sent. The
\r
393 xTimerPendFunctionCall() function is used even though this is
\r
394 not an interrupt because this function is called from the IP task
\r
395 and the IP task cannot itself wait for a socket to bind. The
\r
396 parameters to prvCreatePrintSocket() are not required so set to
\r
398 xTimerPendFunctionCall( prvCreatePrintSocket, NULL, 0, dlDONT_BLOCK );
\r
401 if( xPrintSocket != FREERTOS_INVALID_SOCKET )
\r
403 FreeRTOS_sendto( xPrintSocket, cOutputString, xLength, 0, &xPrintUDPAddress, sizeof( xPrintUDPAddress ) );
\r
405 /* Just because the UDP data logger I'm using is dumb. */
\r
406 FreeRTOS_sendto( xPrintSocket, "\r", sizeof( char ), 0, &xPrintUDPAddress, sizeof( xPrintUDPAddress ) );
\r
410 /* If logging is also to go to either stdout or a disk file then it cannot
\r
411 be output here - so instead write the message to the stream buffer and wake
\r
412 the Win32 thread which will read it from the stream buffer and perform the
\r
414 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) )
\r
416 configASSERT( xLogStreamBuffer );
\r
418 /* How much space is in the buffer? */
\r
419 xLength2 = uxStreamBufferGetSpace( xLogStreamBuffer );
\r
421 /* There must be enough space to write both the string and the length of
\r
423 if( xLength2 >= ( xLength + sizeof( xLength ) ) )
\r
425 /* First write in the length of the data, then write in the data
\r
426 itself. Raising the thread priority is used as a critical section
\r
427 as there are potentially multiple writers. The stream buffer is
\r
428 only thread safe when there is a single writer (likewise for
\r
429 reading from the buffer). */
\r
430 xCurrentTask = GetCurrentThread();
\r
431 iOriginalPriority = GetThreadPriority( xCurrentTask );
\r
432 SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL );
\r
433 uxStreamBufferAdd( xLogStreamBuffer, 0, ( const uint8_t * ) &( xLength ), sizeof( xLength ) );
\r
434 uxStreamBufferAdd( xLogStreamBuffer, 0, ( const uint8_t * ) cOutputString, xLength );
\r
435 SetThreadPriority( GetCurrentThread(), iOriginalPriority );
\r
438 /* xDirectPrint is initialised to pdTRUE, and while it remains true the
\r
439 logging output function is called directly. When the system is running
\r
440 the output function cannot be called directly because it would get
\r
441 called from both FreeRTOS tasks and Win32 threads - so instead wake the
\r
442 Win32 thread responsible for the actual output. */
\r
443 if( xDirectPrint != pdFALSE )
\r
445 /* While starting up, the thread which calls prvWin32LoggingThread()
\r
446 is not running yet and xDirectPrint will be pdTRUE. */
\r
447 prvLoggingFlushBuffer();
\r
449 else if( pvLoggingThreadEvent != NULL )
\r
451 /* While running, wake up prvWin32LoggingThread() to send the
\r
453 SetEvent( pvLoggingThreadEvent );
\r
458 /*-----------------------------------------------------------*/
\r
460 static void prvLoggingFlushBuffer( void )
\r
463 char cPrintString[ dlMAX_PRINT_STRING_LENGTH ];
\r
465 /* Is there more than the length value stored in the circular buffer
\r
466 used to pass data from the FreeRTOS simulator into this Win32 thread? */
\r
467 while( uxStreamBufferGetSize( xLogStreamBuffer ) > sizeof( xLength ) )
\r
469 memset( cPrintString, 0x00, dlMAX_PRINT_STRING_LENGTH );
\r
470 uxStreamBufferGet( xLogStreamBuffer, 0, ( uint8_t * ) &xLength, sizeof( xLength ), pdFALSE );
\r
471 uxStreamBufferGet( xLogStreamBuffer, 0, ( uint8_t * ) cPrintString, xLength, pdFALSE );
\r
473 /* Write the message to standard out if requested to do so when
\r
474 vLoggingInit() was called, or if the network is not yet up. */
\r
475 if( ( xStdoutLoggingUsed != pdFALSE ) || ( FreeRTOS_IsNetworkUp() == pdFALSE ) )
\r
477 /* Write the message to stdout. */
\r
478 printf( "%s", cPrintString ); /*_RB_ Replace with _write(). */
\r
481 /* Write the message to a file if requested to do so when
\r
482 vLoggingInit() was called. */
\r
483 if( xDiskFileLoggingUsed != pdFALSE )
\r
485 prvLogToFile( cPrintString, xLength );
\r
491 /*-----------------------------------------------------------*/
\r
493 static DWORD WINAPI prvWin32LoggingThread( void *pvParameter )
\r
495 const DWORD xMaxWait = 1000;
\r
497 ( void ) pvParameter;
\r
499 /* From now on, prvLoggingFlushBuffer() will only be called from this
\r
501 xDirectPrint = pdFALSE;
\r
505 /* Wait to be told there are message waiting to be logged. */
\r
506 WaitForSingleObject( pvLoggingThreadEvent, xMaxWait );
\r
508 /* Write out all waiting messages. */
\r
509 prvLoggingFlushBuffer();
\r
512 /*-----------------------------------------------------------*/
\r
514 static void prvFileLoggingInit( void )
\r
516 FILE *pxHandle = fopen( pcLogFileName, "a" );
\r
518 if( pxHandle != NULL )
\r
520 fseek( pxHandle, SEEK_END, 0ul );
\r
521 ulSizeOfLoggingFile = ftell( pxHandle );
\r
522 fclose( pxHandle );
\r
526 ulSizeOfLoggingFile = 0ul;
\r
529 /*-----------------------------------------------------------*/
\r
531 static void prvFileClose( void )
\r
533 if( pxLoggingFileHandle != NULL )
\r
535 fclose( pxLoggingFileHandle );
\r
536 pxLoggingFileHandle = NULL;
\r
539 /*-----------------------------------------------------------*/
\r
541 static void prvLogToFile( const char *pcMessage, size_t xLength )
\r
543 if( pxLoggingFileHandle == NULL )
\r
545 pxLoggingFileHandle = fopen( pcLogFileName, "a" );
\r
548 if( pxLoggingFileHandle != NULL )
\r
550 fwrite( pcMessage, 1, xLength, pxLoggingFileHandle );
\r
551 ulSizeOfLoggingFile += xLength;
\r
553 /* If the file has grown to its maximum permissible size then close and
\r
554 rename it - then start with a new file. */
\r
555 if( ulSizeOfLoggingFile > ( size_t ) dlLOGGING_FILE_SIZE )
\r
558 if( _access( pcFullLogFileName, 00 ) == 0 )
\r
560 remove( pcFullLogFileName );
\r
562 rename( pcLogFileName, pcFullLogFileName );
\r
563 ulSizeOfLoggingFile = 0;
\r
567 /*-----------------------------------------------------------*/
\r