Skip to content
Snippets Groups Projects
Service.cpp 2.61 KiB
#include "Service.hpp"

// C++ system level
// #include <cstring>     // memset, strncmp
// #include <cstdlib>     // TODO: is this for memcpy?
// #include <functional>

// ESP32 specific
#include "esp_log.h"

// project specific
#include <Types.hpp>
#include "SiliconTorch/NVSExplorer.hpp"

// qthing stuff
// #include <qthing>


const char* TAG = "ServiceManager";


namespace SiliconTorch {

  namespace ServiceManager {

    const str NVSStateKey = "state";


    Service::Service() {
      // u8 state = 0;  // disabled -> 0   enabled -> 1
      // state = NVSExplorer::NVSExplorer::instance().getUnsignedInt(nameSpace(), NVSStateKey, state);

      // if (state >= (u8)Invalid) state = (u8)Disabled;
      // nvsState = (NVSState)state;
    }

    void Service::postInit() {

      attrsLocked = true;

      u8 state = 0;  // disabled -> 0   enabled -> 1
      state = NVSExplorer::NVSExplorer::instance().getUnsignedInt(getNameSpace(), NVSStateKey, state);

      if (state >= (u8)Invalid) state = (u8)Disabled;
      nvsState = (NVSState)state;
    }

    bool Service::isEnabled() const {
      return nvsState == Enabled;
    }

    void Service::setEnabled(bool enabled) {

      NVSState state = enabled ? Enabled : Disabled;
      u8 stateValue = (u8)state;

      bool result = SiliconTorch::NVSExplorer::NVSExplorer::instance().setU8(getNameSpace(), NVSStateKey, stateValue);

      if (!result) {
        SiliconTorch::NVSExplorer::NVSExplorer::instance().removeKey(getNameSpace(), NVSStateKey);
        result = SiliconTorch::NVSExplorer::NVSExplorer::instance().setU8(getNameSpace(), NVSStateKey, stateValue);
      }

      if (result) {
        nvsState = state;
        ESP_LOGI(TAG, "Setting service[ %s ] to %s", getName().c_str(), enabled ? "enabled[✅]" : "disabled[❌]");
      } else {
        ESP_LOGW(TAG, "Error saving service[ %s] state!", getName().c_str());
      }
    }


    void Service::setName(const str& name) {
      if (!attrsLocked) {
        this->name = name;
      } else {
        // TODO: report error somehow?
      }
    }

    void Service::setNameSpace(const str& nameSpace) {
      if (!attrsLocked) {
        this->nameSpace = nameSpace;
      } else {
        // TODO: report error somehow?
      }
    }

    void Service::setStartOrder(u16 startOrder) {
      if (!attrsLocked) {
        this->startOrder = startOrder;
      } else {
        // TODO: report error somehow?
      }
    }


    const str& Service::getName() const {
      return name;
    }

    const str& Service::getNameSpace() const {
      return nameSpace;
    }

    u16 Service::getStartOrder() const {
      return startOrder;
    }

  }
}