/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include "at1_defines.h"
#include "si5351.h"
#include "commands.h"
#include <string.h>
#include "ringbuf.h"
#include "ringbuf_test.h" // test the ringbuffer
#include "helper.h"	// my toolbox for strings, etc.
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

UART_HandleTypeDef hlpuart1;
DMA_HandleTypeDef hdma_lpuart_rx;

RTC_HandleTypeDef hrtc;

/* Definitions for timeTask */
osThreadId_t timeTaskHandle;
const osThreadAttr_t timeTask_attributes = {
  .name = "timeTask",
  .stack_size = 128 * 4,
  .priority = (osPriority_t) osPriorityNormal,
};
/* Definitions for terminalTask */
osThreadId_t terminalTaskHandle;
const osThreadAttr_t terminalTask_attributes = {
  .name = "terminalTask",
  .stack_size = 256 * 4,
  .priority = (osPriority_t) osPriorityNormal,
};
/* Definitions for morseTask */
osThreadId_t morseTaskHandle;
const osThreadAttr_t morseTask_attributes = {
  .name = "morseTask",
  .stack_size = 128 * 4,
  .priority = (osPriority_t) osPriorityNormal,
};
/* Definitions for clk2Task */
osThreadId_t clk2TaskHandle;
const osThreadAttr_t clk2Task_attributes = {
  .name = "clk2Task",
  .stack_size = 128 * 4,
  .priority = (osPriority_t) osPriorityHigh,
};
/* Definitions for si5351 */
osSemaphoreId_t si5351Handle;
const osSemaphoreAttr_t si5351_attributes = {
  .name = "si5351"
};
/* Definitions for command */
osSemaphoreId_t commandHandle;
const osSemaphoreAttr_t command_attributes = {
  .name = "command"
};
/* USER CODE BEGIN PV */
int leds_on = 1;
uint8_t UART1_rxBuffer[12] = {0};
uint8_t UART1_txBuffer[12];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_I2C1_Init(void);
static void MX_LPUART1_UART_Init(void);
static void MX_RTC_Init(void);
void start_time_task(void *argument);
void start_terminal_task(void *argument);
void start_morse_task(void *argument);
void start_clk2_task(void *argument);

/* USER CODE BEGIN PFP */

void ringbuffer_callback(uint16_t delimiterfound, void * cb_data);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
#define rxbuf_size		64
#define mainbuf_size	64

uint8_t rxbuf[rxbuf_size];
uint8_t done = 0;
hring ring;

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) {
	if (huart->Instance == LPUART1) {
		ringbuf_push(ring, rxbuf, Size);
		//ringbuf_dump(ring);
		HAL_UARTEx_ReceiveToIdle_DMA(huart, rxbuf, rxbuf_size);
		//__HAL_DMA_DISABLE_IT(&hdma_lpuart_rx, DMA_IT_HT);
	} else {
		__NOP();
	}
}

// void (*ringbuf_rcv_cb_t)(uint16_t delimiterfound, void* cb_data);
void ringbuffer_callback(uint16_t delimiterfound, void * cb_data) {

	(void)cb_data;
	(void)delimiterfound;

	HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin);
	osSemaphoreRelease(commandHandle);
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
	/* int status = 0; */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_I2C1_Init();
  MX_LPUART1_UART_Init();
  MX_RTC_Init();
  /* USER CODE BEGIN 2 */
  si5351_inst_t si5351_inst = 0;

  //printf("Date Compile Century: %d\n", DATE_COMPILE_CENTURY);
  //printf("Date Compile Year: %d\n", DATE_COMPILE_YEAR);

  print_system_info();

  // do some tests for ringbuf.h library

  ring = ringbuf_create(mainbuf_size, RINGBUF_ALLOWOVERWRITE);
  if (ring == NULL)
	  puts("Can't create memory for ringbuffer");
  HAL_UARTEx_ReceiveToIdle_DMA(&hlpuart1, rxbuf, rxbuf_size);
  __HAL_DMA_DISABLE_IT(&hdma_lpuart_rx, DMA_IT_HT);

  (void)ringbuf_callback_register(ring, ringbuffer_callback, NULL);
