Files
SE-UGW/src/Gateway.Api/wwwroot/mqtt-topic-browser.js
T
jhartworks 98c48d9d78 Add comprehensive smoke and feature tests for Gateway API
- Introduced LtdFeatureTests to validate BACnet and OPC UA point updates, trend logging, and alarm rule functionality.
- Added OpcUaClientTests to ensure proper OPC UA client configuration, point value synchronization, and session management.
- Created OpcUaFeatureTests to test OPC UA server capabilities, including browsing, reading, writing, and subscription notifications.
- Implemented native_bacnet_test.py for isolated BACnet wire testing, covering discovery, read/write operations, and command processing.
- Added ui-theme-tabs.test.cjs to verify theme switching, tab interactions, and protocol form accessibility in the UI.
2026-11-19 16:06:54 +01:00

274 lines
13 KiB
JavaScript

function viewMqttTopicBrowser() {
return `<article class="card mqtt-topic-browser" id="mqtt-topic-browser">
<div class="card-head"><h2>Topic-Browser</h2><span class="note" data-mqtt-browser-status></span></div>
<form class="form" data-broker-filter>
<div class="row">
<label>Filter am Broker<input name="filter" maxlength="1024" placeholder="z. B. Projekte2019/#" value="${escapeHtml(state.mqttBrowser?.filter || '#')}"></label>
<div class="buttons mqtt-browser-start"><button type="submit" class="btn primary">Topics beobachten</button></div>
</div>
</form>
<div data-mqtt-browser-message role="status"></div>
<div class="grid two mqtt-browser-content" hidden>
<div>
<label>Topic suchen<input type="search" data-topic-search placeholder="Teil des Topic-Pfads"></label>
${can('manage_sources') ? `<div class="buttons mqtt-browser-selection">
<button class="btn" type="button" data-topic-select-all>Alle Treffer auswählen</button>
<button class="btn" type="button" data-topic-clear>Auswahl leeren</button>
<button class="btn primary" type="button" data-topic-import>Auswahl übernehmen</button>
<span class="note" data-topic-selected></span>
</div>` : ''}
<div class="mqtt-topic-tree" data-topic-tree aria-label="Topic-Baum" role="region" tabindex="0"></div>
</div>
<section class="mqtt-topic-detail" data-topic-detail aria-label="Topic-Details"></section>
</div>
</article>`;
}
function mqttTopicNodes(topics) {
const root = new Map();
for (const topic of topics) {
let children = root;
const parts = topic.topic.split('/');
const levels = parts.length > 48 ? [...parts.slice(0, 47), parts.slice(47).join('/')] : parts;
for (let index = 0; index < levels.length; index++) {
const label = levels[index];
const path = levels.slice(0, index + 1).join('/');
if (!children.has(label)) children.set(label, { label, path, children: new Map(), selectable: [] });
const node = children.get(label);
if (topic.valueType && !topic.pointId) node.selectable.push(topic.topic);
if (index === levels.length - 1) node.topic = topic;
children = node.children;
}
}
return root;
}
function bindMqttTopicBrowser() {
const browser = document.querySelector('#mqtt-topic-browser');
if (!browser) return;
const model = state.mqttBrowser ??= {
filter: '#', snapshot: null, query: '', picked: new Set(), expanded: new Map(), focused: null, message: ''
};
const nodes = browser.querySelector('[data-topic-tree]');
const detail = browser.querySelector('[data-topic-detail]');
const form = browser.querySelector('[data-broker-filter]');
const search = browser.querySelector('[data-topic-search]');
const message = browser.querySelector('[data-mqtt-browser-message]');
const content = browser.querySelector('.mqtt-browser-content');
const status = browser.querySelector('[data-mqtt-browser-status]');
const importButton = browser.querySelector('[data-topic-import]');
const canImport = !!importButton;
let visibleTopics = [];
let visibleBranches = new Map();
let busy = false;
let timer;
let revision = 0;
search.value = model.query;
const token = value => escapeHtml(encodeURIComponent(value));
const importable = topic => topic.valueType && !topic.pointId;
const displayType = type => ({ Boolean: 'Binär', Double: 'Zahl', String: 'Text', Json: 'JSON' }[type] || '—');
function renderLeaf(topic, name) {
return `<div class="mqtt-tree-row mqtt-tree-leaf">
${canImport && importable(topic) ? `<input type="checkbox" data-topic-pick="${token(topic.topic)}" aria-label="${escapeHtml(topic.topic)} auswählen">` : ''}
<button type="button" class="btn mqtt-topic-item" data-topic-item="${token(topic.topic)}"
aria-pressed="${topic.topic === model.focused}">${escapeHtml(name || '(leere Ebene)')}</button>
<span class="note mqtt-topic-value" title="${escapeHtml(topic.preview)}">${escapeHtml(topic.preview)}</span>
${topic.pointId ? '<span class="tag gray">übernommen</span>' : ''}</div>`;
}
function renderBranch(branch) {
const opened = model.expanded.get(branch.path) ?? !!model.query;
visibleBranches.set(branch.path, branch.selectable);
return `<li><div class="mqtt-tree-row mqtt-tree-branch">
${canImport && branch.selectable.length ? `<input type="checkbox" data-topic-branch-pick="${token(branch.path)}" aria-label="Zweig ${escapeHtml(branch.path || '/')} auswählen">` : ''}
<button type="button" class="btn" data-topic-branch="${token(branch.path)}" aria-expanded="${opened}">
<span aria-hidden="true">${opened ? '▾' : '▸'}</span> ${escapeHtml(branch.label || '(leere Ebene)')}</button>
</div>${opened ? `<ul>${branch.topic ? `<li>${renderLeaf(branch.topic, branch.label)}</li>` : ''}
${renderNodes(branch.children)}</ul>` : ''}</li>`;
}
function renderNodes(branches) {
return [...branches.values()].map(branch => branch.children.size ? renderBranch(branch) :
`<li>${renderLeaf(branch.topic, branch.label)}</li>`).join('');
}
function renderDetail() {
const topic = model.snapshot?.topics.find(item => item.topic === model.focused);
detail.innerHTML = topic ? `<h3>Topic-Details</h3>
<code class="mqtt-topic-path">${escapeHtml(topic.topic)}</code>
<dl class="connection-facts">
<dt>Werttyp</dt><dd>${displayType(topic.valueType)}</dd>
<dt>Empfangen</dt><dd>${statusTime(topic.receivedAtUtc)}</dd>
<dt>Retained</dt><dd>${topic.retained ? 'Ja' : '—'}</dd>
</dl>
<pre class="mqtt-topic-preview">${escapeHtml(topic.preview)}</pre>
${topic.pointId ? '<p class="note">Als externer Datenpunkt angelegt.</p>' :
canImport && importable(topic) ? '<button type="button" class="btn primary" data-topic-import-one>Datenpunkt übernehmen</button>' :
!topic.valueType ? '<p class="note">Dieser Nachrichtenwert kann nicht als Datenpunkt übernommen werden.</p>' : ''}`
: '<p class="note">Ein Topic auswählen, um Wert und Details zu sehen.</p>';
}
function syncSelection() {
if (!canImport) return;
nodes.querySelectorAll('[data-topic-pick]').forEach(input => {
input.checked = model.picked.has(decodeURIComponent(input.dataset.topicPick));
});
nodes.querySelectorAll('[data-topic-branch-pick]').forEach(input => {
const topics = visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick));
const count = topics.filter(topic => model.picked.has(topic)).length;
input.checked = count === topics.length;
input.indeterminate = count > 0 && count < topics.length;
});
browser.querySelector('[data-topic-selected]').textContent = `${model.picked.size} ausgewählt`;
importButton.disabled = busy || !model.picked.size;
browser.querySelector('[data-topic-select-all]').disabled = !visibleTopics.some(importable);
browser.querySelector('[data-topic-clear]').disabled = !model.picked.size;
}
function render() {
const snapshot = model.snapshot;
const query = model.query.trim().toLowerCase();
visibleTopics = (snapshot?.topics || []).filter(topic => topic.topic.toLowerCase().includes(query));
content.hidden = !snapshot;
message.textContent = model.message;
status.textContent = snapshot ? `${snapshot.connected ? 'Verbunden' : 'Getrennt'} · ${visibleTopics.length} von ${snapshot.topics.length} Topics` : '';
if (!snapshot) return;
if (!model.message && snapshot.error) message.textContent = snapshot.error;
if (snapshot.limitReached && !message.textContent) message.textContent = '3.000 Topics erreicht. Mit einem Broker-Filter lässt sich der Bereich eingrenzen.';
const scroll = nodes.scrollTop;
const focused = nodes.contains(document.activeElement) ? document.activeElement : null;
const focusAttribute = ['data-topic-item', 'data-topic-branch', 'data-topic-pick', 'data-topic-branch-pick'].find(attribute => focused?.hasAttribute(attribute));
visibleBranches = new Map();
nodes.innerHTML = visibleTopics.length ? `<ul>${renderNodes(mqttTopicNodes(visibleTopics))}</ul>` :
`<div class="empty">${query ? 'Keine passenden Topics.' : 'Warte auf Retained- oder neue Nachrichten.'}</div>`;
if (focusAttribute) {
[...nodes.querySelectorAll(`[${focusAttribute}]`)].find(element =>
element.getAttribute(focusAttribute) === focused.getAttribute(focusAttribute))?.focus({ preventScroll: true });
}
nodes.scrollTop = scroll;
if (!detail.contains(document.activeElement)) renderDetail();
syncSelection();
}
function acceptSnapshot(snapshot) {
model.snapshot = snapshot;
const eligible = new Set(snapshot.topics.filter(importable).map(topic => topic.topic));
for (const topic of model.picked) if (!eligible.has(topic)) model.picked.delete(topic);
render();
}
async function refresh() {
clearTimeout(timer);
if (!browser.isConnected || !model.snapshot) return;
if (!busy && !browser.closest('[data-points-panel]')?.hidden) {
const currentRevision = revision;
try {
const snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
if (browser.isConnected && currentRevision === revision) acceptSnapshot(snapshot);
} catch (error) {
if (currentRevision !== revision || !browser.isConnected) return;
model.message = error.message;
render();
return;
}
}
if (browser.isConnected) timer = setTimeout(refresh, 3000);
}
form.addEventListener('submit', async event => {
event.preventDefault();
if (busy) return;
const button = form.querySelector('button');
button.disabled = busy = true;
const currentRevision = ++revision;
clearTimeout(timer);
model.message = 'Broker-Verbindung wird geöffnet …';
render();
try {
const filter = form.elements.filter.value || '#';
const snapshot = await api('/api/mqtt/browser', { method:'POST', body:JSON.stringify({ filter }) });
if (!browser.isConnected || currentRevision !== revision) return;
if (model.snapshot?.sessionId !== snapshot.sessionId) {
model.focused = null;
model.picked.clear();
model.expanded.clear();
}
model.filter = snapshot.filter;
model.message = '';
acceptSnapshot(snapshot);
} catch (error) {
model.snapshot = null;
model.message = error.message;
render();
} finally {
button.disabled = busy = false;
syncSelection();
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
}
});
search.addEventListener('input', () => { model.query = search.value; model.expanded.clear(); render(); });
nodes.addEventListener('click', event => {
const branch = event.target.closest('[data-topic-branch]');
const item = event.target.closest('[data-topic-item]');
if (branch) {
model.expanded.set(decodeURIComponent(branch.dataset.topicBranch), branch.getAttribute('aria-expanded') !== 'true');
render();
} else if (item) {
model.focused = decodeURIComponent(item.dataset.topicItem);
nodes.querySelectorAll('[data-topic-item]').forEach(button => button.setAttribute('aria-pressed', String(button === item)));
renderDetail();
}
});
nodes.addEventListener('change', event => {
const input = event.target;
const selected = input.dataset.topicPick != null ? [decodeURIComponent(input.dataset.topicPick)] :
input.dataset.topicBranchPick != null ? visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick)) : [];
for (const topic of selected) input.checked ? model.picked.add(topic) : model.picked.delete(topic);
syncSelection();
});
async function importTopics(topics) {
if (!topics.length || busy || !model.snapshot) return;
busy = true;
++revision;
detail.querySelector('[data-topic-import-one]')?.setAttribute('disabled', '');
syncSelection();
try {
const result = await api('/api/mqtt/browser/import', {
method:'POST', body:JSON.stringify({ sessionId: model.snapshot.sessionId, topics })
});
model.message = `${result.created} angelegt · ${result.existing} bereits vorhanden · ${result.unavailable} ohne importierbaren Wert`;
await loadData();
model.snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
if (browser.isConnected) renderView();
} catch (error) {
model.message = error.message;
render();
} finally {
busy = false;
detail.querySelector('[data-topic-import-one]')?.removeAttribute('disabled');
syncSelection();
clearTimeout(timer);
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
}
}
if (canImport) {
browser.querySelector('[data-topic-select-all]').addEventListener('click', () => {
visibleTopics.filter(importable).forEach(topic => model.picked.add(topic.topic));
syncSelection();
});
browser.querySelector('[data-topic-clear]').addEventListener('click', () => { model.picked.clear(); syncSelection(); });
importButton.addEventListener('click', () => importTopics([...model.picked]));
detail.addEventListener('click', event => {
if (event.target.closest('[data-topic-import-one]')) importTopics([model.focused]);
});
}
if (model.snapshot) {
acceptSnapshot(model.snapshot);
timer = setTimeout(refresh, 3000);
} else render();
}