Logging til Webserver lavet

This commit is contained in:
2026-07-15 17:15:24 +02:00
parent e2b9f0dc9e
commit ca1a188fea
14 changed files with 803 additions and 405 deletions

View File

@@ -11,10 +11,16 @@ public:
bool sendTagEvent(
const String& json) const;
bool sendLogEntry(
const String& json) const;
private:
static constexpr const char* TagReadEndpointUrl =
"http://filamentguard.maximuss.dk/";
static constexpr const char* TagEventEndpointUrl =
"http://filamentguard.maximuss.dk/";
static constexpr const char* LogEndpointUrl =
"http://filamentguard.maximuss.dk/";
};

View File

@@ -0,0 +1,24 @@
#pragma once
#include <Arduino.h>
enum class FilamentGuardLogLevel
{
Info,
Error
};
struct FilamentGuardLogEntry
{
String deviceId;
String hostname;
String firmwareVersion;
FilamentGuardLogLevel level;
String category;
String message;
String data;
unsigned long uptimeMilliseconds = 0;
};

View File

@@ -0,0 +1,16 @@
#pragma once
#include <Arduino.h>
#include "FilamentGuardLogEntry.h"
class FilamentGuardLogEntrySerializer
{
public:
static String serialize(
const FilamentGuardLogEntry& logEntry);
private:
static const char* logLevelToString(
FilamentGuardLogLevel logLevel);
};

View File

@@ -0,0 +1,63 @@
#pragma once
#include <Arduino.h>
#include "FilamentGuardApiClient.h"
#include "FilamentGuardDeviceInfo.h"
#include "FilamentGuardLogEntry.h"
#include "FilamentGuardLogEntrySerializer.h"
class FilamentGuardLogger
{
public:
void begin(
const String& firmwareVersion);
void setDeviceInfo(
const FilamentGuardDeviceInfo& deviceInfo);
void info(
const String& category,
const String& message,
const String& data = String());
void error(
const String& category,
const String& message,
const String& data = String());
void process();
private:
static constexpr size_t QueueSize = 20;
FilamentGuardLogEntry queue[QueueSize];
size_t queueStart = 0;
size_t queueCount = 0;
String firmwareVersion;
FilamentGuardDeviceInfo deviceInfo;
bool hasDeviceInfo = false;
FilamentGuardLogEntrySerializer serializer;
FilamentGuardApiClient apiClient;
void log(
FilamentGuardLogLevel level,
const String& category,
const String& message,
const String& data);
void writeToSerial(
const FilamentGuardLogEntry& logEntry) const;
void enqueue(
const FilamentGuardLogEntry& logEntry);
bool tryPeek(
FilamentGuardLogEntry& logEntry) const;
void dequeue();
};

View File

@@ -1,8 +1,16 @@
#pragma once
#include "FilamentGuardLogger.h"
class FirmwareUpdater
{
public:
explicit FirmwareUpdater(
FilamentGuardLogger& logger);
bool begin();
void checkForUpdate();
private:
FilamentGuardLogger& logger;
};

View File

