8 Commits
Author SHA1 Message Date
Jakob Gegeniger 22dd3a3ea9 step: hardening, major release 2026-11-03 21:30:02 +01:00
Jakob Gegeniger 4fe0599988 step: less noise 2026-11-03 00:37:12 +01:00
Gustice 2617407d18 watchdog 2026-11-01 16:46:30 +01:00
Jakob Gegeniger e7a9e0316e wip 2026-10-28 21:19:56 +01:00
Jakob Gegeniger 855ffe5915 wip: currentSens 2026-10-25 01:15:13 +02:00
Gustice 85e2e92991 step: Watchdog 2026-10-23 21:41:53 +02:00
Jakob Gegeniger 27a791c4c0 step: Consistent abort msg, live signal and last Will 2026-10-22 22:14:48 +02:00
Jakob Gegeniger dbe482655c step: version-return 2026-10-17 11:46:48 +02:00
14 changed files with 480 additions and 124 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
build/ build/
.cache/ .cache/
deploy/ deploy/
.venv/
+14
View File
@@ -29,4 +29,18 @@ sudo crontab -e
``` ```
```txt ```txt
0 3 * * * /sbin/reboot 0 3 * * * /sbin/reboot
0 23 * * * /sbin/reboot
0 6 * * * /sbin/reboot
*/5 * * * * ping -c 4 8.8.8.8 > /dev/null 2>&1
```
## PowerSavings
```sh
sudo nano /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf
```
```ini
[connection]
wifi.powersave = 2
``` ```
+60 -10
View File
@@ -1,20 +1,20 @@
# Autostart applications # Autostart applications
```sh ```sh
sudo nano /etc/systemd/system/Sword.service sudo nano /etc/systemd/system/SwordMain.service
``` ```
./
```ini ```ini
[Unit] [Unit]
Description=My Raspberry Pi Application Description=IoT Service for Sword Station
After=network-online.target After=network-online.target
Wants=network-online.target Wants=network-online.target
[Service] [Service]
Type=simple Type=simple
User=gustice User=theUser
WorkingDirectory=/home/pi/SwordMain WorkingDirectory=/home/theUser/SwordMain
ExecStart=bash start.sh ExecStart=/home/theUser/SwordMain/run.sh
Restart=on-failure Restart=on-failure
RestartSec=5 RestartSec=5
@@ -23,16 +23,66 @@ WantedBy=multi-user.target
``` ```
```sh ```sh
chmod +x /home/pi/SwordMain/start.sh chmod +x /home/theUser/SwordMain/start.sh
# Reload systemd # Reload systemd
sudo systemctl daemon-reload sudo systemctl daemon-reload
# Enable the service # Enable the service
sudo systemctl enable Sword.service sudo systemctl enable SwordMain.service
# start immediately # start immediately
sudo systemctl start Sword.service sudo systemctl start SwordMain.service
# check status # check status
sudo systemctl status Sword.service sudo systemctl status SwordMain.service
``` ```
game $(pwd)/assets -b "mqtts://excaliburs-erben.de:8883" -t "outdoor/king-arthur/sword/" -p "awesomeexodusoutdooradventures" -u "exodususer" game $(pwd)/assets -b "mqtts://excaliburs-erben.de:8883" -t "outdoor/king-arthur/sword/" -p "awesomeexodusoutdooradventures" -u "exodususer"
## Watchdog
```sh
sudo nano /etc/systemd/system/SwordWatchdog.service
```
```ini
[Unit]
Description=Network Watchdog for Sword
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# user root user
WorkingDirectory=/home/theUser/SwordWatchdog
ExecStart=/home/theUser/SwordWatchdog/watchdog.py
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
```
## WiFi Power
```sh
sudo nano /etc/systemd/system/wifi-txpower.service
# ..
sudo systemctl enable wifi-txpower.service
sudo systemctl start wifi-txpower.service
```
```sh
[Unit]
Description=Set WiFi TX Power limit to prevent overheating
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
# Wait 15 seconds after network connects so the network manager doesn't overwrite it
ExecStartPre=/bin/sleep 15
ExecStart=/sbin/iwconfig wlan0 txpower 20
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
```
+3
View File
@@ -13,3 +13,6 @@ pack_sword:
cp_sword: cp_sword:
@mkdir -p deploy/sword @mkdir -p deploy/sword
@cp build/src/sword/SwordMain deploy/sword @cp build/src/sword/SwordMain deploy/sword
cpexe_toServ:
scp build/src/sword/SwordMain gustice@excaliburs-erben.de:SwordMain
Submodule platform updated: b998471c3f...b74f37d999.
File renamed without changes.
+4 -1
View File
@@ -15,6 +15,7 @@ enum ServiceCommands_e {
PlaySoundPromo, PlaySoundPromo,
PlaySoundDeny, PlaySoundDeny,
PlaySoundChosen, PlaySoundChosen,
SetMaintanence,
}; };
enum GameModeCommands_e { enum GameModeCommands_e {
@@ -22,7 +23,9 @@ enum GameModeCommands_e {
GameFinished, // The Game is finished (resume to Promo mode) GameFinished, // The Game is finished (resume to Promo mode)
GameNextTryLocked, // Lock sword on next try GameNextTryLocked, // Lock sword on next try
GameNextTryRelease, // Release sword on next try GameNextTryRelease, // Release sword on next try
GameAbortTry // Abort this try GameAbortTry, // Abort this try
GamePing, // Test
GameForceAbort // Abort current state
}; };
enum OutgoingCommands_e { enum OutgoingCommands_e {
+58 -25
View File
@@ -4,8 +4,11 @@
class MqttChannel { class MqttChannel {
public: public:
static constexpr array<const char*, 3> Modes = {"Undefined", "Maintanance", "Production"};
MqttChannel(string name, string version, SwordConfig cfg, DeviceIoState& ioStat, SeqLogger& log) MqttChannel(string name, string version, SwordConfig cfg, DeviceIoState& ioStat, SeqLogger& log)
: Config(cfg), : Version(version),
Config(cfg),
IoStat(ioStat), IoStat(ioStat),
Logger(log), Logger(log),
cfgTopic(cfg.StationPath + "cfg"), cfgTopic(cfg.StationPath + "cfg"),
@@ -14,6 +17,7 @@ class MqttChannel {
eventTopic(cfg.StationPath + "event"), eventTopic(cfg.StationPath + "event"),
statTopic(cfg.StationPath + "stat"), statTopic(cfg.StationPath + "stat"),
resetTopic(cfg.StationPath + "reset"), resetTopic(cfg.StationPath + "reset"),
sendTimeout(std::chrono::seconds{1}),
serviceCommands({ serviceCommands({
// cfg-topic // cfg-topic
@@ -24,6 +28,7 @@ class MqttChannel {
{"playSound:Promo", ServiceCommands_e::PlaySoundPromo}, {"playSound:Promo", ServiceCommands_e::PlaySoundPromo},
{"playSound:Deny", ServiceCommands_e::PlaySoundDeny}, {"playSound:Deny", ServiceCommands_e::PlaySoundDeny},
{"playSound:Chosen", ServiceCommands_e::PlaySoundChosen}, {"playSound:Chosen", ServiceCommands_e::PlaySoundChosen},
{"setMaintanance", ServiceCommands_e::SetMaintanence},
}), }),
setCommands({ setCommands({
// cfg-topic // cfg-topic
@@ -37,10 +42,13 @@ class MqttChannel {
{"stayLocked", GameModeCommands_e::GameNextTryLocked}, {"stayLocked", GameModeCommands_e::GameNextTryLocked},
{"releaseLock", GameModeCommands_e::GameNextTryRelease}, {"releaseLock", GameModeCommands_e::GameNextTryRelease},
{"abortTry", GameModeCommands_e::GameAbortTry}, {"abortTry", GameModeCommands_e::GameAbortTry},
{"forceAbort", GameModeCommands_e::GameAbortTry},
{"ping", GameModeCommands_e::GamePing},
}), }),
subTopics{{setTopic, cfgTopic, resetTopic}}, subTopics{{setTopic, cfgTopic, resetTopic}},
client(name, cfg.BrockerUrl, subTopics, client(name, cfg.BrockerUrl, subTopics,
{cfg.MqttUser, cfg.MqttPassword}) { {cfg.MqttUser, cfg.MqttPassword},
MqttClient::LastWill{eventTopic, "offline", 1, false}) {
fmt::println("MQTT: Starting task:"); fmt::println("MQTT: Starting task:");
mqttCall = [this](string topic, string payload) { mqttCall = [this](string topic, string payload) {
fmt::print("MQTT: Got T:'{}' M:'{}'\n", topic, payload); fmt::print("MQTT: Got T:'{}' M:'{}'\n", topic, payload);
@@ -60,6 +68,7 @@ class MqttChannel {
client.registerCallback(mqttCall); client.registerCallback(mqttCall);
client.send(verTopic, fmt::format("{}", version)); client.send(verTopic, fmt::format("{}", version));
client.send(eventTopic, "online");
} }
std::unique_ptr<MqttQe> tryDeque() { std::unique_ptr<MqttQe> tryDeque() {
@@ -90,9 +99,9 @@ class MqttChannel {
fmt::println("Input queue flushed, {} Messages discarted", cnt); fmt::println("Input queue flushed, {} Messages discarted", cnt);
} }
static void runMasterService(Thread::Context& ctx, MqttChannel& instance, function<void()> resetCall, CurrMon& mon) { static void runMasterService(Thread::Context& ctx, MqttChannel& instance, function<void()> resetCall) {
while (true) { while (true) {
auto serMsg = instance.MasterQueue.tryDequeueFor(500ms); auto serMsg = instance.MasterQueue.tryDequeueFor(50ms);
// only resetTopic and cfgTopic arrive here // only resetTopic and cfgTopic arrive here
instance.sendStatusMessage(); instance.sendStatusMessage();
if (!serMsg) { if (!serMsg) {
@@ -102,6 +111,11 @@ class MqttChannel {
if (serMsg->Topic == instance.resetTopic) { if (serMsg->Topic == instance.resetTopic) {
return; return;
} }
if (serMsg->Payload == "setMaintanance") {
std::string m{Modes[static_cast<int>(instance.IoStat.Mode)]};
instance.client.send(instance.verTopic, fmt::format("{}", instance.Version));
continue;
}
auto payload = serMsg->Payload; auto payload = serMsg->Payload;
if (payload == "mute") { if (payload == "mute") {
@@ -140,24 +154,12 @@ class MqttChannel {
break; break;
} }
instance.IoStat.SwordLatch.moveIn(); instance.IoStat.SwordLatch.moveIn();
auto tE = std::chrono::steady_clock::now() + 6s;
while (std::chrono::steady_clock::now() < tE) {
Thread::sleep(100ms);
auto curr = mon.sampleCurrent();
}
auto currE = mon.sampleCurrent();
} break; } break;
case ServiceCommands_e::SetLockClose: { case ServiceCommands_e::SetLockClose: {
if (instance.IoStat.GameRunning) { if (instance.IoStat.GameRunning) {
break; break;
} }
instance.IoStat.SwordLatch.moveOut(); instance.IoStat.SwordLatch.moveOut();
auto tE = std::chrono::steady_clock::now() + 6s;
while (std::chrono::steady_clock::now() < tE) {
Thread::sleep(100ms);
auto curr = mon.sampleCurrent();
}
auto currE = mon.sampleCurrent();
} break; } break;
case ServiceCommands_e::PlaySoundPromo: { case ServiceCommands_e::PlaySoundPromo: {
MediaPlayer::playWavFileAsync(instance.Config.SoundPromo); MediaPlayer::playWavFileAsync(instance.Config.SoundPromo);
@@ -174,18 +176,46 @@ class MqttChannel {
resetCall(); resetCall();
} }
union IoState {
uint32_t raw{};
struct {
uint32_t mode : 2;
uint32_t mute : 1;
uint32_t sS : 1;
uint32_t sE : 1;
uint32_t sP : 1;
uint32_t lE : 1;
uint32_t v : 3;
uint32_t pD : 4;
} state;
};
void sendStatusMessage() { void sendStatusMessage() {
try { try {
auto& s = IoStat; auto& s = IoStat;
client.send(statTopic, fmt::format("M:{},snd:{},sS:{},sE:{},sP:{},lE:{},v:{},pD:{}", IoState ss;
(int)IoStat.Mode, ss.state.mode = (int)IoStat.Mode;
!s.Mute, ss.state.mute = s.Mute;
s.SwordEntry.get(), ss.state.sS = s.SwordEntry.get();
s.SwordEnd.get(), ss.state.sE = s.SwordEnd.get();
s.SwordPulled.get(), ss.state.sP = s.SwordPulled.get();
s.SwordLatch.isLocked(), ss.state.lE = s.SwordLatch.isLocked();
s.Volume, ss.state.v = s.Volume;
s.PromoDelay)); ss.state.pD = s.PromoDelay.count();
if ((ss.raw != lastState.raw) || sendTimeout.tick()) {
client.send(statTopic, fmt::format("M:{},snd:{},sS:{},sE:{},sP:{},lE:{},v:{},pD:{}",
(int)IoStat.Mode,
!s.Mute,
s.SwordEntry.get(),
s.SwordEnd.get(),
s.SwordPulled.get(),
s.SwordLatch.isLocked(),
s.Volume,
s.PromoDelay));
sendTimeout.reset();
}
lastState.raw = ss.raw;
} catch (const exception& exc) { } catch (const exception& exc) {
fmt::println(stderr, "\nERROR: Unable to connect to Setup bridge: {}", exc.what()); fmt::println(stderr, "\nERROR: Unable to connect to Setup bridge: {}", exc.what());
} }
@@ -204,6 +234,7 @@ class MqttChannel {
const std::map<string, ServiceCommands_e>& getSerCommands() { return serviceCommands; } const std::map<string, ServiceCommands_e>& getSerCommands() { return serviceCommands; }
private: private:
std::string Version;
SwordConfig Config; SwordConfig Config;
Queue<MqttQe> MasterQueue; Queue<MqttQe> MasterQueue;
Queue<MqttQe> MqttQueue; Queue<MqttQe> MqttQueue;
@@ -216,6 +247,8 @@ class MqttChannel {
const string eventTopic; const string eventTopic;
const string statTopic; const string statTopic;
const string resetTopic; const string resetTopic;
IoState lastState{};
Tick sendTimeout;
const std::map<string, GameModeCommands_e> gameCommands; const std::map<string, GameModeCommands_e> gameCommands;
const std::map<string, ServiceCommands_e> serviceCommands; const std::map<string, ServiceCommands_e> serviceCommands;
+110 -49
View File
@@ -8,13 +8,22 @@ using namespace std::literals::string_view_literals;
using namespace std::literals::chrono_literals; using namespace std::literals::chrono_literals;
using namespace std; using namespace std;
const string Version = "V 0.9.2"; const string Version = "V 1.0.0";
unique_ptr<SwordConfig> SwordCfg; unique_ptr<SwordConfig> SwordCfg;
unique_ptr<DeviceIoState> IoStat; unique_ptr<DeviceIoState> IoStat;
void processProduction(MqttChannel& mqtt, SeqLogger& log); void processProduction(MqttChannel& mqtt, SeqLogger& log);
void saveFile(string type, vector<float> values) {
auto file = fmt::output_file(type + ".txt");
for (float value : values) {
file.print("{}\n", value);
}
}
void sendOverCurrError(string type) {
}
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
CLI::App app{"Sword Firmware"}; CLI::App app{"Sword Firmware"};
string appName = "SwordDebug"; string appName = "SwordDebug";
@@ -39,6 +48,16 @@ int main(int argc, char* argv[]) {
fmt::println("## Starting Sword Station {}", Version); fmt::println("## Starting Sword Station {}", Version);
CLI11_PARSE(app, argc, argv); CLI11_PARSE(app, argc, argv);
OpMode mode{OpMode::Maintanance};
fmt::println("{}", app.get_description());
if (modeArg == "game") {
fmt::println("starting with game");
mode = OpMode::GamingMode;
} else {
fmt::println("unknown {}", modeArg);
}
std::ostringstream cmdline; std::ostringstream cmdline;
for (int i = 0; i < argc; ++i) { for (int i = 0; i < argc; ++i) {
if (i > 0) if (i > 0)
@@ -68,27 +87,28 @@ int main(int argc, char* argv[]) {
InputTransAware SwordEntry(sbPort); InputTransAware SwordEntry(sbPort);
InputTransAware SwordEnd(sePort); InputTransAware SwordEnd(sePort);
InputTransAware SwordPulled(spPort); InputTransAware SwordPulled(spPort);
LinMot SwordLatch(mOut1, mOut2);
I2cMaster i2cDev(II2cMaster::ClockRate::_400k); log.sendBootUp(Version, MqttChannel::Modes[static_cast<int>(mode)]);
AdcAds1115 adc(i2cDev, AdcAds1115::I2CAddress::Gnd); ICurrentMon* pMon = nullptr;
// Check if the ADC is connected try {
if (!adc.isConnected()) { static I2cMaster i2cDev(II2cMaster::ClockRate::_400k);
fmt::println("Failed to connect ot Sensor {}", modeArg); static AdcAds1115 adc(i2cDev, AdcAds1115::I2CAddress::Gnd);
// Check if the ADC is connected
if (!adc.isConnected()) {
fmt::println("Failed to connect ot Sensor");
}
static CurrMon mon(adc);
pMon = &mon;
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
log.sendEvent("HW-Err", "Failed to init II2-Hardware");
static ICurrentMon fakeMon;
pMon = &fakeMon;
} }
CurrMon mon(adc); LinMot SwordLatch(mOut1, mOut2, *pMon, saveFile);
IoStat = make_unique<DeviceIoState>(SwordEntry, SwordEnd, SwordPulled, SwordLatch); IoStat = make_unique<DeviceIoState>(SwordEntry, SwordEnd, SwordPulled, SwordLatch);
IoStat->Mode = mode;
fmt::println("{}", app.get_description());
if (modeArg == "game") {
fmt::println("starting with game");
IoStat->Mode = OpMode::GamingMode;
} else {
fmt::println("unknown {}", modeArg);
}
constexpr array<const char*, 4> modes = {"Undefined", "Maintanance", "PromoMode", "Production"};
log.sendBootUp(Version, modes[static_cast<int>(IoStat->Mode)]);
MqttChannel mqtt(appName, Version, *SwordCfg, *IoStat, log); MqttChannel mqtt(appName, Version, *SwordCfg, *IoStat, log);
auto resetCall = [&]() { auto resetCall = [&]() {
@@ -96,7 +116,7 @@ int main(int argc, char* argv[]) {
}; };
mqtt.flushInput(); mqtt.flushInput();
static auto conTask = Thread::createExplicit("MqttTask", MqttChannel::runMasterService, ref(mqtt), resetCall, ref(mon)); static auto conTask = Thread::createExplicit("MqttTask", MqttChannel::runMasterService, ref(mqtt), resetCall);
SwordLatch.moveOut(); SwordLatch.moveOut();
fmt::println("Running App"); fmt::println("Running App");
@@ -131,7 +151,7 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
if (IoStat->SwordPulled.isPosEdge()) { if (IoStat->SwordPulled.isPosEdge()) {
if (!IoStat->Mute) { if (!IoStat->Mute) {
if (dP.tick(IoStat->PromoDelay)) { if (dP.tick(IoStat->PromoDelay)) {
log.sendEvent("Pull", "Start Audio"); log.sendEvent("Promo-Pull", "Start Audio");
if (tsf.tick()) { if (tsf.tick()) {
MediaPlayer::playWavFileAsync(SwordCfg->SoundPromo); MediaPlayer::playWavFileAsync(SwordCfg->SoundPromo);
@@ -186,6 +206,23 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
auto& gameCmds = mqtt.getGameCommands(); auto& gameCmds = mqtt.getGameCommands();
static Tick tSend(500ms); static Tick tSend(500ms);
auto sendLogIfAborted = [&log, &mqtt](bool abort) {
if (abort) {
fmt::println("..abort");
log.sendEvent("Req", "Aborted");
mqtt.sendEvent("aborted");
}
};
auto testAbortCondition = [](MqttChannel& mqtt, string cond) -> bool {
auto abortMsg = mqtt.tryDequeueFor(10ms);
return (abortMsg && abortMsg->Payload == cond);
};
auto isDone = [](decltype(std::chrono::steady_clock::now()) until) -> bool {
return std::chrono::steady_clock::now() > until;
};
while (true) { while (true) {
auto msg = mqtt.tryDequeueFor(10ms); auto msg = mqtt.tryDequeueFor(10ms);
IoStat->tick(); IoStat->tick();
@@ -205,35 +242,42 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
} }
switch (code) { switch (code) {
case GameModeCommands_e::GamePing: {
mqtt.sendEvent("pong");
} break;
case GameModeCommands_e::GameStarted: { case GameModeCommands_e::GameStarted: {
fmt::println("Got GameStarted"); fmt::println("Got GameStarted");
log.sendEvent("Req", "GameStarted"); log.sendEvent("Req", "GameStarted");
IoStat->GameRunning = true; IoStat->GameRunning = true;
// todo abort all running tests
} break; } break;
case GameModeCommands_e::GameFinished: { case GameModeCommands_e::GameFinished: {
fmt::println("Got GameFinished"); fmt::println("Got GameFinished");
log.sendEvent("Req", "GameFinished"); log.sendEvent("Req", "GameFinished");
IoStat->GameRunning = false; IoStat->GameRunning = false;
// todo abort all running tests
} break; } break;
case GameModeCommands_e::GameNextTryLocked: { case GameModeCommands_e::GameNextTryLocked: {
bool abort = false; bool abort = false;
fmt::println("Got NextTryLock"); fmt::println("Got NextTryLock");
log.sendEvent("Req", "StayLockded"); log.sendEvent("Req", "StayLockded");
IoStat->SwordLatch.moveOut(); // Lock
while (!abort) { while (!abort) {
IoStat->SwordPulled.sample(); IoStat->SwordPulled.sample();
if (IoStat->SwordPulled.isPosEdge()) { if (IoStat->SwordPulled.isPosEdge()) {
// say: You are not the one // say: You are not the one
mqtt.sendEvent("pull"); mqtt.sendEvent("pull");
MediaPlayer::playWavFileSync(SwordCfg->getNextDeny()); MediaPlayer::playWavFileSync(SwordCfg->getNextDeny());
log.sendEvent("Req", "Pulled"); log.sendEvent("Game", "Pulled");
mqtt.sendEvent("pull-denied"); mqtt.sendEvent("pull-denied");
break; break;
} }
auto abortMsg = mqtt.tryDequeueFor(10ms); abort = testAbortCondition(mqtt, "abortTry");
abort = abortMsg && abortMsg->Payload == "abortTry";
} }
sendLogIfAborted(abort);
} break; } break;
case GameModeCommands_e::GameNextTryRelease: { case GameModeCommands_e::GameNextTryRelease: {
@@ -243,57 +287,76 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
IoStat->SwordLatch.moveIn(); IoStat->SwordLatch.moveIn();
while (!abort) { while (!abort) {
IoStat->SwordEnd.sample(); IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.getState() == pal::InputBiDebounced::State::Passive) { IoStat->SwordEntry.sample();
fmt::println("pulling sword"); if ((!IoStat->SwordEnd.isActive()) || (!IoStat->SwordEntry.isActive())) {
fmt::println("..pulling sword");
if ((!IoStat->SwordEntry.isActive()) && IoStat->SwordEnd.isActive()) {
// Unplausible state
fmt::println("!Sensor Error");
log.sendEvent("Err", "Stuck sensor");
}
break; break;
} }
auto abortMsg = mqtt.tryDequeueFor(10ms); abort = testAbortCondition(mqtt, "abortTry");
abort = abortMsg && abortMsg->Payload == "abortTry";
} }
while (!abort) { while (!abort) {
IoStat->SwordEntry.sample(); IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.getState() == pal::InputBiDebounced::State::Passive) { if (!IoStat->SwordEntry.isActive()) {
fmt::println("sword pulled"); fmt::println("..sword pulled");
break; break;
} }
auto abortMsg = mqtt.tryDequeueFor(10ms); abort = testAbortCondition(mqtt, "abortTry");
abort = abortMsg && abortMsg->Payload == "abortTry";
} }
sendLogIfAborted(abort);
if (abort) { if (abort) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isActive()) {
fmt::println("..lock after abort");
IoStat->SwordLatch.moveOut(); // Lock
log.sendEvent("Req", "Abort, Sword locked");
} else {
log.sendEvent("Req", "Abort, Sword not locked");
}
break; break;
} }
IoStat->SwordEnd.sample(); // still stuck?
bool stuckSensor = (!IoStat->SwordEntry.isActive()) &&
(IoStat->SwordEnd.isActive());
mqtt.sendEvent("pulled-out"); mqtt.sendEvent("pulled-out");
log.sendEvent("Req", "Pulled Out"); log.sendEvent("Game", "Pulled Out");
// say: You ARE the one // say: You ARE the one
MediaPlayer::playWavFileSync(SwordCfg->getNextAllow()); MediaPlayer::playWavFileSync(SwordCfg->getNextAllow());
log.sendEvent("Req", "Ceremony"); log.sendEvent("Game", "Ceremony");
mqtt.sendEvent("ceremonyDone"); mqtt.sendEvent("ceremonyDone");
while (!abort) { while (!abort) {
IoStat->SwordEntry.sample(); IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.getState() == pal::InputBiDebounced::State::Active) { if (IoStat->SwordEntry.isActive()) {
fmt::println("returning sword"); fmt::println("..returning sword");
break; break;
} }
auto abortMsg = mqtt.tryDequeueFor(10ms); abort = testAbortCondition(mqtt, "forceAbort");
abort = abortMsg && abortMsg->Payload == "abortTry"; }
if (stuckSensor) {
fmt::println("..extra wait due to stuck sensor");
Thread::sleep(3s);
} }
while (!abort) { while (!abort) {
IoStat->SwordEnd.sample(); IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.getState() == pal::InputBiDebounced::State::Active) { if (IoStat->SwordEnd.isActive()) {
fmt::println("sword returned"); fmt::println("..sword returned");
break; break;
} }
auto abortMsg = mqtt.tryDequeueFor(10ms); abort = testAbortCondition(mqtt, "forceAbort");
abort = abortMsg && abortMsg->Payload == "abortTry";
} }
if (abort) { sendLogIfAborted(abort);
break; if (abort) break;
}
log.sendEvent("Req", "Put Back"); log.sendEvent("Game", "Put Back");
mqtt.sendEvent("put-in"); mqtt.sendEvent("put-in");
IoStat->SwordLatch.moveOut(); // Lock IoStat->SwordLatch.moveOut(); // Lock
Thread::sleep(3s);
mqtt.sendEvent("locked"); mqtt.sendEvent("locked");
// mqtt.sendEvent("lock-error"); // mqtt.sendEvent("lock-error");
} break; } break;
@@ -304,5 +367,3 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
} }
} }
} }
// todo send state in background
+82 -24
View File
@@ -2,6 +2,7 @@
#include <fcntl.h> #include <fcntl.h>
#include <fmt/core.h> #include <fmt/core.h>
#include <fmt/os.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <sys/poll.h> #include <sys/poll.h>
#include <unistd.h> #include <unistd.h>
@@ -24,37 +25,22 @@
#include "Ads1115.hpp" #include "Ads1115.hpp"
#include "MqttClient.hpp" #include "MqttClient.hpp"
#include "coreExcept.hpp" #include "coreExcept.hpp"
#include "defines.hpp"
#include "gpioPort.hpp" #include "gpioPort.hpp"
#include "i2cPort.hpp" #include "i2cPort.hpp"
#include "logging.hpp" #include "logging.hpp"
#include "queue.hpp" #include "queue.hpp"
#include "textUtils.hpp" #include "textUtils.hpp"
#include "thread.hpp" #include "thread.hpp"
#include "defines.hpp"
class LinMot { class ICurrentMon {
public: public:
LinMot(OutputPort& o1, OutputPort& o2) virtual float sampleCurrent() {
: _out1(o1), return 0;
_out2(o2) {
}
void moveOut() { set(true); }
void moveIn() { set(false); }
bool isLocked() { return _locked; }
private:
OutputPort& _out1;
OutputPort& _out2;
bool _locked{};
void set(bool val) {
_out1.write(val);
_out2.write(!val);
_locked = val;
} }
}; };
class CurrMon { class CurrMon : public ICurrentMon {
// https://www.monolithicpower.com/en/documentview/productdocument/index/version/2/document_type/Datasheet/lang/EN/sku/MCS1802/document_id/5066/ // https://www.monolithicpower.com/en/documentview/productdocument/index/version/2/document_type/Datasheet/lang/EN/sku/MCS1802/document_id/5066/
public: public:
CurrMon(AdcAds1115& adc) CurrMon(AdcAds1115& adc)
@@ -69,10 +55,10 @@ class CurrMon {
_refVal = val / 8; _refVal = val / 8;
} }
float sampleCurrent() { float sampleCurrent() override {
auto val = sample() - _refVal; auto val = sample() - _refVal;
val = val / 0.264; val = val / 0.264;
fmt::println("{:.2} A", val); // fmt::println("{:.2} A", val);
return val; return val;
} }
@@ -87,6 +73,79 @@ class CurrMon {
} }
}; };
class LinMot {
public:
using SaveCall = void (*)(string, vector<float>);
LinMot(OutputPort& o1, OutputPort& o2, ICurrentMon& mon, SaveCall call)
: _out1(o1),
_out2(o2),
_mon(mon),
_saveCb(call) {
}
void moveOut() {
set(true);
auto curr = awaitMove();
_saveCb("Closing", curr);
}
void moveIn() {
set(false);
auto curr = awaitMove();
_saveCb("Opening", curr);
}
bool isLocked() { return _locked; }
private:
OutputPort& _out1;
OutputPort& _out2;
ICurrentMon& _mon;
SaveCall _saveCb;
const float FinThresh = 0.020;
const float AbortThresh = 0.050;
bool _locked{};
void set(bool val) {
_out1.write(val);
_out2.write(!val);
_locked = val;
}
vector<float> awaitMove() {
using namespace std::chrono;
auto tB = steady_clock::now();
auto tE = steady_clock::now() + 6s;
auto tMin = steady_clock::now() + 4s;
vector<float> iSample;
iSample.reserve(200);
Thread::sleep(100ms);
int err{};
while (steady_clock::now() < tE) {
Thread::sleep(50ms);
auto curr = std::abs(_mon.sampleCurrent());
iSample.push_back(curr);
if (curr < FinThresh) {
fmt::println(".. min threshold");
break;
}
if ((curr > AbortThresh) &&
(++err > 3)) {
fmt::println(".. abort due to overcurrent");
break;
}
}
auto t = duration_cast<milliseconds>(steady_clock::now() - tB);
fmt::println(".. fin after {}", t);
iSample.push_back(std::abs(_mon.sampleCurrent()));
while (std::chrono::steady_clock::now() < tMin) {
Thread::sleep(100ms);
}
return iSample;
};
};
class DeviceIoState { class DeviceIoState {
public: public:
DeviceIoState(pal::InputTransAware& entry, DeviceIoState(pal::InputTransAware& entry,
@@ -239,7 +298,7 @@ class MediaPlayer {
static thread playWavFileThread(const string& filePath) { static thread playWavFileThread(const string& filePath) {
if (filePath.empty()) { if (filePath.empty()) {
fmt::println(stderr, "ERROR: Empty file path"); fmt::println(stderr, "ERROR: Empty file path");
thread([](){ Thread::sleep(2s); }); thread([]() { Thread::sleep(2s); });
} }
return thread([filePath]() { return thread([filePath]() {
auto cmd = fmt::format("aplay '{}'", filePath); auto cmd = fmt::format("aplay '{}'", filePath);
@@ -249,5 +308,4 @@ class MediaPlayer {
} }
}); });
} }
}; };
-7
View File
@@ -279,7 +279,6 @@ void processMaintanence(MqttChannel& mqtt) {
} }
} }
IoStat->tick(); IoStat->tick();
mqtt.sendStatusMessage(Mode);
} }
} }
@@ -304,7 +303,6 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
} }
if (chrono::steady_clock::now() > (tn + 1s)) { if (chrono::steady_clock::now() > (tn + 1s)) {
tn = chrono::steady_clock::now(); tn = chrono::steady_clock::now();
mqtt.sendStatusMessage(Mode);
} }
} }
} }
@@ -341,7 +339,6 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) { while (true) {
IoStat->SwordPulled.sample(); IoStat->SwordPulled.sample();
if (IoStat->SwordPulled.isPosEdge()) { if (IoStat->SwordPulled.isPosEdge()) {
mqtt.sendStatusMessage(Mode);
// say: You are not the one // say: You are not the one
MediaPlayer::playWavFile(SwordCfg.getSoundDeny()); MediaPlayer::playWavFile(SwordCfg.getSoundDeny());
Thread::sleep(15s); Thread::sleep(15s);
@@ -358,14 +355,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) { while (true) {
IoStat->SwordEnd.sample(); IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) { if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
while (true) { while (true) {
IoStat->SwordEntry.sample(); IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) { if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
@@ -379,14 +374,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) { while (true) {
IoStat->SwordEnd.sample(); IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) { if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
while (true) { while (true) {
IoStat->SwordEntry.sample(); IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) { if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
-7
View File
@@ -282,7 +282,6 @@ void processMaintanence(MqttChannel& mqtt) {
} }
} }
IoStat->tick(); IoStat->tick();
mqtt.sendStatusMessage(Mode);
} }
} }
@@ -307,7 +306,6 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
} }
if (chrono::steady_clock::now() > (tn + 1s)) { if (chrono::steady_clock::now() > (tn + 1s)) {
tn = chrono::steady_clock::now(); tn = chrono::steady_clock::now();
mqtt.sendStatusMessage(Mode);
} }
} }
} }
@@ -344,7 +342,6 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) { while (true) {
IoStat->SwordPulled.sample(); IoStat->SwordPulled.sample();
if (IoStat->SwordPulled.isPosEdge()) { if (IoStat->SwordPulled.isPosEdge()) {
mqtt.sendStatusMessage(Mode);
// say: You are not the one // say: You are not the one
MediaPlayer::playWavFile(SwordCfg.getSoundDeny()); MediaPlayer::playWavFile(SwordCfg.getSoundDeny());
Thread::sleep(15s); Thread::sleep(15s);
@@ -361,14 +358,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) { while (true) {
IoStat->SwordEnd.sample(); IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) { if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
while (true) { while (true) {
IoStat->SwordEntry.sample(); IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) { if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
@@ -382,14 +377,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) { while (true) {
IoStat->SwordEnd.sample(); IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) { if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
while (true) { while (true) {
IoStat->SwordEntry.sample(); IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) { if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break; break;
} }
} }
+127
View File
@@ -0,0 +1,127 @@
#!/bin/env python
import os
import time
import subprocess
import requests
import sys
from datetime import datetime
# --- Configuration ---
SERVER_TO_PING = "8.8.8.8" # Replace with the server you want to monitor
FAIL_FILE = "ping_fail_timestamp.txt"
# SEQ Logger Configuration
SEQ_URL = "https://log.excaliburs-erben.de/ingest/clef"
SEQ_API_KEY = "9SWjXUxmnzcgCKYfzXMI"
# ---------------------
def ping(host):
"""Returns True if host responds to a ping request."""
command = ['ping', '-c', '1', host]
return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0
def sendSeqPayload(event):
response = requests.post(
SEQ_URL,
json=event,
headers={
"X-Seq-ApiKey": SEQ_API_KEY,
"Content-Type": "application/vnd.serilog.clef",
},
timeout=10
)
if response.status_code in (200, 201):
print("Successfully logged to SEQ.")
return True
print(f"Failed to log to SEQ: HTTP {response.status_code} - {response.text}")
return False
def check_and_report_failure():
"""Checks for the failure file on startup and logs to SEQ if found."""
if os.path.exists(FAIL_FILE):
try:
with open(FAIL_FILE, 'r') as f:
fail_time = f.read().strip()
print(f"Found failure record from: {fail_time}. Sending to SEQ...")
event = {
"@t": datetime.now().isoformat(),
"@mt": "[{App}] Rebooted due to timeout at {FailTime}",
"Level": "Information",
"App": "Watchdog",
"FailTime": fail_time
}
if sendSeqPayload(event):
os.remove(FAIL_FILE)
except Exception as e:
print(f"Error handling the failure file or connecting to SEQ: {e}")
def reset_wifi():
print(f"Network error detected. Resetting wlan0...")
try:
subprocess.run(["sudo", "nmcli", "radio", "wifi", "off"], check=True)
time.sleep(2) # Give it a moment to completely power down the interface
subprocess.run(["sudo", "nmcli", "radio", "wifi", "on"], check=True)
print("WiFi reset command sent. Waiting for network to establish...")
time.sleep(20) # Wait for DHCP and connection to re-establish
event = {
"@t": datetime.now().isoformat(),
"@mt": "[{App}] Reset WiFi due to timeout",
"Level": "Information",
"App": "Watchdog"
}
sendSeqPayload(event)
except subprocess.CalledProcessError as e:
print(f"Failed to reset WiFi: {e}", file=sys.stderr)
except Exception as e:
print(f"Failed in reset Process: {e}", file=sys.stderr)
def reboot_computer():
"""Reboot the system and report any failure."""
result = subprocess.run(["/usr/sbin/reboot"], check=True)
print(f"Reboot command exit code: {result.returncode}")
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr)
return result.returncode == 0
def main():
check_and_report_failure()
print(f"Starting connection monitor. Pinging {SERVER_TO_PING} every 10 seconds...")
fail_count = 0
while True:
if ping(SERVER_TO_PING):
fail_count = 0 # Reset counter on success
# print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping successful.")
else:
fail_count += 1
print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping failed. Consecutive failures: {fail_count}")
if fail_count >= 3:
reset_wifi()
if fail_count >= 6:
fail_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"Ping failed 3 times at {fail_time}. Writing fail-file and rebooting...")
try:
with open(FAIL_FILE, 'w') as f:
f.write(fail_time)
except IOError as e:
print(f"Failed to write fail file: {e}")
reboot_computer()
break
time.sleep(10)
if __name__ == "__main__":
main()
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# IP address of your router to test connectivity
SERVER=192.168.1.1
# Only send 2 pings, waiting 2 seconds maximum
ping -c 2 -W 2 $SERVER > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "$(date) - WiFi connection lost. Restarting wlan0..." >> /var/log/wifi_watchdog.log
# For newer Pi OS (NetworkManager)
nmcli radio wifi off
sleep 2
nmcli radio wifi on
# Older Pi OS
# ip link set wlan0 down
# sleep 2
# ip link set wlan0 up
fi