/*
 * PSE_unit.h
 *
 *  Created on: Aug 9, 2023
 *      Author: leo
 */

#ifndef INC_PSE_UNIT_H_
#define INC_PSE_UNIT_H_

#include <stdint.h>

#include "stm32f1xx_hal.h"

#include "lvgl.h"

// syringe definition
typedef struct{
  char name[16]; // brand / name
  uint16_t diameter; // diameter (in µm)
} pse_syringe;

// Ports available
typedef enum {PORT_X, PORT_Y, PORT_Z, PORT_E} pse_ports;

// stepper controller definitions
typedef struct{
	uint16_t tim_presc; // timer prescaler
	uint16_t tim_period; // timer period

  int32_t steps_counter;
	uint8_t stop_at_limit; // boolean to stop at stop_steps
	int32_t stop_steps; // position to stop at
} pse_stepper_status;

typedef struct{
  GPIO_TypeDef* EN_GPIO_Port; // Pin definitions
  uint16_t EN_GPIO_Pin;
  GPIO_TypeDef* DIR_GPIO_Port;
  uint16_t DIR_GPIO_Pin;
  GPIO_TypeDef* STEP_GPIO_Port;
  uint16_t STEP_GPIO_Pin;

  TIM_HandleTypeDef* tim; // timer assigned to this unit
} pse_stepper_conf;

// readout widgets associated with this unit
typedef struct{
	lv_obj_t* flow;
	lv_obj_t* volume;
	lv_obj_t* enabled;
} pse_home_display;

// unit definition
typedef struct{
  uint8_t enabled;
  pse_ports port; // physical port on which this unit is connected
  uint32_t flow; // flow (in µL.min-1)
  int32_t volume; // current volume dispensed (in µL)
  uint32_t set_volume; // volume to stop at (0 for no max)
  pse_syringe* syringe; // associated syringe
  pse_stepper_conf* stepper_conf; // hardware configuration for the associated stepper
  pse_home_display* home_display; // Widgets for updating the home screen
	pse_stepper_status* stepper_status; // stepper position/speed status
	int32_t start_pos; // movement start position for volume calculation
	uint32_t pL_per_step; // pL delivered per step
} pse_unit;


void load_units(pse_unit* units, pse_syringe* syringes, pse_stepper_conf* stepper_confs, pse_stepper_status* stepper_status, pse_home_display* home_displays, uint8_t unit_num, uint16_t ws_ind);
void load_units_short(pse_unit* units, uint8_t unit_num, uint16_t ws_ind);
void save_units(pse_unit* units, uint8_t unit_num, uint16_t ws_ind);

void pse_unit_compute_volume_delivered(pse_unit* unit);
void pse_unit_compute_volume_per_step(pse_unit* unit);
#endif 