// #define NDEBUG
  // ringbuf_test();

  // 1st SI5351 chip at the I2C bus "hi2c1", address line A0 = 0
  si5351_inst = si5351_init(&hi2c1, 0x60, 25000000);
  {
	  int ready = si5351_i2c_ready(si5351_inst);
	  printf("Si5351 device is %s.\n", (ready==1) ? "ready" : "N/A");
  }
#if 0
  puts("Registers of Device No. 1");
  char buf[33];
  
  for (uint8_t i=0; i <= SI5351_FANOUT_ENABLE; i++) {
	  puts(si5351_read_register_debug(instance_si5351[1], buf, sizeof(buf), i));
  }

  // status = si5351_program(instance_si5351[1]);
  printf("Device #1 gets status %d\n", status);
  printf("Debug:\n%s", si5351_read_debug_msg(instance_si5351[1]));
#endif
  //si5351_set_clk0(instance_si5351[1], 3579545);
  // si5351_set_clk0(instance_si5351[1], 3580000);
  // si5351_set_clk0(instance_si5351[1], 4000000);
#if 0
  si5351_set_clk0(instance_si5351[1], 3510000);
  si5351_enable_output(instance_si5351[1],0);
  HAL_Delay(1000);
  si5351_set_clk0(instance_si5351[1], 6055000);
  si5351_enable_output(instance_si5351[1],0);
  HAL_Delay(1000);
  si5351_set_clk0(instance_si5351[1], 99900000);
  si5351_enable_output(instance_si5351[1],0);
  HAL_Delay(5000);
  si5351_set_clk0(instance_si5351[1], 144500000);
  si5351_enable_output(instance_si5351[1],0);
  HAL_Delay(10000);
#endif

#if 0
  si5351_set_clk0(si5351_inst, 3550000);
  si5351_enable_output(si5351_inst,0);

  si5351_set_clk_phase(si5351_inst,3550000, 255-100, 0, SI5351_PLLA);
  si5351_set_clk_phase(si5351_inst,3550000, 100, 2, SI5351_PLLA);
  si5351_enable_output(si5351_inst,0);
  si5351_enable_output(si5351_inst,2);

  HAL_Delay(10000);
  while(1) {
		for (int i = 0; i< 128; i++) {
			//HAL_Delay(0);
			//printf("phase: %d\n", i);
			si5351_set_clk_phase(si5351_inst,3550000, i, 2,SI5351_PLLA);
			si5351_set_clk_phase(si5351_inst, 3550000,255-i, 0, SI5351_PLLA);
			//si5351_set_clk(si5351_inst,3550001, 2, SI5351_PLLB);
			si5351_enable_output(si5351_inst,0);
			si5351_enable_output(si5351_inst,2);
		}
		for (int i = 127; i>=0; i--) {
			//HAL_Delay(0);
			//printf("phase: %d\n", i);
			si5351_set_clk_phase(si5351_inst,3550000, i, 2,SI5351_PLLA);
			si5351_set_clk_phase(si5351_inst, 3550000,255-i, 0, SI5351_PLLA);
			//si5351_set_clk(si5351_inst,3550001, 2, SI5351_PLLB);
			si5351_enable_output(si5351_inst,0);
			si5351_enable_output(si5351_inst,2);
		}

  }


#endif
  HAL_Delay(1000);

#if 0
	while (1) {

		HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_SET);
		HAL_Delay(100);
		HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

#if 0
		{
			/* for STANDBY MODE only:
			 *
			 */
			/* clear the WU flag */
			__HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);

			/* clear the RTC Wake Up (WU) flag */
			__HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hrtc, RTC_FLAG_WUTF);
		}
#endif
		HAL_SuspendTick();
		HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 0x5000, RTC_WAKEUPCLOCK_RTCCLK_DIV16);

	//	/* Enter STOP 2 mode */
		HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI);
		//HAL_PWR_EnterSTANDBYMode();

		HAL_RTCEx_DeactivateWakeUpTimer(&hrtc);
		SystemClock_Config();
		HAL_ResumeTick();
	}

