Stairs/src/stairs.cpp

126 lines
2.3 KiB
C++
Raw Normal View History

#include <Math.h>
#include <FS.h>
#include "stairs.h"
const static float factorBase = log10(2) / log10(PCA9685::On);
struct Header
{
uint8_t version;
uint8_t rangeCount;
bool useScaling;
};
void Stairs::init(PCA9685* pwmDriver)
{
this->pwmDriver = pwmDriver;
SPIFFS.begin();
this->readRange();
}
uint8_t Stairs::getCount()
{
return StepCount;
}
void Stairs::set(uint8_t step, uint16_t brightness)
{
pwmDriver->setPWM(step, this->getPWMValue(step, brightness));
}
void Stairs::setAll(uint16_t brightness)
{
//pwmDriver->setAll(this->getPWMValue(brightness));
for (uint8_t step = 0; step < StepCount; step++)
pwmDriver->setPWM(step, this->getPWMValue(step, brightness));
}
uint16_t Stairs::getPWMValue(uint8_t step, uint16_t brightness)
{
if (brightness == IStairs::Off || brightness == IStairs::On)
return brightness;
if (step < 0 || step >= StepCount)
return brightness;
Range* range = this->ranges[step];
if (this->useScaling)
{
float factor = ((range->end - range->start) + 1) * factorBase;
brightness = pow(2, (brightness / factor)) - 1 + range->start;
}
else
{
if (brightness < range->start) brightness = range->start;
if (brightness > range->end) brightness = range->end;
}
return brightness;
}
void Stairs::getRange(Stream* stream)
{
stream->write(this->useScaling ? 1 : 0);
stream->write(reinterpret_cast<uint8_t*>(&this->ranges), sizeof(this->ranges));
}
void Stairs::setRange(uint8_t* data)
{
this->useScaling = *data;
data++;
memcpy(this->ranges, data, sizeof(this->ranges));
}
void Stairs::readRange()
{
File f = SPIFFS.open("/range", "r");
if (!f)
return;
if (!f.available())
return;
Header header;
f.readBytes(reinterpret_cast<char*>(&header), sizeof(Header));
if (header.version != 1)
return;
this->useScaling = (header.useScaling == 1);
memset(this->ranges, 0, sizeof(this->ranges));
f.readBytes(reinterpret_cast<char*>(&this->ranges), header.rangeCount * sizeof(Range));
f.close();
}
void Stairs::writeRange()
{
File f = SPIFFS.open("/range", "w");
if (!f)
return;
Header header;
header.version = 1;
header.useScaling = this->useScaling;
header.rangeCount = StepCount;
f.write(reinterpret_cast<uint8_t*>(&header), sizeof(Header));
f.write(reinterpret_cast<uint8_t*>(&this->ranges), sizeof(this->ranges));
f.close();
}