#include "swordMain.hpp" #include "defines.hpp" #include "mqttChannel.hpp" using namespace pal; using namespace std::literals::string_view_literals; using namespace std::literals::chrono_literals; using namespace std; const string Version = "V 0.9.1"; unique_ptr SwordCfg; unique_ptr IoStat; void processPromo(MqttChannel& mqtt, SeqLogger& log); void processProduction(MqttChannel& mqtt, SeqLogger& log); 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 user = "userForMqttBrocker"; string password = "passwordForMqttBorcker"; string logUrl = "log.excaliburs-erben.de"; string logApiKey = "keyForSeqLoggingService"; app.add_option("startmode", modeArg, "Startup mode")->required(); app.add_option("basepath", assetsBasePath, "Base bath for assets")->required(); app.add_option("-n,--name", appName, "Name of App"); app.add_option("-b,--brocker", brocker, "MQTT Topic URL"); app.add_option("-t,--topic", topic, "MQTT Topic"); app.add_option("-p,--passwd", password, "MQTT Brocker password"); app.add_option("-u,--user", user, "MQTT Brocker user"); 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(assetsBasePath, brocker, topic, user, password); { fmt::println("Win files found: {}", SwordCfg->getSoundsAllow().size()); for (const auto& file : SwordCfg->getSoundsAllow()) { fmt::println(" {}", file); } fmt::println("Lose files found: {}", SwordCfg->getSoundsDeny().size()); for (const auto& file : SwordCfg->getSoundsDeny()) fmt::println(" {}", file); } InputPort sbPort(SwordEntryPin, "PinSEntry"); InputPort sePort(SwordEndPin, "PInSEnd"); InputPort spPort(SwordPulledPin, "PInSPull"); 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); // Check if the ADC is connected if (!adc.isConnected()) { fmt::println("Failed to connect ot Sensor {}", modeArg); } CurrMon mon(adc); IoStat = make_unique(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 modes = {"Undefined", "Maintanance", "PromoMode", "Production"}; log.sendBootUp(Version, modes[static_cast(IoStat->Mode)]); MqttChannel mqtt(appName, Version, *SwordCfg, *IoStat, log); auto resetCall = [&]() { log.sendEvent("Reset", ""); }; mqtt.flushInput(); static auto conTask = Thread::createExplicit("MqttTask", MqttChannel::runMasterService, ref(mqtt), resetCall, ref(mon)); SwordLatch.moveOut(); fmt::println("Running App"); while (true) { switch (IoStat->Mode) { case OpMode::Maintanance: { fmt::println("Running Maintanance"); 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); } break; default: break; } } return EXIT_SUCCESS; } enum MuteState { WaitForUnmute, WaitForMute, 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(); if (IoStat->SwordPulled.isPosEdge()) { if (!IoStat->Mute) { if (dP.tick(IoStat->PromoDelay)) { log.sendEvent("Pull", "Start Audio"); if (tsf.tick()) { MediaPlayer::playWavFileAsync(SwordCfg->SoundPromo); } else { MediaPlayer::playWavFileAsync(SwordCfg->SoundPromoShort); } dP.sample(); fmt::println("Muting next for {}", IoStat->PromoDelay); } else { fmt::println("still muted"); } } } if (tmu.tick()) { 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); int current_hour = lTime->tm_hour; switch (muterS) { case WaitForUnmute: if (current_hour >= 9) { fmt::println("[09:00 Threshold] Unmute"); log.sendEvent("Unmute", "Time for unmute"); IoStat->Mute = false; muterS = WaitForMute; } break; case WaitForMute: if (current_hour >= 21) { fmt::println("[21:00 Threshold] Mute"); log.sendEvent("Mute", "Time for mute"); IoStat->Mute = true; muterS = WaitForNextDay; } break; case WaitForNextDay: if (current_hour < 1) { fmt::println("[01:00 Threshold] new day"); muterS = WaitForUnmute; } break; default: break; } } } } void processProduction(MqttChannel& mqtt, SeqLogger& log) { auto& serCmds = mqtt.getSerCommands(); auto& gameCmds = mqtt.getGameCommands(); while (true) { auto msg = mqtt.tryDequeueFor(500ms); IoStat->tick(); if (!msg) { continue; } 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"); log.sendEvent("Req", "GameStarted"); } break; case GameModeCommands_e::GameFinished: { fmt::println("Got GameFinished"); log.sendEvent("Req", "GameFinished"); } break; case GameModeCommands_e::GameNextTryLocked: { bool abort = false; fmt::println("Got NextTryLock"); log.sendEvent("Req", "StayLockded"); 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"); 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 (!abort) { IoStat->SwordEnd.sample(); if (IoStat->SwordEnd.getState() == pal::InputBiDebounced::State::Passive) { fmt::println("pulling sword"); break; } auto abortMsg = mqtt.tryDequeueFor(10ms); abort = abortMsg && abortMsg->Payload == "abortTry"; } while (!abort) { IoStat->SwordEntry.sample(); if (IoStat->SwordEntry.getState() == pal::InputBiDebounced::State::Passive) { fmt::println("sword pulled"); break; } 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::playWavFileSync(SwordCfg->getNextAllow()); mqtt.sendEvent("ceremonyDone"); 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 (!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"); } } } // todo send state in background