2 * FreeRTOS Kernel V10.0.0
\r
3 * Copyright (C) 2017 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. If you wish to use our Amazon
\r
14 * FreeRTOS name, please do so in a fair use way that does not cause confusion.
\r
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
\r
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
\r
18 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
\r
19 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
\r
20 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
\r
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
23 * http://www.FreeRTOS.org
\r
24 * http://aws.amazon.com/freertos
\r
26 * 1 tab == 4 spaces!
\r
30 * Logging utility that allows FreeRTOS tasks to log to a UDP port, stdout, and
\r
31 * disk file without making any Win32 system calls themselves.
\r
33 * Messages logged to a UDP port are sent directly (using FreeRTOS+TCP), but as
\r
34 * FreeRTOS tasks cannot make Win32 system calls messages sent to stdout or a
\r
35 * disk file are sent via a stream buffer to a Win32 thread which then performs
\r
36 * the actual output.
\r
39 /* Standard includes. */
\r
46 /* FreeRTOS includes. */
\r
47 #include <FreeRTOS.h>
\r
50 /* FreeRTOS+TCP includes. */
\r
51 #include "FreeRTOS_IP.h"
\r
52 #include "FreeRTOS_Sockets.h"
\r
53 #include "FreeRTOS_Stream_Buffer.h"
\r
55 /* Demo includes. */
\r
56 #include "demo_logging.h"
\r
58 /*-----------------------------------------------------------*/
\r
60 /* The maximum size to which the log file may grow, before being renamed
\r
62 #define dlLOGGING_FILE_SIZE ( 40ul * 1024ul * 1024ul )
\r
64 /* Dimensions the arrays into which print messages are created. */
\r
65 #define dlMAX_PRINT_STRING_LENGTH 255
\r
67 /* The size of the stream buffer used to pass messages from FreeRTOS tasks to
\r
68 the Win32 thread that is responsible for making any Win32 system calls that are
\r
69 necessary for the selected logging method. */
\r
70 #define dlLOGGING_STREAM_BUFFER_SIZE 32768
\r
72 /* A block time of zero simply means don't block. */
\r
73 #define dlDONT_BLOCK 0
\r
75 /*-----------------------------------------------------------*/
\r
78 * Called from vLoggingInit() to start a new disk log file.
\r
80 static void prvFileLoggingInit( void );
\r
83 * Attempt to write a message to the file.
\r
85 static void prvLogToFile( const char *pcMessage, size_t xLength );
\r
88 * Simply close the logging file, if it is open.
\r
90 static void prvFileClose( void );
\r
93 * Before the scheduler is started this function is called directly. After the
\r
94 * scheduler has started it is called from the Windows thread dedicated to
\r
95 * outputting log messages. Only the windows thread actually performs the
\r
96 * writing so as not to disrupt the simulation by making Windows system calls
\r
97 * from FreeRTOS tasks.
\r
99 static void prvLoggingFlushBuffer( void );
\r
102 * The windows thread that performs the actual writing of messages that require
\r
103 * Win32 system calls. Only the windows thread can make system calls so as not
\r
104 * to disrupt the simulation by making Windows calls from FreeRTOS tasks.
\r
106 static DWORD WINAPI prvWin32LoggingThread( void *pvParam );
\r
109 * Creates the socket to which UDP messages are sent. This function is not
\r
110 * called directly to prevent the print socket being created from within the IP
\r
111 * task - which could result in a deadlock. Instead the function call is
\r
112 * deferred to run in the RTOS daemon task - hence it prototype.
\r
114 static void prvCreatePrintSocket( void *pvParameter1, uint32_t ulParameter2 );
\r
116 /*-----------------------------------------------------------*/
\r
118 /* Windows event used to wake the Win32 thread which performs any logging that
\r
119 needs Win32 system calls. */
\r
120 static void *pvLoggingThreadEvent = NULL;
\r
122 /* Stores the selected logging targets passed in as parameters to the
\r
123 vLoggingInit() function. */
\r
124 BaseType_t xStdoutLoggingUsed = pdFALSE, xDiskFileLoggingUsed = pdFALSE, xUDPLoggingUsed = pdFALSE;
\r
126 /* Circular buffer used to pass messages from the FreeRTOS tasks to the Win32
\r
127 thread that is responsible for making Win32 calls (when stdout or a disk log is
\r
129 static StreamBuffer_t *xLogStreamBuffer = NULL;
\r
131 /* Handle to the file used for logging. This is left open while there are
\r
132 messages waiting to be logged, then closed again in between logs. */
\r
133 static FILE *pxLoggingFileHandle = NULL;
\r
135 /* When true prints are performed directly. After start up xDirectPrint is set
\r
136 to pdFALSE - at which time prints that require Win32 system calls are done by
\r
137 the Win32 thread responsible for logging. */
\r
138 BaseType_t xDirectPrint = pdTRUE;
\r
140 /* File names for the in use and complete (full) log files. */
\r
141 static const char *pcLogFileName = "RTOSDemo.log";
\r
142 static const char *pcFullLogFileName = "RTOSDemo.ful";
\r
144 /* Keep the current file size in a variable, as an optimisation. */
\r
145 static size_t ulSizeOfLoggingFile = 0ul;
\r
147 /* The UDP socket and address on/to which print messages are sent. */
\r
148 Socket_t xPrintSocket = FREERTOS_INVALID_SOCKET;
\r
149 struct freertos_sockaddr xPrintUDPAddress;
\r
151 /*-----------------------------------------------------------*/
\r
153 void vLoggingInit( BaseType_t xLogToStdout, BaseType_t xLogToFile, BaseType_t xLogToUDP, uint32_t ulRemoteIPAddress, uint16_t usRemotePort )
\r
155 /* Can only be called before the scheduler has started. */
\r
156 configASSERT( xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED );
\r
158 #if( ( ipconfigHAS_DEBUG_PRINTF == 1 ) || ( ipconfigHAS_PRINTF == 1 ) )
\r
160 HANDLE Win32Thread;
\r
162 /* Record which output methods are to be used. */
\r
163 xStdoutLoggingUsed = xLogToStdout;
\r
164 xDiskFileLoggingUsed = xLogToFile;
\r
165 xUDPLoggingUsed = xLogToUDP;
\r
167 /* If a disk file is used then initialise it now. */
\r
168 if( xDiskFileLoggingUsed != pdFALSE )
\r
170 prvFileLoggingInit();
\r
173 /* If UDP logging is used then store the address to which the log data
\r
174 will be sent - but don't create the socket yet because the network is
\r
175 not initialised. */
\r
176 if( xUDPLoggingUsed != pdFALSE )
\r
178 /* Set the address to which the print messages are sent. */
\r
179 xPrintUDPAddress.sin_port = FreeRTOS_htons( usRemotePort );
\r
180 xPrintUDPAddress.sin_addr = ulRemoteIPAddress;
\r
183 /* If a disk file or stdout are to be used then Win32 system calls will
\r
184 have to be made. Such system calls cannot be made from FreeRTOS tasks
\r
185 so create a stream buffer to pass the messages to a Win32 thread, then
\r
186 create the thread itself, along with a Win32 event that can be used to
\r
187 unblock the thread. */
\r
188 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) )
\r
190 /* Create the buffer. */
\r
191 xLogStreamBuffer = ( StreamBuffer_t * ) malloc( sizeof( *xLogStreamBuffer ) - sizeof( xLogStreamBuffer->ucArray ) + dlLOGGING_STREAM_BUFFER_SIZE + 1 );
\r
192 configASSERT( xLogStreamBuffer );
\r
193 memset( xLogStreamBuffer, '\0', sizeof( *xLogStreamBuffer ) - sizeof( xLogStreamBuffer->ucArray ) );
\r
194 xLogStreamBuffer->LENGTH = dlLOGGING_STREAM_BUFFER_SIZE + 1;
\r
196 /* Create the Windows event. */
\r
197 pvLoggingThreadEvent = CreateEvent( NULL, FALSE, TRUE, "StdoutLoggingEvent" );
\r
199 /* Create the thread itself. */
\r
200 Win32Thread = CreateThread(
\r
201 NULL, /* Pointer to thread security attributes. */
\r
202 0, /* Initial thread stack size, in bytes. */
\r
203 prvWin32LoggingThread, /* Pointer to thread function. */
\r
204 NULL, /* Argument for new thread. */
\r
205 0, /* Creation flags. */
\r
208 /* Use the cores that are not used by the FreeRTOS tasks. */
\r
209 SetThreadAffinityMask( Win32Thread, ~0x01u );
\r
210 SetThreadPriorityBoost( Win32Thread, TRUE );
\r
211 SetThreadPriority( Win32Thread, THREAD_PRIORITY_IDLE );
\r
216 /* FreeRTOSIPConfig is set such that no print messages will be output.
\r
217 Avoid compiler warnings about unused parameters. */
\r
218 ( void ) xLogToStdout;
\r
219 ( void ) xLogToFile;
\r
220 ( void ) xLogToUDP;
\r
221 ( void ) usRemotePort;
\r
222 ( void ) ulRemoteIPAddress;
\r
224 #endif /* ( ipconfigHAS_DEBUG_PRINTF == 1 ) || ( ipconfigHAS_PRINTF == 1 ) */
\r
226 /*-----------------------------------------------------------*/
\r
228 static void prvCreatePrintSocket( void *pvParameter1, uint32_t ulParameter2 )
\r
230 static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 0 );
\r
233 /* The function prototype is that of a deferred function, but the parameters
\r
234 are not actually used. */
\r
235 ( void ) pvParameter1;
\r
236 ( void ) ulParameter2;
\r
238 xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
\r
240 if( xSocket != FREERTOS_INVALID_SOCKET )
\r
242 /* FreeRTOS+TCP decides which port to bind to. */
\r
243 FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xSendTimeOut ) );
\r
244 FreeRTOS_bind( xSocket, NULL, 0 );
\r
246 /* Now the socket is bound it can be assigned to the print socket. */
\r
247 xPrintSocket = xSocket;
\r
250 /*-----------------------------------------------------------*/
\r
252 void vLoggingPrintf( const char *pcFormat, ... )
\r
254 char cPrintString[ dlMAX_PRINT_STRING_LENGTH ];
\r
255 char cOutputString[ dlMAX_PRINT_STRING_LENGTH ];
\r
256 char *pcSource, *pcTarget, *pcBegin;
\r
257 size_t xLength, xLength2, rc;
\r
258 static BaseType_t xMessageNumber = 0;
\r
260 uint32_t ulIPAddress;
\r
261 const char *pcTaskName;
\r
262 const char *pcNoTask = "None";
\r
263 int iOriginalPriority;
\r
264 HANDLE xCurrentTask;
\r
267 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) || ( xUDPLoggingUsed != pdFALSE ) )
\r
269 /* There are a variable number of parameters. */
\r
270 va_start( args, pcFormat );
\r
272 /* Additional info to place at the start of the log. */
\r
273 if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
\r
275 pcTaskName = pcTaskGetName( NULL );
\r
279 pcTaskName = pcNoTask;
\r
282 if( strcmp( pcFormat, "\n" ) != 0 )
\r
284 xLength = snprintf( cPrintString, dlMAX_PRINT_STRING_LENGTH, "%lu %lu [%s] ",
\r
286 ( unsigned long ) xTaskGetTickCount(),
\r
292 memset( cPrintString, 0x00, dlMAX_PRINT_STRING_LENGTH );
\r
295 xLength2 = vsnprintf( cPrintString + xLength, dlMAX_PRINT_STRING_LENGTH - xLength, pcFormat, args );
\r
300 xLength2 = sizeof( cPrintString ) - 1 - xLength;
\r
301 cPrintString[ sizeof( cPrintString ) - 1 ] = '\0';
\r
304 xLength += xLength2;
\r
307 /* For ease of viewing, copy the string into another buffer, converting
\r
308 IP addresses to dot notation on the way. */
\r
309 pcSource = cPrintString;
\r
310 pcTarget = cOutputString;
\r
312 while( ( *pcSource ) != '\0' )
\r
314 *pcTarget = *pcSource;
\r
318 /* Look forward for an IP address denoted by 'ip'. */
\r
319 if( ( isxdigit( pcSource[ 0 ] ) != pdFALSE ) && ( pcSource[ 1 ] == 'i' ) && ( pcSource[ 2 ] == 'p' ) )
\r
321 *pcTarget = *pcSource;
\r
324 pcBegin = pcTarget - 8;
\r
326 while( ( pcTarget > pcBegin ) && ( isxdigit( pcTarget[ -1 ] ) != pdFALSE ) )
\r
331 sscanf( pcTarget, "%8X", &ulIPAddress );
\r
332 rc = sprintf( pcTarget, "%lu.%lu.%lu.%lu",
\r
333 ( unsigned long ) ( ulIPAddress >> 24UL ),
\r
334 ( unsigned long ) ( (ulIPAddress >> 16UL) & 0xffUL ),
\r
335 ( unsigned long ) ( (ulIPAddress >> 8UL) & 0xffUL ),
\r
336 ( unsigned long ) ( ulIPAddress & 0xffUL ) );
\r
338 pcSource += 3; /* skip "<n>ip" */
\r
342 /* How far through the buffer was written? */
\r
343 xLength = ( BaseType_t ) ( pcTarget - cOutputString );
\r
345 /* If the message is to be logged to a UDP port then it can be sent directly
\r
346 because it only uses FreeRTOS function (not Win32 functions). */
\r
347 if( xUDPLoggingUsed != pdFALSE )
\r
349 if( ( xPrintSocket == FREERTOS_INVALID_SOCKET ) && ( FreeRTOS_IsNetworkUp() != pdFALSE ) )
\r
351 /* Create and bind the socket to which print messages are sent. The
\r
352 xTimerPendFunctionCall() function is used even though this is
\r
353 not an interrupt because this function is called from the IP task
\r
354 and the IP task cannot itself wait for a socket to bind. The
\r
355 parameters to prvCreatePrintSocket() are not required so set to
\r
357 xTimerPendFunctionCall( prvCreatePrintSocket, NULL, 0, dlDONT_BLOCK );
\r
360 if( xPrintSocket != FREERTOS_INVALID_SOCKET )
\r
362 FreeRTOS_sendto( xPrintSocket, cOutputString, xLength, 0, &xPrintUDPAddress, sizeof( xPrintUDPAddress ) );
\r
364 /* Just because the UDP data logger I'm using is dumb. */
\r
365 FreeRTOS_sendto( xPrintSocket, "\r", sizeof( char ), 0, &xPrintUDPAddress, sizeof( xPrintUDPAddress ) );
\r
369 /* If logging is also to go to either stdout or a disk file then it cannot
\r
370 be output here - so instead write the message to the stream buffer and wake
\r
371 the Win32 thread which will read it from the stream buffer and perform the
\r
373 if( ( xStdoutLoggingUsed != pdFALSE ) || ( xDiskFileLoggingUsed != pdFALSE ) )
\r
375 configASSERT( xLogStreamBuffer );
\r
377 /* How much space is in the buffer? */
\r
378 xLength2 = uxStreamBufferGetSpace( xLogStreamBuffer );
\r
380 /* There must be enough space to write both the string and the length of
\r
382 if( xLength2 >= ( xLength + sizeof( xLength ) ) )
\r
384 /* First write in the length of the data, then write in the data
\r
385 itself. Raising the thread priority is used as a critical section
\r
386 as there are potentially multiple writers. The stream buffer is
\r
387 only thread safe when there is a single writer (likewise for
\r
388 reading from the buffer). */
\r
389 xCurrentTask = GetCurrentThread();
\r
390 iOriginalPriority = GetThreadPriority( xCurrentTask );
\r
391 SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL );
\r
392 uxStreamBufferAdd( xLogStreamBuffer, 0, ( const uint8_t * ) &( xLength ), sizeof( xLength ) );
\r
393 uxStreamBufferAdd( xLogStreamBuffer, 0, ( const uint8_t * ) cOutputString, xLength );
\r
394 SetThreadPriority( GetCurrentThread(), iOriginalPriority );
\r
397 /* xDirectPrint is initialised to pdTRUE, and while it remains true the
\r
398 logging output function is called directly. When the system is running
\r
399 the output function cannot be called directly because it would get
\r
400 called from both FreeRTOS tasks and Win32 threads - so instead wake the
\r
401 Win32 thread responsible for the actual output. */
\r
402 if( xDirectPrint != pdFALSE )
\r
404 /* While starting up, the thread which calls prvWin32LoggingThread()
\r
405 is not running yet and xDirectPrint will be pdTRUE. */
\r
406 prvLoggingFlushBuffer();
\r
408 else if( pvLoggingThreadEvent != NULL )
\r
410 /* While running, wake up prvWin32LoggingThread() to send the
\r
412 SetEvent( pvLoggingThreadEvent );
\r
417 /*-----------------------------------------------------------*/
\r
419 static void prvLoggingFlushBuffer( void )
\r
422 char cPrintString[ dlMAX_PRINT_STRING_LENGTH ];
\r
424 /* Is there more than the length value stored in the circular buffer
\r
425 used to pass data from the FreeRTOS simulator into this Win32 thread? */
\r
426 while( uxStreamBufferGetSize( xLogStreamBuffer ) > sizeof( xLength ) )
\r
428 memset( cPrintString, 0x00, dlMAX_PRINT_STRING_LENGTH );
\r
429 uxStreamBufferGet( xLogStreamBuffer, 0, ( uint8_t * ) &xLength, sizeof( xLength ), pdFALSE );
\r
430 uxStreamBufferGet( xLogStreamBuffer, 0, ( uint8_t * ) cPrintString, xLength, pdFALSE );
\r
432 /* Write the message to standard out if requested to do so when
\r
433 vLoggingInit() was called, or if the network is not yet up. */
\r
434 if( ( xStdoutLoggingUsed != pdFALSE ) || ( FreeRTOS_IsNetworkUp() == pdFALSE ) )
\r
436 /* Write the message to stdout. */
\r
437 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