#endif

  /* World Youth ARDF Championship Romania 2022 */
  /* 80 m . RF power 3 W, QRG MOE-MO5: 3550 MHz, MO: 3600 MHz, Antenna 8m
   * 80 m Sprint pwr 1 W, TX 1-5: MOE-MO5: 3530 MHz, S: 3550 MHz, TX 1F-5F MOE-MO5: 3570 MHz
   *             MO: 3600 MHz, Antenna: 8m
   * 2 m RF power 1 W, MOE-MO5: 144.500, MO: 144.900 MHz, crossed dipole
   */
  //si5351_set_clk0(si5351_inst, 3600000); /* MO FOX */
  // si5351_set_clk (si5351_inst, 2, 3551000, SI5351_PLLB);
  // si5351_set_clk (si5351_inst, 2, 3551000, SI5351_PLLB);
  // si5351_set_clk0(si5351_inst, 3600000); /* MO FOX */
  // si5351_set_clk(si5351_inst, 1, 99900000, SI5351_PLLA);
  // si5351_enable_output(si5351_inst,1);
  // HAL_Delay(1000);

#if 0
  si5351_set_clk0(si5351_inst, 3550000);

  si5351_set_clk(si5351_inst, 2, 3570000, SI5351_PLLB);
  si5351_enable_output(NULL,2);
#endif

  /* USER CODE END 2 */

  /* Init scheduler */
  osKernelInitialize();

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* Create the semaphores(s) */
  /* creation of si5351 */
  si5351Handle = osSemaphoreNew(1, 1, &si5351_attributes);

  /* creation of command */
  commandHandle = osSemaphoreNew(1, 1, &command_attributes);

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  /* add semaphores, ... */
  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
  /* USER CODE END RTOS_TIMERS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  /* USER CODE END RTOS_QUEUES */

  /* Create the thread(s) */
  /* creation of timeTask */
  timeTaskHandle = osThreadNew(start_time_task, NULL, &timeTask_attributes);

  /* creation of terminalTask */
  terminalTaskHandle = osThreadNew(start_terminal_task, NULL, &terminalTask_attributes);

  /* creation of morseTask */
  morseTaskHandle = osThreadNew(start_morse_task, (void*) si5351_inst, &morseTask_attributes);

  /* creation of clk2Task */
  clk2TaskHandle = osThreadNew(start_clk2_task, (void*) si5351_inst, &clk2Task_attributes);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

  /* USER CODE BEGIN RTOS_EVENTS */
  /* add events, ... */
  /* USER CODE END RTOS_EVENTS */

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure LSE Drive Capability
  */
  HAL_PWR_EnableBkUpAccess();
  __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_LSE
                              |RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.LSEState = RCC_LSE_ON;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = 0;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 71;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV6;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV8;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV4;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
  HAL_RCCEx_EnableLSCO(RCC_LSCOSOURCE_LSI);
}

/**
  * @brief I2C1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_I2C1_Init(void)
{

  /* USER CODE BEGIN I2C1_Init 0 */

  /* USER CODE END I2C1_Init 0 */

  /* USER CODE BEGIN I2C1_Init 1 */

  /* USER CODE END I2C1_Init 1 */
  hi2c1.Instance = I2C1;
  hi2c1.Init.Timing = 0x00000001;
  hi2c1.Init.OwnAddress1 = 0;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Analogue filter
  */
  if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Digital filter
  */
  if (HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN I2C1_Init 2 */

  /* USER CODE END I2C1_Init 2 */

}

