ok-ready-go/js/localState.js

106 lines
2.4 KiB
JavaScript
Raw Normal View History

2023-02-09 13:23:28 +01:00
document.addEventListener("alpine:init", () => {
Alpine.store("localState", {
_state: 0,
// 0: idle
// 1: starting
// 2: running
// 3: sending time to mqtt
// 4: stopped
// 5: connecting to mqtt
startedAt: null,
time: null,
stateHint: "",
password: null,
init() {
Alpine.effect(() => {
if (this.password == null) {
this.password = localStorage.getItem("password");
} else {
localStorage.setItem("password", this.password);
}
const mqtt = Alpine.store("mqtt");
if (!mqtt) return;
if (this.password == null || this.password == "") {
mqtt.disconnect();
} else {
mqtt.connect();
}
});
Alpine.effect(() => {
switch (this._state) {
case 0:
this.stateHint = "Tap here to start";
break;
case 1:
this.stateHint = "Get ready...";
break;
case 2:
this.stateHint = "Tap anywhere to stop";
break;
case 3:
this.stateHint = "Sending time to MQTT...";
break;
case 4:
this.stateHint = "Tap here to reset";
break;
}
});
},
next() {
playAudio(document.getElementById("sound-silence"));
if (this._state == 1 || this._state == 3) return;
this._setState((this._state + 1) % 5);
},
_setState(state) {
switch (state) {
case 0: {
this.startedAt = null;
this.time = null;
break;
}
case 1: {
playAudio(document.getElementById("sound-ok-ready-go")).then(() => {
Alpine.store("localState")._setState(2);
});
break;
}
case 2: {
this.startedAt = new Date().getTime() - 200;
break;
}
case 3: {
this.time =
2023-02-09 14:06:50 +01:00
Math.floor(((new Date().getTime() - this.startedAt) / 1000).toFixed(2) * 1000);
2023-02-09 13:23:28 +01:00
this.startedAt = null;
sayNumber(this.time / 10);
if (Alpine.store("mqtt").connected) {
Alpine.store("mqtt")
.sendTime(this.time)
.then(() => {
Alpine.store("localState")._setState(4);
});
break;
}
state = 4;
break;
}
default:
break;
}
this._state = state;
},
});
});