Enhance logging functionality across multiple scripts, enabling debug mode checks and detailed communication logs for serial connections and firmware updates.

This commit is contained in:
“VeLiTi”
2025-11-14 16:38:05 +01:00
parent bd27bab30f
commit 04b9814c07
6 changed files with 214 additions and 19 deletions

View File

@@ -5,6 +5,11 @@ handshakeComplete = false;
// Function to log communication to API // Function to log communication to API
async function logCommunication(data, direction) { 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 // Log all communication including connection/disconnection events
try { try {
// Get service token for API authentication // Get service token for API authentication
@@ -64,6 +69,7 @@ async function connectSerial() {
// Log selected port details // Log selected port details
const portInfo = port.getInfo(); const portInfo = port.getInfo();
const portDetails = { const portDetails = {
processStep: 'Assembly',
usbVendorId: portInfo.usbVendorId, usbVendorId: portInfo.usbVendorId,
usbProductId: portInfo.usbProductId, usbProductId: portInfo.usbProductId,
readable: !!port.readable, readable: !!port.readable,
@@ -84,6 +90,7 @@ async function connectSerial() {
// Log successful connection with details // Log successful connection with details
const portInfoSuccess = port.getInfo(); const portInfoSuccess = port.getInfo();
const portDetailsSuccess = { const portDetailsSuccess = {
processStep: 'Assembly',
usbVendorId: portInfoSuccess.usbVendorId, usbVendorId: portInfoSuccess.usbVendorId,
usbProductId: portInfoSuccess.usbProductId, usbProductId: portInfoSuccess.usbProductId,
readable: !!port.readable, readable: !!port.readable,
@@ -528,6 +535,7 @@ async function closePort(){
// Log port closure start // Log port closure start
const portInfo = port.getInfo(); const portInfo = port.getInfo();
const portDetails = { const portDetails = {
processStep: 'Assembly',
usbVendorId: portInfo.usbVendorId, usbVendorId: portInfo.usbVendorId,
usbProductId: portInfo.usbProductId, usbProductId: portInfo.usbProductId,
readable: !!port.readable, readable: !!port.readable,
@@ -581,6 +589,7 @@ async function closePortCarTest(){
// Log port closure start // Log port closure start
const portInfo = port.getInfo(); const portInfo = port.getInfo();
const portDetails = { const portDetails = {
processStep: 'Assembly',
usbVendorId: portInfo.usbVendorId, usbVendorId: portInfo.usbVendorId,
usbProductId: portInfo.usbProductId, usbProductId: portInfo.usbProductId,
readable: !!port.readable, readable: !!port.readable,

View File

@@ -1,5 +1,58 @@
const serialResultsDiv = document.getElementById("serialResults"); 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){ function progressBar(percentage, message, color){
var readbar = document.getElementById("readBar"); var readbar = document.getElementById("readBar");
readBar.style.background = color; readBar.style.background = color;
@@ -7,16 +60,13 @@ function progressBar(percentage, message, color){
readBar.innerHTML = message; readBar.innerHTML = message;
} }
async function getServiceID(){
var data = document.getElementById("servicetoken").innerHTML;
return data
}
async function connectDevice() { async function connectDevice() {
//clear input //clear input
readBar.innerHTML = ''; readBar.innerHTML = '';
serialResultsDiv.innerHTML = ''; serialResultsDiv.innerHTML = '';
// Reset received data buffer for new connection
receivedDataBuffer = '';
//set prgress bar //set prgress bar
progressBar("1", "", ""); progressBar("1", "", "");
@@ -25,16 +75,44 @@ async function connectDevice() {
// Prompt user to select any serial port. // Prompt user to select any serial port.
const filters = [{ usbVendorId: 1027, usbProductId: 24597 }]; const filters = [{ usbVendorId: 1027, usbProductId: 24597 }];
port = await navigator.serial.requestPort({ filters }); 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 }); await port.open({ baudRate: 56700 });
progressBar("10", "Connecting", "#04AA6D"); 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(); listenToPort();
textEncoder = new TextEncoderStream(); textEncoder = new TextEncoderStream();
writableStreamClosed = textEncoder.readable.pipeTo(port.writable); writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
writer = textEncoder.writable.getWriter(); writer = textEncoder.writable.getWriter();
} catch { } catch (error) {
// Log connection failure details
await logCommunication(`Serial connection failed: ${error.message || 'Unknown error'}`, 'disconnected');
if (openPort = 1){ if (openPort = 1){
closePort(); closePort();
console.log("Closing port"); console.log("Closing port");
@@ -52,6 +130,9 @@ async function listenToPort() {
reader = textDecoder.readable.getReader(); reader = textDecoder.readable.getReader();
openPort = 1; openPort = 1;
// Log starting to listen to port
await logCommunication('Starting to listen to serial port', 'connected');
while (true) { while (true) {
const { value, done } = await reader.read(); const { value, done } = await reader.read();
if (done) { 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) if (x.indexOf("SN=") > 0 && x.indexOf("HW=") > 0 && x.indexOf("FW=") >0 && x.indexOf("STATE=") > 0)
{ {
progressBar("60", "Reading device completed", "#04AA6D"); 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); setTimeout(getDeviceData, 4000);
return; return;
} }
@@ -76,8 +161,15 @@ async function listenToPort() {
async function appendToTerminal(newStuff) { async function appendToTerminal(newStuff) {
serialResultsDiv.innerHTML += 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(){ async function getDeviceData(){
var item = serialResultsDiv.innerHTML; var item = serialResultsDiv.innerHTML;
@@ -91,6 +183,8 @@ async function getDeviceData(){
serial = x.substring(b,c); serial = x.substring(b,c);
progressBar("65", "Retrieving device data", "#04AA6D"); progressBar("65", "Retrieving device data", "#04AA6D");
console.log(serial); console.log(serial);
// Log serial number retrieval
await logCommunication(`Serial number retrieved: ${serial}`, 'handshake');
if (x.indexOf("FW=") > 0){ if (x.indexOf("FW=") > 0){
var a = x.indexOf("FW="); var a = x.indexOf("FW=");
@@ -98,6 +192,8 @@ async function getDeviceData(){
var c = b + 8; var c = b + 8;
fw = x.substring(b,c); fw = x.substring(b,c);
fw = fw.replace(/^0+/, ''); fw = fw.replace(/^0+/, '');
// Log firmware version
await logCommunication(`Firmware version retrieved: ${fw}`, 'handshake');
} }
//Check if HW is retrieved from device //Check if HW is retrieved from device
@@ -121,6 +217,8 @@ async function getDeviceData(){
//GET THE COMMITCODE //GET THE COMMITCODE
commitCode = compareCommitCodes("",fw); commitCode = compareCommitCodes("",fw);
// Log hardware version and commit code
await logCommunication(`Hardware version retrieved: ${hw}, Commit code: ${commitCode}`, 'handshake');
getServiceID().then(firmwareUpdate); getServiceID().then(firmwareUpdate);
progressBar("80", "checking for available firmware", "#04AA6D"); progressBar("80", "checking for available firmware", "#04AA6D");
@@ -129,9 +227,12 @@ async function getDeviceData(){
else { else {
progressBar("80", "Reading of device not successful, please try again", "#ff6666"); progressBar("80", "Reading of device not successful, please try again", "#ff6666");
console.log('Reading of device not successful'); 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){ function firmwareUpdate(data){
var serialnumber = serial; var serialnumber = serial;
@@ -140,6 +241,9 @@ function firmwareUpdate(data){
var bearer = 'Bearer ' + data; var bearer = 'Bearer ' + data;
// Log firmware update request
logCommunication(`Requesting firmware update for SN: ${serialnumber}, Version: ${commitCode}, HW: ${hw}`, 'sent');
fetch(url, { fetch(url, {
method: 'GET', method: 'GET',
withCredentials: true, withCredentials: true,
@@ -153,11 +257,15 @@ function firmwareUpdate(data){
.then(firmware=> { .then(firmware=> {
firmwarelocation = './firmware/'+firmware['software']; firmwarelocation = './firmware/'+firmware['software'];
upgraded_version = firmware['version']; upgraded_version = firmware['version'];
// Log firmware response
logCommunication(`Firmware update response: ${firmware['software']}, Version: ${firmware['version']}`, 'received');
return firmwarelocation; return firmwarelocation;
}) })
.catch(error => { .catch(error => {
console.log(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 == ''){ if (hex_fw == 'null' || hex_fw == ''){
//document.getElementById("updateAvailabe").style.display = "none"; //document.getElementById("updateAvailabe").style.display = "none";
progressBar("100", "No firmware found for this device", "#ff6666"); progressBar("100", "No firmware found for this device", "#ff6666");
// Log no firmware found
logCommunication('No firmware found for this device', 'disconnected');
} }
else { else {
var element = document.getElementById("Device_output"); var element = document.getElementById("Device_output");
@@ -217,6 +327,8 @@ function checkAvailableFirmware(){
//COMPARE commitCODE from DEVICE with RETURNED CODE FROM API //COMPARE commitCODE from DEVICE with RETURNED CODE FROM API
if (commitCode.toUpperCase() == upgraded_version.toUpperCase()){ if (commitCode.toUpperCase() == upgraded_version.toUpperCase()){
readBar.innerHTML = 'Latest Firmware already on device'; 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) if (typeof(element) != 'undefined' && element != null)
{ {
@@ -225,6 +337,8 @@ function checkAvailableFirmware(){
} }
else { else {
readBar.innerHTML = 'Firmware available'; readBar.innerHTML = 'Firmware available';
// Log firmware available
logCommunication(`Firmware update available: Current ${commitCode}, Available ${upgraded_version}`, 'received');
if (typeof(element) != 'undefined' && element != null){ if (typeof(element) != 'undefined' && element != null){
document.getElementById("Device_output").style.display = "block"; document.getElementById("Device_output").style.display = "block";
@@ -235,20 +349,42 @@ function checkAvailableFirmware(){
else{ else{
document.getElementById("updateAvailabe").style.display = "none"; document.getElementById("updateAvailabe").style.display = "none";
readBar.innerHTML = 'No firmware found for this device'; readBar.innerHTML = 'No firmware found for this device';
// Log no firmware location
logCommunication('No firmware location available', 'disconnected');
} }
closePort(); closePort();
} }
async function closePort(){ async function closePort(){
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(); reader.cancel();
await readableStreamClosed.catch(() => { /* Ignore the error */ }); await readableStreamClosed.catch(() => { /* Ignore the error */ });
writer.close(); writer.close();
await writableStreamClosed; await writableStreamClosed;
await port.close();
openPort = 0;
console.log('Device connection closed'); console.log('Device connection closed');
await port.close();
// 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');
}
openPort = 0;
readBar.style.width = "100%"; readBar.style.width = "100%";
} }

View File

@@ -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 = { var e = {
184: (e, t, r) => { 184: (e, t, r) => {
@@ -166,13 +213,13 @@ async function createFirmwareUpdate(){
emergencyPlug: { emergencyPlug: {
signature: n.from([30, 149, 15]), signature: n.from([30, 149, 15]),
pageSize: 128, pageSize: 128,
timeout: 400, timeout: 1000,
baudRate: 57600 baudRate: 57600
}, },
EMP2: { EMP2: {
signature: n.from([30, 149, 15]), signature: n.from([30, 149, 15]),
pageSize: 128, pageSize: 128,
timeout: 400, timeout: 1000,
baudRate: 115200 baudRate: 115200
} }
}; };
@@ -184,6 +231,7 @@ async function createFirmwareUpdate(){
baudRate: e.baudRate baudRate: e.baudRate
}); });
r(0); r(0);
await logCommunication('Starting firmware upload process', 'upload');
const a = new c.default; const a = new c.default;
let u = 0, let u = 0,
p = i.length / e.pageSize; p = i.length / e.pageSize;
@@ -194,6 +242,7 @@ async function createFirmwareUpdate(){
r(e) 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 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 { } finally {
s.default.close() s.default.close()
} }

View File

@@ -94,7 +94,7 @@ echo '
<script src = "./assets/DYMO.Label.Framework.latest.js?'.script_version.'" type="text/javascript" charset="UTF-8"> </script> <script src = "./assets/DYMO.Label.Framework.latest.js?'.script_version.'" type="text/javascript" charset="UTF-8"> </script>
<script> <script>
var link = "'.$baseurl.'"; var link = "'.$baseurl.'";
var DEBUG = '.(debug ? 'true' : 'false').';
function startTimer(duration, display) { function startTimer(duration, display) {
var timer = duration, minutes, seconds; var timer = duration, minutes, seconds;
setInterval(function () { setInterval(function () {

View File

@@ -343,7 +343,7 @@ echo '
<script src = "./assets/DYMO.Label.Framework.latest.js?'.script_version.'" type="text/javascript" charset="UTF-8"> </script> <script src = "./assets/DYMO.Label.Framework.latest.js?'.script_version.'" type="text/javascript" charset="UTF-8"> </script>
<script> <script>
var link = "'.$baseurl.'"; var link = "'.$baseurl.'";
var DEBUG = '.(debug ? 'true' : 'false').';
function startGraph(){ function startGraph(){
setInterval(renderChart,5000); setInterval(renderChart,5000);
} }

View File

@@ -58,7 +58,7 @@ $view .= '<div class="content-block">
<div class="" id="updateAvailabe" style="margin-top: 10px;"> <div class="" id="updateAvailabe" style="margin-top: 10px;">
<button class="btn" id="updateFirmware" style="display:none;" <button class="btn" id="updateFirmware" style="display:none;"
emergencyPlug-update emergencyPlug-update verify
board="emergencyPlug" board="emergencyPlug"
port-filters= "[{usbVendorId: 1027, usbProductId: 24597}\];" port-filters= "[{usbVendorId: 1027, usbProductId: 24597}\];"
disabled>Update Firmware disabled>Update Firmware
@@ -99,6 +99,7 @@ echo '
<script src="assets/upload.js?'.script_version.'"></script> <script src="assets/upload.js?'.script_version.'"></script>
<script> <script>
var link = "'.$baseurl.'"; var link = "'.$baseurl.'";
var DEBUG = '.(debug ? 'true' : 'false').';
var port, textEncoder, writableStreamClosed, writer, historyIndex = -1; var port, textEncoder, writableStreamClosed, writer, historyIndex = -1;
const lineHistory = []; const lineHistory = [];
</script>'; </script>';