/**
  * @brief LPUART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_LPUART1_UART_Init(void)
{

  /* USER CODE BEGIN LPUART1_Init 0 */

  /* USER CODE END LPUART1_Init 0 */

  /* USER CODE BEGIN LPUART1_Init 1 */

  /* USER CODE END LPUART1_Init 1 */
  hlpuart1.Instance = LPUART1;
  hlpuart1.Init.BaudRate = 115200;
  hlpuart1.Init.WordLength = UART_WORDLENGTH_8B;
  hlpuart1.Init.StopBits = UART_STOPBITS_1;
  hlpuart1.Init.Parity = UART_PARITY_NONE;
  hlpuart1.Init.Mode = UART_MODE_TX_RX;
  hlpuart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  hlpuart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  hlpuart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_RXOVERRUNDISABLE_INIT|UART_ADVFEATURE_DMADISABLEONERROR_INIT;
  hlpuart1.AdvancedInit.OverrunDisable = UART_ADVFEATURE_OVERRUN_DISABLE;
  hlpuart1.AdvancedInit.DMADisableonRxError = UART_ADVFEATURE_DMA_DISABLEONRXERROR;
  if (HAL_UART_Init(&hlpuart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN LPUART1_Init 2 */

  /* USER CODE END LPUART1_Init 2 */

}

/**
  * @brief RTC Initialization Function
  * @param None
  * @retval None
  */
static void MX_RTC_Init(void)
{

  /* USER CODE BEGIN RTC_Init 0 */

  /* USER CODE END RTC_Init 0 */

  RTC_TimeTypeDef sTime = {0};
  RTC_DateTypeDef sDate = {0};

  /* USER CODE BEGIN RTC_Init 1 */

  /* USER CODE END RTC_Init 1 */

  /** Initialize RTC Only
  */
  hrtc.Instance = RTC;
  hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
  hrtc.Init.AsynchPrediv = 127;
  hrtc.Init.SynchPrediv = 255;
  hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
  hrtc.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;
  hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
  if (HAL_RTC_Init(&hrtc) != HAL_OK)
  {
    Error_Handler();
  }

  /* USER CODE BEGIN Check_RTC_BKUP */

  /* USER CODE END Check_RTC_BKUP */

  /** Initialize RTC and set the Time and Date
  */
  sTime.Hours = 0x0;
  sTime.Minutes = 0x0;
  sTime.Seconds = 0x0;
  sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  sTime.StoreOperation = RTC_STOREOPERATION_RESET;
  if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK)
  {
    Error_Handler();
  }
  sDate.WeekDay = RTC_WEEKDAY_MONDAY;
  sDate.Month = RTC_MONTH_AUGUST;
  sDate.Date = 0x1;
  sDate.Year = 0x22;

  if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BCD) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN RTC_Init 2 */

  /* USER CODE END RTC_Init 2 */

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA2_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA2_Channel7_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA2_Channel7_IRQn, 5, 0);
  HAL_NVIC_EnableIRQ(DMA2_Channel7_IRQn);

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOF_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOG_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  HAL_PWREx_EnableVddIO2();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, LD3_Pin|LD2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOG, GPIO_PIN_6, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LD1_GPIO_Port, LD1_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : PE2 PE3 PE4 PE5
                           PE6 PE7 PE8 PE9
                           PE10 PE11 PE12 PE13
                           PE14 PE15 PE0 PE1 */
  GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3|GPIO_PIN_4|GPIO_PIN_5
                          |GPIO_PIN_6|GPIO_PIN_7|GPIO_PIN_8|GPIO_PIN_9
                          |GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13
                          |GPIO_PIN_14|GPIO_PIN_15|GPIO_PIN_0|GPIO_PIN_1;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);

  /*Configure GPIO pin : B1_Pin */
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : PF0 PF1 PF2 PF3
                           PF4 PF5 PF6 PF7
                           PF8 PF9 PF10 PF11
                           PF12 PF13 PF14 PF15 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3
                          |GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7
                          |GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11
                          |GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);

  /*Configure GPIO pins : PH0 PH3 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_3;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);

  /*Configure GPIO pins : PC0 PC1 PC2 PC3
                           PC4 PC5 PC6 PC8
                           PC9 PC10 PC11 PC12 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3
                          |GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_8
                          |GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

  /*Configure GPIO pins : PA0 PA1 PA2 PA3
                           PA4 PA5 PA6 PA7
                           PA15 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3
                          |GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7
                          |GPIO_PIN_15;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : PB0 PB1 PB2 PB10
                           PB11 PB12 PB13 PB15
                           PB4 PB5 PB6 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_10
                          |GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_15
                          |GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : PG0 PG1 PG2 PG3
                           PG4 PG9 PG10 PG11
                           PG12 PG13 PG14 PG15 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3
                          |GPIO_PIN_4|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11
                          |GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);

  /*Configure GPIO pins : LD3_Pin LD2_Pin */
  GPIO_InitStruct.Pin = LD3_Pin|LD2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : PD8 PD9 PD10 PD11
                           PD12 PD13 PD14 PD15
                           PD0 PD1 PD2 PD3
                           PD4 PD5 PD6 PD7 */
  GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11
                          |GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15
                          |GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3
                          |GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

  /*Configure GPIO pin : USB_OverCurrent_Pin */
  GPIO_InitStruct.Pin = USB_OverCurrent_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(USB_OverCurrent_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : PG6 */
  GPIO_InitStruct.Pin = GPIO_PIN_6;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);

  /*Configure GPIO pin : LD1_Pin */
  GPIO_InitStruct.Pin = LD1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LD1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : USB_SOF_Pin USB_ID_Pin USB_DM_Pin USB_DP_Pin */
  GPIO_InitStruct.Pin = USB_SOF_Pin|USB_ID_Pin|USB_DM_Pin|USB_DP_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
  GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */


