/* * FreeRTOS V1.4.7 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /* * Debug setup instructions: * 1) Open the debug configuration dialog. * 2) Go to the Debugger tab. * 3) If the 'Mode Setup' options are not visible, click the 'Show Generator' button. * 4) In the Mode Setup|Reset Mode drop down ensure that * 'Software System Reset' is selected. */ #include "board_init.h" #include "stdint.h" #include "stdarg.h" /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" /* Includes for Logging task intiialization. */ #include "iot_logging_task.h" /* Add includes for LoRaWAN. */ #include "utilities.h" #include "gpio.h" #include "spi.h" #include "board-config.h" /* Include specific to the LoRa Shield used. */ #if defined( SX1261MBXBAS ) || defined( SX1262MBXCAS ) || defined( SX1262MBXDAS ) #include "sx126x-board.h" #elif defined( LR1110MB1XXS ) #include "lr1110-board.h" #elif defined( SX1272MB2DAS) #include "sx1272-board.h" #elif defined( SX1276MB1LAS ) || defined( SX1276MB1MAS ) #include "sx1276-board.h" #endif /* * Unique Devices IDs register set for STM32L4xxx. Used to calculate the board specific unique ID. */ #define ID1 ( 0x1FFF7590 ) #define ID2 ( 0x1FFF7594 ) #define ID3 ( 0x1FFF7594 ) /* The SPI driver polls at a high priority. The logging task's priority must also * be high to be not be starved of CPU time. */ #define mainLOGGING_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) #define mainLOGGING_TASK_STACK_SIZE ( configMINIMAL_STACK_SIZE * 5 ) #define mainLOGGING_MESSAGE_QUEUE_LENGTH ( 15 ) /*-----------------------------------------------------------*/ void vApplicationDaemonTaskStartupHook( void ); /********************** * Global Variables **********************/ RTC_HandleTypeDef xHrtc; RNG_HandleTypeDef xHrng; /* Private variables ---------------------------------------------------------*/ static UART_HandleTypeDef xConsoleUart; /* Private function prototypes -----------------------------------------------*/ static void SystemClock_Config( void ); static void Console_UART_Init( void ); static void RTC_Init( void ); /** * @brief Initializes the STM32L475 IoT node board. * * Initialization of clock, LEDs, RNG, RTC, and WIFI module. */ static void prvMiscInitialization( void ); /** * @brief Initialization of LoraWAN radio. * */ static void prvLoraWanRadioInit( void ); /** * @brief De-Initialization of LoraWAN radio. * */ static void prvLoraWanDeinit( void ); /** * @brief Initializes the FreeRTOS heap. * * Heap_5 is being used because the RAM is not contiguous, therefore the heap * needs to be initialized. See http://www.freertos.org/a00111.html */ static void prvInitializeHeap( void ); /*-----------------------------------------------------------*/ /** * @brief Application runtime entry point. */ void board_init( void ) { /* Perform any hardware initialization that does not require the RTOS to be * running. */ prvMiscInitialization(); /* Create tasks that are not dependent on the WiFi being initialized. */ xLoggingTaskInitialize( mainLOGGING_TASK_STACK_SIZE, mainLOGGING_TASK_PRIORITY, mainLOGGING_MESSAGE_QUEUE_LENGTH ); } /*-----------------------------------------------------------*/ void vApplicationDaemonTaskStartupHook( void ) { } /*-----------------------------------------------------------*/ /* configUSE_STATIC_ALLOCATION is set to 1, so the application must provide an * implementation of vApplicationGetIdleTaskMemory() to provide the memory that is * used by the Idle task. */ void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, StackType_t ** ppxIdleTaskStackBuffer, uint32_t * pulIdleTaskStackSize ) { /* If the buffers to be provided to the Idle task are declared inside this * function then they must be declared static - otherwise they will be allocated on * the stack and so not exists after this function exits. */ static StaticTask_t xIdleTaskTCB; static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ]; /* Pass out a pointer to the StaticTask_t structure in which the Idle * task's state will be stored. */ *ppxIdleTaskTCBBuffer = &xIdleTaskTCB; /* Pass out the array that will be used as the Idle task's stack. */ *ppxIdleTaskStackBuffer = uxIdleTaskStack; /* Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer. * Note that, as the array is necessarily of type StackType_t, * configMINIMAL_STACK_SIZE is specified in words, not bytes. */ *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; } /*-----------------------------------------------------------*/ /* configUSE_STATIC_ALLOCATION is set to 1, so the application must provide an * implementation of vApplicationGetTimerTaskMemory() to provide the memory that is * used by the RTOS daemon/time task. */ void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, StackType_t ** ppxTimerTaskStackBuffer, uint32_t * pulTimerTaskStackSize ) { /* If the buffers to be provided to the Timer task are declared inside this * function then they must be declared static - otherwise they will be allocated on * the stack and so not exists after this function exits. */ static StaticTask_t xTimerTaskTCB; static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ]; /* Pass out a pointer to the StaticTask_t structure in which the Idle * task's state will be stored. */ *ppxTimerTaskTCBBuffer = &xTimerTaskTCB; /* Pass out the array that will be used as the Timer task's stack. */ *ppxTimerTaskStackBuffer = uxTimerTaskStack; /* Pass out the size of the array pointed to by *ppxTimerTaskStackBuffer. * Note that, as the array is necessarily of type StackType_t, * configMINIMAL_STACK_SIZE is specified in words, not bytes. */ *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; } /*-----------------------------------------------------------*/ /** * @brief Publishes a character to the STM32L475 UART * * This is used to implement the tinyprintf created by Spare Time Labs * http://www.sparetimelabs.com/tinyprintf/tinyprintf.php * * @param pv unused void pointer for compliance with tinyprintf * @param ch character to be printed */ void vSTM32L475putc( void * pv, char ch ) { while( HAL_OK != HAL_UART_Transmit( &xConsoleUart, ( uint8_t * ) &ch, 1, 30000 ) ) { } } /*-----------------------------------------------------------*/ /** * @brief Initializes the board. */ static void prvMiscInitialization( void ) { /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* Configure the system clock. */ SystemClock_Config(); /* Heap_5 is being used because the RAM is not contiguous in memory, so the * heap must be initialized. */ prvInitializeHeap(); BSP_LED_Init( LED_GREEN ); BSP_PB_Init( BUTTON_USER, BUTTON_MODE_EXTI ); /* RNG init function. */ xHrng.Instance = RNG; if( HAL_RNG_Init( &xHrng ) != HAL_OK ) { Error_Handler(); } /* RTC init. */ RTC_Init(); /* UART console init. */ Console_UART_Init(); prvLoraWanRadioInit(); } static void BoardUnusedIoInit( void ) { HAL_DBGMCU_EnableDBGSleepMode( ); HAL_DBGMCU_EnableDBGStopMode( ); HAL_DBGMCU_EnableDBGStandbyMode( ); } static void prvLoraWanRadioInit( void ) { #if defined( SX1261MBXBAS ) || defined( SX1262MBXCAS ) || defined( SX1262MBXDAS ) SpiInit( &SX126x.Spi, SPI_1, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC ); SX126xIoInit( ); #elif defined( LR1110MB1XXS ) SpiInit( &LR1110.spi, SPI_1, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC ); lr1110_board_init_io( &LR1110 ); #elif defined( SX1272MB2DAS ) SpiInit( &SX1272.Spi, SPI_1, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC ); SX1272IoInit( ); #elif defined( SX1276MB1LAS ) || defined( SX1276MB1MAS ) SpiInit( &SX1276.Spi, SPI_1, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC ); SX1276IoInit( ); #endif BoardUnusedIoInit(); #if defined( SX1261MBXBAS ) || defined( SX1262MBXCAS ) || defined( SX1262MBXDAS ) SX126xIoDbgInit( ); // WARNING: If necessary the TCXO control is initialized by SX126xInit function. #elif defined( LR1110MB1XXS ) lr1110_board_init_dbg_io( &LR1110 ); // WARNING: If necessary the TCXO control is initialized by SX126xInit function. #elif defined( SX1272MB2DAS ) SX1272IoDbgInit( ); SX1272IoTcxoInit( ); #elif defined( SX1276MB1LAS ) || defined( SX1276MB1MAS ) SX1276IoDbgInit( ); SX1276IoTcxoInit( ); #endif } static void prvLoraWanDeinit( void ) { #if defined( SX1261MBXBAS ) || defined( SX1262MBXCAS ) || defined( SX1262MBXDAS ) SpiDeInit( &SX126x.Spi ); SX126xIoDeInit( ); #elif defined( LR1110MB1XXS ) SpiDeInit( &LR1110.spi ); lr1110_board_deinit_io( &LR1110 ); #elif defined( SX1272MB2DAS ) SpiDeInit( &SX1272.Spi ); SX1272IoDeInit( ); #elif defined( SX1276MB1LAS ) || defined( SX1276MB1MAS ) SpiDeInit( &SX1276.Spi ); SX1276IoDeInit( ); #endif } /*-----------------------------------------------------------*/ /** * @brief Initializes the system clock. */ static void SystemClock_Config( void ) { RCC_OscInitTypeDef xRCC_OscInitStruct; RCC_ClkInitTypeDef xRCC_ClkInitStruct; RCC_PeriphCLKInitTypeDef xPeriphClkInit; xRCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI; xRCC_OscInitStruct.LSEState = RCC_LSE_ON; xRCC_OscInitStruct.MSIState = RCC_MSI_ON; xRCC_OscInitStruct.MSICalibrationValue = 0; xRCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11; xRCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; xRCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; xRCC_OscInitStruct.PLL.PLLM = 6; xRCC_OscInitStruct.PLL.PLLN = 20; xRCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7; xRCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; xRCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; if( HAL_RCC_OscConfig( &xRCC_OscInitStruct ) != HAL_OK ) { Error_Handler(); } /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 * clocks dividers. */ xRCC_ClkInitStruct.ClockType = ( RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2 ); xRCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; xRCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; xRCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; xRCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if( HAL_RCC_ClockConfig( &xRCC_ClkInitStruct, FLASH_LATENCY_4 ) != HAL_OK ) { Error_Handler(); } xPeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_RNG; xPeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2; xPeriphClkInit.Usart3ClockSelection = RCC_USART3CLKSOURCE_PCLK1; xPeriphClkInit.I2c2ClockSelection = RCC_I2C2CLKSOURCE_PCLK1; xPeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; xPeriphClkInit.RngClockSelection = RCC_RNGCLKSOURCE_MSI; if( HAL_RCCEx_PeriphCLKConfig( &xPeriphClkInit ) != HAL_OK ) { Error_Handler(); } __HAL_RCC_PWR_CLK_ENABLE(); if( HAL_PWREx_ControlVoltageScaling( PWR_REGULATOR_VOLTAGE_SCALE1 ) != HAL_OK ) { Error_Handler(); } /* Enable MSI PLL mode. */ HAL_RCCEx_EnableMSIPLLMode(); } /*-----------------------------------------------------------*/ /** * @brief UART console initialization function. */ static void Console_UART_Init( void ) { xConsoleUart.Instance = USART1; xConsoleUart.Init.BaudRate = 115200; xConsoleUart.Init.WordLength = UART_WORDLENGTH_8B; xConsoleUart.Init.StopBits = UART_STOPBITS_1; xConsoleUart.Init.Parity = UART_PARITY_NONE; xConsoleUart.Init.Mode = UART_MODE_TX_RX; xConsoleUart.Init.HwFlowCtl = UART_HWCONTROL_NONE; xConsoleUart.Init.OverSampling = UART_OVERSAMPLING_16; xConsoleUart.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE; xConsoleUart.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT; BSP_COM_Init( COM1, &xConsoleUart ); } /*-----------------------------------------------------------*/ /** * @brief RTC init function. */ static void RTC_Init( void ) { RTC_TimeTypeDef xsTime; RTC_DateTypeDef xsDate; /* Initialize RTC Only. */ xHrtc.Instance = RTC; xHrtc.Init.HourFormat = RTC_HOURFORMAT_24; xHrtc.Init.AsynchPrediv = 127; xHrtc.Init.SynchPrediv = 255; xHrtc.Init.OutPut = RTC_OUTPUT_DISABLE; xHrtc.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE; xHrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; xHrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; if( HAL_RTC_Init( &xHrtc ) != HAL_OK ) { Error_Handler(); } /* Initialize RTC and set the Time and Date. */ xsTime.Hours = 0x12; xsTime.Minutes = 0x0; xsTime.Seconds = 0x0; xsTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; xsTime.StoreOperation = RTC_STOREOPERATION_RESET; if( HAL_RTC_SetTime( &xHrtc, &xsTime, RTC_FORMAT_BCD ) != HAL_OK ) { Error_Handler(); } xsDate.WeekDay = RTC_WEEKDAY_FRIDAY; xsDate.Month = RTC_MONTH_JANUARY; xsDate.Date = 0x24; xsDate.Year = 0x17; if( HAL_RTC_SetDate( &xHrtc, &xsDate, RTC_FORMAT_BCD ) != HAL_OK ) { Error_Handler(); } } /*-----------------------------------------------------------*/ /** * @brief This function is executed in case of error occurrence. */ void Error_Handler( void ) { while( 1 ) { BSP_LED_Toggle( LED_GREEN ); HAL_Delay( 200 ); } } /*-----------------------------------------------------------*/ /** * @brief Warn user if pvPortMalloc fails. * * Called if a call to pvPortMalloc() fails because there is insufficient * free memory available in the FreeRTOS heap. pvPortMalloc() is called * internally by FreeRTOS API functions that create tasks, queues, software * timers, and semaphores. The size of the FreeRTOS heap is set by the * configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. * */ void vApplicationMallocFailedHook() { taskDISABLE_INTERRUPTS(); for( ; ; ) { } } /*-----------------------------------------------------------*/ /** * @brief Loop forever if stack overflow is detected. * * If configCHECK_FOR_STACK_OVERFLOW is set to 1, * this hook provides a location for applications to * define a response to a stack overflow. * * Use this hook to help identify that a stack overflow * has occurred. * */ void vApplicationStackOverflowHook( TaskHandle_t xTask, char * pcTaskName ) { portDISABLE_INTERRUPTS(); /* Loop forever */ for( ; ; ) { } } /*-----------------------------------------------------------*/ void vApplicationIdleHook( void ) { } /*-----------------------------------------------------------*/ void * malloc( size_t xSize ) { configASSERT( xSize == ~0 ); return NULL; } /*-----------------------------------------------------------*/ void vOutputChar( const char cChar, const TickType_t xTicksToWait ) { ( void ) cChar; ( void ) xTicksToWait; } /*-----------------------------------------------------------*/ void vMainUARTPrintString( char * pcString ) { const uint32_t ulTimeout = 3000UL; HAL_UART_Transmit( &xConsoleUart, ( uint8_t * ) pcString, strlen( pcString ), ulTimeout ); } /*-----------------------------------------------------------*/ void prvGetRegistersFromStack( uint32_t * pulFaultStackAddress ) { /* These are volatile to try and prevent the compiler/linker optimising them * away as the variables never actually get used. If the debugger won't show the * values of the variables, make them global my moving their declaration outside * of this function. */ volatile uint32_t r0; volatile uint32_t r1; volatile uint32_t r2; volatile uint32_t r3; volatile uint32_t r12; volatile uint32_t lr; /* Link register. */ volatile uint32_t pc; /* Program counter. */ volatile uint32_t psr; /* Program status register. */ r0 = pulFaultStackAddress[ 0 ]; r1 = pulFaultStackAddress[ 1 ]; r2 = pulFaultStackAddress[ 2 ]; r3 = pulFaultStackAddress[ 3 ]; r12 = pulFaultStackAddress[ 4 ]; lr = pulFaultStackAddress[ 5 ]; pc = pulFaultStackAddress[ 6 ]; psr = pulFaultStackAddress[ 7 ]; /* Remove compiler warnings about the variables not being used. */ ( void ) r0; ( void ) r1; ( void ) r2; ( void ) r3; ( void ) r12; ( void ) lr; /* Link register. */ ( void ) pc; /* Program counter. */ ( void ) psr; /* Program status register. */ /* When the following line is hit, the variables contain the register values. */ for( ; ; ) { } } /*-----------------------------------------------------------*/ /* The fault handler implementation calls a function called * prvGetRegistersFromStack(). */ void HardFault_Handler( void ) { __asm volatile ( " tst lr, #4 \n" " ite eq \n" " mrseq r0, msp \n" " mrsne r0, psp \n" " ldr r1, [r0, #24] \n" " ldr r2, handler2_address_const \n" " bx r2 \n" " handler2_address_const: .word prvGetRegistersFromStack \n" ); } /*-----------------------------------------------------------*/ /* Psuedo random number generator. Just used by demos so does not need to be * secure. Do not use the standard C library rand() function as it can cause * unexpected behaviour, such as calls to malloc(). */ int iMainRand32( void ) { static UBaseType_t uxlNextRand; /*_RB_ Not seeded. */ const uint32_t ulMultiplier = 0x015a4e35UL, ulIncrement = 1UL; /* Utility function to generate a pseudo random number. */ uxlNextRand = ( ulMultiplier * uxlNextRand ) + ulIncrement; return( ( int ) ( uxlNextRand >> 16UL ) & 0x7fffUL ); } /*-----------------------------------------------------------*/ static void prvInitializeHeap( void ) { static uint8_t ucHeap1[ configTOTAL_HEAP_SIZE ]; static uint8_t ucHeap2[ 22 * 1024 ] __attribute__( ( section( ".freertos_heap2" ) ) ); HeapRegion_t xHeapRegions[] = { { ( unsigned char * ) ucHeap2, sizeof( ucHeap2 ) }, { ( unsigned char * ) ucHeap1, sizeof( ucHeap1 ) }, { NULL, 0 } }; vPortDefineHeapRegions( xHeapRegions ); } /*-----------------------------------------------------------*/ extern void LORAWAN_HAL_GPIO_EXTI_Callback( uint16_t gpioPin ); /** * @brief EXTI line detection callback. * * @param GPIO_Pin: Specifies the port pin connected to corresponding EXTI line. */ void HAL_GPIO_EXTI_Callback( uint16_t GPIO_Pin ) { LORAWAN_HAL_GPIO_EXTI_Callback( GPIO_Pin ); } /*-----------------------------------------------------------*/ /** * @brief Period elapsed callback in non blocking mode * * @note This function is called when TIM1 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback( TIM_HandleTypeDef * htim ) { if( htim->Instance == TIM6 ) { HAL_IncTick(); } } /*-----------------------------------------------------------*/