Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22dd3a3ea9 | ||
|
|
4fe0599988 | ||
|
|
2617407d18 | ||
|
|
e7a9e0316e | ||
|
|
855ffe5915 | ||
|
|
85e2e92991 | ||
|
|
27a791c4c0 |
No files matched your search
@@ -1,3 +1,4 @@
|
|||||||
build/
|
build/
|
||||||
.cache/
|
.cache/
|
||||||
deploy/
|
deploy/
|
||||||
|
.venv/
|
||||||
@@ -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
@@ -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
|
||||||
|
```
|
||||||
+1
-1
Submodule platform updated: b998471c3f...b74f37d999.
File renamed without changes.
@@ -23,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 {
|
||||||
|
|||||||
+38
-15
@@ -17,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
|
||||||
@@ -41,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);
|
||||||
@@ -64,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() {
|
||||||
@@ -94,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) {
|
||||||
@@ -149,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);
|
||||||
@@ -183,9 +176,34 @@ 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;
|
||||||
|
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:{}",
|
client.send(statTopic, fmt::format("M:{},snd:{},sS:{},sE:{},sP:{},lE:{},v:{},pD:{}",
|
||||||
(int)IoStat.Mode,
|
(int)IoStat.Mode,
|
||||||
!s.Mute,
|
!s.Mute,
|
||||||
@@ -195,6 +213,9 @@ class MqttChannel {
|
|||||||
s.SwordLatch.isLocked(),
|
s.SwordLatch.isLocked(),
|
||||||
s.Volume,
|
s.Volume,
|
||||||
s.PromoDelay));
|
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());
|
||||||
}
|
}
|
||||||
@@ -226,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;
|
||||||
|
|||||||
+82
-39
@@ -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.3";
|
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,26 +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;
|
||||||
|
try {
|
||||||
|
static I2cMaster i2cDev(II2cMaster::ClockRate::_400k);
|
||||||
|
static AdcAds1115 adc(i2cDev, AdcAds1115::I2CAddress::Gnd);
|
||||||
// Check if the ADC is connected
|
// Check if the ADC is connected
|
||||||
if (!adc.isConnected()) {
|
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);
|
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);
|
|
||||||
}
|
|
||||||
log.sendBootUp(Version, MqttChannel::Modes[static_cast<int>(IoStat->Mode)]);
|
|
||||||
|
|
||||||
MqttChannel mqtt(appName, Version, *SwordCfg, *IoStat, log);
|
MqttChannel mqtt(appName, Version, *SwordCfg, *IoStat, log);
|
||||||
auto resetCall = [&]() {
|
auto resetCall = [&]() {
|
||||||
@@ -95,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");
|
||||||
@@ -130,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);
|
||||||
@@ -185,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();
|
||||||
@@ -204,23 +242,29 @@ 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;
|
||||||
// system("pinctrl set 6 ip pd");
|
// 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()) {
|
||||||
@@ -231,9 +275,9 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
|
|||||||
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: {
|
||||||
@@ -253,8 +297,7 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
|
|||||||
}
|
}
|
||||||
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();
|
||||||
@@ -262,17 +305,24 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
|
|||||||
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) {
|
||||||
fmt::println("..abort");
|
IoStat->SwordEnd.sample();
|
||||||
log.sendEvent("Req", "Aborted Start");
|
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?
|
IoStat->SwordEnd.sample(); // still stuck?
|
||||||
bool stuckSensor = (!IoStat->SwordEntry.isActive()) && (IoStat->SwordEnd.isActive());
|
bool stuckSensor = (!IoStat->SwordEntry.isActive()) &&
|
||||||
|
(IoStat->SwordEnd.isActive());
|
||||||
|
|
||||||
mqtt.sendEvent("pulled-out");
|
mqtt.sendEvent("pulled-out");
|
||||||
log.sendEvent("Game", "Pulled Out");
|
log.sendEvent("Game", "Pulled Out");
|
||||||
@@ -287,8 +337,7 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
|
|||||||
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) {
|
if (stuckSensor) {
|
||||||
fmt::println("..extra wait due to stuck sensor");
|
fmt::println("..extra wait due to stuck sensor");
|
||||||
@@ -300,18 +349,14 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
|
|||||||
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) {
|
|
||||||
fmt::println("..abortEnd");
|
|
||||||
log.sendEvent("Req", "Aborted End");
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
sendLogIfAborted(abort);
|
||||||
|
if (abort) break;
|
||||||
|
|
||||||
log.sendEvent("Game", "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;
|
||||||
@@ -322,5 +367,3 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// todo send state in background
|
|
||||||
+81
-23
@@ -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,
|
||||||
@@ -249,5 +308,4 @@ class MediaPlayer {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Executable
+127
@@ -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()
|
||||||
Executable
+20
@@ -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
|
||||||
Reference in new issue
Block a user