#ifndef INC_TS_STATE_MACHINE_H
#define INC_TS_STATE_MACHINE_H

#include "stm32f3xx_hal.h"

#include <stdint.h>

// Minimum vehicle side voltage to exit precharge
#define MIN_VEHICLE_SIDE_VOLTAGE 150000 // mV
// Time to wait after reaching 95% of battery voltage before exiting precharge
// Set this to 1000 in scruti to demonstrate the voltage on the multimeter
#define PRECHARGE_95_DURATION 0 // ms
// Time to wait for discharge
#define DISCHARGE_DURATION 5000 // ms
// Time to wait after there is no more error condition before exiting TS_ERROR
#define NO_ERROR_TIME 1000 // ms
// Time to wait for charger voltage before going to TS_ERROR
#define MAX_CHARGING_CHECK_DURATION 2000 // ms
// Time to wait between closing relays
#define RELAY_CLOSE_WAIT 10 // ms

typedef enum {
  TS_INACTIVE,
  TS_ACTIVE,
  TS_PRECHARGE,
  TS_DISCHARGE,
  TS_ERROR,
  TS_CHARGING_CHECK,
  TS_CHARGING
} TSState;

typedef enum {
  TS_ERRORKIND_NONE = 0x00,
  TS_ERRORKIND_SLAVE_TIMEOUT = 0x01,
  TS_ERRORKIND_SLAVE_PANIC = 0x02,
  TS_ERRORKIND_SHUNT_TIMEOUT = 0x03,
  TS_ERRORKIND_SHUNT_OVERCURRENT = 0x04,
  TS_ERRORKIND_SHUNT_OVERTEMP = 0x05
} TSErrorKind;
#define TS_ERROR_SOURCE_SHUNT (1 << 0)
#define TS_ERROR_SOURCE_SLAVES (1 << 1)

typedef struct {
  TSState current_state;
  TSState target_state;
  uint32_t error;
} TSStateHandle;

extern TSStateHandle ts_state;

void ts_sm_init();
void ts_sm_update();

TSState ts_sm_update_inactive();
TSState ts_sm_update_active();
TSState ts_sm_update_precharge();
TSState ts_sm_update_discharge();
TSState ts_sm_update_error();
TSState ts_sm_update_charging_check();
TSState ts_sm_update_charging();

typedef enum { RELAY_NEG, RELAY_POS, RELAY_PRECHARGE } Relay;
void ts_sm_set_relay_positions(TSState state);
void ts_sm_set_relay_position(Relay relay, int closed);
void ts_sm_check_close_wait(int *is_closed, int should_close);

void ts_sm_handle_ams_in(const uint8_t *data);

void ts_sm_set_error_source(uint32_t flag, int state);

#endif // INC_TS_STATE_MACHINE_H