@@ -6,6 +6,7 @@
#include "FilamentGuardApiClient.h"
#include "FilamentGuardDeviceInfo.h"
#include "FilamentGuardLogger.h"
#include "FilamentGuardTagRead.h"
#include "FilamentGuardTagReadSerializer.h"
#include "OpenPrintTagData.h"
@@ -14,7 +15,8 @@
class Pn5180Reader
{
public:
Pn5180Reader();
explicit Pn5180Reader(
FilamentGuardLogger& logger);
void begin();
@@ -44,6 +46,7 @@ private:
OpenPrintTagParser openPrintTagParser;
FilamentGuardTagReadSerializer tagReadSerializer;
FilamentGuardApiClient apiClient;
FilamentGuardLogger& logger;
FilamentGuardDeviceInfo deviceInfo;
@@ -69,11 +72,6 @@ private:
void clearLastUid();
void printUid(
const uint8_t* uid,
uint8_t uidLength,
bool reverseOrder) const;
String formatUid(
const uint8_t* uid,
uint8_t uidLength,
@@ -83,17 +81,9 @@ private:
uint8_t* uid,
uint8_t uidLength);
void printTagRead(
const FilamentGuardTagRead& tagRead) const;
void printTagReadJson(
void logTagRead(
const FilamentGuardTagRead& tagRead) const;
void sendTagRead(
const FilamentGuardTagRead& tagRead) const;
void printBlock(
uint8_t blockNumber,
const uint8_t* data,
uint8_t blockSize) const;
};

View File

@@ -1,8 +1,18 @@
#pragma once
#include "FilamentGuardLogger.h"
class WifiSetup
{
public:
bool connect(const char* hostname);
explicit WifiSetup(
FilamentGuardLogger& logger);
bool connect(
const char* hostname);
void resetSettings();
private:
FilamentGuardLogger& logger;
};

View File

@@ -43,12 +43,6 @@ namespace
"Content-Type",
"application/json");
Serial.println();
Serial.print("Sender ");
Serial.print(description);
Serial.print(" til: ");
Serial.println(endpointUrl);
const int responseCode =
httpClient.POST(json);
@@ -70,30 +64,26 @@ namespace
const String responseBody =
httpClient.getString();
Serial.print("HTTP-status: ");
Serial.println(responseCode);
if (!responseBody.isEmpty())
{
Serial.println("Svar fra API:");
Serial.println(responseBody);
}
const bool successful =
responseCode >= 200 &&
responseCode < 300;
if (successful)
if (!successful)
{
Serial.print(description);
Serial.println(
" blev sendt korrekt.");
}
else
{
Serial.print(description);
Serial.println(
" blev afvist af API'et.");
Serial.print(
" blev afvist. HTTP-status: ");
Serial.println(responseCode);
if (!responseBody.isEmpty())
{
Serial.println(
"Svar fra API:");
Serial.println(
responseBody);
}
}
httpClient.end();
@@ -118,4 +108,13 @@ bool FilamentGuardApiClient::sendTagEvent(
TagEventEndpointUrl,
json,
"taghændelse");
}
bool FilamentGuardApiClient::sendLogEntry(
const String& json) const
{
return postJson(
LogEndpointUrl,
json,
"log");
}

View File

@@ -0,0 +1,58 @@
#include "FilamentGuardLogEntrySerializer.h"
#include <ArduinoJson.h>
String FilamentGuardLogEntrySerializer::serialize(
const FilamentGuardLogEntry& logEntry)
{
JsonDocument document;
document["deviceId"] =
logEntry.deviceId;
document["hostname"] =
logEntry.hostname;
document["firmwareVersion"] =
logEntry.firmwareVersion;
document["level"] =
logLevelToString(
logEntry.level);
document["category"] =
logEntry.category;
document["message"] =
logEntry.message;
document["data"] =
logEntry.data;
document["uptimeMilliseconds"] =
logEntry.uptimeMilliseconds;
String json;
serializeJson(
document,
json);
return json;
}
const char* FilamentGuardLogEntrySerializer::logLevelToString(
const FilamentGuardLogLevel logLevel)
{
switch (logLevel)
{
case FilamentGuardLogLevel::Info:
return "Info";
case FilamentGuardLogLevel::Error:
return "Error";
default:
return "Info";
}
}

245
src/FilamentGuardLogger.cpp Normal file
View File

