9 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
Jakob Gegeniger b34a3a4acd fix: PullDown 2026-10-16 21:29:06 +02:00
20 changed files with 509 additions and 160 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
build/
.cache/
deploy/
.venv/
+1 -3
View File
@@ -11,9 +11,7 @@
"request": "launch",
"program": "${workspaceFolder}/build/src/sword/SwordMain",
"args": [
//"test",
// "promo",
"game",
"game", //"test",
"${workspaceFolder}/assets",
"-n", "SwordDebug",
"-b", "'mqtts://excaliburs-erben.de:8883'",
+1 -1
View File
@@ -1,4 +1,4 @@
; sudo nano /etc/systemd/system/SwordMain.service
; sudo nano /etc/systemd/system/Sword.service
[Unit]
Description=Service for sword stationg
After=network-online.target
+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
```
+56 -6
View File
@@ -6,15 +6,15 @@ 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=/home/pi/SwordMain/start.sh
User=theUser
WorkingDirectory=/home/theUser/SwordMain
ExecStart=/home/theUser/SwordMain/run.sh
Restart=on-failure
RestartSec=5
@@ -23,7 +23,7 @@ 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
@@ -35,4 +35,54 @@ sudo systemctl status SwordMain.service
```
promo $(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:
@mkdir -p deploy/sword
@cp build/src/sword/SwordMain deploy/sword
cpexe_toServ:
scp build/src/sword/SwordMain gustice@excaliburs-erben.de:SwordMain
Submodule platform updated: 6f6a0474cb...b74f37d999.
+1 -1
View File
@@ -16,7 +16,7 @@ BROKER = "excaliburs-erben.de"
PORT = 8883
USERNAME = os.getenv("MQTT_USER", "exodususer")
PASSWORD = os.getenv("MQTT_PASSWORD", "awesomeexodusoutdooradventures")
BASE_TOPIC = "outdoor/king-arthur/sword"
BASE_TOPIC = "staging/outdoor/king-arthur/sword"
YELLOW = "\033[93m"
RESET = "\033[0m"
+1 -1
View File
@@ -1,6 +1,6 @@
#!/bin/bash
/home/gustice/workspace/swordStation/SwordMain \
promo /home/gustice/workspace/swordStation/assets \
game /home/gustice/workspace/swordStation/assets \
-n Sword \
-b mqtts://excaliburs-erben.de:8883 \
-t outdoor/king-arthur/sword/ \
+1
View File
@@ -1,2 +1,3 @@
add_subdirectory(sword)
add_subdirectory(throneBridge)
add_subdirectory(throne)
+1 -1
View File
@@ -42,7 +42,7 @@ class SeqLogger {
{"MessageTemplate", "[{App}]: Got {Event}; " + message},
{"Properties", {
{"App", AppName},
{"Event", Version}
{"Event", event}
}}
}
})}
+4 -2
View File
@@ -15,6 +15,7 @@ enum ServiceCommands_e {
PlaySoundPromo,
PlaySoundDeny,
PlaySoundChosen,
SetMaintanence,
};
enum GameModeCommands_e {
@@ -22,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 {
@@ -57,7 +60,6 @@ struct MqttQe {
enum class OpMode {
Undefined, // Enable in Game mode
Maintanance = 1, // Set Maintanance mode
PromoMode, // Enable PromoMode
GamingMode, // Enable in Game mode
};
+61 -19
View File
@@ -4,8 +4,11 @@
class MqttChannel {
public:
static constexpr array<const char*, 3> Modes = {"Undefined", "Maintanance", "Production"};
MqttChannel(string name, string version, SwordConfig cfg, DeviceIoState& ioStat, SeqLogger& log)
: Config(cfg),
: Version(version),
Config(cfg),
IoStat(ioStat),
Logger(log),
cfgTopic(cfg.StationPath + "cfg"),
@@ -14,8 +17,10 @@ class MqttChannel {
eventTopic(cfg.StationPath + "event"),
statTopic(cfg.StationPath + "stat"),
resetTopic(cfg.StationPath + "reset"),
sendTimeout(std::chrono::seconds{1}),
serviceCommands({ // cfg-topic
serviceCommands({
// cfg-topic
{"openLock", ServiceCommands_e::SetLockOpen},
{"closeLock", ServiceCommands_e::SetLockClose},
{"mute", ServiceCommands_e::SetDisableSound},
@@ -23,21 +28,27 @@ class MqttChannel {
{"playSound:Promo", ServiceCommands_e::PlaySoundPromo},
{"playSound:Deny", ServiceCommands_e::PlaySoundDeny},
{"playSound:Chosen", ServiceCommands_e::PlaySoundChosen},
{"setMaintanance", ServiceCommands_e::SetMaintanence},
}),
setCommands({ // cfg-topic
setCommands({
// cfg-topic
{"volume", ServiceCommands_e::SetConfigVolume},
{"promoDelay", ServiceCommands_e::SetConfigPromoDelay},
}),
gameCommands({ // set-topic
gameCommands({
// set-topic
{"gameStarted", GameModeCommands_e::GameStarted},
{"gameFinished", GameModeCommands_e::GameFinished},
{"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);
@@ -57,6 +68,7 @@ class MqttChannel {
client.registerCallback(mqttCall);
client.send(verTopic, fmt::format("{}", version));
client.send(eventTopic, "online");
}
std::unique_ptr<MqttQe> tryDeque() {
@@ -87,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) {
@@ -99,6 +111,11 @@ class MqttChannel {
if (serMsg->Topic == instance.resetTopic) {
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;
if (payload == "mute") {
@@ -133,22 +150,16 @@ class MqttChannel {
auto code = instance.serviceCommands.at(payload);
switch (code) {
case ServiceCommands_e::SetLockOpen: {
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();
if (instance.IoStat.GameRunning) {
break;
}
auto currE = mon.sampleCurrent();
instance.IoStat.SwordLatch.moveIn();
} break;
case ServiceCommands_e::SetLockClose: {
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();
if (instance.IoStat.GameRunning) {
break;
}
auto currE = mon.sampleCurrent();
instance.IoStat.SwordLatch.moveOut();
} break;
case ServiceCommands_e::PlaySoundPromo: {
MediaPlayer::playWavFileAsync(instance.Config.SoundPromo);
@@ -165,9 +176,34 @@ 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;
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,
@@ -177,6 +213,9 @@ class MqttChannel {
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());
}
@@ -195,6 +234,7 @@ class MqttChannel {
const std::map<string, ServiceCommands_e>& getSerCommands() { return serviceCommands; }
private:
std::string Version;
SwordConfig Config;
Queue<MqttQe> MasterQueue;
Queue<MqttQe> MqttQueue;
@@ -207,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;
+124 -69
View File
@@ -8,21 +8,29 @@ using namespace std::literals::string_view_literals;
using namespace std::literals::chrono_literals;
using namespace std;
const string Version = "V 0.9.1";
const string Version = "V 1.0.0";
unique_ptr<SwordConfig> SwordCfg;
unique_ptr<DeviceIoState> IoStat;
void processPromo(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[]) {
CLI::App app{"Sword Firmware"};
string appName = "SwordDebug";
string modeArg = "test";
string assetsBasePath = "/home/user/assets/sword";
string brocker = "mqtts://excaliburs-erben.de:8883";
string topic = "outdoor/king-arthur/sword/";
string topic = "staging/outdoor/king-arthur/sword/";
string user = "userForMqttBrocker";
string password = "passwordForMqttBorcker";
string logUrl = "log.excaliburs-erben.de";
@@ -40,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)
@@ -60,39 +78,37 @@ int main(int argc, char* argv[]) {
fmt::println(" {}", file);
}
InputPort sbPort(SwordEntryPin, "PinSEntry");
InputPort sePort(SwordEndPin, "PInSEnd");
InputPort spPort(SwordPulledPin, "PInSPull");
InputPort sbPort(SwordEntryPin, "PinSEntry", pal::GpioPort::Normal, pal::GpioPort::PullDown);
InputPort sePort(SwordEndPin, "PInSEnd", pal::GpioPort::Normal, pal::GpioPort::PullDown);
InputPort spPort(SwordPulledPin, "PInSPull", pal::GpioPort::Normal, pal::GpioPort::PullDown);
InputPort sparePort(sparePin, "spare");
OutputPort mOut1(LinMotPin1, "M1:1");
OutputPort mOut2(LinMotPin2, "M1:2");
InputTransAware SwordEntry(sbPort);
InputTransAware SwordEnd(sePort);
InputTransAware SwordPulled(spPort);
LinMot SwordLatch(mOut1, mOut2);
I2cMaster i2cDev(II2cMaster::ClockRate::_400k);
AdcAds1115 adc(i2cDev, AdcAds1115::I2CAddress::Gnd);
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 {}", modeArg);
fmt::println("Failed to connect ot Sensor");
}
CurrMon mon(adc);
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;
}
LinMot SwordLatch(mOut1, mOut2, *pMon, saveFile);
IoStat = make_unique<DeviceIoState>(SwordEntry, SwordEnd, SwordPulled, SwordLatch);
fmt::println("{}", app.get_description());
if (modeArg == "promo") {
fmt::println("starting with promo");
IoStat->Mode = OpMode::PromoMode;
} else if (modeArg == "game") {
fmt::println("starting with promo");
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)]);
IoStat->Mode = mode;
MqttChannel mqtt(appName, Version, *SwordCfg, *IoStat, log);
auto resetCall = [&]() {
@@ -100,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");
@@ -111,10 +127,6 @@ int main(int argc, char* argv[]) {
Thread::sleep(500ms);
IoStat->tick();
} break;
case OpMode::PromoMode: {
fmt::println("Running PromoMode");
processPromo(mqtt, log);
} break;
case OpMode::GamingMode: {
fmt::println("Running GamingMode");
processProduction(mqtt, log);
@@ -133,18 +145,13 @@ enum MuteState {
WaitForNextDay,
};
void processPromo(MqttChannel& mqtt, SeqLogger& log) {
auto muterS = MuteState::WaitForUnmute;
Tick tmu(1min);
Tick tsf(30min);
Waiter dP;
auto& serCmds = mqtt.getSerCommands();
while (true) {
Thread::sleep(10ms);
IoStat->tick();
static Tick tmu(1min);
static Tick tsf(30min);
static Waiter dP;
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);
@@ -154,11 +161,12 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
dP.sample();
fmt::println("Muting next for {}", IoStat->PromoDelay);
} else {
fmt::println("still muted");
fmt::println("await promo delay");
}
}
}
if (tmu.tick()) {
static auto muterS = MuteState::WaitForUnmute;
auto now = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(now);
std::tm* lTime = std::localtime(&time);
@@ -193,15 +201,35 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
}
}
}
}
void processProduction(MqttChannel& mqtt, SeqLogger& log) {
auto& serCmds = mqtt.getSerCommands();
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(500ms);
auto msg = mqtt.tryDequeueFor(10ms);
IoStat->tick();
if (!msg) {
if (!IoStat->GameRunning) {
processPromo(mqtt, log);
}
continue;
}
@@ -214,33 +242,42 @@ 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;
// 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()) {
// say: You are not the one
mqtt.sendEvent("pull");
MediaPlayer::playWavFileSync(SwordCfg->getNextDeny());
log.sendEvent("Req", "Pulled");
log.sendEvent("Game", "Pulled");
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: {
@@ -250,56 +287,76 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
IoStat->SwordLatch.moveIn();
while (!abort) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.getState() == pal::InputBiDebounced::State::Passive) {
fmt::println("pulling sword");
IoStat->SwordEntry.sample();
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;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
abort = testAbortCondition(mqtt, "abortTry");
}
while (!abort) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.getState() == pal::InputBiDebounced::State::Passive) {
fmt::println("sword pulled");
if (!IoStat->SwordEntry.isActive()) {
fmt::println("..sword pulled");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
abort = testAbortCondition(mqtt, "abortTry");
}
sendLogIfAborted(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;
}
IoStat->SwordEnd.sample(); // still stuck?
bool stuckSensor = (!IoStat->SwordEntry.isActive()) &&
(IoStat->SwordEnd.isActive());
mqtt.sendEvent("pulled-out");
log.sendEvent("Req", "Pulled Out");
log.sendEvent("Game", "Pulled Out");
// say: You ARE the one
MediaPlayer::playWavFileSync(SwordCfg->getNextAllow());
log.sendEvent("Game", "Ceremony");
mqtt.sendEvent("ceremonyDone");
while (!abort) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.getState() == pal::InputBiDebounced::State::Active) {
fmt::println("returning sword");
if (IoStat->SwordEntry.isActive()) {
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");
Thread::sleep(3s);
}
while (!abort) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.getState() == pal::InputBiDebounced::State::Active) {
fmt::println("sword returned");
if (IoStat->SwordEnd.isActive()) {
fmt::println("..sword returned");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
abort = testAbortCondition(mqtt, "forceAbort");
}
if (abort) {
break;
}
log.sendEvent("Req", "Put Back");
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;
@@ -310,5 +367,3 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
}
}
}
// todo send state in background
+86 -27
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)
@@ -64,15 +50,15 @@ class CurrMon {
float val{};
for (size_t i = 0; i < 8; i++) {
val += sampe();
val += sample();
}
_refVal = val / 8;
}
float sampleCurrent() {
auto val = sampe() - _refVal;
float sampleCurrent() override {
auto val = sample() - _refVal;
val = val / 0.264;
fmt::println("{:.2} A", val);
// fmt::println("{:.2} A", val);
return val;
}
@@ -80,13 +66,86 @@ class CurrMon {
float _refVal{};
AdcAds1115& _adc;
float sampe() {
float sample() {
float volt;
_adc.readConversionVoltage(volt);
return volt;
}
};
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,
@@ -106,6 +165,7 @@ class DeviceIoState {
}
OpMode Mode{OpMode::Maintanance};
bool GameRunning{};
pal::InputTransAware& SwordEntry;
pal::InputTransAware& SwordEnd;
pal::InputTransAware& SwordPulled;
@@ -238,7 +298,7 @@ class MediaPlayer {
static thread playWavFileThread(const string& filePath) {
if (filePath.empty()) {
fmt::println(stderr, "ERROR: Empty file path");
thread([](){});
thread([]() { Thread::sleep(2s); });
}
return thread([filePath]() {
auto cmd = fmt::format("aplay '{}'", filePath);
@@ -248,5 +308,4 @@ class MediaPlayer {
}
});
}
};
+2 -2
View File
@@ -1,6 +1,6 @@
add_executable(ThroneBridgeMain throneBridgeMain.cpp)
add_executable(ThroneMain throneMain.cpp)
target_link_libraries(ThroneBridgeMain
target_link_libraries(ThroneMain
PkgConfig::LIBGPIOD
base
palAdapt
+2 -15
View File
@@ -180,11 +180,8 @@ int main(int argc, char* argv[]) {
SwordCfg.setVar(assetsBasePath, brocker, topic, user, password);
fmt::println("{}", app.get_description());
if (modeArg == "promo") {
fmt::println("starting with promo");
Mode = OpMode::PromoMode;
} else if (modeArg == "game") {
fmt::println("starting with promo");
if (modeArg == "game") {
fmt::println("starting with game");
Mode = OpMode::GamingMode;
} else {
fmt::println("unknown {}", modeArg);
@@ -232,10 +229,7 @@ int main(int argc, char* argv[]) {
switch (Mode) {
case OpMode::Maintanance: {
fmt::println("Running Maintanance");
// txQueue.emplace<ResponseTxMsg>(msg->code, 0);
processMaintanence(mqtt);
// auto e = make_unique<ResponseTxMsg>(msg->code, 0);
// txQueue.enqueue(move(e));
} break;
case OpMode::PromoMode: {
fmt::println("Running PromoMode");
@@ -285,7 +279,6 @@ void processMaintanence(MqttChannel& mqtt) {
}
}
IoStat->tick();
mqtt.sendStatusMessage(Mode);
}
}
@@ -310,7 +303,6 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
}
if (chrono::steady_clock::now() > (tn + 1s)) {
tn = chrono::steady_clock::now();
mqtt.sendStatusMessage(Mode);
}
}
}
@@ -347,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);
@@ -364,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;
}
}
@@ -385,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;
}
}
+2 -12
View File
@@ -180,11 +180,8 @@ int main(int argc, char* argv[]) {
SwordCfg.setVar(assetsBasePath, brocker, topic, user, password);
fmt::println("{}", app.get_description());
if (modeArg == "promo") {
fmt::println("starting with promo");
Mode = OpMode::PromoMode;
} else if (modeArg == "game") {
fmt::println("starting with promo");
if (modeArg == "game") {
fmt::println("starting with game");
Mode = OpMode::GamingMode;
} else {
fmt::println("unknown {}", modeArg);
@@ -285,7 +282,6 @@ void processMaintanence(MqttChannel& mqtt) {
}
}
IoStat->tick();
mqtt.sendStatusMessage(Mode);
}
}
@@ -310,7 +306,6 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
}
if (chrono::steady_clock::now() > (tn + 1s)) {
tn = chrono::steady_clock::now();
mqtt.sendStatusMessage(Mode);
}
}
}
@@ -347,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);
@@ -364,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;
}
}
@@ -385,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