tagscope 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tagscope/__init__.py +5 -0
- tagscope/__main__.py +3 -0
- tagscope/cli.py +215 -0
- tagscope/collector.py +154 -0
- tagscope/config.py +159 -0
- tagscope/hub.py +148 -0
- tagscope/simulator.py +175 -0
- tagscope/static/app.css +219 -0
- tagscope/static/app.js +469 -0
- tagscope/static/index.html +87 -0
- tagscope/static/vendor/uPlot.LICENSE +21 -0
- tagscope/static/vendor/uPlot.iife.min.js +2 -0
- tagscope/static/vendor/uPlot.min.css +1 -0
- tagscope/storage.py +262 -0
- tagscope/web.py +111 -0
- tagscope-0.1.0.dist-info/METADATA +207 -0
- tagscope-0.1.0.dist-info/RECORD +20 -0
- tagscope-0.1.0.dist-info/WHEEL +4 -0
- tagscope-0.1.0.dist-info/entry_points.txt +2 -0
- tagscope-0.1.0.dist-info/licenses/LICENSE +21 -0
tagscope/static/app.js
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
/* TagScope dashboard. Plain JS, no build step. */
|
|
2
|
+
(() => {
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
const PALETTE = ["#38d9b0", "#6aa8ff", "#f5b13d", "#c792ea", "#ff7a90", "#7fdbff", "#b5e48c", "#ffb86b"];
|
|
6
|
+
const SPARK_SECONDS = 300;
|
|
7
|
+
const MAX_CARDS = 12;
|
|
8
|
+
const $ = (sel, el = document) => el.querySelector(sel);
|
|
9
|
+
const store = {
|
|
10
|
+
get(k, d) { try { const v = localStorage.getItem("tagscope." + k); return v === null ? d : JSON.parse(v); } catch { return d; } },
|
|
11
|
+
set(k, v) { try { localStorage.setItem("tagscope." + k, JSON.stringify(v)); } catch { /* private mode */ } },
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const S = {
|
|
15
|
+
tags: new Map(), // name -> meta
|
|
16
|
+
values: {}, // name -> {value, ts, quality, state}
|
|
17
|
+
servers: [],
|
|
18
|
+
selected: [], // ordered tag names on the trend
|
|
19
|
+
colors: new Map(), // name -> colour
|
|
20
|
+
minutes: store.get("minutes", 15),
|
|
21
|
+
live: true,
|
|
22
|
+
sparks: new Map(), // name -> {t: [], v: []}
|
|
23
|
+
events: [],
|
|
24
|
+
eventFilter: "",
|
|
25
|
+
samples: { n: 0, at: 0, rate: 0 },
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------- utils
|
|
29
|
+
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
30
|
+
const isBool = (name) => { const v = S.values[name]; return S.tags.get(name)?.unit === "" && v && (v.value === 0 || v.value === 1) && /running|on|open|alarm|fault|enabled|active/i.test(name); };
|
|
31
|
+
function fmt(v, unit = "") {
|
|
32
|
+
if (v === null || v === undefined || Number.isNaN(v)) return "–";
|
|
33
|
+
const a = Math.abs(v);
|
|
34
|
+
const d = a >= 1000 ? 0 : a >= 100 ? 1 : a >= 10 ? 2 : 2;
|
|
35
|
+
return v.toLocaleString(undefined, { minimumFractionDigits: unit === "pcs" ? 0 : Math.min(d, 1), maximumFractionDigits: unit === "pcs" ? 0 : d });
|
|
36
|
+
}
|
|
37
|
+
const hhmmss = (ts) => new Date(ts * 1000).toLocaleTimeString([], { hour12: false });
|
|
38
|
+
function toast(msg) { const t = $("#toast"); t.textContent = msg; t.classList.add("show"); clearTimeout(toast.h); toast.h = setTimeout(() => t.classList.remove("show"), 1800); }
|
|
39
|
+
const groupOf = (name) => (name.includes(".") ? name.split(".")[0] : name.includes("/") ? name.split("/")[0] : "");
|
|
40
|
+
const css = (v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim();
|
|
41
|
+
async function api(path) { const r = await fetch(path); if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || r.statusText); return r.json(); }
|
|
42
|
+
|
|
43
|
+
// ---------------------------------------------------------------- theme
|
|
44
|
+
function applyTheme(t) { document.documentElement.dataset.theme = t; store.set("theme", t); if (chart) rebuildChart(); drawAllSparks(); }
|
|
45
|
+
const prefersLight = window.matchMedia && matchMedia("(prefers-color-scheme: light)").matches;
|
|
46
|
+
document.documentElement.dataset.theme = store.get("theme", prefersLight ? "light" : "dark");
|
|
47
|
+
$("#theme").onclick = () => applyTheme(document.documentElement.dataset.theme === "light" ? "dark" : "light");
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------- servers + stats
|
|
50
|
+
function renderServers() {
|
|
51
|
+
$("#servers").innerHTML = S.servers.map((s) =>
|
|
52
|
+
`<span class="server" title="${esc(s.endpoint)}${s.error ? "\n" + esc(s.error) : ""}"><i class="dot ${esc(s.status)}"></i><b>${esc(s.name)}</b>${esc(s.status)}</span>`).join("");
|
|
53
|
+
}
|
|
54
|
+
setInterval(() => { $("#clock").textContent = new Date().toLocaleTimeString([], { hour12: false }); }, 1000);
|
|
55
|
+
async function pollStats() {
|
|
56
|
+
try {
|
|
57
|
+
const o = await api("/api/overview");
|
|
58
|
+
const n = o.stats.samples_written, now = performance.now();
|
|
59
|
+
if (S.samples.at) S.samples.rate = ((n - S.samples.n) / ((now - S.samples.at) / 1000));
|
|
60
|
+
S.samples = { n, at: now, rate: S.samples.rate };
|
|
61
|
+
$("#stat-samples").textContent = n.toLocaleString();
|
|
62
|
+
$("#stat-rate").textContent = Math.max(0, S.samples.rate).toFixed(1);
|
|
63
|
+
} catch { /* offline */ }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---------------------------------------------------------------- tag list
|
|
67
|
+
function colorFor(name) {
|
|
68
|
+
if (!S.colors.has(name)) {
|
|
69
|
+
const used = new Set(S.colors.values());
|
|
70
|
+
S.colors.set(name, PALETTE.find((c) => !used.has(c)) || PALETTE[S.colors.size % PALETTE.length]);
|
|
71
|
+
}
|
|
72
|
+
return S.colors.get(name);
|
|
73
|
+
}
|
|
74
|
+
function renderTagList() {
|
|
75
|
+
const q = $("#search").value.trim().toLowerCase();
|
|
76
|
+
let html = "", lastGroup = null;
|
|
77
|
+
for (const t of S.tags.values()) {
|
|
78
|
+
if (q && !(t.name.toLowerCase().includes(q) || t.description.toLowerCase().includes(q) || t.node.toLowerCase().includes(q))) continue;
|
|
79
|
+
const g = groupOf(t.name);
|
|
80
|
+
if (g !== lastGroup) { html += g ? `<div class="group">${esc(g)}</div>` : ""; lastGroup = g; }
|
|
81
|
+
const sel = S.selected.includes(t.name);
|
|
82
|
+
html += `<button class="tag" role="listitem" data-tag="${esc(t.name)}" title="${esc(t.description || t.node)}">
|
|
83
|
+
<span class="swatch" style="${sel ? `background:${colorFor(t.name)}` : ""}"></span>
|
|
84
|
+
<span class="tag-name">${esc(g ? t.name.slice(g.length + 1) : t.name)}</span>
|
|
85
|
+
<span class="tag-value"></span></button>`;
|
|
86
|
+
}
|
|
87
|
+
$("#taglist").innerHTML = html || `<p class="hint">No tags match “${esc(q)}”.</p>`;
|
|
88
|
+
for (const name of S.tags.keys()) paintTag(name);
|
|
89
|
+
}
|
|
90
|
+
function paintTag(name, flash) {
|
|
91
|
+
const el = $(`.tag[data-tag="${CSS.escape(name)}"]`);
|
|
92
|
+
if (!el) return;
|
|
93
|
+
const v = S.values[name], meta = S.tags.get(name);
|
|
94
|
+
el.classList.toggle("selected", S.selected.includes(name));
|
|
95
|
+
el.classList.remove("high", "low", "bad");
|
|
96
|
+
if (v) {
|
|
97
|
+
if (v.state === "high" || v.state === "low") el.classList.add(v.state);
|
|
98
|
+
if (v.quality === 2) el.classList.add("bad");
|
|
99
|
+
}
|
|
100
|
+
const ve = el.lastElementChild;
|
|
101
|
+
ve.textContent = !v ? "–" : isBool(name) ? (v.value ? "ON" : "OFF") : `${fmt(v.value, meta.unit)} ${meta.unit}`.trim();
|
|
102
|
+
if (flash) { ve.classList.add("flash"); clearTimeout(ve._t); ve._t = setTimeout(() => ve.classList.remove("flash"), 350); }
|
|
103
|
+
}
|
|
104
|
+
$("#taglist").addEventListener("click", (e) => {
|
|
105
|
+
const b = e.target.closest(".tag"); if (!b) return;
|
|
106
|
+
toggleSelected(b.dataset.tag);
|
|
107
|
+
});
|
|
108
|
+
$("#search").addEventListener("input", renderTagList);
|
|
109
|
+
document.addEventListener("keydown", (e) => {
|
|
110
|
+
if (e.key === "/" && document.activeElement !== $("#search")) { e.preventDefault(); $("#search").focus(); }
|
|
111
|
+
if (e.key === "Escape" && document.activeElement === $("#search")) { $("#search").value = ""; renderTagList(); $("#search").blur(); }
|
|
112
|
+
});
|
|
113
|
+
function toggleSelected(name) {
|
|
114
|
+
const i = S.selected.indexOf(name);
|
|
115
|
+
if (i >= 0) { S.selected.splice(i, 1); S.colors.delete(name); }
|
|
116
|
+
else { if (S.selected.length >= 8) { toast("Up to 8 tags on one trend"); return; } S.selected.push(name); colorFor(name); }
|
|
117
|
+
store.set("selected", S.selected);
|
|
118
|
+
renderTagList();
|
|
119
|
+
loadTrend();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------- cards
|
|
123
|
+
function cardTags() {
|
|
124
|
+
const all = [...S.tags.values()];
|
|
125
|
+
const withLimits = all.filter((t) => t.low !== null || t.high !== null);
|
|
126
|
+
const rest = all.filter((t) => !withLimits.includes(t));
|
|
127
|
+
return [...withLimits, ...rest].slice(0, MAX_CARDS).map((t) => t.name);
|
|
128
|
+
}
|
|
129
|
+
function renderCards() {
|
|
130
|
+
$("#cards").innerHTML = cardTags().map((name) => {
|
|
131
|
+
const t = S.tags.get(name);
|
|
132
|
+
return `<article class="card" data-tag="${esc(name)}" title="${esc(t.description || t.node)}">
|
|
133
|
+
<div class="card-top"><span class="card-name">${esc(name)}</span><span class="state hidden"></span></div>
|
|
134
|
+
<div class="card-value">–</div>
|
|
135
|
+
<canvas class="spark"></canvas>
|
|
136
|
+
${t.low !== null || t.high !== null ? `<div class="limits"><div class="band"></div><div class="pos"></div></div>` : ""}
|
|
137
|
+
</article>`;
|
|
138
|
+
}).join("");
|
|
139
|
+
for (const name of cardTags()) paintCard(name);
|
|
140
|
+
}
|
|
141
|
+
$("#cards").addEventListener("click", (e) => { const c = e.target.closest(".card"); if (c) toggleSelected(c.dataset.tag); });
|
|
142
|
+
|
|
143
|
+
function paintCard(name) {
|
|
144
|
+
const el = $(`.card[data-tag="${CSS.escape(name)}"]`);
|
|
145
|
+
if (!el) return;
|
|
146
|
+
const t = S.tags.get(name), v = S.values[name];
|
|
147
|
+
el.classList.remove("high", "low", "bad");
|
|
148
|
+
const st = $(".state", el);
|
|
149
|
+
st.className = "state hidden";
|
|
150
|
+
if (!v) return;
|
|
151
|
+
if (v.state === "high" || v.state === "low") { el.classList.add(v.state); st.className = `state ${v.state}`; st.textContent = v.state; }
|
|
152
|
+
if (v.quality === 2) el.classList.add("bad");
|
|
153
|
+
const valueEl = $(".card-value", el);
|
|
154
|
+
if (isBool(name)) {
|
|
155
|
+
valueEl.innerHTML = v.value ? "Running" : "Stopped";
|
|
156
|
+
st.className = `state ${v.value ? "on" : "off"}`; st.textContent = v.value ? "on" : "off";
|
|
157
|
+
} else {
|
|
158
|
+
valueEl.innerHTML = `${fmt(v.value, t.unit)}<small>${esc(t.unit)}</small>`;
|
|
159
|
+
}
|
|
160
|
+
const lim = $(".limits", el);
|
|
161
|
+
if (lim && v.value !== null) {
|
|
162
|
+
const sp = S.sparks.get(name);
|
|
163
|
+
const lo = t.low ?? Math.min(...(sp?.v.length ? sp.v : [0]));
|
|
164
|
+
const hi = t.high ?? Math.max(...(sp?.v.length ? sp.v : [1]));
|
|
165
|
+
const pad = (hi - lo) * 0.25 || 1;
|
|
166
|
+
const min = lo - pad, max = hi + pad, pct = (x) => Math.min(100, Math.max(0, ((x - min) / (max - min)) * 100));
|
|
167
|
+
const band = $(".band", lim);
|
|
168
|
+
band.style.left = `${t.low !== null ? pct(t.low) : 0}%`;
|
|
169
|
+
band.style.right = `${100 - (t.high !== null ? pct(t.high) : 100)}%`;
|
|
170
|
+
$(".pos", lim).style.left = `calc(${pct(v.value)}% - 1px)`;
|
|
171
|
+
}
|
|
172
|
+
drawSpark(name);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function pushSpark(name, ts, value) {
|
|
176
|
+
if (value === null || value === undefined) return;
|
|
177
|
+
let sp = S.sparks.get(name);
|
|
178
|
+
if (!sp) S.sparks.set(name, (sp = { t: [], v: [] }));
|
|
179
|
+
sp.t.push(ts); sp.v.push(value);
|
|
180
|
+
const cutoff = ts - SPARK_SECONDS;
|
|
181
|
+
while (sp.t.length && sp.t[0] < cutoff) { sp.t.shift(); sp.v.shift(); }
|
|
182
|
+
}
|
|
183
|
+
function drawSpark(name) {
|
|
184
|
+
const el = $(`.card[data-tag="${CSS.escape(name)}"] canvas`);
|
|
185
|
+
const sp = S.sparks.get(name);
|
|
186
|
+
if (!el || !sp || sp.v.length < 2) return;
|
|
187
|
+
const dpr = window.devicePixelRatio || 1, w = el.clientWidth, h = el.clientHeight;
|
|
188
|
+
if (el.width !== w * dpr) { el.width = w * dpr; el.height = h * dpr; }
|
|
189
|
+
const ctx = el.getContext("2d");
|
|
190
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
191
|
+
ctx.clearRect(0, 0, w, h);
|
|
192
|
+
const now = Date.now() / 1000, t0 = now - SPARK_SECONDS;
|
|
193
|
+
let lo = Math.min(...sp.v), hi = Math.max(...sp.v);
|
|
194
|
+
if (hi - lo < 1e-9) { lo -= 1; hi += 1; }
|
|
195
|
+
const x = (t) => ((t - t0) / SPARK_SECONDS) * w, y = (v) => h - 3 - ((v - lo) / (hi - lo)) * (h - 6);
|
|
196
|
+
const v = S.values[name], warn = v && (v.state === "high" || v.state === "low");
|
|
197
|
+
const color = warn ? css("--warn") : css("--accent");
|
|
198
|
+
const bool = isBool(name);
|
|
199
|
+
ctx.beginPath();
|
|
200
|
+
sp.t.forEach((t, i) => {
|
|
201
|
+
if (i === 0) ctx.moveTo(x(t), y(sp.v[i]));
|
|
202
|
+
else if (bool) { ctx.lineTo(x(t), y(sp.v[i - 1])); ctx.lineTo(x(t), y(sp.v[i])); }
|
|
203
|
+
else ctx.lineTo(x(t), y(sp.v[i]));
|
|
204
|
+
});
|
|
205
|
+
ctx.lineTo(w, y(sp.v[sp.v.length - 1]));
|
|
206
|
+
ctx.strokeStyle = color; ctx.lineWidth = 1.6; ctx.lineJoin = "round"; ctx.stroke();
|
|
207
|
+
ctx.lineTo(w, h); ctx.lineTo(x(sp.t[0]), h); ctx.closePath();
|
|
208
|
+
const g = ctx.createLinearGradient(0, 0, 0, h);
|
|
209
|
+
g.addColorStop(0, color + "40"); g.addColorStop(1, color + "00");
|
|
210
|
+
ctx.fillStyle = g; ctx.fill();
|
|
211
|
+
}
|
|
212
|
+
function drawAllSparks() { for (const n of S.sparks.keys()) drawSpark(n); }
|
|
213
|
+
|
|
214
|
+
// ---------------------------------------------------------------- trend chart
|
|
215
|
+
let chart = null, chartData = null, zoomed = false;
|
|
216
|
+
function axisFor(scale, side, color) {
|
|
217
|
+
return {
|
|
218
|
+
scale, side, stroke: css("--muted"), size: 58,
|
|
219
|
+
grid: { show: side === 3, stroke: css("--line"), width: 1 },
|
|
220
|
+
ticks: { show: false },
|
|
221
|
+
values: (u, vals) => vals.map((v) => (v === null ? "" : Math.abs(v) >= 1000 ? v.toLocaleString() : String(+v.toFixed(2)))),
|
|
222
|
+
labelGap: 0, font: `11px ${css("--mono")}`, ...(color ? { stroke: color } : {}),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function buildOpts(names) {
|
|
226
|
+
const scales = { x: { time: true } }, units = [], series = [{}];
|
|
227
|
+
names.forEach((name) => {
|
|
228
|
+
const t = S.tags.get(name);
|
|
229
|
+
const key = isBool(name) ? "__bool" : (t.unit || name);
|
|
230
|
+
if (!units.includes(key)) units.push(key);
|
|
231
|
+
if (key === "__bool") scales[key] = { range: [-0.1, 1.15] };
|
|
232
|
+
else scales[key] = scales[key] || { auto: true };
|
|
233
|
+
series.push({
|
|
234
|
+
label: name, scale: key, stroke: colorFor(name), width: 1.8, spanGaps: true, points: { show: false },
|
|
235
|
+
paths: key === "__bool" ? uPlot.paths.stepped({ align: 1 }) : undefined,
|
|
236
|
+
value: (u, v) => (v === null || v === undefined ? "–" : `${fmt(v, t.unit)} ${t.unit}`.trim()),
|
|
237
|
+
fill: names.length === 1 ? colorFor(name) + "18" : undefined,
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
const axes = [{
|
|
241
|
+
stroke: css("--muted"), grid: { show: true, stroke: css("--line"), width: 1 }, ticks: { show: false }, font: `11px ${css("--sans")}`,
|
|
242
|
+
values: (u, vals) => vals.map((v) => {
|
|
243
|
+
const d = new Date(v * 1000);
|
|
244
|
+
const hm = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", ...(S.minutes <= 10 ? { second: "2-digit" } : {}), hour12: false });
|
|
245
|
+
return S.minutes > 720 && d.getHours() === 0 && d.getMinutes() === 0 ? d.toLocaleDateString([], { day: "numeric", month: "short" }) : hm;
|
|
246
|
+
}),
|
|
247
|
+
}];
|
|
248
|
+
units.slice(0, 2).forEach((u, i) => {
|
|
249
|
+
const firstName = names.find((n) => (isBool(n) ? "__bool" : (S.tags.get(n).unit || n)) === u);
|
|
250
|
+
axes.push(axisFor(u, i === 0 ? 3 : 1, units.length > 1 ? colorFor(firstName) : null));
|
|
251
|
+
});
|
|
252
|
+
const el = $("#chart");
|
|
253
|
+
return {
|
|
254
|
+
width: el.clientWidth, height: el.clientHeight, scales, series, axes,
|
|
255
|
+
legend: { show: false },
|
|
256
|
+
cursor: { drag: { x: true, y: false }, points: { size: 7 } },
|
|
257
|
+
hooks: {
|
|
258
|
+
setCursor: [(u) => updateLegend(u, u.cursor.idx)],
|
|
259
|
+
setSelect: [() => { zoomed = true; setLive(false); }],
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
function updateLegend(u, idx) {
|
|
264
|
+
$("#legend").innerHTML = S.selected.map((name, i) => {
|
|
265
|
+
let v = null;
|
|
266
|
+
if (u && idx !== null && idx !== undefined) {
|
|
267
|
+
const col = u.data[i + 1];
|
|
268
|
+
for (let j = idx; j >= 0; j--) if (col[j] !== null && col[j] !== undefined) { v = col[j]; break; }
|
|
269
|
+
} else v = S.values[name]?.value ?? null;
|
|
270
|
+
const unit = S.tags.get(name).unit;
|
|
271
|
+
const shown = isBool(name) && v !== null ? (v ? "ON" : "OFF") : `${fmt(v, unit)} ${unit}`.trim();
|
|
272
|
+
return `<span><i style="background:${colorFor(name)}"></i>${esc(name)} <b>${shown}</b></span>`;
|
|
273
|
+
}).join("");
|
|
274
|
+
}
|
|
275
|
+
function rebuildChart() {
|
|
276
|
+
if (chart) { chart.destroy(); chart = null; }
|
|
277
|
+
const el = $("#chart");
|
|
278
|
+
el.innerHTML = "";
|
|
279
|
+
if (!S.selected.length) { el.innerHTML = `<div class="empty">Select a tag on the left to plot it</div>`; $("#legend").innerHTML = ""; return; }
|
|
280
|
+
if (!chartData) return;
|
|
281
|
+
chart = new uPlot(buildOpts(S.selected), chartData, el);
|
|
282
|
+
updateLegend(null, null);
|
|
283
|
+
}
|
|
284
|
+
let trendReq = 0;
|
|
285
|
+
async function loadTrend() {
|
|
286
|
+
const req = ++trendReq;
|
|
287
|
+
$("#trend-sub").textContent = S.selected.length ? `· ${S.selected.length} tag${S.selected.length > 1 ? "s" : ""} · last ${label(S.minutes)}` : "";
|
|
288
|
+
if (!S.selected.length) { chartData = null; rebuildChart(); return; }
|
|
289
|
+
const end = Date.now() / 1000;
|
|
290
|
+
const results = await Promise.all(S.selected.map((name) =>
|
|
291
|
+
api(`/api/history?tag=${encodeURIComponent(name)}&minutes=${S.minutes}&end=${end}&points=800`).catch(() => ({ t: [], avg: [] }))));
|
|
292
|
+
if (req !== trendReq) return;
|
|
293
|
+
const tables = results.map((r) => [r.t, r.avg]);
|
|
294
|
+
chartData = tables.length === 1 ? tables[0] : uPlot.join(tables);
|
|
295
|
+
zoomed = false;
|
|
296
|
+
rebuildChart();
|
|
297
|
+
}
|
|
298
|
+
const label = (m) => (m >= 60 ? `${m / 60} h` : `${m} min`);
|
|
299
|
+
|
|
300
|
+
let redrawQueued = false;
|
|
301
|
+
function appendLive(name, ts, value) {
|
|
302
|
+
if (!S.live || !chartData || zoomed) return;
|
|
303
|
+
const i = S.selected.indexOf(name);
|
|
304
|
+
if (i < 0) return;
|
|
305
|
+
const row = new Array(S.selected.length + 1).fill(null);
|
|
306
|
+
row[0] = ts; row[i + 1] = value;
|
|
307
|
+
const x = chartData[0];
|
|
308
|
+
if (x.length && ts < x[x.length - 1]) return; // ignore late arrivals
|
|
309
|
+
chartData.forEach((col, k) => col.push(row[k]));
|
|
310
|
+
const cutoff = Date.now() / 1000 - S.minutes * 60;
|
|
311
|
+
let drop = 0;
|
|
312
|
+
while (drop < x.length && x[drop] < cutoff) drop++;
|
|
313
|
+
if (drop) chartData.forEach((col) => col.splice(0, drop));
|
|
314
|
+
if (!redrawQueued) {
|
|
315
|
+
redrawQueued = true;
|
|
316
|
+
setTimeout(() => {
|
|
317
|
+
redrawQueued = false;
|
|
318
|
+
if (chart && !zoomed) { chart.setData(chartData); updateLegend(null, null); }
|
|
319
|
+
}, 250);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function setLive(on) {
|
|
323
|
+
S.live = on;
|
|
324
|
+
$("#live").classList.toggle("on", on);
|
|
325
|
+
if (on && zoomed) loadTrend();
|
|
326
|
+
}
|
|
327
|
+
$("#live").onclick = () => setLive(!S.live);
|
|
328
|
+
$("#ranges").addEventListener("click", (e) => {
|
|
329
|
+
const b = e.target.closest("button"); if (!b) return;
|
|
330
|
+
for (const x of $("#ranges").children) x.classList.toggle("on", x === b);
|
|
331
|
+
S.minutes = Number(b.dataset.min); store.set("minutes", S.minutes);
|
|
332
|
+
setLive(true); loadTrend();
|
|
333
|
+
});
|
|
334
|
+
$("#chart").addEventListener("dblclick", () => { if (zoomed) { setLive(true); loadTrend(); } });
|
|
335
|
+
$("#export").onclick = () => {
|
|
336
|
+
const tags = S.selected.length ? S.selected : [...S.tags.keys()];
|
|
337
|
+
location.href = `/api/export.csv?tags=${encodeURIComponent(tags.join(","))}&minutes=${S.minutes}`;
|
|
338
|
+
toast(`Exporting ${tags.length} tag${tags.length > 1 ? "s" : ""} · last ${label(S.minutes)}`);
|
|
339
|
+
};
|
|
340
|
+
new ResizeObserver(() => { if (chart) chart.setSize({ width: $("#chart").clientWidth, height: $("#chart").clientHeight }); drawAllSparks(); }).observe($("#chart"));
|
|
341
|
+
|
|
342
|
+
// ---------------------------------------------------------------- events
|
|
343
|
+
const SYSTEM = new Set(["info", "warning", "error"]);
|
|
344
|
+
function renderEvents() {
|
|
345
|
+
const list = S.events.filter((e) => !S.eventFilter || (S.eventFilter === "alarm" ? !SYSTEM.has(e.kind) : SYSTEM.has(e.kind))).slice(0, 150);
|
|
346
|
+
$("#events").innerHTML = list.length
|
|
347
|
+
? list.map((e) => `<li class="${e._new ? "new" : ""}"><time>${hhmmss(e.ts)}</time><span class="kind ${esc(e.kind)}">${esc(e.kind)}</span><span>${esc(e.message)}</span></li>`).join("")
|
|
348
|
+
: `<li class="empty">No events yet. Alarms appear here when a value crosses its limits.</li>`;
|
|
349
|
+
S.events.forEach((e) => delete e._new);
|
|
350
|
+
const active = Object.values(S.values).filter((v) => v.state === "high" || v.state === "low").length;
|
|
351
|
+
const badge = $("#alarm-count");
|
|
352
|
+
badge.textContent = active; badge.classList.toggle("hidden", !active);
|
|
353
|
+
badge.title = `${active} tag(s) outside limits`;
|
|
354
|
+
}
|
|
355
|
+
$("#event-filter").addEventListener("click", (e) => {
|
|
356
|
+
const b = e.target.closest("button"); if (!b) return;
|
|
357
|
+
for (const x of $("#event-filter").children) x.classList.toggle("on", x === b);
|
|
358
|
+
S.eventFilter = b.dataset.kind; renderEvents();
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
// ---------------------------------------------------------------- live feed
|
|
362
|
+
let ws, retry = 500;
|
|
363
|
+
function connect() {
|
|
364
|
+
ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`);
|
|
365
|
+
ws.onopen = () => { retry = 500; };
|
|
366
|
+
ws.onmessage = (m) => {
|
|
367
|
+
const msg = JSON.parse(m.data);
|
|
368
|
+
if (msg.type === "snapshot") {
|
|
369
|
+
S.values = msg.values; S.servers = msg.servers; renderServers();
|
|
370
|
+
for (const n of S.tags.keys()) { paintTag(n); paintCard(n); }
|
|
371
|
+
renderEvents();
|
|
372
|
+
} else if (msg.type === "batch") msg.messages.forEach(handle);
|
|
373
|
+
};
|
|
374
|
+
ws.onclose = () => {
|
|
375
|
+
S.servers = S.servers.map((s) => ({ ...s, status: "disconnected", error: "dashboard lost connection to TagScope" }));
|
|
376
|
+
renderServers();
|
|
377
|
+
setTimeout(connect, (retry = Math.min(retry * 2, 10000)));
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
let alarmsDirty = false;
|
|
381
|
+
function handle(msg) {
|
|
382
|
+
if (msg.type === "value") {
|
|
383
|
+
const { tag, type, ...v } = msg;
|
|
384
|
+
const prev = S.values[tag];
|
|
385
|
+
S.values[tag] = v;
|
|
386
|
+
if (prev && prev.state !== v.state) alarmsDirty = true;
|
|
387
|
+
pushSpark(tag, v.ts, v.value);
|
|
388
|
+
paintTag(tag, true); paintCard(tag);
|
|
389
|
+
appendLive(tag, v.ts, v.value);
|
|
390
|
+
} else if (msg.type === "server") {
|
|
391
|
+
const i = S.servers.findIndex((s) => s.name === msg.server.name);
|
|
392
|
+
if (i >= 0) S.servers[i] = msg.server; else S.servers.push(msg.server);
|
|
393
|
+
renderServers();
|
|
394
|
+
} else if (msg.type === "event") {
|
|
395
|
+
S.events.unshift({ ...msg.event, _new: true });
|
|
396
|
+
S.events.length = Math.min(S.events.length, 500);
|
|
397
|
+
alarmsDirty = true;
|
|
398
|
+
}
|
|
399
|
+
if (alarmsDirty) { alarmsDirty = false; renderEvents(); }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ---------------------------------------------------------------- address space browser
|
|
403
|
+
const dlg = $("#browser");
|
|
404
|
+
$("#open-browser").onclick = async () => {
|
|
405
|
+
const server = S.servers[0]?.name;
|
|
406
|
+
if (!server) return toast("No servers configured");
|
|
407
|
+
$("#browser-server").textContent = `· ${server}`;
|
|
408
|
+
dlg.dataset.server = server;
|
|
409
|
+
$("#tree").innerHTML = `<li class="hint">Loading…</li>`;
|
|
410
|
+
dlg.showModal();
|
|
411
|
+
try { $("#tree").innerHTML = renderNodes(await api(`/api/browse?server=${encodeURIComponent(server)}`)); }
|
|
412
|
+
catch (e) { $("#tree").innerHTML = `<li class="hint">${esc(e.message)}</li>`; }
|
|
413
|
+
};
|
|
414
|
+
$("#close-browser").onclick = () => dlg.close();
|
|
415
|
+
dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); });
|
|
416
|
+
function renderNodes(items) {
|
|
417
|
+
if (!items.length) return `<li class="hint">Empty</li>`;
|
|
418
|
+
return items.map((n) => {
|
|
419
|
+
const folder = n.class === "Object";
|
|
420
|
+
const val = n.value !== null && n.value !== undefined ? `<span class="val">${esc(typeof n.value === "number" ? fmt(n.value) : n.value)}</span>` : "<span></span>";
|
|
421
|
+
return `<li><div class="node ${folder ? "folder" : ""}" data-node="${esc(n.node)}">
|
|
422
|
+
<span class="caret">${folder ? "▸" : n.class === "Variable" ? "•" : ""}</span>
|
|
423
|
+
<span>${esc(n.name)} <code>${esc(n.node)}</code></span>${val}
|
|
424
|
+
${n.class === "Variable" ? `<button class="copy" data-copy="${esc(n.node)}">copy</button>` : "<span></span>"}
|
|
425
|
+
</div></li>`;
|
|
426
|
+
}).join("");
|
|
427
|
+
}
|
|
428
|
+
$("#tree").addEventListener("click", async (e) => {
|
|
429
|
+
const copy = e.target.closest(".copy");
|
|
430
|
+
if (copy) { navigator.clipboard?.writeText(copy.dataset.copy); toast(`Copied ${copy.dataset.copy}`); return; }
|
|
431
|
+
const node = e.target.closest(".node.folder"); if (!node) return;
|
|
432
|
+
const li = node.parentElement;
|
|
433
|
+
if (node.classList.toggle("open")) {
|
|
434
|
+
const ul = document.createElement("ul"); ul.innerHTML = `<li class="hint">Loading…</li>`; li.appendChild(ul);
|
|
435
|
+
try { ul.innerHTML = renderNodes(await api(`/api/browse?server=${encodeURIComponent(dlg.dataset.server)}&node=${encodeURIComponent(node.dataset.node)}`)); }
|
|
436
|
+
catch (err) { ul.innerHTML = `<li class="hint">${esc(err.message)}</li>`; }
|
|
437
|
+
} else li.querySelector("ul")?.remove();
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
// ---------------------------------------------------------------- boot
|
|
441
|
+
async function boot() {
|
|
442
|
+
const o = await api("/api/overview");
|
|
443
|
+
o.tags.forEach((t) => S.tags.set(t.name, t));
|
|
444
|
+
S.values = o.values; S.servers = o.servers;
|
|
445
|
+
const saved = store.get("selected", null);
|
|
446
|
+
S.selected = (saved || ["Tank1.Level", "Pump1.Speed"]).filter((n) => S.tags.has(n));
|
|
447
|
+
if (!S.selected.length) S.selected = [...S.tags.keys()].slice(0, 2);
|
|
448
|
+
S.selected.forEach(colorFor);
|
|
449
|
+
for (const b of $("#ranges").children) b.classList.toggle("on", Number(b.dataset.min) === S.minutes);
|
|
450
|
+
renderServers(); renderTagList(); renderCards();
|
|
451
|
+
S.events = await api("/api/events?limit=200").catch(() => []);
|
|
452
|
+
renderEvents();
|
|
453
|
+
connect();
|
|
454
|
+
loadTrend();
|
|
455
|
+
pollStats(); setInterval(pollStats, 3000);
|
|
456
|
+
// seed sparklines with the last few minutes of history
|
|
457
|
+
const end = Date.now() / 1000;
|
|
458
|
+
await Promise.all(cardTags().map(async (name) => {
|
|
459
|
+
const h = await api(`/api/history?tag=${encodeURIComponent(name)}&minutes=${SPARK_SECONDS / 60}&end=${end}&points=150`).catch(() => null);
|
|
460
|
+
if (!h) return;
|
|
461
|
+
const sp = S.sparks.get(name) || { t: [], v: [] };
|
|
462
|
+
const live = sp.t.length ? sp : null;
|
|
463
|
+
S.sparks.set(name, { t: [...h.t, ...(live ? live.t : [])], v: [...h.avg, ...(live ? live.v : [])] });
|
|
464
|
+
paintCard(name);
|
|
465
|
+
}));
|
|
466
|
+
setInterval(drawAllSparks, 1000);
|
|
467
|
+
}
|
|
468
|
+
boot().catch((e) => { document.body.insertAdjacentHTML("beforeend", `<p class="hint" style="padding:16px">Could not load TagScope: ${esc(e.message)}</p>`); });
|
|
469
|
+
})();
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>TagScope</title>
|
|
7
|
+
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%23121a23'/%3E%3Cpath d='M5 18h5l3-8 5 14 3-9 2 3h4' fill='none' stroke='%2338d9b0' stroke-width='2.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E">
|
|
8
|
+
<link rel="stylesheet" href="/static/vendor/uPlot.min.css">
|
|
9
|
+
<link rel="stylesheet" href="/static/app.css">
|
|
10
|
+
</head>
|
|
11
|
+
<body>
|
|
12
|
+
<header class="topbar">
|
|
13
|
+
<div class="brand">
|
|
14
|
+
<svg viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8" class="brand-bg"/><path d="M5 18h5l3-8 5 14 3-9 2 3h4" class="brand-line"/></svg>
|
|
15
|
+
<span>Tag<b>Scope</b></span>
|
|
16
|
+
</div>
|
|
17
|
+
<div id="servers" class="servers" aria-label="Servers"></div>
|
|
18
|
+
<div class="topbar-right">
|
|
19
|
+
<div class="stat" title="Samples written to the database"><span id="stat-samples">0</span><small>samples</small></div>
|
|
20
|
+
<div class="stat" title="Samples per second"><span id="stat-rate">0</span><small>/s</small></div>
|
|
21
|
+
<div class="stat clock"><span id="clock">--:--:--</span></div>
|
|
22
|
+
<button id="theme" class="icon-btn" title="Toggle light / dark" aria-label="Toggle theme">
|
|
23
|
+
<svg viewBox="0 0 24 24"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg>
|
|
24
|
+
</button>
|
|
25
|
+
</div>
|
|
26
|
+
</header>
|
|
27
|
+
|
|
28
|
+
<div class="layout">
|
|
29
|
+
<aside class="sidebar">
|
|
30
|
+
<div class="search">
|
|
31
|
+
<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
|
|
32
|
+
<input id="search" type="search" placeholder="Filter tags… ( / )" autocomplete="off">
|
|
33
|
+
</div>
|
|
34
|
+
<div id="taglist" class="taglist" role="list"></div>
|
|
35
|
+
<button id="open-browser" class="ghost-btn wide">
|
|
36
|
+
<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v10H3z"/></svg> Browse server
|
|
37
|
+
</button>
|
|
38
|
+
</aside>
|
|
39
|
+
|
|
40
|
+
<main class="main">
|
|
41
|
+
<section id="cards" class="cards" aria-label="Key values"></section>
|
|
42
|
+
|
|
43
|
+
<section class="panel trend">
|
|
44
|
+
<div class="panel-head">
|
|
45
|
+
<h2>Trend <span id="trend-sub" class="muted"></span></h2>
|
|
46
|
+
<div class="panel-tools">
|
|
47
|
+
<div id="ranges" class="segmented" role="tablist">
|
|
48
|
+
<button data-min="5">5m</button><button data-min="15" class="on">15m</button><button data-min="60">1h</button><button data-min="360">6h</button><button data-min="1440">24h</button>
|
|
49
|
+
</div>
|
|
50
|
+
<button id="live" class="pill live on" title="Follow live data"><i></i>Live</button>
|
|
51
|
+
<button id="export" class="ghost-btn" title="Download the selected tags as CSV">
|
|
52
|
+
<svg viewBox="0 0 24 24"><path d="M12 4v11m0 0-4-4m4 4 4-4M5 20h14"/></svg> CSV
|
|
53
|
+
</button>
|
|
54
|
+
</div>
|
|
55
|
+
</div>
|
|
56
|
+
<div id="legend" class="legend"></div>
|
|
57
|
+
<div id="chart" class="chart"></div>
|
|
58
|
+
<p class="hint">Drag to zoom · double-click to reset · click tags on the left to add or remove them</p>
|
|
59
|
+
</section>
|
|
60
|
+
|
|
61
|
+
<section class="panel events">
|
|
62
|
+
<div class="panel-head">
|
|
63
|
+
<h2>Events <span id="alarm-count" class="badge hidden">0</span></h2>
|
|
64
|
+
<div class="segmented small" id="event-filter">
|
|
65
|
+
<button data-kind="" class="on">All</button><button data-kind="alarm">Alarms</button><button data-kind="system">System</button>
|
|
66
|
+
</div>
|
|
67
|
+
</div>
|
|
68
|
+
<ol id="events" class="eventlist"></ol>
|
|
69
|
+
</section>
|
|
70
|
+
</main>
|
|
71
|
+
</div>
|
|
72
|
+
|
|
73
|
+
<dialog id="browser" class="browser">
|
|
74
|
+
<div class="panel-head">
|
|
75
|
+
<h2>Address space <span id="browser-server" class="muted"></span></h2>
|
|
76
|
+
<button class="icon-btn" id="close-browser" aria-label="Close">✕</button>
|
|
77
|
+
</div>
|
|
78
|
+
<ul id="tree" class="tree"></ul>
|
|
79
|
+
<p class="hint">Copy a node id into your <code>tagscope.yaml</code> to start logging it.</p>
|
|
80
|
+
</dialog>
|
|
81
|
+
|
|
82
|
+
<div id="toast" class="toast" role="status"></div>
|
|
83
|
+
|
|
84
|
+
<script src="/static/vendor/uPlot.iife.min.js"></script>
|
|
85
|
+
<script src="/static/app.js"></script>
|
|
86
|
+
</body>
|
|
87
|
+
</html>
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Leon Sorokin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|