@@ -0,0 +1,245 @@
#include "FilamentGuardLogger.h"
#include <WiFi.h>
namespace
{
constexpr unsigned long RetryDelayMilliseconds =
60000;
unsigned long nextSendAttemptAt =
0;
bool isWaitingForRetry()
{
if (nextSendAttemptAt == 0)
{
return false;
}
return static_cast<long>(
millis() -
nextSendAttemptAt) < 0;
}
}
void FilamentGuardLogger::begin(
const String& newFirmwareVersion)
{
firmwareVersion =
newFirmwareVersion;
}
void FilamentGuardLogger::setDeviceInfo(
const FilamentGuardDeviceInfo& newDeviceInfo)
{
deviceInfo =
newDeviceInfo;
hasDeviceInfo = true;
}
void FilamentGuardLogger::info(
const String& category,
const String& message,
const String& data)
{
log(
FilamentGuardLogLevel::Info,
category,
message,
data);
}
void FilamentGuardLogger::error(
const String& category,
const String& message,
const String& data)
{
log(
FilamentGuardLogLevel::Error,
category,
message,
data);
}
void FilamentGuardLogger::process()
{
if (WiFi.status() != WL_CONNECTED)
{
return;
}
if (!hasDeviceInfo)
{
return;
}
if (isWaitingForRetry())
{
return;
}
FilamentGuardLogEntry logEntry;
if (!tryPeek(logEntry))
{
return;
}
if (logEntry.deviceId.isEmpty())
{
logEntry.deviceId =
deviceInfo.deviceId;
}
if (logEntry.hostname.isEmpty())
{
logEntry.hostname =
deviceInfo.hostname;
}
const String json =
serializer.serialize(
logEntry);
if (!apiClient.sendLogEntry(json))
{
nextSendAttemptAt =
millis() +
RetryDelayMilliseconds;
return;
}
nextSendAttemptAt = 0;
dequeue();
}
void FilamentGuardLogger::log(
const FilamentGuardLogLevel level,
const String& category,
const String& message,
const String& data)
{
FilamentGuardLogEntry logEntry;
if (hasDeviceInfo)
{
logEntry.deviceId =
deviceInfo.deviceId;
logEntry.hostname =
deviceInfo.hostname;
}
logEntry.firmwareVersion =
firmwareVersion;
logEntry.level =
level;
logEntry.category =
category;
logEntry.message =
message;
logEntry.data =
data;
logEntry.uptimeMilliseconds =
millis();
writeToSerial(
logEntry);
enqueue(
logEntry);
}
void FilamentGuardLogger::writeToSerial(
const FilamentGuardLogEntry& logEntry) const
{
Serial.print('[');
if (logEntry.level ==
FilamentGuardLogLevel::Error)
{
Serial.print("Error");
}
else
{
Serial.print("Info");
}
Serial.print("] ");
if (!logEntry.category.isEmpty())
{
Serial.print('[');
Serial.print(
logEntry.category);
Serial.print("] ");
}
Serial.println(
logEntry.message);
if (!logEntry.data.isEmpty())
{
Serial.print("Data: ");
Serial.println(
logEntry.data);
}
}
void FilamentGuardLogger::enqueue(
const FilamentGuardLogEntry& logEntry)
{
if (queueCount >= QueueSize)
{
dequeue();
}
const size_t queueIndex =
(queueStart + queueCount) %
QueueSize;
queue[queueIndex] =
logEntry;
++queueCount;
}
bool FilamentGuardLogger::tryPeek(
FilamentGuardLogEntry& logEntry) const
{
if (queueCount == 0)
{
return false;
}
logEntry =
queue[queueStart];
return true;
}
void FilamentGuardLogger::dequeue()
{
if (queueCount == 0)
{
return;
}
queue[queueStart] =
FilamentGuardLogEntry();
queueStart =
(queueStart + 1) %
QueueSize;
--queueCount;
}

View File

@@ -1,50 +1,71 @@
#include "FirmwareUpdater.h"
#include <Arduino.h>
#include <WiFi.h>
#include <SPIFFS.h>
#include <WiFi.h>
#include <esp32FOTA.hpp>
namespace
{
constexpr const char* FirmwareType = "filamentguard";
constexpr const char* FirmwareVersion = "1.0.1";
constexpr const char* FirmwareType =
"filamentguard";
constexpr const char* FirmwareVersion =
"1.0.1";
constexpr const char* ManifestUrl =
"https://ota-filamentguard.maximuss.dk/firmware/manifest.json";
esp32FOTA firmwareUpdate(
FirmwareType,
FirmwareVersion
);
FirmwareVersion);
CryptoFileAsset rootCertificate(
"/root_ca.pem",
&SPIFFS
);
&SPIFFS);
}
FirmwareUpdater::FirmwareUpdater(
FilamentGuardLogger& newLogger)
: logger(newLogger)
{
}
bool FirmwareUpdater::begin()
{
Serial.println("Starter firmware-opdatering...");
logger.info(
"FirmwareUpdater",
"Starter firmware-opdatering.");
if (!SPIFFS.begin(false))
{
Serial.println("Kunne ikke starte SPIFFS.");
logger.error(
"FirmwareUpdater",
"Kunne ikke starte SPIFFS.");
return false;
}
if (!SPIFFS.exists("/root_ca.pem"))
{
Serial.println("Certifikatet /root_ca.pem findes ikke.");
logger.error(
"FirmwareUpdater",
"Certifikatet findes ikke.",
"{\"certificate\":\"/root_ca.pem\"}");
return false;
}
firmwareUpdate.setManifestURL(ManifestUrl);
firmwareUpdate.setRootCA(&rootCertificate);
firmwareUpdate.setManifestURL(
ManifestUrl);
firmwareUpdate.setRootCA(
&rootCertificate);
firmwareUpdate.setProgressCb(
[](size_t progress, size_t total)
[this](
const size_t progress,
const size_t total)
{
if (total == 0)
{
@@ -53,31 +74,52 @@ bool FirmwareUpdater::begin()
const unsigned int percentage =
static_cast<unsigned int>(
(progress * 100) / total
);
(progress * 100) / total);
Serial.printf(
"\rFirmware download: %u%%",
percentage
);
static unsigned int lastLoggedPercentage =
101;
if (progress == total)
const bool shouldLog =
percentage == 100 ||
percentage / 10 !=
lastLoggedPercentage / 10;
if (!shouldLog)
{
Serial.println();
return;
}
}
);
Serial.print("Firmwaretype: ");
Serial.println(FirmwareType);
lastLoggedPercentage =
percentage;
Serial.print("Firmwareversion: ");
Serial.println(FirmwareVersion);
const String progressData =
String("{\"percentage\":") +
percentage +
",\"downloadedBytes\":" +
progress +
",\"totalBytes\":" +
total +
"}";
Serial.print("Manifest: ");
Serial.println(ManifestUrl);
logger.info(
"FirmwareUpdater",
"Firmware downloades.",
progressData);
});
Serial.println("Firmware-opdatering er klar.");
const String firmwareData =
String("{\"firmwareType\":\"") +
FirmwareType +
"\",\"firmwareVersion\":\"" +
FirmwareVersion +
"\",\"manifestUrl\":\"" +
ManifestUrl +
"\"}";
logger.info(
"FirmwareUpdater",
"Firmware-opdatering er klar.",
firmwareData);
return true;
}
@@ -86,26 +128,36 @@ void FirmwareUpdater::checkForUpdate()
{
if (WiFi.status() != WL_CONNECTED)
{
Serial.println(
"Firmwarekontrol sprunget over: Wi-Fi er ikke forbundet."
);
logger.error(
"FirmwareUpdater",
"Firmwarekontrol sprunget over: Wi-Fi er ikke forbundet.");
return;
}
Serial.println("Kontrollerer efter ny firmware...");
logger.info(
"FirmwareUpdater",
"Kontrollerer efter ny firmware.");
const bool updateAvailable =
firmwareUpdate.execHTTPcheck();
if (!updateAvailable)
{
Serial.println("Ingen ny firmware fundet.");
logger.info(
"FirmwareUpdater",
"Ingen ny firmware fundet.");
return;
}
Serial.println("Ny firmware fundet.");
Serial.println("Downloader og installerer firmware...");
logger.info(
"FirmwareUpdater",
"Ny firmware fundet.");
logger.info(
"FirmwareUpdater",
"Downloader og installerer firmware.");
firmwareUpdate.execOTA();
}

