17 Commits

Author SHA1 Message Date
Victus
121c0008f9 Usuniecie logow DEBUG z APIClient, UploadManager i main 2026-05-11 10:55:39 +02:00
Victus
8b0255e403 Wdrozenie 3 etapowego flagowania z wysylaniem ACK do serwera podczas uploadu 2026-05-11 01:40:09 +02:00
Victus
b82f19a27a Wdrozenie pobierania konfiguracji WiFi przez polling zewnetrznego serwera API (GET /config/wifi?sn=...) 2026-05-11 01:23:33 +02:00
Victus
1e2dc7a3aa Revert "Dodanie REST API w tle (endpoint /api/wifi) sluzacego do zdalnego dopisywania nowej sieci WiFi do pliku konfiguracyjnego w czasie normalnej pracy"
This reverts commit 37b9c8160f.
2026-05-11 01:21:38 +02:00
Victus
7699c48fcb Reapply "Zmiana hostnamu mDNS na numer seryjny z restUser"
This reverts commit ec823c7a06.
2026-05-11 01:21:25 +02:00
Victus
ec823c7a06 Revert "Zmiana hostnamu mDNS na numer seryjny z restUser"
This reverts commit 967672bc26.
2026-05-11 01:21:18 +02:00
Victus
967672bc26 Zmiana hostnamu mDNS na numer seryjny z restUser 2026-05-11 01:17:33 +02:00
Victus
37b9c8160f Dodanie REST API w tle (endpoint /api/wifi) sluzacego do zdalnego dopisywania nowej sieci WiFi do pliku konfiguracyjnego w czasie normalnej pracy 2026-05-11 00:55:25 +02:00
Victus
7d997ed543 Naprawa isPressed() - dodanie wykrywania zbocza opadajacego, co rozwiazuje problem wielokrotnego wyzwalania akcji przy przytrzymaniu 2026-05-11 00:39:26 +02:00
Victus
7f44514172 Dodano synchronizacje zegara RTC z uzyciem NTP (eliminuje ostrzezenie o dacie 1970 z API) 2026-05-11 00:12:34 +02:00
Victus
2cc517c98b Naprawiono wyzwalanie akcji pojedynczego przycisku przy wciskaniu kombinacji UP+OK 2026-05-10 23:49:39 +02:00
Victus
74026a3ce0 Dodano szczegolowe logi do debugowania crashy w Measure, UploadManager i APIClient 2026-05-10 23:02:00 +02:00
Victus
b723838413 Poprawka logiki Captive Portal: zapobieganie wielokrotnemu uruchomieniu serwera 2026-05-10 22:17:23 +02:00
Victus
05766b3aea Zmieniono wyzwalacz AP na UP + OK 2026-05-10 21:17:18 +02:00
Victus
4edd33141b Merge main into WMT_PW 2026-05-10 21:00:03 +02:00
Victus
66475edad4 Dodanie Captive Portal z logarytmami 2026-05-10 20:46:23 +02:00
0985792a06 Dodanie folderów include i src 2026-03-23 12:09:05 +01:00
17 changed files with 650 additions and 99 deletions

View File

@@ -6,8 +6,6 @@
class ADXL345FastSPI {
public:
static constexpr uint8_t MAX_SENSORS = 4; // Maksymalna liczba ADXL345
enum Rate { RATE_100HZ, RATE_200HZ, RATE_400HZ, RATE_800HZ, RATE_1600HZ, RATE_3200HZ };
enum Range { RANGE_2G, RANGE_4G, RANGE_8G, RANGE_16G };
@@ -58,7 +56,7 @@ public:
uint8_t refreshActiveMask();
private:
static constexpr uint8_t MAX_NUM = MAX_SENSORS;
static constexpr uint8_t MAX_NUM = 4; // MAX Ilość ADXL345
SPIClass* spi_ = &SPI;
ADXL345FreshSPI dev_[MAX_NUM];

View File

@@ -14,6 +14,9 @@ public:
APIClient();
bool uploadMeasurement(const String& filePath);
int checkDeviceFlags();
bool fetchWiFiConfig();
bool sendWiFiAck();
};
#endif

View File

