/**
* Petite Vue XML Loader
* Loads XML files and converts them to JSON for use with Petite Vue
*
* Features:
* - XML to JSON conversion with namespace support
* - Reactive data binding with Petite Vue
* - Periodic data refresh with form field protection
* - Temperature unit conversion (Celsius/Fahrenheit/Kelvin)
* - Component templates (Agent, Menu, Footer)
*
* Form Field Protection:
* - Automatically detects all form fields (input/select/textarea) with v-model or :value
* - Registers them before Vue mount to preserve user input during periodic updates
* - Only non-form data is refreshed, preventing loss of user edits
*
* MIT License
*/
// Agent (Device Name) template
const AgentTemplate = `
{{ data.Agent?.DeviceName }}
HW Security Protection Enabled
`;
// Menu template
const MenuTemplate = `
Version: {{ data.Agent?.Version }}
`;
// Footer component template
const FooterTemplate = `
`;
// Track form fields outside of AppData (Set cannot be proxied by Vue)
// Contains data paths like 'Network.IPAddr', 'Network.DHCP' etc.
// These fields are excluded from periodic updates to preserve user input
const formFields = new Set();
// Centralized page access rules based on Agent.Features.
const pageFeatureRequirements = {
'general': null,
'network': null,
'security': null,
'snmp': 'SNMP',
'snmp_oid': 'SNMP',
'email': 'SMTP',
'serial': null,
'logtime': null,
'portal': 'Portal',
'mqtt': 'MQTT',
'sensors': 'Sensor',
'inputs': 'BinaryIn',
'binlogic': 'BinaryLogic',
'outputs': 'BinaryOut',
'voutputs': 'BinaryOut',
'pulsest': 'PulseStat',
'pulsestat': 'PulseStat',
'vsp': 'vsp',
'system': null,
'message': null,
'props': null,
'values': null
};
function checkFeatures(xmlPath) {
const page = xmlPath.split('/').pop().split('.')[0].toLowerCase();
if (page in pageFeatureRequirements) {
const requiredFeature = pageFeatureRequirements[page];
if ((requiredFeature == null) || (AppData && AppData.data && AppData.data.Agent && AppData.data.Agent.Features && requiredFeature in AppData.data.Agent.Features)) {
return;
} else {
document.body.innerHTML = '404 Not Found ';
window.location.replace('404');
return;
}
}
}
function addProtectedPath(binding) {
if (!binding || !binding.startsWith('data.')) return;
const path = binding.replace(/^data\./, '').replace(/\?/g, '').replace(/\[[^\]]+\]/g, '');
formFields.add(path);
console.log('Registered protected path:', path);
}
function registerFormProtectionFromDOM() {
document.querySelectorAll('[data-form-protect]').forEach(el => {
addProtectedPath(el.getAttribute('data-form-protect'));
});
document.querySelectorAll('input, select, textarea').forEach(el => {
// Skip buttons
if (el.type === 'button' || el.type === 'submit' || el.type === 'reset') return;
// Check for v-model or v-bind:value (before/after Vue processes them)
const binding = el.getAttribute('v-model') || el.getAttribute('v-bind:value') || el.getAttribute(':value');
addProtectedPath(binding);
});
}
function isPathProtected(path) {
if (formFields.has(path)) return true;
for (const protectedPath of formFields) {
if (path.startsWith(protectedPath + '.')) return true;
if (protectedPath.startsWith(path + '.')) return true;
}
return false;
}
// Global store for Petite Vue application
const AppData = {
data: {},
status: {},
addon: {},
// Agent component
Agent: () => ({
$template: AgentTemplate
}),
// Menu component
Menu: () => ({
$template: MenuTemplate
}),
// Footer component
Footer: () => ({
$template: FooterTemplate
}),
/**
* Convert temperature value based on unit from addon.xml settings
* @param {number|string} value - Temperature value (already in actual degrees, not tenths)
* @param {string} varUnits - Original unit from sensor ('C', etc.)
* @param {boolean} showUnits - Whether to include unit symbol
* @returns {string} Formatted temperature value
*/
createValue(value, varUnits, showUnits = false) {
const units = this.addon?.Global?.Units || 'Celsius';
const sysUnits = this.addon?.Global?.SysUnits || 'Celsius';
const val = parseFloat(value);
// console.log('=== createValue ===');
// console.log('Input value:', value);
// console.log('varUnits:', varUnits);
// console.log('showUnits:', showUnits);
// console.log('units (from addon):', units);
// console.log('sysUnits (from addon):', sysUnits);
// console.log('parsed val:', val);
// Check if conversion is needed
if (varUnits === 'C' && units !== 'Celsius' && val !== -999.9 && sysUnits === 'Celsius') {
// console.log('-> CONVERSION needed');
// Value is already in degrees Celsius, convert to other units
let result;
if (units === 'Kelvin') {
result = Math.round((val + 273.15) * 100) / 100;
// console.log('-> Kelvin result:', result);
} else if (units === 'Fahrenheit') {
result = Math.round((val * 1.8 + 32) * 100) / 100;
// console.log('-> Fahrenheit calculation:', val, '*', 1.8, '+', 32, '=', result);
} else {
result = Math.round(val * 100) / 100;
// console.log('-> Celsius result:', result);
}
if (showUnits) {
if (units === 'Kelvin') return result + ' K';
if (units === 'Fahrenheit') return result + ' °F';
return result + ' °C';
}
// console.log('-> Returning (no units):', result.toString());
return result.toString();
} else {
// console.log('-> NO conversion needed');
// No conversion needed, return as-is
const result = val;
if (showUnits) {
if (varUnits === 'C') {
if (units === 'Kelvin') return result + ' K';
if (units === 'Fahrenheit') return result + ' °F';
return result + ' °C';
}
return result + ' ' + varUnits;
}
// console.log('-> Returning (no units):', result.toString());
return result.toString();
}
},
/**
* Get unit symbol based on original unit and addon.xml settings
* @param {string} varUnits - Original unit from sensor ('C', etc.)
* @returns {string} Unit symbol
*/
getUnit(varUnits) {
const units = this.addon?.Global?.Units || 'Celsius';
if (varUnits === 'C') {
if (units === 'Kelvin') return 'K';
if (units === 'Fahrenheit') return '°F';
return '°C';
}
return varUnits;
},
/**
* Load XML file and convert to JSON
* @param {string} xmlPath - Path to XML file
* @param {string} assignTo - Property to assign the result to ('data', 'status', or null)
* @param {boolean} callSetup - Whether to call setup functions after loading
* @returns {Promise} Parsed JSON object or null on error
*/
async loadData(xmlPath, assignTo = 'data', callSetup = false) {
try {
const response = await fetch(xmlPath);
const xmlText = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
// Extract root element (set:Root)
const root = xmlDoc.getElementsByTagNameNS('http://www.etech.cz/XMLSchema/poseidon/values.xsd', 'Root')[0]
|| xmlDoc.documentElement;
// Convert XML to JSON
const json = this.xmlToJson(root);
if (assignTo) {
this[assignTo] = json;
}
if (callSetup) {
setTimeout(() => this.callSetupFunctions(), 500);
}
return json;
} catch (error) {
console.error('Error loading XML:', error);
return null;
}
},
/**
* Call setup functions after data is loaded
*/
callSetupFunctions() {
// Set document title from device name
if (this.data.Agent?.DeviceName) {
document.title = this.data.Agent.DeviceName;
}
// Set copyright year
const copyrightEl = document.getElementById("copyrightYear");
if (copyrightEl) {
copyrightEl.innerHTML = new Date().getFullYear();
}
},
/**
* Convert XML element to JSON object
* @param {Element} xml - XML element
* @returns {Object|string} JSON representation
*/
xmlToJson(xml) {
const obj = {};
// Attributes
if (xml.attributes) {
for (let attr of xml.attributes) {
obj['@' + attr.name] = attr.value;
}
}
// Text content (if no child elements)
if (xml.childNodes.length === 1 && xml.childNodes[0].nodeType === 3) {
const textValue = xml.childNodes[0].textContent.trim();
return textValue.length !== 0 ? textValue : null;
}
// Empty element - return empty string instead of empty object
if (xml.childNodes.length === 0) {
return '';
}
// Child elements
const children = {};
for (let node of xml.childNodes) {
if (node.nodeType === 1) { // Element node
const nodeName = node.localName || node.tagName;
if (!children[nodeName]) {
children[nodeName] = [];
}
children[nodeName].push(this.xmlToJson(node));
}
}
// Convert array to object or value if only one element
for (let key in children) {
if (children[key].length === 1) {
obj[key] = children[key][0];
} else {
obj[key] = children[key];
}
}
return obj;
}
};
/**
* Initialize Petite Vue application with XML data loading
* - Loads main XML data file and assigns to AppData.data
* - Loads addon.xml and assigns to AppData.addon (non-reactive)
* - Registers all form fields (input/select/textarea with v-model or :value) before mount
* - Creates reactive data and mounts Petite Vue app
* - Periodically updates data from XML, but skips form fields to prevent overwriting user input
* - Sets up document title and copyright year
*
* @param {string} [xmlPath] - Path to main XML file; if not provided, derived from HTML filename
* @param {number} [intervalMs=0] - Interval in milliseconds for periodic updates (0 = no periodic updates)
* @param {string} [mountSelector='#app'] - CSS selector to mount Petite Vue app
*/
function initPetiteVue(xmlPath, intervalMs = 0, mountSelector = '#app') {
document.addEventListener('DOMContentLoaded', async () => {
// Derive XML path from HTML file if not specified
if (!xmlPath) {
const currentPage = window.location.pathname.split('/').pop();
xmlPath = currentPage.replace(/\.html?$/i, '.xml');
}
// Load main data into AppData.data
await AppData.loadData(xmlPath, 'data', true);
// Load addon.xml into AppData.addon (non-reactive, once only)
AppData.addon = await AppData.loadData('addon.xml', null, false) || {};
// Make data reactive
AppData.data = PetiteVue.reactive({ ...AppData.data });
// Register all form fields BEFORE mount - scan raw HTML for v-model or :value
document.querySelectorAll('input, select, textarea').forEach(el => {
// Skip buttons
if (el.type === 'button' || el.type === 'submit' || el.type === 'reset') return;
// Check for v-model or v-bind:value (before Vue processes them)
const binding = el.getAttribute('v-model') || el.getAttribute('v-bind:value') || el.getAttribute(':value');
if (binding && binding.startsWith('data.')) {
// Extract path: "data.Network?.IPAddr" -> "Network.IPAddr"
const path = binding.replace(/^data\./, '').replace(/\?/g, '');
formFields.add(path);
console.log('Registered form field:', path);
}
});
// Create and mount Petite Vue app
const app = PetiteVue.createApp(AppData);
app.mount(mountSelector);
// Register again AFTER mount, templates/v-for are now real DOM.
registerFormProtectionFromDOM();
checkFeatures(xmlPath);
// Notify pages that Petite Vue app is mounted and initial data is ready.
window.dispatchEvent(new CustomEvent('PetiteVueInitialized'));
// Periodically refresh status.xml
// Only start periodic updates if interval > 0
if (intervalMs > 0) {
setInterval(async () => {
const newData = await AppData.loadData(xmlPath, null, false);
if (!newData || typeof newData !== 'object') return;
// Update data, but skip form fields
Object.keys(newData).forEach(section => {
if (typeof newData[section] === 'object' && newData[section] !== null && !Array.isArray(newData[section])) {
// It's an object with properties
Object.keys(newData[section]).forEach(key => {
const path = `${section}.${key}`;
// Only update if NOT a form field
if (!formFields.has(path) && !isPathProtected(path)) {
if (!AppData.data[section]) {
AppData.data[section] = {};
}
AppData.data[section][key] = newData[section][key];
}
// else {
// console.log('Skipping form field update:', path);
// }
});
} else {
// Top-level value or array - update if not a form field
if (!formFields.has(section) && !isPathProtected(section)) {
AppData.data[section] = newData[section];
}
}
});
}, intervalMs);
}
});
}
// Export for use in HTML
if (typeof module !== 'undefined' && module.exports) {
module.exports = { initPetiteVue, AppData };
}