#include CurrentTransformer::CurrentTransformer(AnalogCard* analogCard, uint8_t pin, float *voltage, std::function adcToCurrent, uint32_t conversionInterval) { this->analogCard = analogCard; this->pin = pin; this->voltage = voltage; this->adcToCurrent = adcToCurrent; } void CurrentTransformer::bindFRAM(FRAM *fram, uint8_t framAddress) { this->fram = fram; this->framAddress = framAddress; } void CurrentTransformer::begin() { this->beginConversion(); } void CurrentTransformer::loop() { if (this->lastConversionTime == 0) { this->lastConversionTime = millis(); } static uint32_t lastConversionLoopTime = 0; if (millis() - lastConversionLoopTime > this->conversionInterval) { this->beginConversion(); lastConversionLoopTime = millis(); } } void CurrentTransformer::beginConversion() { uint16_t adcValue = this->analogCard->analogRead(this->pin); this->current = this->adcToCurrent(adcValue); this->setEnergy(this->energy + this->current * *this->voltage * (millis() - this->lastConversionTime) / 3600000); // in Wh this->lastConversionTime = millis(); for (auto const& callback : this->callbacks) { callback.second(this->current, this->energy); } } void CurrentTransformer::setEnergy(float energy) { this->energy = energy; if (this->autoSave) { this->saveEnergy(); } } void CurrentTransformer::resetEnergy() { this->setEnergy(0); } float CurrentTransformer::getCurrent() { return this->current; } long double CurrentTransformer::getEnergy() { return this->energy; } uint8_t CurrentTransformer::registerCallback(std::function callback) { this->callbacks[this->handler_count] = callback; return this->handler_count++; } void CurrentTransformer::unregisterCallback(uint8_t handler) { this->callbacks.erase(handler); } void CurrentTransformer::saveEnergy(){ this->fram->write(this->framAddress, (uint8_t*)&this->energy, 16); } void CurrentTransformer::loadEnergy(){ this->fram->read(this->framAddress, (uint8_t*)&this->energy, 16); } void CurrentTransformer::setEnergyAutoSave(bool autoSave){ this->autoSave = autoSave; } float CurrentTransformer::getVoltage(){ return *this->voltage; } float CurrentTransformer::getPower(){ return this->current * *this->voltage; }