step: GameMode

This commit is contained in:
Jakob Gegeniger committed 2026-10-15 00:36:49 +02:00
1 parent c1e8f2a7a4
commit 313e097a53
8 files changed
+251 -46

No files matched your search

+1 -2
View File
@@ -17,8 +17,7 @@
"${workspaceFolder}/assets",
"-n", "SwordDebug",
"-b", "'mqtts://excaliburs-erben.de:8883'",
// "-t", "'staging/outdoor/king-arthur/sword/'",
"-t", "'outdoor/king-arthur/sword/'",
"-t", "'staging/outdoor/king-arthur/sword/'",
"-p", "'awesomeexodusoutdooradventures'",
"-u", "'exodususer'",
"-l", "'log.excaliburs-erben.de'",
+4
View File
@@ -9,3 +9,7 @@ pack_sword:
@cp -r assets deploy/sword
@cd deploy && tar -czvf swordMain.tar.gz sword
@echo .. extract with "tar -xzvf"
cp_sword:
@mkdir -p deploy/sword
@cp build/src/sword/SwordMain deploy/sword
+1
View File
@@ -0,0 +1 @@
paho-mqtt>=2.0
+153
View File
@@ -0,0 +1,153 @@
#!/bin/env python
# mosquitto_pub -h excaliburs-erben.de -p 8883 -t "outdoor/king-arthur/sword/set" -m "gameFinished"
# -u "exodususer" -P "awesomeexodusoutdooradventures"
import os
import sys
import ssl
import threading
import readline
import atexit
import paho.mqtt.client as mqtt
# MQTT configuration
BROKER = "excaliburs-erben.de"
PORT = 8883
USERNAME = os.getenv("MQTT_USER", "exodususer")
PASSWORD = os.getenv("MQTT_PASSWORD", "awesomeexodusoutdooradventures")
BASE_TOPIC = "outdoor/king-arthur/sword"
YELLOW = "\033[93m"
RESET = "\033[0m"
Topics = [
(f"{BASE_TOPIC}/ver", 0),
# (f"{BASE_TOPIC}/stat", 0),
(f"{BASE_TOPIC}/event", 0),
(f"{BASE_TOPIC}/set", 0),
(f"{BASE_TOPIC}/reset", 0),
]
def on_connect(client, userdata, flags, reason_code, properties):
global Topics
if reason_code.is_failure:
print(f"MQTT connection failed: {reason_code}")
return
print(f"Connected to {BROKER}:{PORT}")
client.subscribe(Topics)
print("Subscribed to:")
for topic, _ in Topics:
print(f" {topic}")
print("\nEnter topic:message to publish (e.g. set:blabla)")
print("Type 'quit' to exit.\n")
def on_connect_one(client, topic, reason_code):
if reason_code.is_failure:
print(f"MQTT connection failed: {reason_code}")
return
print(f"Connected to {BROKER}:{PORT}")
topics = [
(f"{BASE_TOPIC}/{topic}", 0),
]
client.subscribe(topics)
print("Subscribed to:")
for topic, _ in topics:
print(f" {topic}")
print("\nEnter topic:message to publish (e.g. set:blabla)")
print("Type 'quit' to exit.\n")
def on_message(client, userdata, message):
topic = message.topic
payload = message.payload.decode("utf-8", errors="replace")
print(f"{YELLOW}>> got: {topic} : {payload}{RESET}", flush=True)
def on_disconnect(client, userdata, disconnect_flags,
reason_code, properties):
if reason_code.is_failure:
print(f"MQTT disconnected: {reason_code}", file=sys.stderr)
def main():
client_Id = "sword-tester"
if len(sys.argv) > 1:
topic = sys.argv[1]
global Topics
Topics = [ (f"{BASE_TOPIC}/{topic}", 0) ]
client_Id = client_Id + topic
try:
client = mqtt.Client(
mqtt.CallbackAPIVersion.VERSION2,
client_id=client_Id,
)
client.username_pw_set(USERNAME, PASSWORD)
# Port 8883 normally uses TLS with certificate verification.
client.tls_set(cert_reqs=ssl.CERT_REQUIRED)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect(BROKER, PORT, keepalive=60)
client.loop_start()
while True:
try:
line = input("> ")
except EOFError:
break
if line.strip().lower() in ("quit", "exit"):
break
if ":" not in line:
print("Format: topic:message (e.g. set:blabla)")
continue
topic_suffix, payload = line.split(":", 1)
topic_suffix = topic_suffix.strip()
if not topic_suffix:
print("Topic cannot be empty.")
continue
# Prevent accidental topic injection or MQTT wildcards.
if any(c in topic_suffix for c in ("+", "#", "/", "\0")):
print("Enter a single topic name, e.g. set or event.")
continue
topic = f"{BASE_TOPIC}/{topic_suffix}"
info = client.publish(topic, payload, qos=0)
if info.rc == mqtt.MQTT_ERR_SUCCESS:
try:
info.wait_for_publish(timeout=5)
if info.is_published():
print(f"Sent: {topic} : {payload}")
else:
print("Publish is still pending.")
except (RuntimeError, ValueError) as exc:
print(f"Publish error: {exc}")
else:
print(f"Publish failed: {mqtt.error_string(info.rc)}")
except KeyboardInterrupt:
print("\nStopping...")
except (OSError, mqtt.MqttError) as exc:
print(f"MQTT error: {exc}", file=sys.stderr)
finally:
client.disconnect()
client.loop_stop()
if __name__ == "__main__":
main()
+1
View File
@@ -22,6 +22,7 @@ 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
};
enum OutgoingCommands_e {
+16 -13
View File
@@ -8,7 +8,6 @@ class MqttChannel {
: Config(cfg),
IoStat(ioStat),
Logger(log),
runTopic(cfg.StationPath + "run"),
cfgTopic(cfg.StationPath + "cfg"),
setTopic(cfg.StationPath + "set"),
verTopic(cfg.StationPath + "ver"),
@@ -16,13 +15,7 @@ class MqttChannel {
statTopic(cfg.StationPath + "stat"),
resetTopic(cfg.StationPath + "reset"),
gameCommands({
{"gameStarted", GameModeCommands_e::GameStarted},
{"gameFinished", GameModeCommands_e::GameFinished},
{"stayLocked", GameModeCommands_e::GameNextTryLocked},
{"releaseLock", GameModeCommands_e::GameNextTryRelease},
}),
serviceCommands({
serviceCommands({ // cfg-topic
{"openLock", ServiceCommands_e::SetLockOpen},
{"closeLock", ServiceCommands_e::SetLockClose},
{"mute", ServiceCommands_e::SetDisableSound},
@@ -31,11 +24,18 @@ class MqttChannel {
{"playSound:Deny", ServiceCommands_e::PlaySoundDeny},
{"playSound:Chosen", ServiceCommands_e::PlaySoundChosen},
}),
setCommands({
setCommands({ // cfg-topic
{"volume", ServiceCommands_e::SetConfigVolume},
{"promoDelay", ServiceCommands_e::SetConfigPromoDelay},
}),
subTopics{{runTopic, setTopic, cfgTopic, resetTopic}},
gameCommands({ // set-topic
{"gameStarted", GameModeCommands_e::GameStarted},
{"gameFinished", GameModeCommands_e::GameFinished},
{"stayLocked", GameModeCommands_e::GameNextTryLocked},
{"releaseLock", GameModeCommands_e::GameNextTryRelease},
{"abortTry", GameModeCommands_e::GameAbortTry},
}),
subTopics{{setTopic, cfgTopic, resetTopic}},
client(name, cfg.BrockerUrl, subTopics,
{cfg.MqttUser, cfg.MqttPassword}) {
fmt::println("MQTT: Starting task:");
@@ -90,6 +90,7 @@ class MqttChannel {
static void runMasterService(Thread::Context& ctx, MqttChannel& instance, function<void()> resetCall, CurrMon& mon) {
while (true) {
auto serMsg = instance.MasterQueue.tryDequeueFor(500ms);
// only resetTopic and cfgTopic arrive here
instance.sendStatusMessage();
if (!serMsg) {
continue;
@@ -116,6 +117,8 @@ class MqttChannel {
if (val >= 20 && val <= 100) {
instance.IoStat.Volume = val;
MediaPlayer::setVolume(val);
} else {
instance.Logger.sendEvent("Vol", "discarded volume");
}
}
if (payload.starts_with("promoDelay:")) {
@@ -148,13 +151,13 @@ class MqttChannel {
auto currE = mon.sampleCurrent();
} break;
case ServiceCommands_e::PlaySoundPromo: {
MediaPlayer::playWavFile(instance.Config.SoundPromo);
MediaPlayer::playWavFileAsync(instance.Config.SoundPromo);
} break;
case ServiceCommands_e::PlaySoundDeny: {
MediaPlayer::playWavFile(instance.Config.getNextDeny());
MediaPlayer::playWavFileAsync(instance.Config.getNextDeny());
} break;
case ServiceCommands_e::PlaySoundChosen: {
MediaPlayer::playWavFile(instance.Config.getNextAllow());
MediaPlayer::playWavFileAsync(instance.Config.getNextAllow());
} break;
}
}
+55 -19
View File
@@ -8,7 +8,7 @@ using namespace std::literals::string_view_literals;
using namespace std::literals::chrono_literals;
using namespace std;
const string Version = "V 0.9.0";
const string Version = "V 0.9.1";
unique_ptr<SwordConfig> SwordCfg;
unique_ptr<DeviceIoState> IoStat;
@@ -37,7 +37,16 @@ int main(int argc, char* argv[]) {
app.add_option("-l,--log", logUrl, "Logging Service");
app.add_option("-k,--key", logApiKey, "Logging API Key");
fmt::println("## Starting Sword Station {}", Version);
CLI11_PARSE(app, argc, argv);
std::ostringstream cmdline;
for (int i = 0; i < argc; ++i) {
if (i > 0)
cmdline << ' ';
cmdline << argv[i];
}
fmt::println(" CallArgs {}", cmdline.str());
SeqLogger log(logUrl, logApiKey, appName);
SwordCfg = make_unique<SwordConfig>(assetsBasePath, brocker, topic, user, password);
@@ -99,11 +108,8 @@ int main(int argc, char* argv[]) {
switch (IoStat->Mode) {
case OpMode::Maintanance: {
fmt::println("Running Maintanance");
// txQueue.emplace<ResponseTxMsg>(msg->code, 0);
Thread::sleep(500ms);
IoStat->tick();
// auto e = make_unique<ResponseTxMsg>(msg->code, 0);
// txQueue.enqueue(move(e));
} break;
case OpMode::PromoMode: {
fmt::println("Running PromoMode");
@@ -141,9 +147,9 @@ void processPromo(MqttChannel& mqtt, SeqLogger& log) {
log.sendEvent("Pull", "Start Audio");
if (tsf.tick()) {
MediaPlayer::playWavFile(SwordCfg->SoundPromo);
MediaPlayer::playWavFileAsync(SwordCfg->SoundPromo);
} else {
MediaPlayer::playWavFile(SwordCfg->SoundPromoShort);
MediaPlayer::playWavFileAsync(SwordCfg->SoundPromoShort);
}
dP.sample();
fmt::println("Muting next for {}", IoStat->PromoDelay);
@@ -199,7 +205,14 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
continue;
}
auto code = gameCmds.at(msg->Payload);
auto code = GameAbortTry;
try {
code = gameCmds.at(msg->Payload);
} catch (const std::exception& e) {
fmt::println("Code not parsable {}", msg->Payload);
break;
}
switch (code) {
case GameModeCommands_e::GameStarted: {
fmt::println("Got GameStarted");
@@ -212,65 +225,88 @@ void processProduction(MqttChannel& mqtt, SeqLogger& log) {
} break;
case GameModeCommands_e::GameNextTryLocked: {
bool abort = false;
fmt::println("Got NextTryLock");
log.sendEvent("Req", "StayLockded");
while (true) {
while (!abort) {
IoStat->SwordPulled.sample();
if (IoStat->SwordPulled.isPosEdge()) {
// say: You are not the one
MediaPlayer::playWavFile(SwordCfg->getNextDeny());
Thread::sleep(5s);
log.sendEvent("Req", "Pulled");
mqtt.sendEvent("pull");
MediaPlayer::playWavFileSync(SwordCfg->getNextDeny());
log.sendEvent("Req", "Pulled");
mqtt.sendEvent("pull-denied");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
}
} break;
case GameModeCommands_e::GameNextTryRelease: {
bool abort = false;
fmt::println("NextTryRelease");
log.sendEvent("Req", "UnlockSword");
IoStat->SwordLatch.moveIn();
while (true) {
while (!abort) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.getState() == pal::InputBiDebounced::State::Passive) {
fmt::println("pulling sword");
break;
}
Thread::sleep(10ms);
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
}
while (true) {
while (!abort) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.getState() == pal::InputBiDebounced::State::Passive) {
fmt::println("sword pulled");
break;
}
Thread::sleep(10ms);
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
}
if (abort) {
break;
}
mqtt.sendEvent("pulled-out");
log.sendEvent("Req", "Pulled Out");
// say: You ARE the one
MediaPlayer::playWavFile(SwordCfg->getNextAllow());
Thread::sleep(5s);
MediaPlayer::playWavFileSync(SwordCfg->getNextAllow());
mqtt.sendEvent("ceremonyDone");
while (true) {
while (!abort) {
IoStat->SwordEntry.sample();
if (IoStat->SwordEntry.getState() == pal::InputBiDebounced::State::Active) {
fmt::println("returning sword");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
}
while (true) {
while (!abort) {
IoStat->SwordEnd.sample();
if (IoStat->SwordEnd.getState() == pal::InputBiDebounced::State::Active) {
fmt::println("sword returned");
break;
}
auto abortMsg = mqtt.tryDequeueFor(10ms);
abort = abortMsg && abortMsg->Payload == "abortTry";
}
if (abort) {
break;
}
log.sendEvent("Req", "Put Back");
mqtt.sendEvent("put-in");
IoStat->SwordLatch.moveOut(); // Lock
Thread::sleep(3s);
mqtt.sendEvent("locked");
// mqtt.sendEvent("lock-error");
} break;
default:
// nothing to doe here
fmt::println("oopsie");
}
}
}
+20 -12
View File
@@ -197,20 +197,14 @@ struct SwordConfig {
class MediaPlayer {
public:
static void playWavFile(const string& filePath) {
if (filePath.empty()) {
fmt::println(stderr, "ERROR: Empty file path");
return;
}
thread audioThread([filePath]() {
auto cmd = fmt::format("aplay '{}'", filePath);
auto result = system(cmd.c_str());
if (result != 0) {
fmt::println(stderr, "ERROR: Failed to play audio file: '{}'", filePath);
}
});
static void playWavFileAsync(const string& filePath) {
auto audioThread = playWavFileThread(filePath);
audioThread.detach();
}
static void playWavFileSync(const string& filePath) {
auto audioThread = playWavFileThread(filePath);
audioThread.join();
}
static void setVolume(int volume) {
if (volume < 0) {
@@ -241,4 +235,18 @@ class MediaPlayer {
}
return {};
}
static thread playWavFileThread(const string& filePath) {
if (filePath.empty()) {
fmt::println(stderr, "ERROR: Empty file path");
thread([](){});
}
return thread([filePath]() {
auto cmd = fmt::format("aplay '{}'", filePath);
auto result = system(cmd.c_str());
if (result != 0) {
fmt::println(stderr, "ERROR: Failed to play audio file: '{}'", filePath);
}
});
}
};