/**
  * @brief  UART error callback.
  * @param  huart UART handle.
  * @retval None
  */
__weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(huart);

  /* NOTE : This function should not be modified, when the callback is needed,
            the HAL_UART_ErrorCallback can be implemented in the user file.
   */
  printf("UART error %ld\n", huart->ErrorCode);
  if (HAL_UART_Init(&hlpuart1) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None
  */
int __io_putchar(int ch)
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART1 and Loop until the end of transmission */
  uint8_t xch = (uint8_t)ch;
  volatile HAL_StatusTypeDef hstat;
/*
 * Only for Windows PCs or Eclipse Terminal:
*/
#if 1
  if(ch=='\n')	/* 0xA, 10, LF */
	__io_putchar('\r'); /* 0xD, 13, CR */
#endif
  // HAL_UART_Transmit(&hlpuart1, &xch, 1, HAL_MAX_DELAY);
  do {
	  hstat = HAL_UART_Transmit_IT(&hlpuart1, &xch, 1);
  } while (hstat == HAL_BUSY);
  return ch;
}

int _write(int fd, unsigned char *p, int len)
{
	int l = len;
	(void)fd;
	while (l--)
		__io_putchar(*p++);
	return len;
}

void print_system_info(void) {
	puts("*************************************");
	puts(PROGRAM_ID " " AUTHOR_STRING);
	puts("Compiled: " __DATE__ " " __TIME__);
	puts(osKernelSystemId);
	printf("CMSIS V%u.%u\n", __CM_CMSIS_VERSION_MAIN, __CM_CMSIS_VERSION_SUB);
	printf("STM32L4 CMSIS Device V%u.%u.%u.%u\n", __STM32L4_CMSIS_VERSION_MAIN,
			__STM32L4_CMSIS_VERSION_SUB1,__STM32L4_CMSIS_VERSION_SUB2,__STM32L4_CMSIS_VERSION_RC);
	printf("HAL Driver V%hu.%hu.%hu.%hu\n", (uint8_t)(HAL_GetHalVersion()>>24), (uint8_t)(HAL_GetHalVersion()>>16),
			(uint8_t)(HAL_GetHalVersion()>>8), (uint8_t) HAL_GetHalVersion());
	printf("Si5351 Driver V%u.%u.%u\n", __SI5351__, __SI5351_MINOR__, __SI5351_PATCHLEVEL__);
	printf("GNU Compiler Collection V%u.%u.%u\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
	puts("Byte Order: little-endian");
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
	puts("Byte Order: big-endian");
#endif
	puts("Newlib V" _NEWLIB_VERSION);
}

void make_di_dah(si5351_inst_t inst, unsigned int dah, uint32_t delay, uint8_t clk) {
#define SEMAPHORE 0
	/* inner function, no need to check inst, clk, nor delay */
#if 1
	if (leds_on) {
		if (clk==0)
			HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_SET);
		else
			HAL_GPIO_WritePin(LD3_GPIO_Port, LD3_Pin, GPIO_PIN_SET);
	}
#endif
#if SEMAPHORE
	osSemaphoreAcquire(si5351Handle, osWaitForever);
#endif
	(void) si5351_enable_output(inst, clk);
#if SEMAPHORE
	osSemaphoreRelease(si5351Handle);
#endif
	osDelay(dah ? 3*delay : delay); // dit: 1 unit; dah 3 units length
#if 1
	if (clk==0)
		HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
	else
		HAL_GPIO_WritePin(LD3_GPIO_Port, LD3_Pin, GPIO_PIN_RESET);
#endif
#if SEMAPHORE
	osSemaphoreAcquire(si5351Handle, osWaitForever);
#endif
	(void) si5351_disable_output(inst, clk);
#if SEMAPHORE
	osSemaphoreRelease(si5351Handle);
#endif
	osDelay(delay);	// one unit of inter character space (gap b/w dits and dahs within a character)
}

