// NTP headers #include #include #include template class SessionManager { public: SessionManager(int scaleDoutPin, int scaleSckPin, uint8_t tareAvgCount); void begin(); void tare(); long tareOffset() const { return scale_.offset(); }; void startMeasurements(); void stopMeasurements(); bool isMeasuring() const { return measuring_; } SessionT &session() { return session_; } void iteration(); private: WiFiUDP ntpUDP_; NTPClient timeClient_; Scale scale_; //MockScale scale; SessionT session_; bool measuring_; long lastCallTime_; int scaleDoutPin_; int scaleSckPin_; uint8_t tareAvgCount_; }; // ------------------------------------------------------------------------------------------------ template SessionManager::SessionManager(int scaleDoutPin, int scaleSckPin, uint8_t tareAvgCount) : timeClient_(ntpUDP_, "pool.ntp.org"), measuring_(false), lastCallTime_(0), scaleDoutPin_(scaleDoutPin), scaleSckPin_(scaleSckPin), tareAvgCount_(tareAvgCount) { } template void SessionManager::tare() { if(measuring_) stopMeasurements(); Serial.println("Beginning tare"); scale_.begin(scaleDoutPin_, scaleSckPin_); scale_.tare(CONFIG_TARE_AVG_COUNT); Serial.println("Finished tare"); } template void SessionManager::begin() { timeClient_.begin(); timeClient_.update(); tare(); session_.init(timeClient_.getEpochTime()); } template void SessionManager::startMeasurements() { if(measuring_ == true) return; measuring_ = true; lastCallTime_ = 0; session_.init(timeClient_.getEpochTime()); } template void SessionManager::stopMeasurements() { if(measuring_ == false) return; session_.finalize(); measuring_ = false; } template void SessionManager::iteration() { if (!measuring_) return; uint16_t measurement = -1; bool measurementDone = false; while(!measurementDone) measurementDone = scale_.measure(measurement); bool addPointSuccessful = session_.addPoint(measurement); Serial.printf("Measured: %d\n", measurement); if (!addPointSuccessful) { Serial.println("Maximum time of session reached - stopping"); stopMeasurements(); return; } if (lastCallTime_ != 0) { const long cycleDuration = millis() - lastCallTime_; if (cycleDuration <= CONFIG_MEASURE_DELAY) { delay(CONFIG_MEASURE_DELAY - cycleDuration); } else { const long skipped = (cycleDuration / CONFIG_MEASURE_DELAY); Serial.printf("Warning: measurements skipped: %ld, cycleDuration %ld", skipped, cycleDuration); for (int i = 0; i < skipped; ++i) session_.addPoint(measurement); delay(CONFIG_MEASURE_DELAY * (skipped + 1) - cycleDuration); } } lastCallTime_ = millis(); }