View File

@@ -2,9 +2,17 @@
#include <cstring>
Pn5180Reader::Pn5180Reader()
: iso15693Reader(NssPin, BusyPin, ResetPin),
iso14443Reader(NssPin, BusyPin, ResetPin)
Pn5180Reader::Pn5180Reader(
FilamentGuardLogger& newLogger)
: iso15693Reader(
NssPin,
BusyPin,
ResetPin),
iso14443Reader(
NssPin,
BusyPin,
ResetPin),
logger(newLogger)
{
}
@@ -20,7 +28,8 @@ void Pn5180Reader::begin()
void Pn5180Reader::setDeviceInfo(
const FilamentGuardDeviceInfo& newDeviceInfo)
{
deviceInfo = newDeviceInfo;
deviceInfo =
newDeviceInfo;
}
void Pn5180Reader::printVersionInformation()
@@ -47,54 +56,63 @@ void Pn5180Reader::printVersionInformation()
eepromVersion,
sizeof(eepromVersion));
Serial.println();
Serial.println("PN5180 versionsoplysninger:");
if (!productRead ||
!firmwareRead ||
!eepromRead)
{
Serial.println(
logger.error(
"NfcReader",
"Kunne ikke laese versionsoplysninger fra PN5180.");
return;
}
Serial.printf(
"Produktversion: %u.%u\n",
productVersion[1],
productVersion[0]);
const String versionData =
String("{\"productVersion\":\"") +
productVersion[1] +
"." +
productVersion[0] +
"\",\"firmwareVersion\":\"" +
firmwareVersion[1] +
"." +
firmwareVersion[0] +
"\",\"eepromVersion\":\"" +
eepromVersion[1] +
"." +
eepromVersion[0] +
"\"}";
Serial.printf(
"Firmwareversion: %u.%u\n",
firmwareVersion[1],
firmwareVersion[0]);
Serial.printf(
"EEPROM-version: %u.%u\n",
eepromVersion[1],
eepromVersion[0]);
logger.info(
"NfcReader",
"PN5180 versionsoplysninger laest.",
versionData);
}
void Pn5180Reader::checkForTag()
{
bool tagFound = false;
if (activeProtocol == TagProtocol::Iso14443A)
if (activeProtocol ==
TagProtocol::Iso14443A)
{
tagFound = checkIso14443Tag();
tagFound =
checkIso14443Tag();
}
else if (activeProtocol == TagProtocol::Iso15693)
else if (activeProtocol ==
TagProtocol::Iso15693)
{
tagFound = checkIso15693Tag();
tagFound =
checkIso15693Tag();
}
else
{
tagFound = checkIso14443Tag();
tagFound =
checkIso14443Tag();
if (!tagFound)
{
tagFound = checkIso15693Tag();
tagFound =
checkIso15693Tag();
}
}
@@ -120,21 +138,24 @@ bool Pn5180Reader::checkIso14443Tag()
}
const uint8_t uidLength =
iso14443Reader.readCardSerial(uid);
iso14443Reader.readCardSerial(
uid);
if (uidLength == 0)
{
return false;
}
if (activeProtocol == TagProtocol::Iso14443A)
if (activeProtocol ==
TagProtocol::Iso14443A)
{
return isSameUid(
uid,
uidLength);
}
if (activeProtocol != TagProtocol::None)
if (activeProtocol !=
TagProtocol::None)
{
return false;
}
@@ -144,15 +165,19 @@ bool Pn5180Reader::checkIso14443Tag()
uidLength,
TagProtocol::Iso14443A);
Serial.print(
"ISO14443A-tag fundet | UID: ");
const String tagData =
String("{\"protocol\":\"ISO14443A\",") +
"\"tagUid\":\"" +
formatUid(
uid,
uidLength,
false) +
"\"}";
printUid(
uid,
uidLength,
false);
Serial.println();
logger.info(
"NfcReader",
"ISO14443A-tag fundet.",
tagData);
return true;
}
@@ -165,7 +190,8 @@ bool Pn5180Reader::checkIso15693Tag()
iso15693Reader.setupRF();
const ISO15693ErrorCode result =
iso15693Reader.getInventory(uid);
iso15693Reader.getInventory(
uid);
if (result != ISO15693_EC_OK)
{
@@ -174,14 +200,16 @@ bool Pn5180Reader::checkIso15693Tag()
constexpr uint8_t uidLength = 8;
if (activeProtocol == TagProtocol::Iso15693)
if (activeProtocol ==
TagProtocol::Iso15693)
{
return isSameUid(
uid,
uidLength);
}
if (activeProtocol != TagProtocol::None)
if (activeProtocol !=
TagProtocol::None)
{
return false;
}
@@ -197,7 +225,8 @@ bool Pn5180Reader::checkIso15693Tag()
iso15693Reader.getInventory(
confirmedUid);
if (confirmationResult != ISO15693_EC_OK)
if (confirmationResult !=
ISO15693_EC_OK)
{
return false;
}
@@ -215,15 +244,19 @@ bool Pn5180Reader::checkIso15693Tag()
uidLength,
TagProtocol::Iso15693);
Serial.print(
"ISO15693-tag fundet | UID: ");
const String tagData =
String("{\"protocol\":\"ISO15693\",") +
"\"tagUid\":\"" +
formatUid(
uid,
uidLength,
true) +
"\"}";
printUid(
uid,
uidLength,
true);
Serial.println();
logger.info(
"NfcReader",
"ISO15693-tag fundet.",
tagData);
dumpIso15693Tag(
uid,
@@ -239,7 +272,8 @@ bool Pn5180Reader::checkIso15693Tag()
void Pn5180Reader::handleTagMissing()
{
if (activeProtocol == TagProtocol::None)
if (activeProtocol ==
TagProtocol::None)
{
return;
}
@@ -252,14 +286,29 @@ void Pn5180Reader::handleTagMissing()
return;
}
Serial.println("NFC-tag fjernet.");
const bool reverseOrder =
activeProtocol ==
TagProtocol::Iso15693;
const String tagData =
String("{\"tagUid\":\"") +
formatUid(
lastUid,
lastUidLength,
reverseOrder) +
"\"}";
logger.info(
"NfcReader",
"NFC-tag fjernet.",
tagData);
clearLastUid();
}
bool Pn5180Reader::isSameUid(
const uint8_t* uid,
uint8_t uidLength) const
const uint8_t uidLength) const
{
if (uid == nullptr ||
uidLength != lastUidLength)
@@ -275,8 +324,8 @@ bool Pn5180Reader::isSameUid(
void Pn5180Reader::rememberUid(
const uint8_t* uid,
uint8_t uidLength,
TagProtocol protocol)
const uint8_t uidLength,
const TagProtocol protocol)
{
std::memset(
lastUid,
@@ -288,8 +337,12 @@ void Pn5180Reader::rememberUid(
uid,
uidLength);
lastUidLength = uidLength;
activeProtocol = protocol;
lastUidLength =
uidLength;
activeProtocol =
protocol;
missingScanCount = 0;
}
@@ -301,26 +354,16 @@ void Pn5180Reader::clearLastUid()
sizeof(lastUid));
lastUidLength = 0;
activeProtocol = TagProtocol::None;
missingScanCount = 0;
}
activeProtocol =
TagProtocol::None;
void Pn5180Reader::printUid(
const uint8_t* uid,
uint8_t uidLength,
bool reverseOrder) const
{
Serial.print(
formatUid(
uid,
uidLength,
reverseOrder));
missingScanCount = 0;
}
String Pn5180Reader::formatUid(
const uint8_t* uid,
uint8_t uidLength,
bool reverseOrder) const
const uint8_t uidLength,
const bool reverseOrder) const
{
if (uid == nullptr ||
uidLength == 0)
@@ -331,7 +374,10 @@ String Pn5180Reader::formatUid(
String result;
result.reserve(
static_cast<size_t>(uidLength) * 3 - 1);
static_cast<size_t>(
uidLength) *
3 -
1);
for (uint8_t index = 0;
index < uidLength;
@@ -351,7 +397,8 @@ String Pn5180Reader::formatUid(
uid[uidIndex],
HEX);
if (index < uidLength - 1)
if (index <
uidLength - 1)
{
result += ':';
}
@@ -364,34 +411,32 @@ String Pn5180Reader::formatUid(
void Pn5180Reader::dumpIso15693Tag(
uint8_t* uid,
uint8_t uidLength)
const uint8_t uidLength)
{
constexpr uint8_t blockSize = 4;
constexpr uint8_t numberOfBlocks = 80;
constexpr size_t memorySize =
static_cast<size_t>(blockSize) *
static_cast<size_t>(
blockSize) *
numberOfBlocks;
uint8_t memory[memorySize] = {};
bool allBlocksRead = true;
Serial.println();
Serial.println(
"ISO15693 hukommelsesoplysninger:");
const String memoryData =
String("{\"blockSizeBytes\":") +
blockSize +
",\"numberOfBlocks\":" +
numberOfBlocks +
",\"memorySizeBytes\":" +
memorySize +
"}";
Serial.print("Blokstoerrelse: ");
Serial.print(blockSize);
Serial.println(" bytes");
Serial.print("Antal blokke: ");
Serial.println(numberOfBlocks);
Serial.print("Samlet hukommelse: ");
Serial.print(memorySize);
Serial.println(" bytes");
Serial.println();
logger.info(
"NfcReader",
"Laeser ISO15693-hukommelse.",
memoryData);
for (uint8_t blockNumber = 0;
blockNumber < numberOfBlocks;
@@ -399,7 +444,8 @@ void Pn5180Reader::dumpIso15693Tag(
{
uint8_t* blockData =
memory +
static_cast<size_t>(blockNumber) *
static_cast<size_t>(
blockNumber) *
blockSize;
const ISO15693ErrorCode readResult =
@@ -409,34 +455,38 @@ void Pn5180Reader::dumpIso15693Tag(
blockData,
blockSize);
if (readResult != ISO15693_EC_OK)
if (readResult !=
ISO15693_EC_OK)
{
allBlocksRead = false;
Serial.print("Blok ");
Serial.print(blockNumber);
const String errorData =
String("{\"blockNumber\":") +
blockNumber +
",\"errorCode\":" +
static_cast<int>(
readResult) +
"}";
Serial.print(
" kunne ikke laeses. Fejlkode: ");
Serial.println(
static_cast<int>(readResult));
logger.error(
"NfcReader",
"ISO15693-blok kunne ikke laeses.",
errorData);
}
}
Serial.println();
if (!allBlocksRead)
{
Serial.println(
"OpenPrintTag-parseren blev ikke startet, "
"fordi en eller flere blokke ikke kunne laeses.");
logger.error(
"NfcReader",
"OpenPrintTag-parseren blev ikke startet, fordi en eller flere blokke ikke kunne laeses.");
return;
}
Serial.println(
"Fortolker OpenPrintTag-data...");
logger.info(
"NfcReader",
"Fortolker OpenPrintTag-data.");
OpenPrintTagData openPrintTagData;
@@ -445,7 +495,8 @@ void Pn5180Reader::dumpIso15693Tag(
memorySize,
openPrintTagData))
{
Serial.println(
logger.error(
"NfcReader",
"OpenPrintTag-data kunne ikke fortolkes.");
return;
@@ -465,104 +516,24 @@ void Pn5180Reader::dumpIso15693Tag(
tagRead.tag =
openPrintTagData;
printTagRead(tagRead);
printTagReadJson(tagRead);
sendTagRead(tagRead);
logTagRead(
tagRead);
sendTagRead(
tagRead);
}
void Pn5180Reader::printTagRead(
const FilamentGuardTagRead& tagRead) const
{
Serial.println();
Serial.println(
"FilamentGuard tagregistrering:");
Serial.print("Device ID: ");
Serial.println(
tagRead.device.deviceId);
Serial.print("Hostname: ");
Serial.println(
tagRead.device.hostname);
Serial.print("Tag UID: ");
Serial.println(
tagRead.tag.tagUid);
Serial.print("Instance UUID: ");
Serial.println(
tagRead.tag.instanceUuid);
Serial.print("Producent: ");
Serial.println(
tagRead.tag.brand);
Serial.print("Materiale: ");
Serial.println(
tagRead.tag.materialName);
Serial.print("Materialetype: ");
Serial.println(
tagRead.tag.materialType);
Serial.print("Farve: ");
Serial.println(
tagRead.tag.colorHex);
if (tagRead.tag.hasNominalWeight)
{
Serial.print("Nominel vaegt: ");
Serial.print(
tagRead.tag.nominalWeightGrams);
Serial.println(" g");
}
if (tagRead.tag.hasActualWeight)
{
Serial.print("Faktisk startvaegt: ");
Serial.print(
tagRead.tag.actualWeightGrams);
Serial.println(" g");
}
if (tagRead.tag.hasSpoolWeight)
{
Serial.print("Spolevaegt: ");
Serial.print(
tagRead.tag.spoolWeightGrams);
Serial.println(" g");
}
Serial.print("Forbrugt vaegt: ");
Serial.print(
tagRead.tag.consumedWeightGrams);
Serial.println(" g");
Serial.print("Resterende vaegt: ");
Serial.print(
tagRead.tag.remainingWeightGrams);
Serial.println(" g");
Serial.println();
}
void Pn5180Reader::printTagReadJson(
void Pn5180Reader::logTagRead(
const FilamentGuardTagRead& tagRead) const
{
const String json =
tagReadSerializer.serialize(
tagRead);
Serial.println(
"FilamentGuard JSON:");
Serial.println(json);
Serial.println();
logger.info(
"NfcReader",
"OpenPrintTag registreret.",
json);
}
void Pn5180Reader::sendTagRead(
@@ -572,63 +543,6 @@ void Pn5180Reader::sendTagRead(
tagReadSerializer.serialize(
tagRead);
apiClient.sendTagRead(json);
}
void Pn5180Reader::printBlock(
uint8_t blockNumber,
const uint8_t* data,
uint8_t blockSize) const
{
Serial.print("Blok ");
if (blockNumber < 10)
{
Serial.print('0');
}
Serial.print(blockNumber);
Serial.print(": ");
for (uint8_t index = 0;
index < blockSize;
++index)
{
if (data[index] < 0x10)
{
Serial.print('0');
}
Serial.print(
data[index],
HEX);
if (index < blockSize - 1)
{
Serial.print(' ');
}
}
Serial.print(" | ");
for (uint8_t index = 0;
index < blockSize;
++index)
{
const char character =
static_cast<char>(
data[index]);
if (character >= 32 &&
character <= 126)
{
Serial.print(character);
}
else
{
Serial.print('.');
}
}
Serial.println();
apiClient.sendTagRead(
json);
}

View File

@@ -4,7 +4,14 @@
#include <WiFi.h>
#include <WiFiManager.h>
bool WifiSetup::connect(const char* hostname)
WifiSetup::WifiSetup(
FilamentGuardLogger& newLogger)
: logger(newLogger)
{
}
bool WifiSetup::connect(
const char* hostname)
{
WiFi.mode(WIFI_OFF);
delay(100);
@@ -16,35 +23,42 @@ bool WifiSetup::connect(const char* hostname)
wifiManager.setConfigPortalTimeout(180);
Serial.print("Hostname: ");
Serial.println(hostname);
const String connectionData =
String("{\"hostname\":\"") +
hostname +
"\"}";
Serial.println("Forbinder til Wi-Fi...");
logger.info(
"WiFi",
"Forbinder til Wi-Fi.",
connectionData);
const bool connected =
wifiManager.autoConnect(
"FilamentGuard-Setup"
);
"FilamentGuard-Setup");
if (!connected)
{
Serial.println(
"Wi-Fi-opsætning fejlede eller fik timeout."
);
logger.error(
"WiFi",
"Wi-Fi-opsætning fejlede eller fik timeout.");
return false;
}
Serial.println("Wi-Fi forbundet.");
const String wifiData =
String("{\"hostname\":\"") +
WiFi.getHostname() +
"\",\"ssid\":\"" +
WiFi.SSID() +
"\",\"ipAddress\":\"" +
WiFi.localIP().toString() +
"\"}";
Serial.print("Hostname: ");
Serial.println(WiFi.getHostname());
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("IP-adresse: ");
Serial.println(WiFi.localIP());
logger.info(
"WiFi",
"Wi-Fi forbundet.",
wifiData);
return true;
}
@@ -55,7 +69,7 @@ void WifiSetup::resetSettings()
wifiManager.resetSettings();
Serial.println(
"Gemte Wi-Fi-oplysninger er slettet."
);
logger.info(
"WiFi",
"Gemte Wi-Fi-oplysninger er slettet.");
}

View File

@@ -1,18 +1,28 @@
#include <Arduino.h>
#include <WiFi.h>
#include "DeviceIdentity.h"
#include "DeviceSettings.h"
#include "FilamentGuardDeviceInfo.h"
#include "FilamentGuardLogger.h"
#include "FirmwareUpdater.h"
#include "Pn5180Reader.h"
#include "WifiSetup.h"
namespace
{
constexpr const char* FirmwareVersion =
"1.0.1";
}
FilamentGuardLogger logger;
DeviceSettings deviceSettings;
DeviceIdentity deviceIdentity;
WifiSetup wifiSetup;
FirmwareUpdater firmwareUpdater;
Pn5180Reader pn5180Reader;
WifiSetup wifiSetup(logger);
FirmwareUpdater firmwareUpdater(logger);
Pn5180Reader pn5180Reader(logger);
FilamentGuardDeviceInfo deviceInfo;
@@ -21,13 +31,19 @@ void setup()
Serial.begin(115200);
delay(1000);
Serial.println();
Serial.println("FilamentGuard starter...");
Serial.println("Firmwareversion: 1.0.1");
Serial.println("OTA-testen lykkedes.");
logger.begin(
FirmwareVersion);
Serial.println();
Serial.println("Initialiserer PN5180...");
logger.info(
"System",
"FilamentGuard starter.",
String("{\"firmwareVersion\":\"") +
FirmwareVersion +
"\"}");
logger.info(
"NfcReader",
"Initialiserer PN5180.");
pn5180Reader.begin();
pn5180Reader.printVersionInformation();
@@ -36,69 +52,52 @@ void setup()
deviceSettings.getOrCreateHostname();
deviceInfo =
deviceIdentity.create(hostname);
deviceIdentity.create(
hostname);
logger.setDeviceInfo(
deviceInfo);
pn5180Reader.setDeviceInfo(
deviceInfo);
Serial.println();
Serial.println("Enhedsidentitet:");
const String deviceData =
String("{\"deviceId\":\"") +
deviceInfo.deviceId +
"\",\"hostname\":\"" +
deviceInfo.hostname +
"\"}";
Serial.print("Device ID: ");
Serial.println(
deviceInfo.deviceId);
Serial.print("Hostname: ");
Serial.println(
deviceInfo.hostname);
logger.info(
"System",
"Enhedsidentitet oprettet.",
deviceData);
if (!wifiSetup.connect(
deviceInfo.hostname.c_str()))
{
Serial.println(
"Kunne ikke forbinde til Wi-Fi.");
Serial.println(
"Genstarter om 5 sekunder...");
logger.error(
"System",
"Enheden genstarter om 5 sekunder.");
delay(5000);
ESP.restart();
}
Serial.print(
"Wi-Fi forbundet | Hostname: ");
Serial.print(
WiFi.getHostname());
Serial.print(" | SSID: ");
Serial.print(WiFi.SSID());
Serial.print(" | IP: ");
Serial.print(WiFi.localIP());
Serial.print(" | Signal: ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
if (!firmwareUpdater.begin())
{
Serial.println(
"Firmware-opdatering kunne ikke startes.");
}
else
if (firmwareUpdater.begin())
{
firmwareUpdater.checkForUpdate();
}
Serial.println();
Serial.println(
logger.info(
"NfcReader",
"Klar til at laese ISO15693-tags.");
}
void loop()
{
pn5180Reader.checkForTag();
logger.process();
delay(200);
}