3 Commits
Author SHA1 Message Date
leukipp b467711914 build: update version 2024-12-15 19:51:45 +01:00
leukipp 8ac11731c8 ref: verify hardware 2024-12-15 19:51:11 +01:00
leukipp 7f54996960 ref: entry point 2024-12-15 19:49:53 +01:00
7 changed files with 208 additions and 74 deletions
+142
View File
@@ -0,0 +1,142 @@
const fs = require("fs");
const path = require("path");
const readline = require("readline/promises");
const integration = require("./src/integration");
const hardware = require("./src/hardware");
const webview = require("./src/webview");
const { app } = require("electron");
/**
* This promise resolves when the app has finished initializing,
* allowing to safely create browser windows and perform other
* initialization tasks.
*/
app.whenReady().then(async () => {
let args = parseArgs(process);
let argsProvided = !!Object.keys(args).length;
let argsFilePath = path.join(app.getPath("userData"), "Arguments.json");
let argsFileExists = fs.existsSync(argsFilePath);
// Setup arguments from file path
if ("setup" in args || (!argsProvided && !argsFileExists)) {
await sleep(3000);
do {
args = await promptArgs(process);
} while (!Object.keys(args).length);
fs.writeFileSync(argsFilePath, JSON.stringify(args, null, 2));
} else if (!argsProvided && argsFileExists) {
args = JSON.parse(fs.readFileSync(argsFilePath));
}
console.log(JSON.stringify(args, null, 2));
// Chained init functions
const chained = [webview.init, hardware.init, integration.init];
for (const init of chained) {
if (!(await init(args))) {
break;
}
}
});
/**
* Parses command-line arguments from the given process object.
*
* @param {Object} proc - The process object.
* @returns {Object} An object mapping argument names to their corresponding values.
*/
const parseArgs = (proc) => {
let args = {};
proc.argv.slice(1).forEach((arg) => {
if (arg !== ".") {
const [key, value] = arg.split("=");
args[key.replace("--", "").replace("-", "_")] = value;
}
});
return args;
};
/**
* Prompts argument values on the command-line.
*
* @param {Object} proc - The process object.
* @returns {Object} An object mapping argument names to their corresponding values.
*/
const promptArgs = async (proc) => {
const read = readline.createInterface({
input: proc.stdin,
output: proc.stdout,
});
// Array of arguments
const arguments = [
{
key: "web_url",
question: "\nEnter WEB url",
fallback: "http://192.168.1.42:8123",
},
{
key: "web_theme",
question: "Enter WEB theme",
fallback: "dark",
},
{
key: "web_zoom",
question: "Enter WEB zoom level",
fallback: "1.25",
},
{
key: "mqtt_url",
question: "\nEnter MQTT url",
fallback: "mqtt://192.168.1.42:1883",
},
{
key: "mqtt_user",
question: "Enter MQTT username",
fallback: "kiosk",
},
{
key: "mqtt_password",
question: "Enter MQTT password",
fallback: "password",
},
{
key: "mqtt_discovery",
question: "Enter MQTT discovery prefix",
fallback: "homeassistant",
},
{
key: "check",
question: "\nEverything looks good?",
fallback: "yes",
},
];
// Prompt each argument and wait for the answer
let args = {};
for (const { key, question, fallback } of arguments) {
if (key === "check") {
const json = JSON.stringify(args, null, 2);
const prompt = `${question}\n${json}\n(${fallback}): `;
const answer = (await read.question(prompt)).trim() || fallback;
if (!["y", "yes"].includes(answer)) {
args = {};
}
} else {
const prompt = `${question} (${fallback}): `;
const answer = (await read.question(prompt)).trim() || fallback;
args[key] = answer;
}
}
read.close();
return args;
};
/**
* Helper function for asynchronous sleep.
*
* @param {number} ms - Sleep time in milliseconds.
* @returns {Promise} A promise resolving after the timeout.
*/
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
-35
View File
@@ -1,35 +0,0 @@
const integration = require("./src/integration");
const hardware = require("./src/hardware");
const webview = require("./src/webview");
const { app } = require("electron");
/**
* This promise resolves when the app has finished initializing,
* allowing to safely create browser windows and perform other
* initialization tasks.
*/
app.whenReady().then(() => {
const args = parseArgs(process);
webview.init(args) && hardware.init(args) && integration.init(args);
});
/**
* Parses command-line arguments from the given process object.
*
* @param {Object} proc - The process object.
* @returns {Object} An object mapping argument names to their corresponding values.
*/
const parseArgs = (proc) => {
let argv = proc.argv.slice(1).join(" ").trim();
if (argv.length && argv[0] == ".") {
argv = argv.slice(1);
}
argv = argv.replace(/--|=/g, " ").replace(/\s+/g, " ");
argv = argv.trim().split(" ");
argv = argv.reduce(
(args, k, i, v) =>
i % 2 ? args : { ...args, [k.replace("-", "_")]: v[i + 1] },
{}
);
return argv;
};
+6 -3
View File
@@ -2,9 +2,9 @@
"name": "touchkio",
"description": "Home Assistant Touch Kiosk",
"author": "leukipp",
"version": "0.0.1",
"version": "0.0.2",
"license": "MIT",
"main": "main.js",
"main": "index.js",
"scripts": {
"start": "electron . --web-url=https://demo.home-assistant.io",
"build": "electron-forge make"
@@ -26,8 +26,11 @@
"name": "@electron-forge/maker-deb",
"config": {
"options": {
"productName": "TouchKio",
"icon": "img/icon.png",
"category": "Network"
"categories": [
"Network"
]
}
}
}
+36 -12
View File
@@ -18,12 +18,24 @@ global.HARDWARE = global.HARDWARE || {
* @param {Object} args - The command-line arguments to customize the initialization process.
* @returns {boolean} Returns true if the initialization was successful.
*/
const init = (args) => {
const model = getModel();
const valid = model && model.includes("Raspberry Pi 5");
const init = async (args) => {
if (!args.mqtt_url) {
return false;
}
// Check supported hardware
if (valid) {
if (!hardwareExists()) {
console.warn("Hardware not supported");
return false;
}
// Check supported model
const model = getModel();
if (!model || !model.includes("Raspberry Pi 5")) {
console.warn(`Device ${model} not supported`);
return false;
}
console.log("\nModel:", getModel());
console.log("Serial Number:", getSerialNumber());
console.log("Host Name:", getHostName());
@@ -41,11 +53,8 @@ const init = (args) => {
// Check for display changes
setInterval(update, 500);
} else {
console.warn(`Device ${model} not supported`);
}
return valid;
return true;
};
/**
@@ -78,6 +87,21 @@ const update = () => {
}
};
/**
* Verifies hardware compatibility by checking the presence of necessary sys files.
*
* @returns {bool} Returns true if all files exists.
*/
const hardwareExists = () => {
const files = [
"/sys/firmware/devicetree/base/model",
"/sys/firmware/devicetree/base/serial-number",
"/sys/class/backlight/10-0045/brightness",
"/sys/class/backlight/10-0045/bl_power",
];
return files.every((file) => fs.existsSync(file));
};
/**
* Gets the Raspberry Pi model name using `/sys/firmware/devicetree/base/model`.
*
@@ -192,8 +216,8 @@ const getDisplayStatus = () => {
*/
const setDisplayStatus = (status, callback = null) => {
if (status !== "ON" && status !== "OFF") {
console.error("Status must be 'ON' or 'OFF'.");
if (typeof callback === "function") callback(null, "Invalid status.");
console.error("Status must be 'ON' or 'OFF'");
if (typeof callback === "function") callback(null, "Invalid status");
return;
}
const args = status === "ON" ? ["--on", "*"] : ["--off", "*"];
@@ -240,8 +264,8 @@ const getDisplayBrightness = () => {
*/
const setDisplayBrightness = (brightness, callback = null) => {
if (typeof brightness !== "number" || brightness < 1 || brightness > 100) {
console.error("Brightness must be a number between 1 and 100.");
if (typeof callback === "function") callback(null, "Invalid brightness.");
console.error("Brightness must be a number between 1 and 100");
if (typeof callback === "function") callback(null, "Invalid brightness");
return;
}
const value = Math.max(1, Math.min(Math.round((brightness / 100) * 31), 31));
+2 -2
View File
@@ -13,7 +13,7 @@ global.INTEGRATION = global.INTEGRATION || {
* @param {Object} args - The command-line arguments to customize the initialization process.
* @returns {boolean} Returns true if the initialization was successful.
*/
const init = (args) => {
const init = async (args) => {
if (!args.mqtt_url) {
return false;
}
@@ -196,7 +196,7 @@ const initRefresh = (client) => {
)
.on("message", (topic, message) => {
if (topic === `${root}/execute`) {
console.log("Refresh webview...");
console.log("Refreshing webview...");
hardware.setDisplayStatus("ON");
WEBVIEW.view.webContents.reloadIgnoringCache();
}
+2 -2
View File
@@ -15,9 +15,9 @@ global.WEBVIEW = global.WEBVIEW || {
* @param {Object} args - The command-line arguments to customize the initialization process.
* @returns {boolean} Returns true if the initialization was successful.
*/
const init = (args) => {
const init = async (args) => {
if (!args.web_url) {
console.error("Please provide the '--web-url' parameter.");
console.error("Please provide the '--web-url' parameter");
return app.quit();
}
const url = new URL(args.web_url);
+2 -2
View File
@@ -246,9 +246,9 @@
optionalDependencies:
global-agent "^3.0.0"
"@electron/node-gyp@git+https://github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2":
"@electron/node-gyp@https://github.com/electron/node-gyp#06b29aafb7708acef8b3669835c8a7857ebc92d2":
version "10.2.0-electron.1"
resolved "git+https://github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2"
resolved "https://github.com/electron/node-gyp#06b29aafb7708acef8b3669835c8a7857ebc92d2"
dependencies:
env-paths "^2.2.0"
exponential-backoff "^3.1.1"