#ifndef HELIOS_IM1281C_H
#define HELIOS_IM1281C_H

#include <Arduino.h>
#include <ModbusMaster.h>

struct IM1281CAData
{
  float voltage = 0.0f;
  float current = 0.0f;
  float power = 0.0f;
  float energy = 0.0f;
  float powerFactor = 0.0f;
  float co2 = 0.0f;
  float temperature = 0.0f;
  float frequency = 0.0f;
  bool valid = false;
};

struct IM1281CBData
{
  float voltage = 0.0f;
  float current = 0.0f;
  float power = 0.0f;
  float energy = 0.0f;
  float powerFactor = 0.0f;
  float co2 = 0.0f;
  bool valid = false;
};

class IM1281C
{
public:
  IM1281C();

  bool begin(HardwareSerial &serial,
             int8_t rxPin,
             int8_t txPin,
             uint8_t slaveAddress = 1,
             uint32_t baudRate = 4800,
             uint32_t serialConfig = SERIAL_8N1);

  bool readA();
  bool readB();
  bool readAll();

  const IM1281CAData &a() const;
  const IM1281CBData &b() const;
  uint8_t lastAResult() const;
  uint8_t lastBResult() const;

private:
  static uint32_t combineWords(uint16_t highWord, uint16_t lowWord);
  static float scaleValue(uint32_t raw, float scale);

  ModbusMaster _node;
  HardwareSerial *_serial;
  uint8_t _slaveAddress;
  uint8_t _lastAResult;
  uint8_t _lastBResult;
  IM1281CAData _a;
  IM1281CBData _b;
};

#endif // HELIOS_IM1281C_H