void morse(si5351_inst_t inst, char * s, uint32_t delay, uint8_t clk) {

	static const uint8_t mcode[] = {
		0x0d,0x57,0x77,0x17,0x01,0x75,0x1f,0x55,0x05,0xfd,
		0x37,0x5d,0x0f,0x07,0x3f,0x7d,0xdf,0x1d,0x15,0x03,
		0x35,0xd5,0x3d,0xd7,0xf7,0x5f,
		0xf8,0xf0,0xe0,0xc0,0x80,0x00,0x08,0x18,0x38,0x78
	};
	uint8_t ch;
	if(clk >= 3 || !delay)
		return;

	while ((ch = *s++)) {
		/* ASCII code: numbers b/w 0x30 - 0x39  chars b/w 0x41 - 0x5A and 0x61 - 0x7A */
		if ((ch > 0x40 && ch < 0x5B) || (ch > 0x60 && ch < 0x7B)) {
			ch &= 0xDF; // make upper case
			ch = mcode[ch - 0x41]; // index 0 for 'A'
		} else if (ch > 0x2F && ch < 0x3A) {
			ch = mcode[ch - 22];
		} else {
			switch(ch) {	/* special characters */
				case '.': ch = 0xaa; /* . 0b101010 10 */
					break;
				case '/': ch = 0x48; /* / 0b01001 000 */
					break;
				case ',': ch = 0xce; /* , 0b110011 10 */
					break;
				case '=': ch = 0x88; /* = 0b10001 000 */
					break;
				case '?': ch = 0x32; /* ? 0b001100 10 */
					break;
				case ':': ch = 0x1e; /* : 0b000111 10 */
					break;
				case '!': ch = 0xd6; /* ! 0b110101 10 */
					break;
				case '$': ch = 0x04; /* error 0b00000 100 */
					break;
				case ' ': /* make a word break */
					osDelay(7*delay); /* fall through */
				default:
					ch = 0xF4;	/* unknown character - do nothing */
					break;
				}
		}
		if(ch & 0x01) { // character encoding
			for (int i=4; i>0; i--) {
				switch ((ch & 0x03)) {
					case 0: /* the end */
						i = 0;
						break;
					case 1: /* did */
						make_di_dah(inst, 0, delay, clk);
						break;
					case 3: /* dah */
						make_di_dah(inst, 1, delay, clk);
						break;
					case 2: /* failure */
					default:
						i = -1;
						break;
				}
				ch >>= 2;
			}
		} else if ((ch & 0x07) == 0) { // number encoding or special chars 5 long
			ch >>= 3;
			for (int i= 5; i>0; i--) {
				make_di_dah(inst, ch & 0x01, delay, clk);
				ch >>= 1;
			}
		} else if ((ch & 0x03) == 0x2) { // special characters encoding 6 long
			ch >>= 2;
			for (int i=6; i>0; i--) {
				make_di_dah(inst, ch & 0x01, delay, clk);
				ch >>= 1;
			}
		} else { /* error sign 0x04 etc. or 7 long */
			if (ch == 0x04)
				for (int i=8; i>0; i--)
					make_di_dah(inst, 0, delay, clk);
		}
		osDelay(3 * delay);	//word inter character space (gap b/w the characters of a word) 3 units
	}
}

/* USER CODE END 4 */

/* USER CODE BEGIN Header_start_time_task */
/**
  * @brief  Function implementing the timeTask thread.
  * @param  argument: Not used
  * @retval None
  */
