/*
 * TMP144.h
 *
 *  Created on: Mar 22, 2022
 *      Author: Jasper
 */

#ifndef INC_TMP144_H_
#define INC_TMP144_H_

#include "common_defs.h"

#include "stm32f4xx_hal.h"
#include "stm32f4xx_hal_def.h"
#include "stm32f4xx_hal_uart.h"

#define N_TEMP_SENSORS 32
#define TMP144_RESPONSE_TIMEOUT 100 /* ms */

extern volatile uint16_t temperatures[N_TEMP_SENSORS];
extern volatile uint16_t min_temperature;
extern volatile uint16_t max_temperature;

typedef enum {
  TMP144_IDLE,
  TMP144_RESETTING,
  TMP144_INITIALIZING,
  TMP144_READING_TEMP,
  TMP144_ERROR
} TMP144State;

typedef struct {
  UART_HandleTypeDef* handle;
  TMP144State state;

  uint8_t rxbuf[34];

  size_t n_sensors;

  uint32_t expected_response_time;
} TMP144Bus;

extern volatile TMP144Bus tmp144_bus_busbar;
extern volatile TMP144Bus tmp144_bus_other;

HAL_StatusTypeDef tmp144_init(UART_HandleTypeDef* busbar_side,
                              UART_HandleTypeDef* other_side);

HAL_StatusTypeDef tmp144_check_timeouts();

HAL_StatusTypeDef tmp144_init_reset(TMP144Bus* bus);
HAL_StatusTypeDef tmp144_init_post_reset(TMP144Bus* bus);
HAL_StatusTypeDef tmp144_init_post_addr(TMP144Bus* bus);

HAL_StatusTypeDef tmp144_read_temps();
HAL_StatusTypeDef tmp144_send_read_temps(TMP144Bus* bus);
HAL_StatusTypeDef tmp144_recv_temps(TMP144Bus* bus);

void tmp144_handle_rx_cplt(UART_HandleTypeDef* handle);

#endif /* INC_TMP144_H_ */