2 * FreeRTOS Kernel V10.2.1
\r
3 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
\r
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
\r
6 * this software and associated documentation files (the "Software"), to deal in
\r
7 * the Software without restriction, including without limitation the rights to
\r
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
\r
9 * the Software, and to permit persons to whom the Software is furnished to do so,
\r
10 * subject to the following conditions:
\r
12 * The above copyright notice and this permission notice shall be included in all
\r
13 * copies or substantial portions of the Software.
\r
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
\r
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
\r
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
\r
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
\r
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
\r
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
22 * http://www.FreeRTOS.org
\r
23 * http://aws.amazon.com/freertos
\r
25 * 1 tab == 4 spaces!
\r
29 * Logging utility that allows FreeRTOS tasks to log to a UDP port, stdout, and
\r
30 * disk file without making any Win32 system calls themselves.
\r
32 * Messages logged to a UDP port are sent directly (using FreeRTOS+TCP), but as
\r
33 * FreeRTOS tasks cannot make Win32 system calls messages sent to stdout or a
\r
34 * disk file are sent via a stream buffer to a Win32 thread which then performs
\r
35 * the actual output.
\r
38 /* Standard includes. */
\r
45 /* FreeRTOS includes. */
\r
46 #include <FreeRTOS.h>
\r
49 /* FreeRTOS+TCP includes. */
\r
50 #include "FreeRTOS_IP.h"
\r
51 #include "FreeRTOS_Sockets.h"
\r
52 #include "FreeRTOS_Stream_Buffer.h"
\r
54 /* Demo includes. */
\r
55 #include "demo_logging.h"
\r
57 /*-----------------------------------------------------------*/
\r
59 /* The maximum size to which the log file may grow, before being renamed
\r
61 #define dlLOGGING_FILE_SIZE ( 40ul * 1024ul * 1024ul )
\r
63 /* Dimensions the arrays into which print messages are created. */
\r
64 #define dlMAX_PRINT_STRING_LENGTH 255
\r
66 /* The size of the stream buffer used to pass messages from FreeRTOS tasks to
\r
67 the Win32 thread that is responsible for making any Win32 system calls that are
\r
68 necessary for the selected logging method. */
\r
69 #define dlLOGGING_STREAM_BUFFER_SIZE 32768
\r
71 /* A block time of zero simply means don't block. */
\r
72 #define dlDONT_BLOCK 0
\r
74 /*-----------------------------------------------------------*/
\r
77 * Called from vLoggingInit() to start a new disk log file.
\r
79 static void prvFileLoggingInit( void );
\r
82 * Attempt to write a message to the file.
\r
84 static void prvLogToFile( const char *pcMessage, size_t xLength );
\r
87 * Simply close the logging file, if it is open.
\r
89 static void prvFileClose( void );
\r
92 * Before the scheduler is started this function is called directly. After the
\r
93 * scheduler has started it is called from the Windows thread dedicated to
\r
94 * outputting log messages. Only the windows thread actually performs the
\r
95 * writing so as not to disrupt the simulation by making Windows system calls
\r
96 * from FreeRTOS tasks.
\r
98 static void prvLoggingFlushBuffer( void );
\r
101 * The windows thread that performs the actual writing of messages that require
\r
102 * Win32 system calls. Only the windows thread can make system calls so as not
\r
103 * to disrupt the simulation by making Windows calls from FreeRTOS tasks.
\r
105 static DWORD WINAPI prvWin32LoggingThread( void *pvParam );
\r
108 * Creates the socket to which UDP messages are sent. This function is not
\r
109 * called directly to prevent the print socket being created from within the IP
\r
110 * task - which could result in a deadlock. Instead the function call is
\r
111 * deferred to run in the RTOS daemon task - hence it prototype.
\r
113 static void prvCreatePrintSocket( void *pvParameter1, uint32_t ulParameter2 );
\r
115 /*-----------------------------------------------------------*/
\r
117 /* Windows event used to wake the Win32 thread which performs any logging that
\r
118 needs Win32 system calls. */
\r
119 static void *pvLoggingThreadEvent = NULL;
\r
121 /* Stores the selected logging targets passed in as parameters to the
\r
122 vLoggingInit() function. */
\r
123 BaseType_t xStdoutLoggingUsed = pdFALSE, xDiskFileLoggingUsed = pdFALSE, xUDPLoggingUsed = pdFALSE;
\r
125 /* Circular buffer used to pass messages from the FreeRTOS tasks to the Win32
\r
126 thread that is responsible for making Win32 calls (when stdout or a disk log is
\r
128 static StreamBuffer_t *xLogStreamBuffer = NULL;
\r
130 /* Handle to the file used for logging. This is left open while there are
\r
131 messages waiting to be logged, then closed again in between logs. */
\r
132 static FILE *pxLoggingFileHandle = NULL;
\r
134 /* When true prints are performed directly. After start up xDirectPrint is set
\r
135 to pdFALSE - at which time prints that require Win32 system calls are done by
\r
136 the Win32 thread responsible for logging. */
\r
137 BaseType_t xDirectPrint = pdTRUE;
\r
139 /* File names for the in use and complete (full) log files. */
\r
140 static const char *pcLogFileName = "RTOSDemo.log";
\r
141 static const char *pcFullLogFileName = "RTOSDemo.ful";
\r
143 /* As an optimization, the current file size is kept in a variable. */
\r
144 static size_t ulSizeOfLoggingFile = 0ul;
\r
146 /* The UDP socket and address on/to which print messages are sent. */
\r
147 Socket_t xPrintSocket = FREERTOS_INVALID_SOCKET;
\r
148 struct freertos_sockaddr xPrintUDPAddress;
\r
150 /*-----------------------------------------------------------*/
\r
152 void vLoggingInit( BaseType_t xLogToStdout, BaseType_t xLogToFile, BaseType_t xLogToUDP, uint32_t ulRemoteIPAddress, uint16_t usRemotePort )
\r
154 /* Can only be called before the scheduler has started. */
\r
155 configASSERT( xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED );
\r
157 #if( ( ipconfigHAS_DEBUG_PRINTF == 1 ) || ( ipconfigHAS_PRINTF == 1 ) )
\r
159 HANDLE Win32Thread;
\r
161 /* Record which output methods are to be used. */
\r
162 xStdoutLoggingUsed = xLogToStdout;
\r
163 xDiskFileLoggingUsed = xLogToFile;
\r
164 xUDPLoggingUsed = xLogToUDP;
\r
166 /* If a disk file is used then initialize it now. */
\r
167 if( xDiskFileLoggingUsed != pdFALSE )
\r
169 prvFileLoggingInit();
\r
172 /* If UDP logging is used then store the address to which the log data
\r
173 will be sent - but don't create the socket yet because the network is
\r
174 not initialized. */
\r
175 if( xUDPLoggingUsed != pdFALSE )
\r
177 /* Set the address to which the print messages are sent. */
\r
178 xPrintUDPAddress.sin_port = FreeRTOS_htons( usRemotePort );
\r
179 xPrintUDPAddress.sin_addr = ulRemoteIPAddress;
\r
182 /* If a disk file or stdout are to be used then Win32 system calls will
\r
183 have to be made. Such system calls cannot be made from FreeRTOS tasks
\r
184 so create a stream buffer to pass the messages to a Win32 thread, then
\r
185 create the thread itself, along with a Win32 event that can be used to
\r
186 unblock the thread. */
\r
187 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) )
\r
189 /* Create the buffer. */
\r
190 xLogStreamBuffer = ( StreamBuffer_t * ) malloc( sizeof( *xLogStreamBuffer ) - sizeof( xLogStreamBuffer->ucArray ) + dlLOGGING_STREAM_BUFFER_SIZE + 1 );
\r
191 configASSERT( xLogStreamBuffer );
\r
192 memset( xLogStreamBuffer, '\0', sizeof( *xLogStreamBuffer ) - sizeof( xLogStreamBuffer->ucArray ) );
\r
193 xLogStreamBuffer->LENGTH = dlLOGGING_STREAM_BUFFER_SIZE + 1;
\r
195 /* Create the Windows event. */
\r
196 pvLoggingThreadEvent = CreateEvent( NULL, FALSE, TRUE, "StdoutLoggingEvent" );
\r
198 /* Create the thread itself. */
\r
199 Win32Thread = CreateThread(
\r
200 NULL, /* Pointer to thread security attributes. */
\r
201 0, /* Initial thread stack size, in bytes. */
\r
202 prvWin32LoggingThread, /* Pointer to thread function. */
\r
203 NULL, /* Argument for new thread. */
\r
204 0, /* Creation flags. */
\r
207 /* Use the cores that are not used by the FreeRTOS tasks. */
\r
208 SetThreadAffinityMask( Win32Thread, ~0x01u );
\r
209 SetThreadPriorityBoost( Win32Thread, TRUE );
\r
210 SetThreadPriority( Win32Thread, THREAD_PRIORITY_IDLE );
\r
215 /* FreeRTOSIPConfig is set such that no print messages will be output.
\r
216 Avoid compiler warnings about unused parameters. */
\r
217 ( void ) xLogToStdout;
\r
218 ( void ) xLogToFile;
\r
219 ( void ) xLogToUDP;
\r
220 ( void ) usRemotePort;
\r
221 ( void ) ulRemoteIPAddress;
\r
223 #endif /* ( ipconfigHAS_DEBUG_PRINTF == 1 ) || ( ipconfigHAS_PRINTF == 1 ) */
\r
225 /*-----------------------------------------------------------*/
\r
227 static void prvCreatePrintSocket( void *pvParameter1, uint32_t ulParameter2 )
\r
229 static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 0 );
\r
232 /* The function prototype is that of a deferred function, but the parameters
\r
233 are not actually used. */
\r
234 ( void ) pvParameter1;
\r
235 ( void ) ulParameter2;
\r
237 xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
\r
239 if( xSocket != FREERTOS_INVALID_SOCKET )
\r
241 /* FreeRTOS+TCP decides which port to bind to. */
\r
242 FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xSendTimeOut ) );
\r
243 FreeRTOS_bind( xSocket, NULL, 0 );
\r
245 /* Now the socket is bound it can be assigned to the print socket. */
\r
246 xPrintSocket = xSocket;
\r
249 /*-----------------------------------------------------------*/
\r
251 void vLoggingPrintf( const char *pcFormat, ... )
\r
253 char cPrintString[ dlMAX_PRINT_STRING_LENGTH ];
\r
254 char cOutputString[ dlMAX_PRINT_STRING_LENGTH ];
\r
255 char *pcSource, *pcTarget, *pcBegin;
\r
256 size_t xLength, xLength2, rc;
\r
257 static BaseType_t xMessageNumber = 0;
\r
259 uint32_t ulIPAddress;
\r
260 const char *pcTaskName;
\r
261 const char *pcNoTask = "None";
\r
262 int iOriginalPriority;
\r
263 HANDLE xCurrentTask;
\r
266 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) || ( xUDPLoggingUsed != pdFALSE ) )
\r
268 /* There are a variable number of parameters. */
\r
269 va_start( args, pcFormat );
\r
271 /* Additional info to place at the start of the log. */
\r
272 if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
\r
274 pcTaskName = pcTaskGetName( NULL );
\r
278 pcTaskName = pcNoTask;
\r
281 if( strcmp( pcFormat, "\n" ) != 0 )
\r
283 xLength = snprintf( cPrintString, dlMAX_PRINT_STRING_LENGTH, "%lu %lu [%s] ",
\r
285 ( unsigned long ) xTaskGetTickCount(),
\r
291 memset( cPrintString, 0x00, dlMAX_PRINT_STRING_LENGTH );
\r
294 xLength2 = vsnprintf( cPrintString + xLength, dlMAX_PRINT_STRING_LENGTH - xLength, pcFormat, args );
\r
299 xLength2 = dlMAX_PRINT_STRING_LENGTH - 1 - xLength;
\r
300 cPrintString[ dlMAX_PRINT_STRING_LENGTH - 1 ] = '\0';
\r
303 xLength += xLength2;
\r
306 /* For ease of viewing, copy the string into another buffer, converting
\r
307 IP addresses to dot notation on the way. */
\r
308 pcSource = cPrintString;
\r
309 pcTarget = cOutputString;
\r
311 while( ( *pcSource ) != '\0' )
\r
313 *pcTarget = *pcSource;
\r
317 /* Look forward for an IP address denoted by 'ip'. */
\r
318 if( ( isxdigit( pcSource[ 0 ] ) != pdFALSE ) && ( pcSource[ 1 ] == 'i' ) && ( pcSource[ 2 ] == 'p' ) )
\r
320 *pcTarget = *pcSource;
\r
323 pcBegin = pcTarget - 8;
\r
325 while( ( pcTarget > pcBegin ) && ( isxdigit( pcTarget[ -1 ] ) != pdFALSE ) )
\r
330 sscanf( pcTarget, "%8X", &ulIPAddress );
\r
331 rc = sprintf( pcTarget, "%lu.%lu.%lu.%lu",
\r
332 ( unsigned long ) ( ulIPAddress >> 24UL ),
\r
333 ( unsigned long ) ( (ulIPAddress >> 16UL) & 0xffUL ),
\r
334 ( unsigned long ) ( (ulIPAddress >> 8UL) & 0xffUL ),
\r
335 ( unsigned long ) ( ulIPAddress & 0xffUL ) );
\r
337 pcSource += 3; /* skip "<n>ip" */
\r
341 /* How far through the buffer was written? */
\r
342 xLength = ( BaseType_t ) ( pcTarget - cOutputString );
\r
344 /* If the message is to be logged to a UDP port then it can be sent directly
\r
345 because it only uses FreeRTOS function (not Win32 functions). */
\r
346 if( xUDPLoggingUsed != pdFALSE )
\r
348 if( ( xPrintSocket == FREERTOS_INVALID_SOCKET ) && ( FreeRTOS_IsNetworkUp() != pdFALSE ) )
\r
350 /* Create and bind the socket to which print messages are sent. The
\r
351 xTimerPendFunctionCall() function is used even though this is
\r
352 not an interrupt because this function is called from the IP task
\r
353 and the IP task cannot itself wait for a socket to bind. The
\r
354 parameters to prvCreatePrintSocket() are not required so set to
\r
356 xTimerPendFunctionCall( prvCreatePrintSocket, NULL, 0, dlDONT_BLOCK );
\r
359 if( xPrintSocket != FREERTOS_INVALID_SOCKET )
\r
361 FreeRTOS_sendto( xPrintSocket, cOutputString, xLength, 0, &xPrintUDPAddress, sizeof( xPrintUDPAddress ) );
\r
363 /* Just because the UDP data logger I'm using is dumb. */
\r
364 FreeRTOS_sendto( xPrintSocket, "\r", sizeof( char ), 0, &xPrintUDPAddress, sizeof( xPrintUDPAddress ) );
\r
368 /* If logging is also to go to either stdout or a disk file then it cannot
\r
369 be output here - so instead write the message to the stream buffer and wake
\r
370 the Win32 thread which will read it from the stream buffer and perform the
\r
372 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) )
\r
374 configASSERT( xLogStreamBuffer );
\r
376 /* How much space is in the buffer? */
\r
377 xLength2 = uxStreamBufferGetSpace( xLogStreamBuffer );
\r
379 /* There must be enough space to write both the string and the length of
\r
381 if( xLength2 >= ( xLength + sizeof( xLength ) ) )
\r
383 /* First write in the length of the data, then write in the data
\r
384 itself. Raising the thread priority is used as a critical section
\r
385 as there are potentially multiple writers. The stream buffer is
\r
386 only thread safe when there is a single writer (likewise for
\r
387 reading from the buffer). */
\r
388 xCurrentTask = GetCurrentThread();
\r
389 iOriginalPriority = GetThreadPriority( xCurrentTask );
\r
390 SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL );
\r
391 uxStreamBufferAdd( xLogStreamBuffer, 0, ( const uint8_t * ) &( xLength ), sizeof( xLength ) );
\r
392 uxStreamBufferAdd( xLogStreamBuffer, 0, ( const uint8_t * ) cOutputString, xLength );
\r
393 SetThreadPriority( GetCurrentThread(), iOriginalPriority );
\r
396 /* xDirectPrint is initialized to pdTRUE, and while it remains true the
\r
397 logging output function is called directly. When the system is running
\r
398 the output function cannot be called directly because it would get
\r
399 called from both FreeRTOS tasks and Win32 threads - so instead wake the
\r
400 Win32 thread responsible for the actual output. */
\r
401 if( xDirectPrint != pdFALSE )
\r
403 /* While starting up, the thread which calls prvWin32LoggingThread()
\r
404 is not running yet and xDirectPrint will be pdTRUE. */
\r
405 prvLoggingFlushBuffer();
\r
407 else if( pvLoggingThreadEvent != NULL )
\r
409 /* While running, wake up prvWin32LoggingThread() to send the
\r
411 SetEvent( pvLoggingThreadEvent );
\r
416 /*-----------------------------------------------------------*/
\r
418 static void prvLoggingFlushBuffer( void )
\r
421 char cPrintString[ dlMAX_PRINT_STRING_LENGTH ];
\r
423 /* Is there more than the length value stored in the circular buffer
\r
424 used to pass data from the FreeRTOS simulator into this Win32 thread? */
\r
425 while( uxStreamBufferGetSize( xLogStreamBuffer ) > sizeof( xLength ) )
\r
427 memset( cPrintString, 0x00, dlMAX_PRINT_STRING_LENGTH );
\r
428 uxStreamBufferGet( xLogStreamBuffer, 0, ( uint8_t * ) &xLength, sizeof( xLength ), pdFALSE );
\r
429 uxStreamBufferGet( xLogStreamBuffer, 0, ( uint8_t * ) cPrintString, xLength, pdFALSE );
\r
431 /* Write the message to standard out if requested to do so when
\r
432 vLoggingInit() was called, or if the network is not yet up. */
\r
433 if( ( xStdoutLoggingUsed != pdFALSE ) || ( FreeRTOS_IsNetworkUp() == pdFALSE ) )
\r
435 /* Write the message to stdout. */
\r
436 printf( "%s", cPrintString ); /*_RB_ Replace with _write(). */
\r
440 /* Write the message to a file if requested to do so when
\r
441 vLoggingInit() was called. */
\r
442 if( xDiskFileLoggingUsed != pdFALSE )
\r
444 prvLogToFile( cPrintString, xLength );
\r
450 /*-----------------------------------------------------------*/
\r
452 static DWORD WINAPI prvWin32LoggingThread( void *pvParameter )
\r
454 const DWORD xMaxWait = 1000;
\r
456 ( void ) pvParameter;
\r
458 /* From now on, prvLoggingFlushBuffer() will only be called from this
\r
460 xDirectPrint = pdFALSE;
\r
464 /* Wait to be told there are message waiting to be logged. */
\r
465 WaitForSingleObject( pvLoggingThreadEvent, xMaxWait );
\r
467 /* Write out all waiting messages. */
\r
468 prvLoggingFlushBuffer();
\r
471 /*-----------------------------------------------------------*/
\r
473 static void prvFileLoggingInit( void )
\r
475 FILE *pxHandle = fopen( pcLogFileName, "a" );
\r
477 if( pxHandle != NULL )
\r
479 fseek( pxHandle, SEEK_END, 0ul );
\r
480 ulSizeOfLoggingFile = ftell( pxHandle );
\r
481 fclose( pxHandle );
\r
485 ulSizeOfLoggingFile = 0ul;
\r
488 /*-----------------------------------------------------------*/
\r
490 static void prvFileClose( void )
\r
492 if( pxLoggingFileHandle != NULL )
\r
494 fclose( pxLoggingFileHandle );
\r
495 pxLoggingFileHandle = NULL;
\r
498 /*-----------------------------------------------------------*/
\r
500 static void prvLogToFile( const char *pcMessage, size_t xLength )
\r
502 if( pxLoggingFileHandle == NULL )
\r
504 pxLoggingFileHandle = fopen( pcLogFileName, "a" );
\r
507 if( pxLoggingFileHandle != NULL )
\r
509 fwrite( pcMessage, 1, xLength, pxLoggingFileHandle );
\r
510 ulSizeOfLoggingFile += xLength;
\r
512 /* If the file has grown to its maximum permissible size then close and
\r
513 rename it - then start with a new file. */
\r
514 if( ulSizeOfLoggingFile > ( size_t ) dlLOGGING_FILE_SIZE )
\r
517 if( _access( pcFullLogFileName, 00 ) == 0 )
\r
519 remove( pcFullLogFileName );
\r
521 rename( pcLogFileName, pcFullLogFileName );
\r
522 ulSizeOfLoggingFile = 0;
\r
526 /*-----------------------------------------------------------*/
\r