402 lines
14 KiB
C++
402 lines
14 KiB
C++
#include "throneBridgeMain.hpp"
|
|
|
|
using namespace pal;
|
|
using namespace std::literals::string_view_literals;
|
|
using namespace std::literals::chrono_literals;
|
|
using namespace std;
|
|
|
|
constexpr uint8_t VersionArr[4] = {'V', 0, 8, 0};
|
|
const string Version = "V 0.8.0";
|
|
// const string Version = fmt::format("{} {}.{}.{}", VersionArr[0], VersionArr[1], VersionArr[2], VersionArr[3]);
|
|
|
|
SwordConfig SwordCfg{};
|
|
unique_ptr<DeviceIoState> IoStat;
|
|
OpMode Mode = OpMode::Maintanance;
|
|
|
|
void processMaintanence(MqttChannel& mqtt);
|
|
void processPromo(MqttChannel& mqtt, SeqLogger& log);
|
|
void processProduction(MqttChannel& mqtt, SeqLogger& log);
|
|
|
|
/// @brief MQTT-Service provider
|
|
void MQttServiceTask(Thread::Context& ctx, Queue<RxMsg>& rxQueue, Queue<TxMsg>& txQueue) {
|
|
string runTopic = SwordCfg.getStationPath() + "run";
|
|
string intTopic = SwordCfg.getStationPath() + "int";
|
|
string statTopic = SwordCfg.getStationPath() + "stat";
|
|
|
|
fmt::println("MQTT: Starting task:");
|
|
fmt::println(" Topic: {}", runTopic);
|
|
|
|
auto mqttCallback = [&](string topic, string payload) {
|
|
fmt::print("MQTT: on sendTrigger {}:{}'\n", topic, payload);
|
|
|
|
static std::map<string, IncommingCommands_e> commands = {
|
|
{"Qurey", IncommingCommands_e::Qurey},
|
|
{"SetMaintanance", IncommingCommands_e::SetMaintanance},
|
|
{"SetPromoMode", IncommingCommands_e::SetPromoMode},
|
|
{"SetGamingMode", IncommingCommands_e::SetGamingMode},
|
|
};
|
|
static std::map<string, ServiceCommands_e> serCommands = {
|
|
{"ServiceOpen", ServiceCommands_e::Open},
|
|
{"ServiceClose", ServiceCommands_e::Close},
|
|
{"ServicePlay1", ServiceCommands_e::Play1},
|
|
{"ServicePlay2", ServiceCommands_e::Play2},
|
|
{"ServicePlay3", ServiceCommands_e::Play3},
|
|
};
|
|
static std::map<string, GameModeCommands_e> gameCommands = {
|
|
{"GameStayLocked", GameModeCommands_e::GameNextTryLocked},
|
|
{"GameReleaseLock", GameModeCommands_e::GameNextTryRelease},
|
|
};
|
|
|
|
if (topic != runTopic) {
|
|
fmt::print("MQTT: ignore invalid topic {}'\n", topic);
|
|
return;
|
|
}
|
|
|
|
if (commands.contains(payload)) {
|
|
rxQueue.emplace<RxMsg>(commands.at(payload));
|
|
return;
|
|
}
|
|
if (serCommands.contains(payload)) {
|
|
auto code = serCommands.at(payload);
|
|
rxQueue.emplace<RxMsg>(code);
|
|
return;
|
|
}
|
|
if (gameCommands.contains(payload)) {
|
|
rxQueue.emplace<RxMsg>(serCommands.at(payload));
|
|
return;
|
|
}
|
|
|
|
fmt::print("MQTT: unknown command {}:{}'\n", topic, payload);
|
|
};
|
|
|
|
try {
|
|
std::vector<string> topicsToRegister{runTopic};
|
|
MqttClient client("Sword", SwordCfg.getBrockerUrl(), topicsToRegister, {SwordCfg.getMqttUser(), SwordCfg.getMqttPassword()});
|
|
fmt::println("MQTT: service: successfully connected ...");
|
|
client.registerCallback(mqttCallback);
|
|
|
|
client.send(statTopic, fmt::format("{} Mode={}, sE:0,sS:0,sP:0,lE:0",
|
|
Version, (int)Mode));
|
|
|
|
int cnt = 0;
|
|
fmt::println("MQTT: Running ...");
|
|
while (!ctx.isCancelled()) {
|
|
auto tx = txQueue.dequeue();
|
|
|
|
switch (tx->cmd) {
|
|
case OutgoingCommands_e::Status: {
|
|
auto& s = *IoStat;
|
|
client.send(statTopic, fmt::format("{} Mode={}, sE:{},sS:{},sP:{},lE:{}",
|
|
Version, (int)Mode,
|
|
s.SwordEnd.isActive(),
|
|
s.SwordEntry.isActive(),
|
|
s.SwordPulled.isActive(),
|
|
s.SwordLatch.isLocked()));
|
|
} break;
|
|
case OutgoingCommands_e::Response:
|
|
client.send(intTopic, "some response");
|
|
break;
|
|
case OutgoingCommands_e::Error:
|
|
client.send(intTopic, "some error");
|
|
break;
|
|
case OutgoingCommands_e::PullHappend:
|
|
client.send(intTopic, "pulled");
|
|
break;
|
|
|
|
default:
|
|
break;
|
|
}
|
|
client.send(intTopic, "sent");
|
|
}
|
|
} catch (const exception& exc) {
|
|
fmt::println(stderr, "\nERROR: Unable to connect to Setup bridge: {}", exc.what());
|
|
ctx.markFailed();
|
|
}
|
|
}
|
|
|
|
/// @brief LoRa-Service provider
|
|
void LoRaServiceTask(Thread::Context& ctx, Queue<RxMsg>& rxQueue, Queue<TxMsg>& txQueue) {
|
|
fmt::println("LoRa: Starting task:");
|
|
|
|
auto loraCallback = [&](std::vector<uint8_t> data) {
|
|
auto hex = bytesToHex(data);
|
|
auto str = bytesToPrintable(data);
|
|
fmt::print("LoRa: Received Byts: {}\n 0x{}\n {}\n", data.size(), hex, str);
|
|
|
|
auto e = std::make_unique<RxMsg>(0);
|
|
rxQueue.enqueue(std::move(e));
|
|
return true;
|
|
};
|
|
auto spi = SpiPort({.mode = SpiPort::Mode0,
|
|
.cs = SpiPort::Cs0,
|
|
.frequ = 1'000'000});
|
|
|
|
LoRa loRa({
|
|
.frequency = 868'000'000,
|
|
.port = spi,
|
|
.DioPin = GPIO_DIO0_PIN,
|
|
.resetPin = GPIO_RST_PIN,
|
|
},
|
|
loraCallback);
|
|
|
|
fmt::println("LoRa: Running ...");
|
|
while (!ctx.isCancelled()) {
|
|
auto tx = txQueue.dequeue();
|
|
loRa.send({0});
|
|
// printf ("Message: %s %lu\n", msg->message.c_str(), msg->cnt);
|
|
}
|
|
|
|
try {
|
|
} catch (const exception& exc) {
|
|
fmt::println(stderr, "\nERROR: Unable to connect to Setup bridge: {}", exc.what());
|
|
ctx.markFailed();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char* argv[]) {
|
|
CLI::App app{"Sword Firmware"};
|
|
string modeArg = "test";
|
|
string assetsBasePath = "/home/user/assets";
|
|
string brocker = "mqtts://excaliburs-erben.de:8883";
|
|
string topic = "staging/outdoor/king-arthur/sword/";
|
|
string user = "exodususer";
|
|
string password = "awesomeexodusoutdooradventures";
|
|
string logUrl = "log.excaliburs-erben.de";
|
|
string logApiKey = "9SWjXUxmnzcgCKYfzXMI";
|
|
app.add_option("startmode", modeArg, "Startup mode")->required();
|
|
app.add_option("basepath", assetsBasePath, "Base bath for assets")->required();
|
|
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");
|
|
|
|
CLI11_PARSE(app, argc, argv);
|
|
|
|
SeqLogger log(logUrl, logApiKey, "Sword");
|
|
SwordCfg.setVar(assetsBasePath, brocker, topic, user, password);
|
|
|
|
fmt::println("{}", app.get_description());
|
|
if (modeArg == "game") {
|
|
fmt::println("starting with game");
|
|
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>(Mode)]);
|
|
|
|
auto itrHandler = [&]() {
|
|
TriggeredInput itr(26, "PItr");
|
|
while (true) {
|
|
cout << "Await next interrupt\n";
|
|
if (itr.await()) {
|
|
cout << "Interrupt Event\n";
|
|
}
|
|
}
|
|
};
|
|
thread interruptThread(itrHandler);
|
|
|
|
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);
|
|
|
|
IoStat = make_unique<DeviceIoState>(SwordEntry, SwordEnd, SwordPulled, SwordLatch);
|
|
|
|
static Queue<RxMsg> rxQueue;
|
|
static Queue<TxMsg> txQueue;
|
|
MqttChannel mqtt(Version, SwordCfg, *IoStat, log);
|
|
auto resetCall = [&]() {
|
|
log.sendEvent("Reset", "");
|
|
};
|
|
|
|
mqtt.flushInput();
|
|
static auto conTask = Thread::createExplicit("MqttTask", MqttChannel::runMasterService, ref(mqtt), resetCall);
|
|
|
|
SwordLatch.moveOut();
|
|
fmt::println("Running App");
|
|
while (true) {
|
|
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");
|
|
processPromo(mqtt, log);
|
|
} break;
|
|
case OpMode::GamingMode: {
|
|
fmt::println("Running GamingMode");
|
|
processProduction(mqtt, log);
|
|
} break;
|
|
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
interruptThread.join();
|
|
return EXIT_SUCCESS;
|
|
}
|
|
|
|
void processMaintanenceCommand(enum ServiceCommands_e code) {
|
|
switch (code) {
|
|
case ServiceCommands_e::SetLockOpen: {
|
|
IoStat->SwordLatch.moveIn();
|
|
} break;
|
|
case ServiceCommands_e::SetLockClose: {
|
|
IoStat->SwordLatch.moveOut();
|
|
} break;
|
|
case ServiceCommands_e::PlaySoundPromo: {
|
|
MediaPlayer::playWavFile(SwordCfg.getSoundPromo());
|
|
} break;
|
|
case ServiceCommands_e::PlaySoundDeny: {
|
|
MediaPlayer::playWavFile(SwordCfg.getSoundDeny());
|
|
} break;
|
|
case ServiceCommands_e::PlaySoundChosen: {
|
|
MediaPlayer::playWavFile(SwordCfg.getSoundAllow());
|
|
} break;
|
|
}
|
|
}
|
|
|
|
void processMaintanence(MqttChannel& mqtt) {
|
|
auto& serCmds = mqtt.getSerCommands();
|
|
while (true) {
|
|
auto msg = mqtt.tryDequeueFor(500ms);
|
|
if (msg) {
|
|
if (serCmds.contains(msg->Payload)) {
|
|
auto code = serCmds.at(msg->Payload);
|
|
processMaintanenceCommand(code);
|
|
}
|
|
}
|
|
IoStat->tick();
|
|
mqtt.sendStatusMessage(Mode);
|
|
}
|
|
}
|
|
|
|
void processPromo(MqttChannel& mqtt, SeqLogger& log) {
|
|
auto tn = chrono::steady_clock::now();
|
|
auto& serCmds = mqtt.getSerCommands();
|
|
while (true) {
|
|
auto msg = mqtt.tryDequeueFor(10ms);
|
|
if (msg) {
|
|
if (serCmds.contains(msg->Payload)) {
|
|
auto code = serCmds.at(msg->Payload);
|
|
processMaintanenceCommand(code);
|
|
}
|
|
}
|
|
IoStat->tick();
|
|
if (IoStat->SwordPulled.isPosEdge()) {
|
|
log.sendEvent("Pull", "Start Audio");
|
|
MediaPlayer::playWavFile(SwordCfg.getSoundPromo());
|
|
fmt::println("Waiting for {}", IoStat->PromoDelay);
|
|
Thread::sleep(IoStat->PromoDelay);
|
|
fmt::println("Waiting done");
|
|
}
|
|
if (chrono::steady_clock::now() > (tn + 1s)) {
|
|
tn = chrono::steady_clock::now();
|
|
mqtt.sendStatusMessage(Mode);
|
|
}
|
|
}
|
|
}
|
|
|
|
void processProduction(MqttChannel& mqtt, SeqLogger& log) {
|
|
auto& serCmds = mqtt.getSerCommands();
|
|
auto& gameCmds = mqtt.getGameCommands();
|
|
while (true) {
|
|
auto msg = mqtt.tryDeque();
|
|
if (!msg) {
|
|
continue;
|
|
}
|
|
|
|
if (serCmds.contains(msg->Payload)) {
|
|
auto code = serCmds.at(msg->Payload);
|
|
processMaintanenceCommand(code);
|
|
continue;
|
|
}
|
|
|
|
auto code = gameCmds.at(msg->Payload);
|
|
switch (code) {
|
|
case GameModeCommands_e::GameStarted: {
|
|
fmt::println("Got GameStarted");
|
|
log.sendEvent("Req", "GameStarted");
|
|
}
|
|
case GameModeCommands_e::GameFinished: {
|
|
fmt::println("Got GameFinished");
|
|
log.sendEvent("Req", "GameFinished");
|
|
}
|
|
|
|
case GameModeCommands_e::GameNextTryLocked: {
|
|
fmt::println("Got NextTryLock");
|
|
log.sendEvent("Req", "StayLockded");
|
|
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);
|
|
log.sendEvent("Req", "Pulled");
|
|
mqtt.sendEvent("pull");
|
|
}
|
|
}
|
|
} break;
|
|
|
|
case GameModeCommands_e::GameNextTryRelease: {
|
|
fmt::println("NextTryRelease");
|
|
log.sendEvent("Req", "UnlockSword");
|
|
IoStat->SwordLatch.moveIn();
|
|
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;
|
|
}
|
|
}
|
|
mqtt.sendEvent("pulled-out");
|
|
log.sendEvent("Req", "Pulled Out");
|
|
// say: You ARE the one
|
|
MediaPlayer::playWavFile(SwordCfg.getSoundAllow());
|
|
Thread::sleep(15s);
|
|
mqtt.sendEvent("ceremonyDone");
|
|
|
|
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;
|
|
}
|
|
}
|
|
log.sendEvent("Req", "Put Back");
|
|
mqtt.sendEvent("put-in");
|
|
} break;
|
|
}
|
|
}
|
|
}
|