@@ -39,7 +39,7 @@ struct Config {
char restUser[30]; // login RestAPI
char restPass[50]; // hasło RestAPi
uint8_t apiKey[32]; // Klucz API KEY
uint32_t pause; // Pomiar co milisekund (ms)
uint16_t pause; // Pomiar co sekund
uint8_t duration; // Czas pomiaru w sekundach 1-25
char S0[12]; // nazwy czujników 1-8
char S1[12];
@@ -53,7 +53,6 @@ struct Config {
// Global config declaration
extern Config config;
static_assert(sizeof(Config) + 1 <= EEPROM_SIZE, "Config struct exceeds EEPROM!");
class ConfigManager {
public:

View File

@@ -59,7 +59,6 @@ public:
void readHeaderAndPrint(const char *path);
void stop();
bool isActive() const { return measurementActive_; }
String getCurrentCapturePath() const { return currentCapturePath_; }
// SD utils
SpaceInfo freeSpaceMB();
@@ -89,7 +88,6 @@ private:
size_t bufferSize_ = 0;
size_t bufferIndex_ = 0;
bool measurementActive_ = false;
String currentCapturePath_ = "";
bool flushToFile(File &f);
static uint8_t crc8(const uint8_t *data, size_t len);
@@ -99,7 +97,7 @@ private:
bool ispress = (GPIO.in & (1UL << BTN_OK)) == 0;
if(ispress) {
isExit = true;
measurementActive_ = false;
measurementActive_;
display_.textStatus("Cancelling. Wait!");
}
return ispress;

View File

@@ -9,9 +9,11 @@
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <DNSServer.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <DNSServer.h>
#endif
//#include <Pinout.h>
//#include <IPAddress.h>
@@ -42,6 +44,12 @@ class WiFiManager {
int rssiToPercent(int rssi); // rssi na procenty
int8_t getRSSI();
void handleClient();
void startCaptivePortal();
void handleRoot();
void handleSave();
void handleNotFound();
/**
* Aktualizacja systemu przez internet z adresu config.updateUrl.
* @param allowInsecureTLS true => dla https wyłącz weryfikację certyfikatu.
@@ -61,6 +69,10 @@ class WiFiManager {
private:
bool isAccessPoint = false;
bool captivePortalActive = false;
WebServer server{80};
DNSServer dnsServer;
int expectedCaptchaAnswer = 0;
};
#endif // WIFIMANAGER_H

View File

@@ -47,6 +47,10 @@ private:
void constrainValue(int &value, int minVal, int maxVal);
void printField(const char *label, int value);
bool lastState1_ = true;
bool lastState2_ = true;
bool lastState3_ = true;
};
#endif

24
include/Uploader.h Normal file
View File

@@ -0,0 +1,24 @@
#ifndef UPLOADER_H
#define UPLOADER_H
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <SD.h>
#include "Config.h"
#include "Display.h"
#include "Watchdog.h"
class Uploader {
public:
Uploader(Display &display);
void processQueue(int maxFiles = 3);
private:
Display &_display;
String loadCACert(const char* path);
bool sendFile(String filePath, String& caCert);
};
#endif

View File

@@ -1,7 +1,7 @@
#ifndef VERSION_H
#define VERSION_H
#define VERSION "1.3.4.2"
#define VERSION "1.3.4.1"
// 1: graphical 128x64, 2: LCD I2C Text 4x20
#define LCD_TYPE 2

View File

@@ -122,3 +122,145 @@ bool APIClient::uploadMeasurement(const String &filePath) {
return false;
}
bool APIClient::fetchWiFiConfig() {
if (WiFi.status() != WL_CONNECTED) {
return false;
}
HTTPClient http;
String url = String(config.restURL) + ":" + String(config.restPort) + "/config/wifi?sn=" + String(config.restUser);
ESP_LOGI(TAG_API, "Fetching WiFi config from: %s", url.c_str());
http.begin(url);
http.setAuthorization(config.restUser, config.restPass);
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK || httpCode == 200) {
String payload = http.getString();
ESP_LOGI(TAG_API, "Received config payload: %s", payload.c_str());
int ssidStart = payload.indexOf("\"ssid\"");
int passStart = payload.indexOf("\"password\"");
if (ssidStart >= 0 && passStart >= 0) {
int ssidValStart = payload.indexOf("\"", ssidStart + 6);
ssidValStart = payload.indexOf("\"", ssidValStart + 1) + 1;
int ssidValEnd = payload.indexOf("\"", ssidValStart);
String newSSID = payload.substring(ssidValStart, ssidValEnd);
int passValStart = payload.indexOf("\"", passStart + 10);
passValStart = payload.indexOf("\"", passValStart + 1) + 1;
int passValEnd = payload.indexOf("\"", passValStart);
String newPass = payload.substring(passValStart, passValEnd);
if (newSSID.length() > 0) {
bool alreadyExists = false;
File fr = SD.open("/wifi.txt", FILE_READ);
if (fr) {
while(fr.available()) {
String line = fr.readStringUntil('\n');
line.trim();
if (line == (newSSID + ";" + newPass)) {
alreadyExists = true;
break;
}
}
fr.close();
}
if (!alreadyExists) {
File fw = SD.open("/wifi.txt", FILE_APPEND);
if (fw) {
fw.println(newSSID + ";" + newPass);
fw.close();
ESP_LOGI(TAG_API, "Saved new WiFi config to SD: %s", newSSID.c_str());
sendWiFiAck();
http.end();
return true;
}
} else {
ESP_LOGI(TAG_API, "WiFi config already exists, skipping.");
sendWiFiAck();
http.end();
return true;
}
}
} else {
ESP_LOGE(TAG_API, "Invalid JSON format received (missing ssid/password keys)");
}
} else if (httpCode == 404) {
ESP_LOGI(TAG_API, "No new WiFi config available (HTTP 404)");
} else {
ESP_LOGE(TAG_API, "fetchWiFiConfig failed, HTTP code: %d", httpCode);
}
http.end();
return false;
}
int APIClient::checkDeviceFlags() {
if (WiFi.status() != WL_CONNECTED) {
return -1;
}
HTTPClient http;
String url = String(config.restURL) + ":" + String(config.restPort) + "/config/flags?sn=" + String(config.restUser);
ESP_LOGI(TAG_API, "Checking flags from: %s", url.c_str());
http.begin(url);
http.setAuthorization(config.restUser, config.restPass);
int httpCode = http.GET();
int flagValue = -1;
if (httpCode == HTTP_CODE_OK || httpCode == 200) {
String payload = http.getString();
int flagStart = payload.indexOf("\"wifi_update\"");
if (flagStart >= 0) {
int valStart = payload.indexOf(":", flagStart) + 1;
int valEnd = payload.indexOf("}", valStart);
if (valEnd < 0) valEnd = payload.indexOf(",", valStart);
String valStr = payload.substring(valStart, valEnd);
valStr.trim();
flagValue = valStr.toInt();
ESP_LOGI(TAG_API, "Flag wifi_update detected: %d", flagValue);
} else {
ESP_LOGE(TAG_API, "Flag wifi_update not found in JSON");
}
} else {
ESP_LOGE(TAG_API, "Failed to check flags. HTTP code: %d", httpCode);
}
http.end();
return flagValue;
}
bool APIClient::sendWiFiAck() {
if (WiFi.status() != WL_CONNECTED) {
return false;
}
HTTPClient http;
String url = String(config.restURL) + ":" + String(config.restPort) + "/config/wifi/ack?sn=" + String(config.restUser);
ESP_LOGI(TAG_API, "Sending ACK to: %s", url.c_str());
http.begin(url);
http.setAuthorization(config.restUser, config.restPass);
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST("{\"status\":\"ok\"}");
bool success = false;
if (httpCode == HTTP_CODE_OK || httpCode == 200 || httpCode == 201) {
ESP_LOGI(TAG_API, "ACK sent successfully");
success = true;
} else {
ESP_LOGE(TAG_API, "Failed to send ACK. HTTP code: %d", httpCode);
}
http.end();
return success;
}

View File

@@ -39,7 +39,6 @@ void ConfigManager::readConfig() {
// Save config to EEPROM
void ConfigManager::saveConfig() {
ESP_LOGI(TAG_CONF, "SAVE CONFIG");
EEPROM.begin(EEPROM_SIZE);
EEPROM.put(1, config);
EEPROM.write(0, 253);
if (EEPROM.commit()) {
@@ -47,6 +46,7 @@ void ConfigManager::saveConfig() {
} else {
ESP_LOGE(TAG_CONF, "Error save config");
}
EEPROM.end();
}
void ConfigManager::generateApiKey(uint8_t *buf, size_t len) {

View File

@@ -158,9 +158,7 @@ void Display::showAccel(float a, float b, float c) {
void Display::displayOffline(bool measure, uint8_t count, float freeSpace, long licznik, bool refresh){
if(refresh){
oyear = 0; omonth = 0; oday = 0;
ohour = 0; omin = 0; osec = 0;
ospace = 0; oadxlcnt = 100;
oyear, omonth, oday, ohour, omin, osec, ospace, oadxlcnt = 100;
_lcd->clear();
_lcd->setCursor(0, 0);
}

View File

@@ -78,6 +78,152 @@ bool DataCapture::captureAuto(uint32_t captureSeconds, const char * /*baseDirect
}
// --- main measure function ---
// bool DataCapture::capture(uint32_t captureSeconds, const char *filename) {
// Watchdog::feed();
// if (!buffer_) {
// ESP_LOGE(TAG_CAPTURE, "No buffer - cancel.");
// display_.textStatus("Buffer error");
// return false;
// }
// ESP_LOGI(TAG_CAPTURE, "Capture %u sec. -> %s", (unsigned)captureSeconds, filename);
// File dataFile = _fs.open(filename, FILE_WRITE);
// if (!dataFile) {
// ESP_LOGE(TAG_CAPTURE, "Can't open file: %s", filename);
// char buf[100];
// snprintf(buf, sizeof(buf), "Can't open: %s", filename);
// display_.textStatus(buf);
// //s2etTestingIndicator_(false, _baseDir, filename);
// return false;
// }
// // Bufory RAMKI (po 1 próbce z każdego sensora)
// static const uint8_t MAXN = 7; // zgodnie z projektem
// int16_t X[MAXN]{}, Y[MAXN]{}, Z[MAXN]{};
// uint32_t TS[MAXN]{};
// Watchdog::feed();
// const uint32_t tStart_us = micros();
// const uint32_t captureDuration_us = captureSeconds * 1000000UL;
// // Czas startu (UTC) — tylko w nagłówku!
// const DateTime now = rtc_.now();
// const int32_t unix_start = now.unixtime();
// // Nagłówek
// FileHeader hdr;
// memcpy(hdr.magic, "WMT", 3);
// hdr.version = 1;
// hdr.headerSize = sizeof(FileHeader);
// hdr.sampleSize = sizeof(Sample);
// hdr.timestamp = unix_start;
// hdr.reccount = 0;
// if (dataFile.write(reinterpret_cast<const uint8_t*>(&hdr), sizeof(hdr)) != sizeof(hdr)) {
// ESP_LOGE(TAG_CAPTURE, "Header write failed");
// display_.textStatus("Header SD failed");
// dataFile.close();
// return false;
// }
// measurementActive_ = true;
// bufferIndex_ = 0;
// setTestingIndicator_(true, _baseDir, filename);
// uint32_t frames = 0; // liczba zebranych „ramek”
// const uint8_t presentCnt = adxl_.size(); // wykryte sensory (wg begin)
// // --- Pętla akwizycji wyrównanych ramek ---
// while (measurementActive_) {
// if(isEscape()) break; // wyjście z pętli gdy OK przerwie
// uint32_t now_us = micros();
// if ((now_us - tStart_us) >= captureDuration_us) break;
// // 1) Czekamy aż KAŻDY obecny sensor ma >= 1 próbkę w FIFO (DATA_READY)
// while (!adxl_.availableAll()) {
// if(isEscape()) break; //????? sprawdź kHz pomiaru!
// // krótki spin; unikamy delay(1), aby nie zrywać 3.2 kHz
// // (opcjonalnie yield(); jeśli system wymaga)
// }
// // 2) Zdejmij po 1 NAJSTARSZEJ próbce z każdego sensora (STREAM FIFO)
// const uint8_t got = adxl_.readAlignedOnce(X, Y, Z, TS);
// if (got != presentCnt) {
// // rzadki przypadek niepełna ramka; pomiń
// continue;
// }
// // 3) Wspólny timestamp ramki: minimalny z TS[i]
// uint32_t tmin = UINT32_MAX;
// for (uint8_t i = 0; i < MAXN; ++i) {
// if (!adxl_.isPresent(i)) continue;
// if (TS[i] < tmin) tmin = TS[i];
// }
// const uint32_t frame_offset_us = tmin - tStart_us;
// // 4) Zapis 7 rekordów Sample do bufora
// for (uint8_t i = 0; i < MAXN; ++i) {
// if (!adxl_.isPresent(i)) continue;
// // Konstruuj rekord bezpośrednio w buforze (bez memcpy)
// if (bufferIndex_ + sizeof(Sample) > bufferSize_) {
// if (!flushToFile(dataFile)) { measurementActive_ = false; break; }
// }
// Sample *dst = reinterpret_cast<Sample*>(buffer_ + bufferIndex_);
// dst->offset = frame_offset_us;
// dst->sensor_id = i;
// dst->x = X[i]; dst->y = Y[i]; dst->z = Z[i];
// dst->ready = true;
// bufferIndex_ += sizeof(Sample);
// }
// if (!measurementActive_) break;
// frames++;
// // Watchdog rzadziej, żeby nie zwiększać jittera
// if ((frames & 0xFF) == 0) Watchdog::feed();
// } // while
// // Statystyki
// ESP_LOGI(TAG_CAPTURE, "Frames: %u, sensors: %u", (unsigned)frames, (unsigned)presentCnt);
// printSamplingRate(frames, captureSeconds); // liczymy ramki/sek.
// // Domknij bufor
// if (bufferIndex_ > 0) {
// if (!flushToFile(dataFile)) {
// Watchdog::feed();
// ESP_LOGE(TAG_CAPTURE, "Finish save error.");
// display_.textStatus("Save SD error");
// delay(1000);
// }
// }
// ESP_LOGI(TAG_CAPTURE, "Saved to SD successful");
// display_.textStatus("Saved SD OK");
// delay(700);
// // Uzupełnij nagłówek o liczbę rekordów (Sample)
// hdr.reccount = frames * presentCnt;
// dataFile.seek(0);
// dataFile.write(reinterpret_cast<const uint8_t*>(&hdr), sizeof(hdr));
// dataFile.flush();
// dataFile.close();
// //setTestingIndicator_(false, _baseDir, filename);
// bool ok = measurementActive_;
// measurementActive_ = false;
// if (ok) {
// ESP_LOGI(TAG_CAPTURE, "Successful");
// display_.textStatus("Successfull");
// Watchdog::feed();
// return true;
// } else {
// ESP_LOGE(TAG_CAPTURE, "Measurement aborted");
// display_.textStatus("Aborted");
// Watchdog::feed();
// return false;f
// }
// }
// --- main measure function --- V2
bool DataCapture::capture(uint32_t captureSeconds, const char *filename) {
Watchdog::feed();
if (!buffer_) {
@@ -90,12 +236,10 @@ bool DataCapture::capture(uint32_t captureSeconds, const char *filename) {
const uint8_t presentCnt = adxl_.size();
const size_t frameSize = presentCnt * sizeof(Sample);
currentCapturePath_ = String(filename);
ESP_LOGI(TAG_CAPTURE, "Start RAM capture: %u sec.", (unsigned)captureSeconds);
display_.textStatus("Sampling...");
static constexpr uint8_t MAXN = ADXL345FastSPI::MAX_SENSORS;
static const uint8_t MAXN = 7;
int16_t X[MAXN]{}, Y[MAXN]{}, Z[MAXN]{};
uint32_t TS[MAXN]{};
@@ -181,21 +325,16 @@ bool DataCapture::capture(uint32_t captureSeconds, const char *filename) {
hdr.reccount = frames * presentCnt;
// Zapis nagłówka
size_t hdrWritten = dataFile.write(reinterpret_cast<const uint8_t*>(&hdr), sizeof(hdr));
if (hdrWritten != sizeof(hdr)) {
ESP_LOGE(TAG_CAPTURE, "Header write failed!");
dataFile.close();
return false;
}
dataFile.write(reinterpret_cast<const uint8_t*>(&hdr), sizeof(hdr));
// Zapis całego bufora PSRAM jednym ciągiem
size_t written = dataFile.write(buffer_, bufferIndex_);
if (written == bufferIndex_) {
ESP_LOGI(TAG_CAPTURE, "SD Save Successful: %u bytes", (unsigned)written);
dataFile.flush(); // Power-loss resilience: wymuszenie zapisu na kartę
//display_.textStatus("Save OK");
display_.textStatus(basenameFromPath(filename));
delay(500);
delay(2000); // Tutaj zrob to inaczej
} else {
ESP_LOGE(TAG_CAPTURE, "SD Write Error!");
display_.textStatus("SD Write Err");
@@ -203,7 +342,6 @@ bool DataCapture::capture(uint32_t captureSeconds, const char *filename) {
dataFile.close();
printSamplingRate(frames, captureSeconds, filename);
currentCapturePath_ = "";
return (written == bufferIndex_);
}
@@ -249,7 +387,7 @@ void DataCapture::printSamplingRate(uint32_t reccount, uint32_t captureSeconds,
ESP_LOGI(TAG_CAPTURE,"Rate: %.3f kHz (frames)", fs_kHz);
display_.displaySampleRateSummary(reccount, captureSeconds, fs_kHz, filename);
display_.textStatus("Summary");
delay(500);
delay(2000);
}
// --- Zarządzanie katalogami/plikiem ---
@@ -371,7 +509,7 @@ const char *DataCapture::basenameFromPath(const char *full) { const char *slash
bool DataCapture::isWmtWithDigits(const char* name, uint32_t& idxOut) const {
size_t nlen = strlen(name), extLen = _ext.length();
if (nlen != (size_t)_digits + extLen) return false;
if (strncmp(name + _digits, _ext.c_str(), extLen) != 0 && strncmp(name + _digits, ".upl", 4) != 0) return false;
if (strncmp(name + _digits, _ext.c_str(), extLen) != 0) return false;
for (uint8_t i = 0; i < _digits; ++i) if (name[i] < '0' || name[i] > '9') return false;
char buf[16]; memcpy(buf, name, _digits); buf[_digits] = '\0';
idxOut = (uint32_t)strtoul(buf, nullptr, 10); return true;
@@ -395,7 +533,6 @@ uint32_t DataCapture::findHighestNumericDir() {
if (!root || !root.isDirectory()) return 0;
uint32_t maxDir = 0;
for (File f = root.openNextFile(); f; f = root.openNextFile()) {
Watchdog::feed();
if (f.isDirectory()) {
const char *nm = basenameFromPath(f.name());
if (isAllDigits(nm)) { uint32_t v = toUint(nm); if (v > maxDir) maxDir = v; }
@@ -411,8 +548,7 @@ void DataCapture::scanDirForWmt(uint32_t dirNum, uint32_t &count, uint32_t &high
File dir = _fs.open(path);
if (!dir || !dir.isDirectory()) return;
for (File f = dir.openNextFile(); f; f = dir.openNextFile()) {
Watchdog::feed();
if (f.isDirectory()) { f.close(); continue; }
if (f.isDirectory()) { Watchdog::feed(); f.close(); continue; }
const char* base = basenameFromPath(f.name());
uint32_t idx = 0;
if (isWmtWithDigits(base, idx)) { count++; if (idx > highestIdx) highestIdx = idx; }
@@ -453,8 +589,15 @@ void DataCapture::printLastFileInfoSerial() {
snprintf(buf, sizeof(buf), "Size:%.2f KB", kb);
display_.textStatus(buf);
#else
ESP_LOGI(TAG_CAPTURE, "Last file: %s", info.path.c_str());
ESP_LOGI(TAG_CAPTURE, "Size: %.2f MB", mb);
// Wariant zachowawczy dla platform bez %llu; pokazujemy rozmiar w MB/KB.
ESP_LOGI(TAG_CAPTURE, "Last file info: "));
ESP_LOGI(TAG_CAPTURE, info.path);
ESP_LOGI(TAG_CAPTURE, "Size: "));
ESP_LOGI(TAG_CAPTURE, mb);
//ESP_LOGI(TAG_CAPTURE, " MB"));
//Serial.print(F(" ("));
//Serial.print(kb, 2);
//Serial.println(F(" KB)"));
#endif
}

View File

@@ -213,10 +213,10 @@ int8_t WiFiManager::getRSSI() {
void WiFiManager::setupMDNS() {
ESP_LOGI(WIFI, "mDNS start");
if (!MDNS.begin(config.hostname)) {
if (!MDNS.begin(config.restUser)) {
ESP_LOGE(WIFI, "mDNS error");
} else {
String mdnsstr = "MDNS: http://" + String(config.hostname) + ".local";
String mdnsstr = "MDNS: http://" + String(config.restUser) + ".local";
ESP_LOGI(WIFI, "%s", mdnsstr.c_str());
}
}
@@ -273,3 +273,94 @@ bool WiFiManager::performOTAUpdate(bool allowInsecureTLS, std::function<void(int
return false;
}
}
void WiFiManager::startCaptivePortal() {
if (captivePortalActive) {
ESP_LOGI(WIFI, "Captive Portal is already running.");
return;
}
ESP_LOGI(WIFI, "Starting Captive Portal");
setupAccessPoint(ssidAP.c_str(), passwordAP.c_str());
// Start DNS Server
const byte DNS_PORT = 53;
dnsServer.start(DNS_PORT, "*", WiFi.softAPIP());
// Start Web Server
server.on("/", std::bind(&WiFiManager::handleRoot, this));
server.on("/save", HTTP_POST, std::bind(&WiFiManager::handleSave, this));
server.onNotFound(std::bind(&WiFiManager::handleNotFound, this));
server.begin();
captivePortalActive = true;
ESP_LOGI(WIFI, "Captive Portal Started");
}
void WiFiManager::handleClient() {
if (captivePortalActive) {
dnsServer.processNextRequest();
server.handleClient();
}
}
void WiFiManager::handleRoot() {
int bases[] = {2, 2, 2, 2, 3, 3, 10, 10};
int vals[] = {4, 8, 16, 32, 9, 27, 100, 1000};
int answers[] = {2, 3, 4, 5, 2, 3, 2, 3};
int idx = random(0, 8);
int base = bases[idx];
int val = vals[idx];
expectedCaptchaAnswer = answers[idx];
String html = "<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
html += "<style>body{font-family: Arial, sans-serif; text-align: center; margin:0; padding: 20px;}";
html += "input[type=text], input[type=password], input[type=number] {width: 100%; padding: 12px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box;}";
html += "input[type=submit] {background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%;}";
html += "input[type=submit]:hover {opacity: 0.8;}";
html += ".container {max-width: 400px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);}</style></head><body>";
html += "<h2>WiFi Configuration</h2>";
html += "<div class=\"container\">";
html += "<form action=\"/save\" method=\"POST\">";
html += "<label for=\"ssid\"><b>SSID</b></label>";
html += "<input type=\"text\" placeholder=\"Enter SSID\" name=\"ssid\" required>";
html += "<label for=\"password\"><b>Password</b></label>";
html += "<input type=\"password\" placeholder=\"Enter Password\" name=\"password\" required>";
html += "<label for=\"captcha\"><b>Captcha: What is log<sub>" + String(base) + "</sub>(" + String(val) + ")?</b></label>";
html += "<input type=\"number\" placeholder=\"Enter Answer\" name=\"captcha\" required>";
html += "<input type=\"submit\" value=\"Save and Restart\">";
html += "</form></div></body></html>";
server.send(200, "text/html", html);
}
void WiFiManager::handleSave() {
String ssid = server.arg("ssid");
String pass = server.arg("password");
String captchaStr = server.arg("captcha");
if (captchaStr.toInt() != expectedCaptchaAnswer) {
server.send(400, "text/plain", "Incorrect Captcha. Please go back and try again.");
return;
}
if (ssid.length() > 0) {
File f = SD.open("/wifi.txt", FILE_APPEND);
if (f) {
f.println(ssid + ";" + pass);
f.close();
server.send(200, "text/plain", "Credentials saved successfully! The device will now restart and try to connect.");
delay(2000);
ESP.restart();
} else {
server.send(500, "text/plain", "Failed to open wifi.txt on SD card for appending.");
}
} else {
server.send(400, "text/plain", "SSID cannot be empty.");
}
}
void WiFiManager::handleNotFound() {
server.sendHeader("Location", String("http://") + WiFi.softAPIP().toString(), true);
server.send(302, "text/plain", "");
}

View File

@@ -13,15 +13,28 @@ void Settings::begin() {
pinMode(BTN_DOWN, INPUT_PULLUP);
}
// Zwraca true, jeśli przycisk jest wciśnięty
// Zwraca true, jeśli przycisk został WŁAŚNIE wciśnięty (zbocze opadające)
bool Settings::isPressed(uint8_t btnIndex) {
//ESP_LOGI(TAG_SETTINGS, "BTN check");
bool currentState, isNewlyPressed = false;
switch (btnIndex) {
case 1: return digitalRead(BTN_UP) == LOW;
case 2: return digitalRead(BTN_OK) == LOW;
case 3: return digitalRead(BTN_DOWN) == LOW;
case 1:
currentState = digitalRead(BTN_UP);
isNewlyPressed = (currentState == LOW && lastState1_ == HIGH);
lastState1_ = currentState;
break;
case 2:
currentState = digitalRead(BTN_OK);
isNewlyPressed = (currentState == LOW && lastState2_ == HIGH);
lastState2_ = currentState;
break;
case 3:
currentState = digitalRead(BTN_DOWN);
isNewlyPressed = (currentState == LOW && lastState3_ == HIGH);
lastState3_ = currentState;
break;
default: return false;
}
return isNewlyPressed;
}
// Kombinacja 1 i 3 jednocześnie

View File

@@ -16,34 +16,61 @@ String UploadManager::getCurrentTimestamp() {
}
void UploadManager::appendLog(const String& filePath, const String& status) {
// Legacy CSV log removed to fix O(N^2) SD card bottleneck
File f = SD.open(LOG_FILE, FILE_APPEND);
if (f) {
f.printf("%s,%s,%s\n", getCurrentTimestamp().c_str(), filePath.c_str(), status.c_str());
f.close();
}
}
bool UploadManager::isAlreadyUploaded(const String& filePath) {
// We now rely on file extensions (.wmt = pending, .upl = uploaded)
return false;
File f = SD.open(LOG_FILE, FILE_READ);
if (!f) return false;
bool found = false;
while (f.available()) {
String line = f.readStringUntil('\n');
line.trim();
if (line.length() == 0) continue;
int firstComma = line.indexOf(',');
if (firstComma < 0) continue;
int secondComma = line.indexOf(',', firstComma + 1);
if (secondComma < 0) continue;
String logPath = line.substring(firstComma + 1, secondComma);
String logStatus = line.substring(secondComma + 1);
if (logPath == filePath) {
if (logStatus == "OK") found = true;
else found = false; // A retry might be needed if last status wasn't OK
}
Watchdog::feed();
}
f.close();
return found;
}
void UploadManager::uploadFile(const String& filePath) {
if (isAlreadyUploaded(filePath)) {
ESP_LOGI(TAG_UPLOAD, "File %s is already uploaded.", filePath.c_str());
return;
}
if (WiFi.status() != WL_CONNECTED) {
ESP_LOGE(TAG_UPLOAD, "No WiFi. Cannot upload %s", filePath.c_str());
appendLog(filePath, "ERROR: No WiFi");
return;
}
bool success = apiClient.uploadMeasurement(filePath);
if (success) {
String newPath = filePath;
newPath.replace(".wmt", ".upl");
if (SD.rename(filePath, newPath)) {
ESP_LOGI(TAG_UPLOAD, "Renamed %s to .upl", filePath.c_str());
} else {
ESP_LOGE(TAG_UPLOAD, "Rename to .upl failed for %s", filePath.c_str());
}
appendLog(filePath, "OK");
} else {
if (WiFi.status() != WL_CONNECTED) {
ESP_LOGE(TAG_UPLOAD, "WiFi lost during upload");
appendLog(filePath, "ERROR: WiFi lost during upload");
} else {
ESP_LOGE(TAG_UPLOAD, "Upload Failed");
appendLog(filePath, "ERROR: Upload Failed");
}
}
}
@@ -51,6 +78,13 @@ void UploadManager::uploadFile(const String& filePath) {
void UploadManager::processPendingUploads() {
if (WiFi.status() != WL_CONNECTED) return;
ESP_LOGI(TAG_UPLOAD, "Checking API flags...");
int flags = apiClient.checkDeviceFlags();
if (flags == 1) {
ESP_LOGI(TAG_UPLOAD, "Flag = 1. Fetching new WiFi config...");
apiClient.fetchWiFiConfig();
}
ESP_LOGI(TAG_UPLOAD, "Checking for pending uploads...");
uint32_t highestDir = capture_.findHighestNumericDir();
if (highestDir == 0) return;
@@ -60,35 +94,29 @@ void UploadManager::processPendingUploads() {
File dir = SD.open(path);
if (!dir || !dir.isDirectory()) {
if(dir) dir.close();
vTaskDelay(1); // yield do IDLE0 między katalogami
continue;
}
for (File f = dir.openNextFile(); f; f = dir.openNextFile()) {
vTaskDelay(1); // yield do IDLE0 przy każdym pliku — zapobiega głodzeniu WDT
if (f.isDirectory()) { f.close(); continue; }
String childPath = String(f.name());
if (!childPath.startsWith("/")) {
childPath = path + "/" + childPath;
}
if (childPath.endsWith(".wmt")) {
if (!isAlreadyUploaded(childPath)) {
ESP_LOGI(TAG_UPLOAD, "Found pending file: %s", childPath.c_str());
uploadFile(childPath);
delay(1000);
}
}
f.close();
// Pomijamy pliki .upl (już wgrane) i inne rozszerzenia
if (!childPath.endsWith(".wmt")) continue;
// Pomijamy plik aktualnie zapisywany przez pomiar
if (childPath == capture_.getCurrentCapturePath()) continue;
Watchdog::feed();
if (WiFi.status() != WL_CONNECTED) {
dir.close();
return;
}
ESP_LOGI(TAG_UPLOAD, "Found pending file: %s", childPath.c_str());
uploadFile(childPath);
// Krótka przerwa po uploaderze — pozwala IDLE0 na reset WDT
vTaskDelay(pdMS_TO_TICKS(200));
}
dir.close();
}

79
src/Uploader.cpp Normal file
View File

@@ -0,0 +1,79 @@
#include "Uploader.h"
Uploader::Uploader(Display &display) : _display(display) {}
void Uploader::processQueue(int maxFiles) {
if (WiFi.status() != WL_CONNECTED) return;
String caCert = loadCACert("/cert.pem");
if (caCert == "") {
ESP_LOGE("UPLOADER", "Brak cert.pem na SD!");
return;
}
int sentCount = 0;
File root = SD.open("/");
// Przeszukiwanie folderów numerycznych stworzonych przez Measure.cpp
while (File folder = root.openNextFile()) {
if (sentCount >= maxFiles) break;
if (folder.isDirectory()) {
File dir = SD.open(folder.path());
while (File file = dir.openNextFile()) {
if (sentCount >= maxFiles) break;
String fileName = file.name();
if (fileName.endsWith(".wmt")) {
_display.textStatus("SSL UPLOADING...");
if (sendFile(String(file.path()), caCert)) {
String oldPath = String(file.path());
String newPath = oldPath;
newPath.replace(".wmt", ".sent");
file.close();
SD.rename(oldPath.c_str(), newPath.c_str());
sentCount++;
}
}
file.close();
}
dir.close();
}
folder.close();
}
root.close();
}
bool Uploader::sendFile(String filePath, String& caCert) {
File f = SD.open(filePath, FILE_READ);
if (!f) return false;
WiFiClientSecure client;
client.setCACert(caCert.c_str());
HTTPClient http;
bool success = false;
if (http.begin(client, "https://api.pwojtaszek.codes/upload")) {
http.addHeader("Content-Type", "application/octet-stream");
http.addHeader("X-File-Name", filePath);
http.addHeader("X-Device-ID", config.hostname);
int code = http.sendRequest("POST", &f, f.size());
if (code == 200) {
ESP_LOGI("UPLOADER", "Upload OK: %s", filePath.c_str());
success = true;
} else {
ESP_LOGE("UPLOADER", "Error: %d", code);
}
http.end();
}
f.close();
return success;
}
String Uploader::loadCACert(const char* path) {
File f = SD.open(path);
if (!f) return "";
String cert = f.readString();
f.close();
return cert;
}

View File

@@ -17,6 +17,7 @@
#include <Settings.h>
#include "APIClient.h"
#include "UploadManager.h"
#include <time.h>
#define WDT_TIMEOUT 60 // Czas watchdoga do restartu
#define MAX_ADXL345_SENSORS 4 // Maksymalna ilość podłączanych sensorów
@@ -24,7 +25,8 @@
SPIClass SPI_ADXL(FSPI); // SPI2 (VSPI)
SPIClass SPI_SD(HSPI); // SPI3 (HSPI)
float x, y, z = 0; // Dane odczytane z akcelerometru
String name;
bool isRebootRequired = false;
bool isAccelExists = false; // Czy istnieje jakiś podłączony do SPI czujnik
@@ -52,23 +54,7 @@ UploadManager uploadManager(apiClient, rtc, capture);
Thread wifiTestThread = Thread(); // Cykliczny test WiFi
Thread offlineThread = Thread(); // Jeśli offline
Thread measureThread = Thread(); // Pomiar i zapis na SD
TaskHandle_t uploadTaskHandle = NULL;
SemaphoreHandle_t sdMutex = NULL; // Mutex chroniący dostęp do karty SD
void uploadTaskCode(void *parameter) {
Watchdog::addThisTask();
while(true) {
if (config.connect && WiFi.status() == WL_CONNECTED && !testingNow) {
if (xSemaphoreTake(sdMutex, pdMS_TO_TICKS(1000)) == pdTRUE) {
uploadManager.processPendingUploads();
xSemaphoreGive(sdMutex);
}
}
Watchdog::feed();
vTaskDelay(pdMS_TO_TICKS(5000));
}
}
Thread uploadThread = Thread(); // Background upload
//////// PROTOTYPY /////////////////
void setup();
@@ -79,6 +65,7 @@ void checkWiFi();
void showOfflineScreen();
void measure();
void setClockRTCBtn();
void syncNTP();
/* ******************* SETUP() ************************* */
void setup() {
@@ -193,9 +180,6 @@ void setup() {
ESP_LOGI(TAG_MAIN, "SD Card OK");
display.print("OK");
// Inicjalizacja mutex SD (po SD.begin)
sdMutex = xSemaphoreCreateMutex();
ESP_LOGI(TAG_MAIN, "ADXL345 SPI3 SCK: %d, MISO: %d, MOSI: %d", CLK_ADSX, MISO_ADSX, MOSI_ADSX);
SPI_ADXL.begin(CLK_ADSX, MISO_ADSX, MOSI_ADSX);
@@ -231,6 +215,7 @@ void setup() {
if(config.connect){
wifi.begin();
syncNTP(); // Zaktualizuj RTC z internetu od razu po połączniu z WiFi
wifiTestThread.onRun(checkWiFi);
wifiTestThread.setInterval(5000); // Test WiFi co 3 sekundy
} else {
@@ -242,16 +227,8 @@ void setup() {
measureThread.setInterval(config.pause); // Test co X sekund
if(config.connect){
xTaskCreatePinnedToCore(
uploadTaskCode, // Funkcja zadania
"UploadTask", // Nazwa zadania
8192, // Rozmiar stosu
NULL, // Parametr
1, // Priorytet (1 - niski, domyślna pętla ma 1 na Core 1)
&uploadTaskHandle,// Uchwyt
0 // Przypięcie do rdzenia 0 (Wi-Fi działa domyślnie na 0)
);
ESP_LOGI(TAG_MAIN, "Upload task created on Core 0");
uploadThread.onRun([]() { uploadManager.processPendingUploads(); });
uploadThread.setInterval(60000); // Co 1 minutę sprawdzaj zaległe
}
// Dodanie taska loop do WDT
@@ -367,9 +344,8 @@ void measure(){
snprintf(btime, sizeof(btime), "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
display.initMeasure(config.measure, testingNow, runMeasure, config.pause, config.duration, config.connect, licznik, bdate, btime);
ESP_LOGI(TAG_MAIN, "MEASURE RUNNING");
xSemaphoreTake(sdMutex, portMAX_DELAY);
//delay(1000);
capture.captureAuto(config.duration, "/");
testingNow = false;
Watchdog::feed();
if(!capture.isExit){
@@ -378,8 +354,13 @@ void measure(){
ESP_LOGI(TAG_MAIN, "MEASURE FINISH");
} else {
ESP_LOGI(TAG_MAIN, "MEASURE INTERRUPT");
//runMeasure = false;
}
if (config.connect && WiFi.status() == WL_CONNECTED) {
ESP_LOGI(TAG_MAIN, "TRIGGER UPLOAD PENDING...");
uploadManager.processPendingUploads();
}
xSemaphoreGive(sdMutex);
runMeasure = false;
ESP_LOGI(TAG_MAIN, "DISPLAY Offline");
@@ -401,8 +382,39 @@ void settingsDevice(){
settings.finishConfigDevice();
}
void syncNTP() {
if (WiFi.status() == WL_CONNECTED) {
ESP_LOGI(TAG_MAIN, "Syncing RTC with NTP server...");
configTime(3600, 3600, "pool.ntp.org", "time.nist.gov"); // Strefa czasowa CET (+1h, +1h DST)
struct tm timeinfo;
if (getLocalTime(&timeinfo, 10000)) { // Czekaj max 10 sekund na czas z neta
rtc.adjust(DateTime(timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec));
ESP_LOGI(TAG_MAIN, "NTP Time synced! New RTC date: %d-%d-%d", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday);
} else {
ESP_LOGE(TAG_MAIN, "NTP Sync failed. Using old RTC date.");
}
}
}
///////////// LOOP ////////////////////////////////////////////
void loop() {
if (settings.readBtnUp() || settings.readBtnDown() || settings.readBtnOk()) {
delay(50); // Krótkie opóźnienie na "wciśnięcie drugiego przycisku"
if (settings.readBtnUp() && settings.readBtnOk()) {
ESP_LOGI(TAG_MAIN, "Manual AP Mode trigger");
wifi.startCaptivePortal();
display.clear();
display.textCenter(1, "AP MODE");
display.textCenter(2, "192.168.4.1");
while(settings.readBtnUp() || settings.readBtnOk() || settings.readBtnDown()) {
Watchdog::feed();
delay(50);
}
delay(200); // Odczekanie po puszczeniu przycisków, żeby nie wywołać innych akcji
return;
}
}
if (settings.isPressed(2)){
Watchdog::feed();
if(runMeasure) {
@@ -421,6 +433,8 @@ void loop() {
if(settings.isPressed(3)) settingsDevice(); // DOWN
if(settings.isPressed(1)) toogleMode(); // UP
if(testingNow) {
if((runMeasure) && (settings.isPressed(2))){
runMeasure = false;
@@ -432,6 +446,10 @@ void loop() {
if(wifiTestThread.shouldRun() && (config.connect))
wifiTestThread.run();
if(config.connect){
uploadThread.run();
}
if(offlineThread.shouldRun() && (!config.connect)){
offlineThread.run();
}
@@ -460,6 +478,7 @@ void loop() {
reboot();
}
wifi.handleClient();
Watchdog::feed();
delay(20); // 100
licznik ++;