Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/update #53

Merged
merged 9 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion index.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ main {
}

button {
margin-top: 2rem;
margin-top: 1rem;
width: 200px;
background-color: #121212;
color: white;
Expand Down Expand Up @@ -99,3 +99,12 @@ form {
.group-c {
width: 280px;
}

.warning {
border: 2px solid;
padding: 0.5rem;
background-color: #f4a203;
margin-top: 1rem;
margin-left: auto;
margin-right: auto;
}
9 changes: 9 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ <h3 class="medium">Würfel C: Medium</h3>
</div>
</div>
</div>

<div class="warning">⚠️Warnung: Speichern verursacht Kosten ⚠️</div>
<button type="submit">Speichern</button>
</form>
</main>
Expand Down Expand Up @@ -216,6 +218,13 @@ <h3 class="medium">Würfel C: Medium</h3>
</body>
<script type="text/javascript">
function onSubmit(event) {
const confirmationText = `Speichern verursacht kosten. Sind Sie sich sicher, diese Änderungen speichern zu wollen?`;

if (confirm(confirmationText) === false) {
event.preventDefault();
return;
}

event.preventDefault();

const labels = {};
Expand Down
16 changes: 9 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
setTimeout(async () => {
const bluetoothSerialMonitors = import("./services/bluetooth/bluetooth.js");
const server = import("./services/rest/rest.js");
const { webSocketServer } = import("./services/socket/socket.js");
const { gpioProcess } = import("./services/gpio/gpio.js");
await import("./services/print/print.js");
const { bluetoothSerialMonitors } = await import(
"./services/bluetooth/bluetooth.js"
);
const { server } = await import("./services/rest/rest.js");
const { webSocketServer } = await import("./services/socket/socket.js");
const { gpioProcess } = await import("./services/gpio/gpio.js");
// await import("./services/print/print.js");
await import("./services/browser/browser.js");

process.on("SIGINT", () => closeEverything(1));

process.on("SIGTERM", () => closeEverything(0));

function closeEverything(eventId) {
bluetoothSerialMonitors.forEach((monitor) => monitor.kill());
server.close();
webSocketServer.clients.forEach((client) => client.close());
webSocketServer.close();
gpioProcess.kill();
bluetoothSerialMonitors.forEach((monitor) => monitor.kill());

process.exit(eventId);
}
}, 30_000);
}, 10_000);
78 changes: 50 additions & 28 deletions services/bluetooth/bluetooth.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import childProcess from "child_process";
import {
setDiceSide,
getDices,
setDiceConnectionStatus,
} from "../state/state.js";
import { setDiceSide, setDiceConnectionStatus } from "../state/state.js";

const diceAMacAddress = process.env.DICE_A_MAC_ADDRESS;
const rfcommA = "1";
Expand All @@ -13,21 +9,33 @@ const diceCMacAddress = process.env.DICE_C_MAC_ADDRESS;
const rfcommC = "3";

const dices = [
{ diceId: "A", diceMacAddress: diceAMacAddress, rfcomm: rfcommA },
{ diceId: "B", diceMacAddress: diceBMacAddress, rfcomm: rfcommB },
{ diceId: "C", diceMacAddress: diceCMacAddress, rfcomm: rfcommC },
{
diceId: "A",
diceMacAddress: diceAMacAddress,
rfcomm: rfcommA,
},
{
diceId: "B",
diceMacAddress: diceBMacAddress,
rfcomm: rfcommB,
},
{
diceId: "C",
diceMacAddress: diceCMacAddress,
rfcomm: rfcommC,
},
];

const bluetoothSerialMonitors = dices.map((dice) =>
export const bluetoothSerialMonitors = dices.map((dice) =>
createBluetoothSerialMonitor(dice),
);

function createBluetoothSerialMonitor({ diceId, diceMacAddress, rfcomm }) {
let isRestarting = false;

console.log(
`createBluetoothSerialMonitor, ${diceId}, ${diceMacAddress}, ${rfcomm}`,
);
// console.log(
// `createBluetoothSerialMonitor, ${diceId}, ${diceMacAddress}, ${rfcomm}`,
// );

bindDiceToRfcomm(diceMacAddress, rfcomm);

Expand All @@ -39,10 +47,18 @@ function createBluetoothSerialMonitor({ diceId, diceMacAddress, rfcomm }) {

const initial = setTimeout(
() => setDiceConnectionStatus({ [diceId]: "connected" }),
5000,
5_000,
);

picocom.stdout.on("data", (data) => {
const trimmedData = data.toString().trim();
// console.log("data", trimmedData);

if (trimmedData.length > 2) {
// console.log("data is bigger than 2, ignoring for setting dice");
return;
}

/**
* The old dices send the side in the format "A1", "B2", "C3".
* The new dices send the side in the format "1", "2", "3".
Expand All @@ -52,9 +68,13 @@ function createBluetoothSerialMonitor({ diceId, diceMacAddress, rfcomm }) {
* dice id in the firmware anymore.
*/
const side = data.toString().replace(/^\D+/g, "");
// console.log("side", side);

clearTimeout(initial);

setDiceSide(`${diceId}${side}`);
console.log(getDices());

// console.log(getDices());
});

picocom.stderr.on("data", (data) => {
Expand All @@ -69,9 +89,9 @@ function createBluetoothSerialMonitor({ diceId, diceMacAddress, rfcomm }) {
clearTimeout(initial);
cleanup({ diceId, diceMacAddress, rfcomm });

console.log(
`picocom for dice ${diceId} threw an error. Retrying in 10 seconds..`,
);
// console.log(
// `picocom for dice ${diceId} threw an error. Retrying in 30 seconds..`,
// );

setTimeout(
() =>
Expand All @@ -97,19 +117,21 @@ function cleanup({ diceId, diceMacAddress, rfcomm }) {
function bindDiceToRfcomm(diceMacAddress, rfcomm) {
const stdout = childProcess.execSync(
`sudo rfcomm bind ${rfcomm} ${diceMacAddress}`,
{ stdio: "ignore" },
);
console.log(
`bound dice ${diceMacAddress} to rfcomm${rfcomm}, stdout:`,
stdout.toString(),
);
// console.log(
// `bound dice ${diceMacAddress} to rfcomm${rfcomm}, stdout:`,
// stdout.toString(),
// );
}

function releaseDiceToRfcomm(diceMacAddress, rfcomm) {
const stdout = childProcess.execSync(`sudo rfcomm release rfcomm${rfcomm}`);
console.log(
`released dice ${diceMacAddress} from rfcomm${rfcomm}, stdout:`,
stdout.toString(),
);
const stdout = childProcess.execSync(`sudo rfcomm release rfcomm${rfcomm}`, {
stdio: "ignore",
});
// console.log(
// `released dice ${diceMacAddress} from rfcomm${rfcomm}, stdout:`,
// stdout.toString(),
// );
}

export default bluetoothSerialMonitors;
1;
2 changes: 1 addition & 1 deletion services/rest/idea-generation/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ export const strategies = {
* The amount of pregenerated ideas that need to be generated in advance.
* @type {number}
*/
export const MIN_AMOUNT_OF_PREGENERATED_IDEAS = 2;
export const MIN_AMOUNT_OF_PREGENERATED_IDEAS = 1;
7 changes: 7 additions & 0 deletions services/rest/paths/labels/labels.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { getLabels, setLabels } from "../../../state/state.js";

const port = process.env.API_PORT;

/**
* Handles the labels endpoint
* @param request
Expand Down Expand Up @@ -40,4 +42,9 @@ function handlePutLabels({ body, response }) {
setLabels(newLabels);

response.end(JSON.stringify({ message: "success" }));

/**
* start pregeneration in the background
*/
fetch(`http://localhost:${port}/pregenerate`).catch(console.error);
}
9 changes: 1 addition & 8 deletions services/rest/rest.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import http from "node:http";
import crypto from "node:crypto";
import { handleIsApiAlive } from "./paths/default.js";
import { handleLabels } from "./paths/labels/labels.js";
import { handleShutdown } from "./paths/shutdown/shutdown.js";
Expand All @@ -10,7 +9,7 @@ import { handleRegenerateOnlyPdfs } from "./paths/regenerate-only-pdfs/regenerat

const port = process.env.API_PORT;

const server = http.createServer();
export const server = http.createServer();

server.on("request", handleRequest);

Expand All @@ -20,10 +19,6 @@ server.on("request", handleRequest);
* @param {ServerResponse} response
*/
function handleRequest(request, response) {
const requestId = crypto.randomUUID();
console.time(`request ${requestId} time`);
response.on("close", () => console.timeEnd(`request ${requestId} time`));

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "OPTIONS, PUT, GET");

Expand Down Expand Up @@ -73,5 +68,3 @@ function handleRequest(request, response) {
server.listen(port, () => console.info("listening on port:", port));

server.on("close", () => console.log("api server closed"));

export default server;
15 changes: 12 additions & 3 deletions services/rest/rest.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ describe("services/rest", () => {

assert.strictEqual(response.status, 204);
assert.strictEqual(
response.headers.get("access-control-allow-origin"),
response.headers.get("Access-Control-Allow-Origin"),
"*",
);
assert.strictEqual(
response.headers.get("access-control-request-method"),
response.headers.get("Access-Control-Allow-Methods"),
"OPTIONS, PUT, GET",
);
});
Expand Down Expand Up @@ -52,19 +52,28 @@ describe("services/rest", () => {
const currentLabels = getLabels();
const givenLabels = { ...currentLabels, A1: "some other label" };

const response = await fetch("http://localhost:8000/labels", {
const promise = fetch("http://localhost:8000/labels", {
method: "PUT",
body: JSON.stringify({ labels: givenLabels }),
});

t.mock.method(global, "fetch");
fetch.mock.mockImplementationOnce(async () => ({
json: () => Promise.resolve({ message: "success" }),
}));

const response = await promise;

const actualResponse = await response.json();
const expectedResponse = { message: "success" };

const actualLabels = getLabels();
const expectedLabels = givenLabels;
const expectedFetchUrl = `http://localhost:${process.env.API_PORT}/pregenerate`;

assert.deepStrictEqual(actualResponse, expectedResponse);
assert.deepStrictEqual(actualLabels, expectedLabels);
assert.strictEqual(fetch.mock.calls[0].arguments[0], expectedFetchUrl);

// reset labels
setLabels(currentLabels);
Expand Down
4 changes: 2 additions & 2 deletions services/socket/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ webSocketServer.on("connection", function connection(webSocket) {
webSocket.on("error", console.error);

webSocket.on("message", function message(data) {
console.log("received: %s", data);
// console.log("received: %s", data);
});

webSocket.send(getDicesAsJson());
Expand All @@ -22,7 +22,7 @@ webSocketServer.on("connection", function connection(webSocket) {
webSocketServer.on("close", () => console.log("websocket server closed"));

export function broadcast(data) {
console.log("broadcast", data);
// console.log("broadcast", data);
webSocketServer.clients.forEach((client) => {
if (client.readyState !== WebSocket.OPEN) {
return;
Expand Down
2 changes: 1 addition & 1 deletion services/state/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export function setDiceSide(input) {

const [diceId, diceSide] = diceIdAndSide;

setDices(diceId, { ...dices[diceId], side: diceSide });
setDices(diceId, { status: "connected", side: diceSide });
}

export function getDices() {
Expand Down