7 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
13 changed files with 441 additions and 117 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
build/
.cache/
deploy/
.venv/
+14
View File
@@ -29,4 +29,18 @@ sudo crontab -e
```
```txt
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
```sh
sudo nano /etc/systemd/system/Sword.service
sudo nano /etc/systemd/system/SwordMain.service
```
./
```ini
[Unit]
Description=My Raspberry Pi Application
Description=IoT Service for Sword Station
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=gustice
WorkingDirectory=/home/pi/SwordMain
ExecStart=bash start.sh
User=theUser
WorkingDirectory=/home/theUser/SwordMain
ExecStart=/home/theUser/SwordMain/run.sh
Restart=on-failure
RestartSec=5
@@ -23,16 +23,66 @@ WantedBy=multi-user.target
```
```sh
chmod +x /home/pi/SwordMain/start.sh
chmod +x /home/theUser/SwordMain/start.sh
# Reload systemd
sudo systemctl daemon-reload
# Enable the service
sudo systemctl enable Sword.service
sudo systemctl enable SwordMain.service
# start immediately
sudo systemctl start Sword.service
sudo systemctl start SwordMain.service
# 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"
## 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
```
Submodule platform updated: b998471c3f...b74f37d999.
File renamed without changes.
+3 -1
View File
@@ -23,7 +23,9 @@ enum GameModeCommands_e {
GameFinished, // The Game is finished (resume to Promo mode)
GameNextTryLocked, // Lock 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 {
+47 -24
View File
@@ -17,6 +17,7 @@ class MqttChannel {
eventTopic(cfg.StationPath + "event"),
statTopic(cfg.StationPath + "stat"),
resetTopic(cfg.StationPath + "reset"),
sendTimeout(std::chrono::seconds{1}),
serviceCommands({
// cfg-topic
@@ -41,10 +42,13 @@ class MqttChannel {
{"stayLocked", GameModeCommands_e::GameNextTryLocked},
{"releaseLock", GameModeCommands_e::GameNextTryRelease},
{"abortTry", GameModeCommands_e::GameAbortTry},
{"forceAbort", GameModeCommands_e::GameAbortTry},
{"ping", GameModeCommands_e::GamePing},
}),
subTopics{{setTopic, cfgTopic, resetTopic}},
client(name, cfg.BrockerUrl, subTopics,
{cfg.MqttUser, cfg.MqttPassword}) {
{cfg.MqttUser, cfg.MqttPassword},
MqttClient::LastWill{eventTopic, "offline", 1, false}) {
fmt::println("MQTT: Starting task:");
mqttCall = [this](string topic, string payload) {
fmt::print("MQTT: Got T:'{}' M:'{}'\n", topic, payload);
@@ -64,6 +68,7 @@ class MqttChannel {
client.registerCallback(mqttCall);
client.send(verTopic, fmt::format("{}", version));
client.send(eventTopic, "online");
}
std::unique_ptr<MqttQe> tryDeque() {
@@ -94,9 +99,9 @@ class MqttChannel {
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) {
auto serMsg = instance.MasterQueue.tryDequeueFor(500ms);
auto serMsg = instance.MasterQueue.tryDequeueFor(50ms);
// only resetTopic and cfgTopic arrive here
instance.sendStatusMessage();
if (!serMsg) {
@@ -149,24 +154,12 @@ class MqttChannel {
break;
}
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;
case ServiceCommands_e::SetLockClose: {
if (instance.IoStat.GameRunning) {
break;
}
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;
case ServiceCommands_e::PlaySoundPromo: {
MediaPlayer::playWavFileAsync(instance.Config.SoundPromo);
@@ -183,18 +176,46 @@ class MqttChannel {
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() {
try {
auto& s = IoStat;
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));
IoState ss;
ss.state.mode = (int)IoStat.Mode;
ss.state.mute = s.Mute;
ss.state.sS = s.SwordEntry.get();
ss.state.sE = s.SwordEnd.get();
ss.state.sP = s.SwordPulled.get();
ss.state.lE = s.SwordLatch.isLocked();
ss.state.v = s.Volume;
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) {
fmt::println(stderr, "\nERROR: Unable to connect to Setup bridge: {}", exc.what());
}
@@ -226,6 +247,8 @@ class MqttChannel {
const string eventTopic;
const string statTopic;
const string resetTopic;
IoState lastState{};
Tick sendTimeout;
const std::map<string, GameModeCommands_e> gameCommands;
const std::map<string, ServiceCommands_e> serviceCommands;
+86 -43
View File
@@ -8,13 +8,22 @@ using namespace std::literals::string_view_literals;
using namespace std::literals::chrono_literals;
using namespace std;
const string Version = "V 0.9.3";
const string Version = "V 1.0.0";
unique_ptr<SwordConfig> SwordCfg;
unique_ptr<DeviceIoState> IoStat;
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[]) {
CLI::App app{"Sword Firmware"};
string appName = "SwordDebug";
@@ -39,6 +48,16 @@ int main(int argc, char* argv[]) {
fmt::println("## Starting Sword Station {}", Version);
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;
for (int i = 0; i < argc; ++i) {
if (i > 0)
@@ -68,26 +87,28 @@ int main(int argc, char* argv[]) {
InputTransAware SwordEntry(sbPort);
InputTransAware SwordEnd(sePort);
InputTransAware SwordPulled(spPort);
LinMot SwordLatch(mOut1, mOut2);
I2cMaster i2cDev(II2cMaster::ClockRate::_400k);
AdcAds1115 adc(i2cDev, AdcAds1115::I2CAddress::Gnd);
// Check if the ADC is connected
if (!adc.isConnected()) {
fmt::println("Failed to connect ot Sensor {}", modeArg);
log.sendBootUp(Version, MqttChannel::Modes[static_cast<int>(mode)]);
ICurrentMon* pMon = nullptr;
try {
static I2cMaster i2cDev(II2cMaster::ClockRate::_400k);
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);
fmt::println("{}", app.get_description());
if (modeArg == "game") {
fmt::println("starting with game");
IoStat->Mode = OpMode::GamingMode;
} else {
fmt::println("unknown {}", modeArg);
}
log.sendBootUp(Version, MqttChannel::Modes[static_cast<int>(IoStat->Mode)]);
IoStat->Mode = mode;
MqttChannel mqtt(appName, Version, *SwordCfg, *IoStat, log);
auto resetCall = [&]() {
@@ -95,7 +116,7 @@ int main(int argc, char* argv[]) {
};
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();
fmt::println("Running App");
@@ -130,7 +151,7 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
if (IoStat->SwordPulled.isPosEdge()) {
if (!IoStat->Mute) {
if (dP.tick(IoStat->PromoDelay)) {
log.sendEvent("Pull", "Start Audio");
log.sendEvent("Promo-Pull", "Start Audio");
if (tsf.tick()) {
MediaPlayer::playWavFileAsync(SwordCfg->SoundPromo);
@@ -185,6 +206,23 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
auto& gameCmds = mqtt.getGameCommands();
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) {
auto msg = mqtt.tryDequeueFor(10ms);
IoStat->tick();
@@ -204,23 +242,29 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
}
switch (code) {
case GameModeCommands_e::GamePing: {
mqtt.sendEvent("pong");
} break;
case GameModeCommands_e::GameStarted: {
fmt::println("Got GameStarted");
log.sendEvent("Req", "GameStarted");
IoStat->GameRunning = true;
// system("pinctrl set 6 ip pd");
// todo abort all running tests
} break;
case GameModeCommands_e::GameFinished: {
fmt::println("Got GameFinished");
log.sendEvent("Req", "GameFinished");
IoStat->GameRunning = false;
// todo abort all running tests
} break;
case GameModeCommands_e::GameNextTryLocked: {
bool abort = false;
fmt::println("Got NextTryLock");
log.sendEvent("Req", "StayLockded");
IoStat->SwordLatch.moveOut(); // Lock
while (!abort) {
IoStat->SwordPulled.sample();
if (IoStat->SwordPulled.isPosEdge()) {
@@ -231,9 +275,9 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
mqtt.sendEvent("pull-denied");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
abort = testAbortCondition(mqtt, "abortTry");
}
sendLogIfAborted(abort);
} break;
case GameModeCommands_e::GameNextTryRelease: {
@@ -253,8 +297,7 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
}
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
abort = testAbortCondition(mqtt, "abortTry");
}
while (!abort) {
IoStat->SwordEntry.sample();
@@ -262,17 +305,24 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
fmt::println("..sword pulled");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
abort = testAbortCondition(mqtt, "abortTry");
}
sendLogIfAborted(abort);
if (abort) {
fmt::println("..abort");
log.sendEvent("Req", "Aborted Start");
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;
}
IoStat->SwordEnd.sample(); // still stuck?
bool stuckSensor = (!IoStat->SwordEntry.isActive()) && (IoStat->SwordEnd.isActive());
IoStat->SwordEnd.sample(); // still stuck?
bool stuckSensor = (!IoStat->SwordEntry.isActive()) &&
(IoStat->SwordEnd.isActive());
mqtt.sendEvent("pulled-out");
log.sendEvent("Game", "Pulled Out");
@@ -287,8 +337,7 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
fmt::println("..returning sword");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
abort = testAbortCondition(mqtt, "forceAbort");
}
if (stuckSensor) {
fmt::println("..extra wait due to stuck sensor");
@@ -300,18 +349,14 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
fmt::println("..sword returned");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
}
if (abort) {
fmt::println("..abortEnd");
log.sendEvent("Req", "Aborted End");
break;
abort = testAbortCondition(mqtt, "forceAbort");
}
sendLogIfAborted(abort);
if (abort) break;
log.sendEvent("Game", "Put Back");
mqtt.sendEvent("put-in");
IoStat->SwordLatch.moveOut(); // Lock
Thread::sleep(3s);
mqtt.sendEvent("locked");
// mqtt.sendEvent("lock-error");
} break;
@@ -322,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 <fmt/core.h>
#include <fmt/os.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <unistd.h>
@@ -24,37 +25,22 @@
#include "Ads1115.hpp"
#include "MqttClient.hpp"
#include "coreExcept.hpp"
#include "defines.hpp"
#include "gpioPort.hpp"
#include "i2cPort.hpp"
#include "logging.hpp"
#include "queue.hpp"
#include "textUtils.hpp"
#include "thread.hpp"
#include "defines.hpp"
class LinMot {
class ICurrentMon {
public:
LinMot(OutputPort& o1, OutputPort& o2)
: _out1(o1),
_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;
virtual float sampleCurrent() {
return 0;
}
};
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/
public:
CurrMon(AdcAds1115& adc)
@@ -69,10 +55,10 @@ class CurrMon {
_refVal = val / 8;
}
float sampleCurrent() {
float sampleCurrent() override {
auto val = sample() - _refVal;
val = val / 0.264;
fmt::println("{:.2} A", val);
// fmt::println("{:.2} A", 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 {
public:
DeviceIoState(pal::InputTransAware& entry,
@@ -239,7 +298,7 @@ class MediaPlayer {
static thread playWavFileThread(const string& filePath) {
if (filePath.empty()) {
fmt::println(stderr, "ERROR: Empty file path");
thread([](){ Thread::sleep(2s); });
thread([]() { Thread::sleep(2s); });
}
return thread([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();
mqtt.sendStatusMessage(Mode);
}
}
@@ -304,7 +303,6 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
}
if (chrono::steady_clock::now() > (tn + 1s)) {
tn = chrono::steady_clock::now();
mqtt.sendStatusMessage(Mode);
}
}
}
@@ -341,7 +339,6 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) {
IoStat->SwordPulled.sample();
if (IoStat->SwordPulled.isPosEdge()) {
mqtt.sendStatusMessage(Mode);
// say: You are not the one
MediaPlayer::playWavFile(SwordCfg.getSoundDeny());
Thread::sleep(15s);
@@ -358,14 +355,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break;
}
}
while (true) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break;
}
}
@@ -379,14 +374,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break;
}
}
while (true) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break;
}
}
-7
View File
@@ -282,7 +282,6 @@ void processMaintanence(MqttChannel& mqtt) {
}
}
IoStat->tick();
mqtt.sendStatusMessage(Mode);
}
}
@@ -307,7 +306,6 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
}
if (chrono::steady_clock::now() > (tn + 1s)) {
tn = chrono::steady_clock::now();
mqtt.sendStatusMessage(Mode);
}
}
}
@@ -344,7 +342,6 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) {
IoStat->SwordPulled.sample();
if (IoStat->SwordPulled.isPosEdge()) {
mqtt.sendStatusMessage(Mode);
// say: You are not the one
MediaPlayer::playWavFile(SwordCfg.getSoundDeny());
Thread::sleep(15s);
@@ -361,14 +358,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break;
}
}
while (true) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break;
}
}
@@ -382,14 +377,12 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
while (true) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
break;
}
}
while (true) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.isNegEdge()) {
mqtt.sendStatusMessage(Mode);
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