diff --git a/RESTserver/LEGGIMI.md b/RESTserver/LEGGIMI.md index 136ba48..4085101 100644 --- a/RESTserver/LEGGIMI.md +++ b/RESTserver/LEGGIMI.md @@ -35,6 +35,7 @@ La latenza media (ritardo) tra un evento e la sua segnalazione in un client WEB 3. **Configurazione:** * Aggiorna il tuo percorso di installazione nel file `run_server.bat` + * Per gli utenti Linux/Raspberry Pi, รจ fornito il file `iotwebui.service` per l'avvio automatico tramite systemd. 4. **Test e debug** Ci sono tre file principali: diff --git a/RESTserver/README.md b/RESTserver/README.md index c8ac31a..6859169 100644 --- a/RESTserver/README.md +++ b/RESTserver/README.md @@ -33,6 +33,7 @@ The average latency (delay) between an event and its reporting in a WEB client u * Click on `install_server.bat`: it will install the updated dependencies in the 'node_modules' dir. 3. **Configuration:** * Update your installation path in the `run_server.bat` file + * For Linux/Raspberry Pi users, a `iotwebui.service` file is provided for autostart functionality via systemd. 4. **Testing and debugging** There are three main files: * `server.js`: the executable file with the IoTrest implementation, to be launched in a terminal or using `run_server.bat`. diff --git a/RESTserver/iotwebui.service b/RESTserver/iotwebui.service new file mode 100644 index 0000000..c846f96 --- /dev/null +++ b/RESTserver/iotwebui.service @@ -0,0 +1,15 @@ +[Unit] +Description=IoTwebUI REST Server +After=network.target + +[Service] +Type=simple +# Update the path to your actual installation directory +WorkingDirectory=/opt/IoTwebUI/RESTserver +ExecStart=/usr/bin/node server.js +Restart=on-failure +RestartSec=5 +User=pi + +[Install] +WantedBy=multi-user.target diff --git a/RESTserver/server.js b/RESTserver/server.js index 0ed1723..b92e244 100644 --- a/RESTserver/server.js +++ b/RESTserver/server.js @@ -45,18 +45,40 @@ let connectedClient = null; }); }); -// Improved getAnswer function using async/await +// Improved getAnswer function using queue to solve race conditions on multi-requests +let requestQueue = []; +let isFetching = false; + async function getAnswer(message) { if (!connectedClient) { throw new Error('No connected client'); } - connectedClient.send(message); // Send the request message return new Promise((resolve, reject) => { - connectedClient.onmessage = ({ data }) => { - resolve(data); - }; - }); + requestQueue.push({ message, resolve, reject }); + processQueue(); + }); +} + +function processQueue() { + if (isFetching || requestQueue.length === 0 || !connectedClient) return; + + isFetching = true; + const task = requestQueue.shift(); + + connectedClient.onmessage = ({ data }) => { + isFetching = false; + task.resolve(data); + processQueue(); + }; + + try { + connectedClient.send(task.message); + } catch(e) { + isFetching = false; + task.reject(e); + processQueue(); + } } // Define HAPI route for fetching all data