From 04b9814c07f3f60d31f5692fc8f7534c75f886ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CVeLiTi=E2=80=9D?= <“info@veliti.nl”> Date: Fri, 14 Nov 2025 16:38:05 +0100 Subject: [PATCH] Enhance logging functionality across multiple scripts, enabling debug mode checks and detailed communication logs for serial connections and firmware updates. --- assets/readdevice.js | 9 +++ assets/scripts.js | 162 +++++++++++++++++++++++++++++++++++++++---- assets/upload.js | 55 ++++++++++++++- buildtool.php | 2 +- cartest_manage.php | 2 +- firmwaretool.php | 3 +- 6 files changed, 214 insertions(+), 19 deletions(-) diff --git a/assets/readdevice.js b/assets/readdevice.js index 9a3e85a..379b221 100644 --- a/assets/readdevice.js +++ b/assets/readdevice.js @@ -5,6 +5,11 @@ handshakeComplete = false; // Function to log communication to API async function logCommunication(data, direction) { + // Only log if debug mode is enabled + if (typeof DEBUG === 'undefined' || !DEBUG) { + return; + } + // Log all communication including connection/disconnection events try { // Get service token for API authentication @@ -64,6 +69,7 @@ async function connectSerial() { // Log selected port details const portInfo = port.getInfo(); const portDetails = { + processStep: 'Assembly', usbVendorId: portInfo.usbVendorId, usbProductId: portInfo.usbProductId, readable: !!port.readable, @@ -84,6 +90,7 @@ async function connectSerial() { // Log successful connection with details const portInfoSuccess = port.getInfo(); const portDetailsSuccess = { + processStep: 'Assembly', usbVendorId: portInfoSuccess.usbVendorId, usbProductId: portInfoSuccess.usbProductId, readable: !!port.readable, @@ -528,6 +535,7 @@ async function closePort(){ // Log port closure start const portInfo = port.getInfo(); const portDetails = { + processStep: 'Assembly', usbVendorId: portInfo.usbVendorId, usbProductId: portInfo.usbProductId, readable: !!port.readable, @@ -581,6 +589,7 @@ async function closePortCarTest(){ // Log port closure start const portInfo = port.getInfo(); const portDetails = { + processStep: 'Assembly', usbVendorId: portInfo.usbVendorId, usbProductId: portInfo.usbProductId, readable: !!port.readable, diff --git a/assets/scripts.js b/assets/scripts.js index 273e918..12d0961 100644 --- a/assets/scripts.js +++ b/assets/scripts.js @@ -1,5 +1,58 @@ const serialResultsDiv = document.getElementById("serialResults"); +// Buffer for accumulating received data before logging +let receivedDataBuffer = ''; + +// Function to log communication to API +async function logCommunication(data, direction) { + // Only log if debug mode is enabled + if (typeof DEBUG === 'undefined' || !DEBUG) { + return; + } + + // Log all communication including connection/disconnection events + try { + // Get service token for API authentication + const serviceToken = document.getElementById("servicetoken")?.innerHTML || ''; + + // Get serial number if available + let serialNumber = ''; + if (typeof serial !== 'undefined' && serial) { + serialNumber = serial; + } + + const logData = { + data: data, + direction: direction, // 'sent', 'received', 'connected', 'disconnected', 'handshake' + timestamp: new Date().toISOString(), + serial_number: serialNumber, + maintenance_run: 0 // Not used in scripts.js, set to 0 + }; + + // Get base URL for API calls (assuming 'link' variable is defined globally) + const url = link + '/v2/com_log/log'; + + const bearer = 'Bearer ' + serviceToken; + + const response = await fetch(url, { + method: 'POST', + withCredentials: true, + credentials: 'include', + headers: { + 'Authorization': bearer, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(logData) + }); + + if (!response.ok) { + console.warn('Failed to log communication:', response.status); + } + } catch (error) { + console.warn('Error logging communication:', error); + } +} + function progressBar(percentage, message, color){ var readbar = document.getElementById("readBar"); readBar.style.background = color; @@ -7,16 +60,13 @@ function progressBar(percentage, message, color){ readBar.innerHTML = message; } -async function getServiceID(){ - var data = document.getElementById("servicetoken").innerHTML; - return data -} - async function connectDevice() { //clear input readBar.innerHTML = ''; serialResultsDiv.innerHTML = ''; + // Reset received data buffer for new connection + receivedDataBuffer = ''; //set prgress bar progressBar("1", "", ""); @@ -25,17 +75,45 @@ async function connectDevice() { // Prompt user to select any serial port. const filters = [{ usbVendorId: 1027, usbProductId: 24597 }]; port = await navigator.serial.requestPort({ filters }); + + // Log selected port details + const portInfo = port.getInfo(); + const portDetails = { + processStep: 'Firmware', + usbVendorId: portInfo.usbVendorId, + usbProductId: portInfo.usbProductId, + readable: !!port.readable, + writable: !!port.writable, + opened: port.readable !== null && port.writable !== null + }; + await logCommunication(`Selected USB device - ${JSON.stringify(portDetails)}`, 'connected'); + await port.open({ baudRate: 56700 }); progressBar("10", "Connecting", "#04AA6D"); + // Log successful connection with details + const portInfoSuccess = port.getInfo(); + const portDetailsSuccess = { + processStep: 'Firmware', + usbVendorId: portInfoSuccess.usbVendorId, + usbProductId: portInfoSuccess.usbProductId, + readable: !!port.readable, + writable: !!port.writable, + opened: port.readable !== null && port.writable !== null + }; + await logCommunication(`Serial port opened successfully (baudRate: 56700) - ${JSON.stringify(portDetailsSuccess)}`, 'connected'); + listenToPort(); textEncoder = new TextEncoderStream(); writableStreamClosed = textEncoder.readable.pipeTo(port.writable); writer = textEncoder.writable.getWriter(); - } catch { - if (openPort = 1){ + } catch (error) { + // Log connection failure details + await logCommunication(`Serial connection failed: ${error.message || 'Unknown error'}`, 'disconnected'); + + if (openPort = 1){ closePort(); console.log("Closing port"); alert("System is still trying to close the serial port. If this message continues to come up please refresh this page."); @@ -52,6 +130,9 @@ async function listenToPort() { reader = textDecoder.readable.getReader(); openPort = 1; + // Log starting to listen to port + await logCommunication('Starting to listen to serial port', 'connected'); + while (true) { const { value, done } = await reader.read(); if (done) { @@ -67,6 +148,10 @@ async function listenToPort() { if (x.indexOf("SN=") > 0 && x.indexOf("HW=") > 0 && x.indexOf("FW=") >0 && x.indexOf("STATE=") > 0) { progressBar("60", "Reading device completed", "#04AA6D"); + // Log combined received data when device identification is complete + await logCommunication(`Device identification data received: ${receivedDataBuffer.trim()}`, 'handshake'); + // Reset buffer for next connection + receivedDataBuffer = ''; setTimeout(getDeviceData, 4000); return; } @@ -76,8 +161,15 @@ async function listenToPort() { async function appendToTerminal(newStuff) { serialResultsDiv.innerHTML += newStuff; + + // Log received data + await logCommunication(newStuff.trim(), 'received'); } +async function getServiceID(){ + var data = document.getElementById("servicetoken").innerHTML; + return data +} async function getDeviceData(){ var item = serialResultsDiv.innerHTML; @@ -91,6 +183,8 @@ async function getDeviceData(){ serial = x.substring(b,c); progressBar("65", "Retrieving device data", "#04AA6D"); console.log(serial); + // Log serial number retrieval + await logCommunication(`Serial number retrieved: ${serial}`, 'handshake'); if (x.indexOf("FW=") > 0){ var a = x.indexOf("FW="); @@ -98,6 +192,8 @@ async function getDeviceData(){ var c = b + 8; fw = x.substring(b,c); fw = fw.replace(/^0+/, ''); + // Log firmware version + await logCommunication(`Firmware version retrieved: ${fw}`, 'handshake'); } //Check if HW is retrieved from device @@ -121,6 +217,8 @@ async function getDeviceData(){ //GET THE COMMITCODE commitCode = compareCommitCodes("",fw); + // Log hardware version and commit code + await logCommunication(`Hardware version retrieved: ${hw}, Commit code: ${commitCode}`, 'handshake'); getServiceID().then(firmwareUpdate); progressBar("80", "checking for available firmware", "#04AA6D"); @@ -129,9 +227,12 @@ async function getDeviceData(){ else { progressBar("80", "Reading of device not successful, please try again", "#ff6666"); console.log('Reading of device not successful'); + // Log failure to read device data + await logCommunication('Failed to retrieve complete device data (HW and FW)', 'disconnected'); } } } + function firmwareUpdate(data){ var serialnumber = serial; @@ -140,6 +241,9 @@ function firmwareUpdate(data){ var bearer = 'Bearer ' + data; + // Log firmware update request + logCommunication(`Requesting firmware update for SN: ${serialnumber}, Version: ${commitCode}, HW: ${hw}`, 'sent'); + fetch(url, { method: 'GET', withCredentials: true, @@ -153,11 +257,15 @@ function firmwareUpdate(data){ .then(firmware=> { firmwarelocation = './firmware/'+firmware['software']; upgraded_version = firmware['version']; + // Log firmware response + logCommunication(`Firmware update response: ${firmware['software']}, Version: ${firmware['version']}`, 'received'); return firmwarelocation; }) .catch(error => { console.log(error) + // Log firmware fetch error + logCommunication(`Firmware update fetch error: ${error.message}`, 'disconnected'); }) @@ -210,6 +318,8 @@ function checkAvailableFirmware(){ if (hex_fw == 'null' || hex_fw == ''){ //document.getElementById("updateAvailabe").style.display = "none"; progressBar("100", "No firmware found for this device", "#ff6666"); + // Log no firmware found + logCommunication('No firmware found for this device', 'disconnected'); } else { var element = document.getElementById("Device_output"); @@ -217,6 +327,8 @@ function checkAvailableFirmware(){ //COMPARE commitCODE from DEVICE with RETURNED CODE FROM API if (commitCode.toUpperCase() == upgraded_version.toUpperCase()){ readBar.innerHTML = 'Latest Firmware already on device'; + // Log firmware up to date + logCommunication(`Firmware is up to date: ${commitCode}`, 'received'); if (typeof(element) != 'undefined' && element != null) { @@ -225,6 +337,8 @@ function checkAvailableFirmware(){ } else { readBar.innerHTML = 'Firmware available'; + // Log firmware available + logCommunication(`Firmware update available: Current ${commitCode}, Available ${upgraded_version}`, 'received'); if (typeof(element) != 'undefined' && element != null){ document.getElementById("Device_output").style.display = "block"; @@ -235,20 +349,42 @@ function checkAvailableFirmware(){ else{ document.getElementById("updateAvailabe").style.display = "none"; readBar.innerHTML = 'No firmware found for this device'; + // Log no firmware location + logCommunication('No firmware location available', 'disconnected'); } closePort(); } async function closePort(){ - reader.cancel(); - await readableStreamClosed.catch(() => { /* Ignore the error */ }); + + try { + // Log port closure start + const portInfo = port.getInfo(); + const portDetails = { + processStep: 'Firmware', + usbVendorId: portInfo.usbVendorId, + usbProductId: portInfo.usbProductId, + readable: !!port.readable, + writable: !!port.writable, + opened: port.readable !== null && port.writable !== null + }; + await logCommunication(`Starting port closure - ${JSON.stringify(portDetails)}`, 'disconnected'); + + reader.cancel(); + await readableStreamClosed.catch(() => { /* Ignore the error */ }); + writer.close(); + await writableStreamClosed; + console.log('Device connection closed'); + await port.close(); - writer.close(); - await writableStreamClosed; + // Log successful port closure + await logCommunication(`Serial port closed successfully - VendorID: ${portInfo.usbVendorId}, ProductID: ${portInfo.usbProductId}`, 'disconnected'); + } catch (error) { + // Log port closure failure + await logCommunication(`Serial port closure failed: ${error.message || 'Unknown error'}`, 'disconnected'); + } - await port.close(); openPort = 0; - console.log('Device connection closed'); readBar.style.width = "100%"; } diff --git a/assets/upload.js b/assets/upload.js index 0845eb1..020918d 100644 --- a/assets/upload.js +++ b/assets/upload.js @@ -68,7 +68,54 @@ async function createFirmwareUpdate(){ } -/*! For license information please see main.js.LICENSE.txt */ +async function logCommunication(data, direction) { + // Only log if debug mode is enabled + if (typeof DEBUG === 'undefined' || !DEBUG) { + return; + } + + try { + // Get service token for API authentication + const serviceToken = document.getElementById("servicetoken")?.innerHTML || ''; + + // Get serial number if available + let serialNumber = ''; + if (typeof serial !== 'undefined' && serial) { + serialNumber = serial; + } + + const logData = { + data: data, + direction: direction, // 'sent', 'received', 'connected', 'disconnected', 'handshake', 'upload', 'verify' + timestamp: new Date().toISOString(), + serial_number: serialNumber, + maintenance_run: 0 // Not applicable for upload, set to 0 + }; + + // Get base URL for API calls (assuming 'link' variable is defined globally) + const url = link + '/v2/com_log/log'; + + const bearer = 'Bearer ' + serviceToken; + + const response = await fetch(url, { + method: 'POST', + withCredentials: true, + credentials: 'include', + headers: { + 'Authorization': bearer, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(logData) + }); + + if (!response.ok) { + console.warn('Failed to log communication:', response.status); + } + } catch (error) { + console.warn('Error logging communication:', error); + } +} + (() => { var e = { 184: (e, t, r) => { @@ -166,13 +213,13 @@ async function createFirmwareUpdate(){ emergencyPlug: { signature: n.from([30, 149, 15]), pageSize: 128, - timeout: 400, + timeout: 1000, baudRate: 57600 }, EMP2: { signature: n.from([30, 149, 15]), pageSize: 128, - timeout: 400, + timeout: 1000, baudRate: 115200 } }; @@ -184,6 +231,7 @@ async function createFirmwareUpdate(){ baudRate: e.baudRate }); r(0); + await logCommunication('Starting firmware upload process', 'upload'); const a = new c.default; let u = 0, p = i.length / e.pageSize; @@ -194,6 +242,7 @@ async function createFirmwareUpdate(){ r(e) } }, await f.default.series([a.sync.bind(a, o, 3, e.timeout), a.sync.bind(a, o, 3, e.timeout), a.sync.bind(a, o, 3, e.timeout), a.verifySignature.bind(a, o, e.signature, e.timeout), a.setOptions.bind(a, o, {}, e.timeout), a.enterProgrammingMode.bind(a, o, e.timeout), a.upload.bind(a, o, i, e.pageSize, e.timeout), n ? a.verify.bind(a, o, i, e.pageSize, e.timeout) : h, a.exitProgrammingMode.bind(a, o, e.timeout)]) + await logCommunication('Firmware upload process completed', 'upload'); } finally { s.default.close() } diff --git a/buildtool.php b/buildtool.php index d580df4..e5c97d6 100644 --- a/buildtool.php +++ b/buildtool.php @@ -94,7 +94,7 @@ echo ' ';