#include <SPI.h>
#include <MS5611_SPI.h>

#include "baro_channel.h"

namespace {

class BaroSpiChannel : public BaroChannel
{
public:
  BaroSpiChannel()
    : BaroChannel("spi", LED_BARO_SPI_PIN), _driver(BARO_SPI_CS_PIN, &SPI) {}

protected:
  bool driverBegin() override
  {
    if (!_busStarted)
    {
      SPI.begin();
      _busStarted = true;
    }

    //  Both must precede begin(), which re-applies the stored SPI speed and
    //  then talks to the part.
    _driver.setSPIspeed(BARO_SPI_CLOCK_HZ);
    _driver.setOversampling(BARO_OVERSAMPLING);

    return _driver.begin();
  }

  void driverReadProm(uint16_t *prom) override
  {
    for (uint8_t i = 0; i < 8; i++) prom[i] = _driver.getProm(i);
  }

  bool  driverRead() override        { return _driver.read() == MS5611_READ_OK; }
  float driverPressure() override    { return _driver.getPressure(); }
  float driverTemperature() override { return _driver.getTemperature(); }

private:
  MS5611_SPI _driver;
  bool       _busStarted = false;
};

BaroSpiChannel instance;

}  // namespace

BaroChannel &baroSpiChannel() { return instance; }