/* USER CODE END Header_start_time_task */
void start_time_task(void *argument)
{
  /* USER CODE BEGIN 5 */
	(void) argument;	//unused argument

	int sw, sw_last = GPIO_PIN_RESET;

	int counter = 6;

	/* Infinite loop */
	for(;;) {
		//HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin);
		HAL_GPIO_WritePin(LD1_GPIO_Port, LD1_Pin, GPIO_PIN_SET);
		osDelay(100);
		//HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin);
		HAL_GPIO_WritePin(LD1_GPIO_Port, LD1_Pin, GPIO_PIN_RESET);
		sw = HAL_GPIO_ReadPin(B1_GPIO_Port, B1_Pin);
		if (sw_last == GPIO_PIN_RESET && sw == GPIO_PIN_SET) {
			leds_on = !leds_on;
			counter--;
		}
		sw_last = sw;
		osDelay(5000);
		if (counter == 4) {
			vTaskSuspend(morseTaskHandle);
		}
		if (counter == 2) {
			vTaskSuspend(clk2TaskHandle);
		}
		if (!counter) {
			vTaskSuspend(NULL);
		}
	}

  /* USER CODE END 5 */
}

/* USER CODE BEGIN Header_start_terminal_task */

/**
* @brief Function implementing the terminalTask thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_start_terminal_task */
void start_terminal_task(void *argument)
{
  /* USER CODE BEGIN start_terminal_task */
	(void)argument;

	char data[RINGBUF_MAX_READ_LEN + 1];
	char *tdata = data;
	int bytes;
	int rv;

	/* Infinite loop */
	for(;;) {
		//HAL_UART_Receive_IT(&hlpuart1, UART1_rxBuffer, 1);
		// osSemaphoreRelease is in the callback function when a command is entered
		osSemaphoreAcquire(commandHandle, osWaitForever);

		do {
			bytes = ringbuf_read(ring, data);
			// printf("READ (%d): %s\n",bytes, data);
			if (bytes) {
				//ringbuf_dump(ring);
				tdata = trim(data);
				// printf("TRIMMED (%d): %s\n",strlen(tdata), tdata);
				rv = cmd_interpreter(tdata);
				if (rv < 0) {
					printf("ERROR: %d\n", -rv);
				}
			}
			if (ringbuf_is_empty(ring))
				break;
		} while (bytes);
	}
  /* USER CODE END start_terminal_task */
}

/* USER CODE BEGIN Header_start_morse_task */
/**
* @brief Function implementing the morseTask thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_start_morse_task */
void start_morse_task(void *argument)
{
  /* USER CODE BEGIN start_morse_task */
	static const uint32_t delay = 100;
	static const uint8_t clk = 0;
	si5351_inst_t inst = argument;
	int i = 0;
	uint32_t morsedelay = delay;
	si5351_set_clk0(inst, 3600000); /* MO FOX */

	/* Infinite loop */
	for (;;) {
		// check clock RTC for e.g. cycle of 1 minutes TX with 4 minutes pause period
		if(++i % 32) { /* do this 31 times, then Morse my callsign once at high speed */
			morse(inst, "MO", morsedelay, clk);
		} else {
			morsedelay = delay/3;
			morse(inst, "f0x.at1 de oe3tkt/p", morsedelay, clk);
			morsedelay = delay;
		}
		osDelay(7*morsedelay);
  }
  /* USER CODE END start_morse_task */
}

/* USER CODE BEGIN Header_start_clk2_task */
/**
* @brief Function implementing the clk2Task thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_start_clk2_task */
void start_clk2_task(void *argument)
{
  /* USER CODE BEGIN start_clk2_task */
	static const uint32_t delay = 100;
	static const uint8_t clk =2;
	si5351_inst_t inst = argument;
	int i = 0;
	uint32_t morsedelay = delay;
	si5351_set_clk (inst, clk, 3582000, SI5351_PLLB);

	/* Infinite loop */
	for (;;) {
		// check clock RTC for e.g. cycle of 1 minutes TX with 4 minutes pause period
		if(++i % 32) { /* do this 31 times, then Morse my callsign once at high speed */
			morse(inst, "MOe", morsedelay, clk);
		} else {
			morsedelay = delay/3;
			morse(inst, "f0x.at1 de oe3tkt/p", morsedelay, clk);
			morsedelay = delay;
		}
		osDelay(7*morsedelay);
  }
  /* USER CODE END start_clk2_task */
}

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM6 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)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM6) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  puts("ERROR HANDLER");
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
	printf("Wrong parameters value: file %s on line %u\r\n", file, line);
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
