diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..b802caf
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,28 @@
+**
+!api/
+!api/package*.json
+!api/src/
+!api/src/**
+!collector/
+!collector/package*.json
+!collector/src/
+!collector/src/**
+!runner/
+!runner/package*.json
+!runner/src/
+!runner/src/**
+!web/
+!web/package*.json
+!web/index.html
+!web/vite.config.js
+!web/public/
+!web/public/**
+!web/src/
+!web/src/**
+!shared/
+!shared/*.mjs
+**/node_modules
+**/dist
+**/.env
+**/.env.*
+**/.git
diff --git a/.env.example b/.env.example
index 64c9c2f..f9b0b10 100644
--- a/.env.example
+++ b/.env.example
@@ -9,5 +9,6 @@ MARIADB_ROOT_PASSWORD=SE3112
MARIADB_PASSWORD=3112
DB_PASSWORD_FALLBACK=root
REDIS_PASSWORD=replace-with-a-long-random-redis-password
-CORS_ORIGIN=http://localhost:5173
-VITE_API_PORT=18080
\ No newline at end of file
+CORS_ORIGIN=http://localhost:81
+LEGACY_TREND_TIME_ZONE=Europe/Berlin
+VITE_API_PORT=18080
diff --git a/.gitignore b/.gitignore
index 426bb6d..ba71ae4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,5 +4,4 @@ dist
npm-debug.log*
.scratch/runtime
data/
-web/src
.env
diff --git a/README.md b/README.md
index be03e0b..30289f2 100644
--- a/README.md
+++ b/README.md
@@ -89,7 +89,7 @@ SeLTD/
```text
Browser
│
- │ http://localhost:5173
+ │ http://localhost:81
▼
React/Vite Frontend (web)
│
@@ -115,7 +115,7 @@ Wichtig: Die API laeuft im Container intern auf Port `8080`, wird aber nach auss
| Service | Container | Interner Port | Host-Port | Zweck |
| --- | --- | ---: | ---: | --- |
-| Web | `seltd-web` | 5173 | 5173 | React/Vite-Oberflaeche |
+| Web | `seltd-web` | 5173 | 81 | React/Vite-Oberflaeche |
| API | `seltd-api` | 8080 | 18080 | REST-API |
| Collector | `seltd-collector` | 18110 | 18110 | Quellen, Datenpunkte, Scans, Polling |
| MariaDB | `seltd-mariadb` | 3306 | 3306 | Trend- und Benutzerdaten |
@@ -168,30 +168,9 @@ docker ps -a
### 3. Aufrufen
Nun stehen dir mehrere Tools zur Verfügung:
-<<<<<<< HEAD
-
-Frontend | `http://localhost:5173`
+| Frontend | `http://localhost:81` |
--> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends.
-API Healthcheck | `http://localhost:18080/api/health`
---> hier kannst du schauen ob die API läuft
-
-Collector Healthcheck | `http://localhost:18110/health`
---> hier kannst du schauen ob der Collector läuft, was nur wichtig ist, wenn du Datenpunkte per OPC,KNX, Modbus oder Bacnet angebunden hast.
-
-Dockhand | `http://localhost:3000`
---> Dockhand ist Container verwaltungstool, dass es dir ermöglicht, auch grafisch den Zustand deiner Container und deines Stacks zu sehen.
- Der Vorteil hier, im Gegensatz zur normalen Docker Desktopoberfläche: Du kannst es auf jedem beliebigen anderen Rechner, der auf dein Netzwerk zugriff hat, öffnen.
-
-cAdvisor | `http://localhost:9090`
---> Cadvisor stellt alle Containerdaten für Monitoring und Analyticprogramme bereit.
- So kann bei einer größeren Anlage, das Dockersystem mitr Prometheus oder ähnlichem überwacht werden.
- Cadvisor stellt di Daten per html bereit, kannst du dir gern anschauen, ist aber ziemlich unübersichtlich.
-=======
-| Frontend | `http://localhost:5173` |
---> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends.
->>>>>>> c06fe1fd4df46b203002412d6d8d0362c979166c
-
| API Healthcheck | `http://localhost:18080/api/health` |
--> hier kannst du schauen ob die API läuft
@@ -230,6 +209,7 @@ Die wichtigsten Variablen liegen in `.env`.
| `MARIADB_ROOT_PASSWORD` | `SE3112` | MariaDB-Root-Passwort |
| `DB_PASSWORD_FALLBACK` | `root` | Fallback fuer alte Entwicklungsvolumes |
| `CORS_ORIGIN` | `*` | Erlaubter Browser-Ursprung fuer API-Aufrufe |
+| `LEGACY_TREND_TIME_ZONE` | `Europe/Berlin` | Zeitzone der gespeicherten Controllerzeit in Bestandstabellen mit `Wert1` usw. Fuer bereits in UTC gespeicherte Bestandsdaten `+00:00` setzen. |
| `VITE_API_PORT` | `18080` | API-Port, den das Frontend im Browser nutzt |
| `POLL_TICK_MS` | `1000` | Collector-Tick fuer Polling-Pruefung |
@@ -538,10 +518,10 @@ docker ps
curl http://localhost:18080/api/health
```
-Wenn Frontend lokal auf `localhost:5173` laeuft:
+Wenn das Frontend lokal auf `localhost:81` laeuft:
```env
-CORS_ORIGIN=*
+CORS_ORIGIN=http://localhost:81
```
Danach API neu starten:
@@ -693,4 +673,4 @@ npm --prefix symcon-collector run check
npm --prefix bacnet-collector run check
npm --prefix runner run check
npm --prefix web run check
-```
\ No newline at end of file
+```
diff --git a/api/Dockerfile b/api/Dockerfile
index 9b90684..b8ade08 100644
--- a/api/Dockerfile
+++ b/api/Dockerfile
@@ -1,11 +1,12 @@
FROM node:22-alpine
-WORKDIR /app
+WORKDIR /app/api
-COPY package*.json ./
+COPY api/package*.json ./
RUN npm ci
-COPY src ./src
+COPY api/src ./src
+COPY shared /app/shared
EXPOSE 8080
diff --git a/api/src/db.js b/api/src/db.js
index 8a3e06a..a579def 100644
--- a/api/src/db.js
+++ b/api/src/db.js
@@ -1,8 +1,9 @@
import mysql from "mysql2/promise";
import { config } from "./config.js";
+import { setUtcSession } from "../../shared/trend-time.mjs";
function createPool(password) {
- return mysql.createPool({
+ const pool = mysql.createPool({
host: config.dbHost,
port: config.dbPort,
user: config.dbUser,
@@ -13,7 +14,10 @@ function createPool(password) {
namedPlaceholders: true,
multipleStatements: true,
charset: "utf8mb4",
+ timezone: "Z",
});
+ pool.on("connection", setUtcSession);
+ return pool;
}
const candidatePasswords = [...new Set([config.dbPassword, config.dbPasswordFallback].filter(Boolean))];
@@ -32,9 +36,19 @@ function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
-async function queryWithCredentials(sql, values) {
+async function execute(pool, sql, values, isolated) {
+ if (!isolated) return pool.query(sql, values);
+ const connection = await pool.getConnection();
try {
- return await activePool.query(sql, values);
+ return await connection.query(sql);
+ } finally {
+ connection.destroy();
+ }
+}
+
+async function queryWithCredentials(sql, values, isolated) {
+ try {
+ return await execute(activePool, sql, values, isolated);
} catch (error) {
if (!isAccessDenied(error) || candidatePasswords.length < 2) {
throw error;
@@ -44,7 +58,7 @@ async function queryWithCredentials(sql, values) {
if (password === activePassword) continue;
const fallbackPool = createPool(password);
try {
- const result = await fallbackPool.query(sql, values);
+ const result = await execute(fallbackPool, sql, values, isolated);
const previousPool = activePool;
activePool = fallbackPool;
activePassword = password;
@@ -74,4 +88,5 @@ async function query(sql, values) {
throw lastError;
}
-export const pool = { query };
\ No newline at end of file
+export const pool = { query };
+export const importSql = (sql) => queryWithCredentials(sql, undefined, true);
diff --git a/api/src/index.js b/api/src/index.js
index 3956aa3..b8b9215 100644
--- a/api/src/index.js
+++ b/api/src/index.js
@@ -3,7 +3,10 @@ import cors from "cors";
import express from "express";
import { authenticateToken, authenticateTokenOptional, createToken, requireRoles } from "./auth.js";
import { config } from "./config.js";
-import { pool } from "./db.js";
+import { importSql, pool } from "./db.js";
+import { AUTO_UNIT } from "../../shared/engineering-units.mjs";
+import { normalizeTrendChartSettings } from "../../shared/trend-chart-settings.mjs";
+import { DEFAULT_TREND_PRESET, TREND_PRESETS } from "../../shared/trend-preferences.mjs";
import {
createTrendTable,
ensureIspMetadata,
@@ -11,12 +14,14 @@ import {
fetchLatestValues,
fetchTrendSeries,
getAvailableIsps,
+ migrateLegacyUserLevels,
normalizeEngineeringUnit,
normalizeRange,
resolveTrendTablePointCount,
sanitizeIspName,
sanitizePointIndex,
updateIspMetadata,
+ verifyLegacyTrendTimeZone,
} from "./lib/isp.js";
import {
deleteSelection,
@@ -292,17 +297,19 @@ async function listRunnerQueue() {
}
});
}
+async function resolveAccessibleSelection(selectionId, user) {
+ const selection = await getSelection(redis, selectionId);
+ if (!canUseSelection(selection, user)) {
+ throw new Error("Selection not found or not accessible.");
+ }
+ return selection;
+}
+
async function resolveSelectionPoints(body, user) {
if (body.selectionId) {
- const selection = await getSelection(redis, body.selectionId);
-
- if (!canUseSelection(selection, user)) {
- throw new Error("Selection not found or not accessible.");
- }
-
+ const selection = await resolveAccessibleSelection(body.selectionId, user);
return assertPoints(selection.points || []);
}
-
return assertPoints(body.points || []);
}
@@ -536,15 +543,21 @@ app.put(
points.forEach((point) => {
const pointIndex = sanitizePointIndex(point.pointIndex);
const key = String(pointIndex);
+ const existing = metadata.points[key] || {};
+ const alias = String(point.alias || "").trim() || existing.alias || `Wert${pointIndex}`;
+ const kind = point.kind === "digital" ? "digital" : "analog";
+ const unit = point.unit ?? existing.unit;
+ const unitAuto = unit === AUTO_UNIT || !unit || (point.unit == null && existing.unitAuto === true);
metadata.points[key] = {
- ...metadata.points[key],
- alias: String(point.alias || metadata.points[key].alias).trim() || metadata.points[key].alias,
- unit: normalizeEngineeringUnit(point.unit || metadata.points[key].unit),
- factor: Number.isFinite(Number(point.factor)) ? Number(point.factor) : metadata.points[key].factor,
- kind: point.kind === "digital" ? "digital" : "analog",
- min: Number.isFinite(Number(point.min)) ? Number(point.min) : metadata.points[key].min,
- max: Number.isFinite(Number(point.max)) ? Number(point.max) : metadata.points[key].max,
- color: typeof point.color === "string" ? point.color : metadata.points[key].color,
+ ...existing,
+ alias,
+ unit: normalizeEngineeringUnit(unitAuto ? AUTO_UNIT : unit, kind, alias),
+ unitAuto,
+ factor: Number.isFinite(Number(point.factor)) ? Number(point.factor) : (existing.factor ?? 1),
+ kind,
+ min: Number.isFinite(Number(point.min)) ? Number(point.min) : (existing.min ?? 0),
+ max: Number.isFinite(Number(point.max)) ? Number(point.max) : (existing.max ?? 100),
+ color: typeof point.color === "string" ? point.color : existing.color,
};
});
}
@@ -574,7 +587,7 @@ app.post("/api/units", authenticateToken, requirePermission("edit_aliases"), wra
}));
app.patch("/api/units/:symbol", authenticateToken, requirePermission("edit_aliases"), wrap(async (req, res) => {
- const existingSymbol = decodeURIComponent(req.params.symbol || "").trim();
+ const existingSymbol = String(req.params.symbol || "").trim();
if (!existingSymbol) {
return res.status(400).json({ error: "Einheit fehlt." });
}
@@ -632,7 +645,8 @@ app.post(
throw new Error("SQL-Inhalt ist leer.");
}
- await pool.query(sql);
+ await importSql(sql);
+ await migrateLegacyUserLevels(pool);
const isps = await getAvailableIsps(pool, config.dbName);
res.json({ ok: true, importedTables: isps.length, filename: req.body.filename || null });
})
@@ -757,6 +771,7 @@ app.post("/api/selections", authenticateToken, requirePermission("view_trends"),
description: String(req.body.description || "").trim(),
shared: Boolean(req.body.shared),
points,
+ chartSettings: normalizeTrendChartSettings(req.body.chartSettings, points),
});
res.status(201).json({ selection });
@@ -779,9 +794,12 @@ app.put("/api/selections/:selectionId", authenticateToken, requirePermission("vi
{
...existing,
name: String(req.body.name || existing.name).trim(),
- description: String(req.body.description || existing.description || "").trim(),
+ description: String(req.body.description ?? existing.description ?? "").trim(),
shared: typeof req.body.shared === "boolean" ? req.body.shared : existing.shared,
points,
+ chartSettings: normalizeTrendChartSettings(
+ req.body.chartSettings === undefined ? existing.chartSettings : req.body.chartSettings, points
+ ),
},
existing.id
);
@@ -804,9 +822,37 @@ app.delete("/api/selections/:selectionId", authenticateToken, requirePermission(
res.status(204).send();
}));
+async function getTrendDefaults() {
+ const stored = await redis.get("settings:trend:default-preset");
+ return { defaultPresetDays: TREND_PRESETS.some(({ value }) => value === stored) ? stored : DEFAULT_TREND_PRESET };
+}
+
+async function getTrendDisplayOptions(user) {
+ const [preferences, defaults] = await Promise.all([getPreferences(redis, user?.sub), getTrendDefaults()]);
+ return { ...defaults, maxSeries: preferences.maxTrendSeries };
+}
+
+async function fetchDisplayTrend(points, range, { maxSeries, defaultPresetDays }) {
+ const trend = await fetchTrendSeries(pool, redis, points.slice(0, maxSeries), normalizeRange(range, defaultPresetDays));
+ return { ...trend, requestedSeriesCount: points.length, maxSeries };
+}
+
+app.get("/api/settings/trend", wrap(async (_req, res) => {
+ res.json(await getTrendDefaults());
+}));
+
+app.put("/api/settings/trend", authenticateToken, requireRoles("admin"), wrap(async (req, res) => {
+ const defaultPresetDays = String(req.body?.defaultPresetDays ?? "");
+ if (!TREND_PRESETS.some(({ value }) => value === defaultPresetDays)) {
+ return res.status(400).json({ error: "Bitte einen gültigen Standardzeitraum auswählen." });
+ }
+ await redis.set("settings:trend:default-preset", defaultPresetDays);
+ res.json({ defaultPresetDays });
+}));
+
app.post("/api/trends/query", authenticateTokenOptional, wrap(async (req, res) => {
const points = await resolveSelectionPoints(req.body, resolveViewerUser(req));
- const trendData = await fetchTrendSeries(pool, redis, points, normalizeRange(req.body.range));
+ const trendData = await fetchDisplayTrend(points, req.body.range, await getTrendDisplayOptions(req.user));
res.json(trendData);
}));
@@ -830,13 +876,20 @@ app.post("/api/dashboard/data", authenticateTokenOptional, wrap(async (req, res)
const widgets = Array.isArray(req.body.widgets) ? req.body.widgets : [];
const results = [];
const viewer = resolveViewerUser(req);
+ const trendOptions = widgets.some((widget) => widget.type === "chart") ? await getTrendDisplayOptions(req.user) : null;
for (const widget of widgets) {
- const points = widget.selectionId ? await resolveSelectionPoints({ selectionId: widget.selectionId }, viewer) : assertPoints(widget.points || []);
+ const selection = widget.selectionId ? await resolveAccessibleSelection(widget.selectionId, viewer) : null;
+ const points = assertPoints(selection ? selection.points : (widget.points || []));
if (widget.type === "chart") {
- const trendData = await fetchTrendSeries(pool, redis, points, normalizeRange(widget.range));
- results.push({ id: widget.id, type: widget.type, ...trendData });
+ const trendData = await fetchDisplayTrend(points, widget.range, trendOptions);
+ results.push({
+ id: widget.id,
+ type: widget.type,
+ ...trendData,
+ ...(selection ? { chartSettings: normalizeTrendChartSettings(selection.chartSettings, points) } : {}),
+ });
} else {
const values = await fetchLatestValues(pool, redis, points);
results.push({ id: widget.id, type: widget.type, values });
@@ -870,7 +923,8 @@ app.put("/api/integrations", authenticateToken, requirePermission("manage_integr
}));
app.get("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (_req, res) => {
- res.json({ jobs: await listRunnerJobs(), queue: await listRunnerQueue() });
+ const [jobs, queue, integration] = await Promise.all([listRunnerJobs(), listRunnerQueue(), redis.get("integration:api")]);
+ res.json({ jobs, queue, mailConfigured: Boolean(JSON.parse(integration || "{}").mailApiKey) });
}));
app.post("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (req, res) => {
@@ -922,6 +976,8 @@ app.use((error, _req, res, _next) => {
await ensureUtf8Database();
await ensureUserSchema();
+await verifyLegacyTrendTimeZone(pool);
+await migrateLegacyUserLevels(pool);
await ensureRolesSchema();
await ensureAdminUser();
diff --git a/api/src/lib/isp.js b/api/src/lib/isp.js
index 88cc632..e55c9c4 100644
--- a/api/src/lib/isp.js
+++ b/api/src/lib/isp.js
@@ -1,4 +1,7 @@
-const META_PREFIX = "meta:isp:";
+import { AUTO_UNIT, DEFAULT_ANALOG_UNIT, resolveEngineeringUnit } from "../../../shared/engineering-units.mjs";
+import { LEGACY_DATUM_UTC, LEGACY_TREND_TIME_ZONE } from "../../../shared/trend-time.mjs";
+
+const META_PREFIX = "meta:isp:";
export const LEGACY_POINT_LIMIT = 200;
export const LOCAL_POINT_LIMIT = 2000;
@@ -106,40 +109,18 @@ function parseHslColor(value) {
};
}
-function createRandomPointColor(seed) {
- const hue = Math.round((seed * 47 + 17 + Math.random() * 28) % 360);
- const saturation = 72 + (seed % 4) * 4;
- const lightness = 45 + (seed % 3) * 4;
- return hslToHex(hue, saturation, lightness);
-}
-
-export function normalizeEngineeringUnit(value, kind = "analog") {
- const normalizedKind = kind === "digital" ? "digital" : "analog";
- const raw = String(value ?? "").trim();
- if (!raw) {
- return normalizedKind === "digital" ? "bool" : "\u00B0C";
- }
-
- if (normalizedKind === "digital" && /^(?:bool|boolean)$/i.test(raw)) {
- return "bool";
- }
-
- if (/^\?C$/i.test(raw) || /^\u00B0\s*C$/i.test(raw) || (/[^\x00-\x7F]/.test(raw) && /C/i.test(raw))) {
- return normalizedKind === "digital" ? "bool" : "\u00B0C";
- }
-
- return raw;
-}
+export const normalizeEngineeringUnit = resolveEngineeringUnit;
function createDefaultPoint(index) {
return {
alias: `Wert${index}`,
- unit: "\u00B0C",
+ unit: DEFAULT_ANALOG_UNIT,
+ unitAuto: true,
factor: 1,
kind: "analog",
min: 0,
max: 100,
- color: createRandomPointColor(index),
+ color: "#000000",
};
}
@@ -174,7 +155,7 @@ export async function createLegacyWideTrendTable(pool, tableName) {
CREATE TABLE IF NOT EXISTS \`${safeTable}\` (
\`id\` INT(11) NOT NULL AUTO_INCREMENT,
\`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- \`userlevel\` INT(1) NOT NULL,
+ \`userlevel\` INT(1) NULL DEFAULT NULL,
${buildValueColumns()},
PRIMARY KEY (\`id\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -205,6 +186,40 @@ export async function createTrendTable(pool, tableName) {
return safeTable;
}
+export async function migrateLegacyUserLevels(pool) {
+ const [columns] = await pool.query(`
+ SELECT c.TABLE_NAME AS tableName, c.COLUMN_TYPE AS columnType,
+ c.COLUMN_DEFAULT AS defaultValue, c.COLUMN_COMMENT AS comment
+ FROM information_schema.COLUMNS c
+ JOIN information_schema.TABLES t
+ ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
+ WHERE c.TABLE_SCHEMA = DATABASE()
+ AND c.TABLE_NAME REGEXP '^(isp[a-z0-9_]*|trend_[a-z0-9_]+)$'
+ AND t.TABLE_TYPE = 'BASE TABLE'
+ AND c.COLUMN_NAME = 'userlevel' AND c.IS_NULLABLE = 'NO'
+ AND EXISTS (
+ SELECT 1 FROM information_schema.COLUMNS v
+ WHERE v.TABLE_SCHEMA = c.TABLE_SCHEMA AND v.TABLE_NAME = c.TABLE_NAME
+ AND v.COLUMN_NAME REGEXP '^Wert[0-9]+$'
+ )
+ `);
+ for (const { tableName, columnType, defaultValue, comment } of columns) {
+ const table = sanitizeIspName(tableName);
+ if (!/^(?:tinyint|smallint|mediumint|int|bigint)(?:\(\d+\))?(?: unsigned)?(?: zerofill)?$/i.test(columnType)) {
+ throw new Error(`Unexpected userlevel column type in ${table}.`);
+ }
+ const defaultSql = /^-?\d+$/.test(String(defaultValue)) ? String(defaultValue) : "NULL";
+ await pool.query(`ALTER TABLE \`${table}\` MODIFY COLUMN \`userlevel\` ${columnType} NULL DEFAULT ${defaultSql} COMMENT ?`, [comment]);
+ }
+}
+
+export async function verifyLegacyTrendTimeZone(pool) {
+ const [[row]] = await pool.query("SELECT CONVERT_TZ('2026-01-01 12:00:00', ?, '+00:00') AS converted", [LEGACY_TREND_TIME_ZONE]);
+ if (!row.converted) {
+ throw new Error(`MariaDB cannot resolve LEGACY_TREND_TIME_ZONE=${LEGACY_TREND_TIME_ZONE}. Check its time zone tables.`);
+ }
+}
+
async function loadSourcePointSeeds(pool, tableName) {
const safeTable = sanitizeIspName(tableName);
@@ -275,7 +290,10 @@ async function describeTrendTable(pool, dbName, tableName) {
const widePointCount = columnNames.filter((name) => /^Wert\d+$/i.test(name)).length;
if (widePointCount > 0) {
- const [rows] = await pool.query(`SELECT COUNT(*) AS rowCount, MAX(datum) AS latestTimestamp FROM \`${safeTable}\``);
+ const [rows] = await pool.query(
+ `SELECT COUNT(*) AS rowCount, CONVERT_TZ(MAX(datum), ?, '+00:00') AS latestTimestamp FROM \`${safeTable}\``,
+ [LEGACY_TREND_TIME_ZONE]
+ );
return {
tableName: safeTable,
storage: "wide",
@@ -393,7 +411,8 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO
parsed.points[pointKey] = {
...defaultPoint,
alias: initialAlias,
- unit: normalizeEngineeringUnit(sourceSeed?.unit || defaultPoint.unit, sourceSeed?.kind || defaultPoint.kind),
+ unit: normalizeEngineeringUnit(sourceSeed?.unit, sourceSeed?.kind || defaultPoint.kind, initialAlias),
+ unitAuto: !sourceSeed?.unit,
kind: sourceSeed?.kind || defaultPoint.kind,
};
changed = true;
@@ -412,18 +431,16 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO
point.kind = sourceSeed.kind;
changed = true;
}
- const normalizedUnit = normalizeEngineeringUnit(point.unit, point.kind || sourceSeed?.kind || defaultPoint.kind);
+ const kind = point.kind || sourceSeed?.kind || defaultPoint.kind;
+ const normalizedUnit = normalizeEngineeringUnit(
+ point.unitAuto === true ? AUTO_UNIT : (point.unit || sourceSeed?.unit),
+ kind,
+ point.alias
+ );
if (normalizedUnit !== point.unit) {
point.unit = normalizedUnit;
changed = true;
}
- if ((!point.unit || point.unit === normalizeEngineeringUnit(defaultPoint.unit, defaultPoint.kind)) && sourceSeed?.unit) {
- const seededUnit = normalizeEngineeringUnit(sourceSeed.unit, sourceSeed.kind || point.kind || defaultPoint.kind);
- if (point.unit !== seededUnit) {
- point.unit = seededUnit;
- changed = true;
- }
- }
if (!point.kind) {
point.kind = sourceSeed?.kind || defaultPoint.kind;
changed = true;
@@ -468,7 +485,8 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO
metadata.points[pointKey] = {
...metadata.points[pointKey],
alias: sourceSeed.alias || sourceSeed.name || metadata.points[pointKey].alias,
- unit: normalizeEngineeringUnit(sourceSeed.unit || metadata.points[pointKey].unit, sourceSeed.kind || metadata.points[pointKey].kind),
+ unit: normalizeEngineeringUnit(sourceSeed.unit, sourceSeed.kind, sourceSeed.alias || sourceSeed.name),
+ unitAuto: !sourceSeed.unit,
kind: sourceSeed.kind || metadata.points[pointKey].kind,
};
});
@@ -581,8 +599,11 @@ export async function fetchTrendSeries(pool, redis, points, range) {
const limit = range.maxRows || 4000;
const [rows] = await pool.query(
- `SELECT datum, ${columns} FROM \`${isp}\` WHERE datum BETWEEN ? AND ? ORDER BY datum DESC LIMIT ?`,
- [range.from, range.to, limit]
+ `SELECT ${LEGACY_DATUM_UTC} AS datum, ${columns} FROM \`${isp}\`
+ WHERE datum BETWEEN DATE_SUB(?, INTERVAL 1 DAY) AND DATE_ADD(?, INTERVAL 1 DAY)
+ AND ${LEGACY_DATUM_UTC} BETWEEN ? AND ?
+ ORDER BY \`${isp}\`.datum DESC LIMIT ?`,
+ [LEGACY_TREND_TIME_ZONE, range.from, range.to, LEGACY_TREND_TIME_ZONE, range.from, range.to, limit]
);
rows.reverse().forEach((row) => {
@@ -673,7 +694,10 @@ export async function fetchLatestValues(pool, redis, points) {
.map((descriptor) => `\`Wert${descriptor.pointIndex}\``)
.join(", ");
- const [rows] = await pool.query(`SELECT datum, ${columns} FROM \`${isp}\` ORDER BY datum DESC LIMIT 1`);
+ const [rows] = await pool.query(
+ `SELECT ${LEGACY_DATUM_UTC} AS datum, ${columns} FROM \`${isp}\` ORDER BY \`${isp}\`.datum DESC LIMIT 1`,
+ [LEGACY_TREND_TIME_ZONE]
+ );
const row = rows[0];
pointDescriptors.forEach((descriptor) => {
@@ -690,8 +714,8 @@ export async function fetchLatestValues(pool, redis, points) {
return values;
}
-export function normalizeRange(input = {}) {
- const presetDays = Number(input.presetDays || 1);
+export function normalizeRange(input = {}, defaultPresetDays = 1) {
+ const presetDays = Number(input.presetDays || defaultPresetDays);
const maxRows = Number(input.maxRows || 4000);
const now = new Date();
const to = input.to ? new Date(input.to) : now;
diff --git a/api/src/lib/store.js b/api/src/lib/store.js
index 54a6524..440c825 100644
--- a/api/src/lib/store.js
+++ b/api/src/lib/store.js
@@ -1,4 +1,7 @@
const SELECTION_SET_KEY = "selection:ids";
+import { DEFAULT_UNITS as DEFAULT_UNIT_DEFINITIONS, normalizeUnitSymbol as canonicalUnitSymbol } from "../../../shared/engineering-units.mjs";
+import { DEFAULT_MAX_TREND_SERIES, normalizeMaxTrendSeries } from "../../../shared/trend-preferences.mjs";
+
const SELECTION_SEQ_KEY = "selection:seq";
const ROLE_SET_KEY = "role:names";
const UNIT_SET_KEY = "unit:symbols";
@@ -24,33 +27,12 @@ export const DEFAULT_ROLE_DEFINITIONS = [
},
];
-export const DEFAULT_UNIT_DEFINITIONS = [
- { symbol: "\u00B0C", label: "Grad Celsius", isSystem: true },
- { symbol: "%", label: "Prozent", isSystem: true },
- { symbol: "K", label: "Kelvin", isSystem: true },
- { symbol: "V", label: "Volt", isSystem: true },
- { symbol: "A", label: "Ampere", isSystem: true },
- { symbol: "Pa", label: "Pascal", isSystem: true },
- { symbol: "bool", label: "Digital / Bool", isSystem: true },
-];
-
function safeParse(jsonValue) {
return jsonValue ? JSON.parse(jsonValue) : null;
}
function normalizeUnitSymbol(value, fallback = "") {
- const raw = String(value ?? "").trim();
- const collapsed = raw.replace(/\s+/g, "");
-
- if (!collapsed) {
- return fallback;
- }
-
- if (/^\?C$/i.test(collapsed) || /^Â?\u00B0C$/i.test(collapsed)) {
- return "\u00B0C";
- }
-
- return raw;
+ return canonicalUnitSymbol(value) || fallback;
}
function unitStorageKey(symbol) {
@@ -179,11 +161,14 @@ export async function listUnits(redis) {
const symbols = await redis.smembers(UNIT_SET_KEY);
const items = await Promise.all(symbols.map((symbol) => redis.get(unitStorageKey(symbol))));
- return items
- .map((item) => safeParse(item))
- .filter(Boolean)
- .map((unit) => normalizeUnitRecord(unit))
- .sort((left, right) => left.symbol.localeCompare(right.symbol, "de-DE"));
+ const units = new Map();
+ for (const item of items) {
+ const record = safeParse(item);
+ if (!record) continue;
+ const unit = normalizeUnitRecord(record);
+ if (!units.has(unit.symbol) || record.symbol === unit.symbol) units.set(unit.symbol, unit);
+ }
+ return [...units.values()].sort((left, right) => left.symbol.localeCompare(right.symbol, "de-DE"));
}
export async function saveUnit(redis, unit, previousSymbol = "") {
@@ -264,11 +249,14 @@ export async function saveDashboard(redis, userId, dashboard) {
}
export async function getPreferences(redis, userId) {
- return safeParse(await redis.get(`preferences:${userId}`)) || {
+ const stored = userId == null ? null : safeParse(await redis.get(`preferences:${userId}`));
+ return {
theme: "system",
csvDelimiter: ";",
sidebarPinned: true,
trendLineWidth: 1.8,
+ ...stored,
+ maxTrendSeries: normalizeMaxTrendSeries(stored?.maxTrendSeries, DEFAULT_MAX_TREND_SERIES),
};
}
@@ -281,6 +269,7 @@ export async function savePreferences(redis, userId, preferences) {
csvDelimiter: preferences.csvDelimiter || current.csvDelimiter || ";",
sidebarPinned: typeof preferences.sidebarPinned === "boolean" ? preferences.sidebarPinned : current.sidebarPinned,
trendLineWidth: Number.isFinite(Number(preferences.trendLineWidth)) ? Number(preferences.trendLineWidth) : Number(current.trendLineWidth || 1.8),
+ maxTrendSeries: normalizeMaxTrendSeries(preferences.maxTrendSeries, current.maxTrendSeries),
updatedAt: new Date().toISOString(),
};
await redis.set(`preferences:${userId}`, JSON.stringify(payload));
diff --git a/collector/Dockerfile b/collector/Dockerfile
index 9a868eb..d6d869a 100644
--- a/collector/Dockerfile
+++ b/collector/Dockerfile
@@ -2,10 +2,11 @@ FROM node:22-alpine
WORKDIR /app
-COPY package*.json ./
+COPY collector/package*.json ./
RUN npm ci
-COPY src ./src
+COPY collector/src ./src
+COPY shared /shared
RUN mkdir -p /app/data
EXPOSE 18110
diff --git a/collector/src/index.js b/collector/src/index.js
index c02e343..8d6b9bb 100644
--- a/collector/src/index.js
+++ b/collector/src/index.js
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
import { Buffer } from "node:buffer";
import net from "node:net";
import mysql from "mysql2/promise";
+import { resolveEngineeringUnit } from "../../shared/engineering-units.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const dataDir = join(__dirname, "..", "data");
@@ -192,27 +193,8 @@ function normalizeText(value) {
return repairText(String(value === undefined || value === null ? "" : value).trim());
}
-function normalizeUnit(value) {
- const raw = normalizeText(value);
- const collapsed = raw.replace(/\s+/g, "");
- if (!collapsed) {
- return "°C";
- }
-
- if (/^(?:\?C|\u00B0C)$/i.test(collapsed)) {
- return "°C";
- }
-
- return raw;
-}
-
-function normalizePointUnit(value, kind = "analog") {
- const normalizedKind = normalizePointKind(kind);
- const raw = normalizeText(value);
- if (!raw) {
- return normalizedKind === "digital" ? "bool" : "°C";
- }
- return normalizeUnit(raw);
+function normalizePointUnit(value, kind, name) {
+ return resolveEngineeringUnit(normalizeText(value), normalizePointKind(kind), name);
}
function normalizePointIndex(value, fallback) {
@@ -308,7 +290,7 @@ function parseModbusCsv(payload) {
pointIndex,
name: normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`,
alias: normalizeText(get("alias", get("name", `Register ${index + 1}`))) || normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`,
- unit: normalizePointUnit(get("unit"), get("kind", get("type", "analog"))),
+ unit: normalizePointUnit(get("unit"), get("kind", get("type", "analog")), get("alias", get("name"))),
dataType: get("datatype", "holding-register"),
kind: normalizePointKind(get("kind", get("type", "analog"))),
enabled: payload.enabled === true,
@@ -361,7 +343,7 @@ function parseKnxXml(payload) {
pointIndex: index + 1,
name,
alias: name,
- unit: normalizePointUnit("", dpt.startsWith("1.") ? "digital" : "analog"),
+ unit: normalizePointUnit("", dpt.startsWith("1.") ? "digital" : "analog", name),
dataType: dpt || "group-address",
kind: dpt.startsWith("1.") ? "digital" : "analog",
enabled: payload.enabled === true,
@@ -401,7 +383,7 @@ function createManualDatapoint(store, payload) {
pointIndex,
name,
alias,
- unit: normalizePointUnit(payload.unit, payload.kind),
+ unit: normalizePointUnit(payload.unit, payload.kind, alias),
kind: normalizePointKind(payload.kind),
enabled: payload.enabled !== false,
alarmEnabled: payload.alarmEnabled === true,
@@ -438,7 +420,7 @@ function createScanDatapoint(source, payload, index) {
pointIndex,
name: normalizeText(payload.name || alias) || alias,
alias,
- unit: normalizePointUnit(payload.unit, payload.kind),
+ unit: normalizePointUnit(payload.unit, payload.kind, alias),
kind: normalizePointKind(payload.kind),
enabled: payload.enabled === true,
alarmEnabled: payload.alarmEnabled === true,
@@ -936,7 +918,7 @@ function mapIpsymconVariable(source, variable, categoryId, index) {
nodeId: String(variableId),
dataType: variableType ? `ipsymcon-${variableType}` : "ipsymcon-variable",
kind,
- unit: normalizePointUnit(variable?.unit, kind),
+ unit: normalizePointUnit(variable?.unit, kind, name),
currentValue: variable?.value ?? null,
quality: normalizeText(variable?.quality || "unknown"),
path: normalizeText(variable?.actual_path || ""),
@@ -1744,7 +1726,7 @@ async function ensureTrendTable(tableName) {
CREATE TABLE IF NOT EXISTS \`${table}\` (
\`id\` INT(11) NOT NULL AUTO_INCREMENT,
\`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- \`userlevel\` INT(1) NOT NULL,
+ \`userlevel\` INT(1) NULL DEFAULT NULL,
${buildValueColumns()},
PRIMARY KEY (\`id\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
@@ -1898,7 +1880,7 @@ async function syncDatapointRegistryEntries(datapoints) {
normalizeText(datapoint.alias || datapoint.name || `Wert${datapoint.pointIndex}`),
normalizeText(datapoint.name || datapoint.alias || `Wert${datapoint.pointIndex}`),
String(datapoint.protocol || "unknown"),
- normalizeUnit(datapoint.unit || ""),
+ normalizePointUnit(datapoint.unit, datapoint.kind, datapoint.alias || datapoint.name),
String(datapoint.kind || "analog"),
datapoint.enabled === true ? 1 : 0,
datapoint.alarmEnabled === true ? 1 : 0,
@@ -2359,7 +2341,7 @@ const server = createServer(async (req, res) => {
address: typeof body.address === "string" ? normalizeText(body.address) : store.datapoints[index].address,
nodeId: typeof body.nodeId === "string" ? normalizeText(body.nodeId) : store.datapoints[index].nodeId,
dataType: typeof body.dataType === "string" && body.dataType.trim() ? normalizeText(body.dataType) : store.datapoints[index].dataType,
- unit: body.unit ? normalizePointUnit(body.unit, body.kind || store.datapoints[index].kind) : store.datapoints[index].unit,
+ unit: body.unit != null ? normalizePointUnit(body.unit, body.kind || store.datapoints[index].kind, body.alias || body.name || store.datapoints[index].alias) : store.datapoints[index].unit,
kind: body.kind ? normalizePointKind(body.kind) : store.datapoints[index].kind,
scale: Number.isFinite(Number(body.scale)) ? Number(body.scale) : store.datapoints[index].scale,
};
diff --git a/docker-compose.yml b/docker-compose.yml
index 57ce38d..a363535 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -38,7 +38,8 @@ services:
api:
build:
- context: ./api
+ context: .
+ dockerfile: api/Dockerfile
container_name: seltd-api
restart: unless-stopped
environment:
@@ -49,6 +50,7 @@ services:
DB_USER: root
DB_PASSWORD: ${MARIADB_ROOT_PASSWORD:-SE3112}
DB_PASSWORD_FALLBACK: ${DB_PASSWORD_FALLBACK:-root}
+ LEGACY_TREND_TIME_ZONE: ${LEGACY_TREND_TIME_ZONE:-Europe/Berlin}
REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}@redis:6379/0
JWT_SECRET: ${JWT_SECRET:-change-me}
ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
@@ -71,13 +73,14 @@ services:
web:
build:
- context: ./web
+ context: .
+ dockerfile: web/Dockerfile
container_name: seltd-web
restart: unless-stopped
environment:
VITE_API_PORT: ${VITE_API_PORT:-18080}
ports:
- - "5173:5173"
+ - "81:5173"
depends_on:
api:
condition: service_healthy
@@ -89,7 +92,8 @@ services:
collector:
build:
- context: ./collector
+ context: .
+ dockerfile: collector/Dockerfile
container_name: seltd-collector
restart: unless-stopped
environment:
@@ -160,7 +164,8 @@ services:
runner:
build:
- context: ./runner
+ context: .
+ dockerfile: runner/Dockerfile
container_name: seltd-runner
restart: unless-stopped
environment:
@@ -173,6 +178,7 @@ services:
EXPORT_DIR: /exports
RUNNER_TICK_MS: ${RUNNER_TICK_MS:-1000}
RUNNER_TIMEZONE: ${RUNNER_TIMEZONE:-Europe/Berlin}
+ LEGACY_TREND_TIME_ZONE: ${LEGACY_TREND_TIME_ZONE:-Europe/Berlin}
volumes:
- runner_exports:/exports
depends_on:
diff --git a/runner/Dockerfile b/runner/Dockerfile
index 2ae2592..e1437ea 100644
--- a/runner/Dockerfile
+++ b/runner/Dockerfile
@@ -1,7 +1,8 @@
FROM node:22-alpine
-WORKDIR /app
-COPY package*.json ./
+WORKDIR /app/runner
+COPY runner/package*.json ./
RUN npm install
-COPY src ./src
+COPY runner/src ./src
+COPY shared /app/shared
RUN mkdir -p /exports
CMD ["npm", "start"]
diff --git a/runner/src/index.js b/runner/src/index.js
index aa31a45..529fc46 100644
--- a/runner/src/index.js
+++ b/runner/src/index.js
@@ -5,6 +5,8 @@ import https from "node:https";
import path from "node:path";
import Redis from "ioredis";
import mysql from "mysql2/promise";
+import { LEGACY_DATUM_UTC, LEGACY_TREND_TIME_ZONE, setUtcSession } from "../../shared/trend-time.mjs";
+import { normalizeUnitSymbol } from "../../shared/engineering-units.mjs";
const redis = new Redis(process.env.REDIS_URL || "redis://redis:6379", { maxRetriesPerRequest: 2 });
const db = mysql.createPool({
@@ -14,9 +16,11 @@ const db = mysql.createPool({
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "SE3112",
charset: "utf8mb4",
+ timezone: "Z",
waitForConnections: true,
connectionLimit: 3,
});
+db.on("connection", setUtcSession);
const exportDir = process.env.EXPORT_DIR || "/exports";
const tickMs = Math.max(500, Number(process.env.RUNNER_TICK_MS || 1000));
const timeZone = process.env.RUNNER_TIMEZONE || "Europe/Berlin";
@@ -87,7 +91,7 @@ async function getPointMeta(isp, pointIndex) {
const point = Array.isArray(points)
? points.find((item) => Number(item.pointIndex) === Number(pointIndex))
: points[String(pointIndex)] || points[Number(pointIndex)];
- return { alias: point?.alias || `Wert${pointIndex}`, unit: point?.unit || "" };
+ return { alias: point?.alias || `Wert${pointIndex}`, unit: normalizeUnitSymbol(point?.unit) };
}
async function exportSelection(job, selection) {
@@ -113,8 +117,10 @@ async function exportSelection(job, selection) {
} else {
const column = `Wert${pointIndex}`;
const [data] = await db.query(
- `SELECT datum, \`${column}\` AS value FROM \`${table}\` WHERE datum >= ? ORDER BY datum ASC`,
- [since],
+ `SELECT ${LEGACY_DATUM_UTC} AS datum, \`${column}\` AS value FROM \`${table}\`
+ WHERE datum >= DATE_SUB(?, INTERVAL 1 DAY) AND ${LEGACY_DATUM_UTC} >= ?
+ ORDER BY \`${table}\`.datum ASC`,
+ [LEGACY_TREND_TIME_ZONE, since, LEGACY_TREND_TIME_ZONE, since],
);
for (const item of data) {
const value = formatExportValue(item.value);
diff --git a/shared/engineering-units.mjs b/shared/engineering-units.mjs
new file mode 100644
index 0000000..d07d5b8
--- /dev/null
+++ b/shared/engineering-units.mjs
@@ -0,0 +1,49 @@
+export const AUTO_UNIT = "__auto__";
+export const DEFAULT_ANALOG_UNIT = "\u00B0C";
+export const DIGITAL_UNIT = "Digital";
+
+export const DEFAULT_UNITS = [
+ [DEFAULT_ANALOG_UNIT, "Grad Celsius"],
+ ["%", "Prozent"],
+ ["K", "Kelvin"],
+ ["V", "Volt"],
+ ["A", "Ampere"],
+ ["Pa", "Pascal"],
+ [DIGITAL_UNIT, "Digital"],
+ ["ppm", "Parts per million"],
+ ["%RH", "Relative Feuchte"],
+ ["COV", "COV"],
+ ["mBar", "Millibar"],
+ ["Bar", "Bar"],
+ ["kW", "Kilowatt"],
+ ["kWh", "Kilowattstunden"],
+ ["Liter", "Liter"],
+ ["m\u00B3", "Kubikmeter"],
+].map(([symbol, label]) => ({ symbol, label, isSystem: true }));
+
+export function normalizeUnitSymbol(value) {
+ const symbol = String(value ?? "").trim();
+ if (/^(?:bool|boolean|digital)$/i.test(symbol)) return DIGITAL_UNIT;
+ if (/^(?:\?C|\u00C2*\u00B0\s*C)$/i.test(symbol)) return DEFAULT_ANALOG_UNIT;
+ if (/^%\s*rh$/i.test(symbol)) return "%RH";
+ if (/^m(?:\^?3|\u00B3)$/i.test(symbol)) return "m\u00B3";
+ return DEFAULT_UNITS.find((unit) => unit.symbol.toLowerCase() === symbol.toLowerCase())?.symbol ?? symbol;
+}
+
+export function detectEngineeringUnit(name, kind) {
+ if (kind === "digital") return DIGITAL_UNIT;
+ const label = String(name ?? "").toLowerCase();
+ if (/co[2\u2082]/.test(label)) return "ppm";
+ if (/feucht|humidity/.test(label)) return "%RH";
+ if (/energie|energy|kwh/.test(label)) return "kWh";
+ if (/leistung|power/.test(label)) return "kW";
+ if (/druck|pressure/.test(label)) return /m\s*bar|millibar/.test(label) ? "mBar" : "Pa";
+ if (/temp|f(?:\u00FC|ue)hler/.test(label)) return DEFAULT_ANALOG_UNIT;
+ return "";
+}
+
+export function resolveEngineeringUnit(value, kind, name) {
+ const unit = normalizeUnitSymbol(value);
+ if (unit && unit !== AUTO_UNIT) return unit;
+ return detectEngineeringUnit(name, kind) || DEFAULT_ANALOG_UNIT;
+}
diff --git a/shared/trend-chart-settings.mjs b/shared/trend-chart-settings.mjs
new file mode 100644
index 0000000..083d3e1
--- /dev/null
+++ b/shared/trend-chart-settings.mjs
@@ -0,0 +1,51 @@
+export const CHART_DIVISIONS = [3, 4, 6, 8, 10];
+
+export const DEFAULT_CHART_SETTINGS = {
+ divisions: 6,
+ grid: "both",
+ gridStyle: "dashed",
+ shadedBands: false,
+ opacity: 100,
+ highContrast: false,
+ axes: {},
+ assignments: {},
+};
+
+function entries(value) {
+ return value && typeof value === "object" && !Array.isArray(value) ? Object.entries(value) : [];
+}
+
+function numericBound(value) {
+ if (typeof value === "number" && Number.isFinite(value)) return value;
+ if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value);
+ return "";
+}
+
+export function normalizeTrendChartSettings(input, points) {
+ const settings = input || {};
+ const pointKeys = points && new Set(points.map((point) => `${point.isp}:${point.pointIndex}`));
+ const axes = Object.fromEntries(entries(settings.axes)
+ .filter(([id, axis]) => axis && typeof axis === "object" && (
+ (id.startsWith("unit:") && id.length <= 261)
+ || (id.startsWith("point:") && (!pointKeys || pointKeys.has(id.slice(6))))
+ ))
+ .map(([id, axis]) => [id, {
+ ...(axis.side === "left" || axis.side === "right" ? { side: axis.side } : {}),
+ mode: axis.mode === "manual" ? "manual" : "auto",
+ min: numericBound(axis.min),
+ max: numericBound(axis.max),
+ }]));
+ const assignments = Object.fromEntries(entries(settings.assignments)
+ .filter(([key, value]) => value === "own" && (!pointKeys || pointKeys.has(key))));
+
+ return {
+ divisions: CHART_DIVISIONS.includes(settings.divisions) ? settings.divisions : DEFAULT_CHART_SETTINGS.divisions,
+ grid: ["both", "horizontal", "vertical", "none"].includes(settings.grid) ? settings.grid : DEFAULT_CHART_SETTINGS.grid,
+ gridStyle: settings.gridStyle === "solid" ? "solid" : DEFAULT_CHART_SETTINGS.gridStyle,
+ shadedBands: settings.shadedBands === true,
+ opacity: Number.isFinite(settings.opacity) ? Math.max(20, Math.min(100, settings.opacity)) : DEFAULT_CHART_SETTINGS.opacity,
+ highContrast: settings.highContrast === true,
+ axes,
+ assignments,
+ };
+}
diff --git a/shared/trend-preferences.mjs b/shared/trend-preferences.mjs
new file mode 100644
index 0000000..aa42366
--- /dev/null
+++ b/shared/trend-preferences.mjs
@@ -0,0 +1,24 @@
+export const DEFAULT_TREND_PRESET = "1";
+export const DEFAULT_MAX_TREND_SERIES = 10;
+export const MAX_TREND_SERIES = 100;
+
+export const TREND_PRESETS = [
+ { value: "0.0034722222", label: "5 min" },
+ { value: "0.0069444444", label: "10 min" },
+ { value: "0.0208333333", label: "30 min" },
+ { value: "0.0416666667", label: "1 h" },
+ { value: "0.0833333333", label: "2 h" },
+ { value: "0.25", label: "6 h" },
+ { value: "0.5", label: "12 h" },
+ { value: "1", label: "24 h" },
+ { value: "2", label: "2 Tage" },
+ { value: "3", label: "3 Tage" },
+ { value: "7", label: "7 Tage" },
+ { value: "14", label: "14 Tage" },
+ { value: "30", label: "30 Tage" },
+];
+
+export function normalizeMaxTrendSeries(value, fallback = DEFAULT_MAX_TREND_SERIES) {
+ const count = Number(value);
+ return Number.isInteger(count) && count >= 1 && count <= MAX_TREND_SERIES ? count : fallback;
+}
diff --git a/shared/trend-time.mjs b/shared/trend-time.mjs
new file mode 100644
index 0000000..bb47283
--- /dev/null
+++ b/shared/trend-time.mjs
@@ -0,0 +1,6 @@
+export const LEGACY_TREND_TIME_ZONE = process.env.LEGACY_TREND_TIME_ZONE || "Europe/Berlin";
+export const LEGACY_DATUM_UTC = "CONVERT_TZ(datum, ?, '+00:00')";
+
+export function setUtcSession(connection) {
+ connection.query("SET time_zone = '+00:00'");
+}
diff --git a/web/Dockerfile b/web/Dockerfile
index 2e02921..930f1fe 100644
--- a/web/Dockerfile
+++ b/web/Dockerfile
@@ -1,11 +1,14 @@
FROM node:22-alpine
-WORKDIR /app
+WORKDIR /app/web
-COPY package*.json ./
+COPY web/package*.json ./
RUN npm ci
-COPY . .
+COPY web/index.html web/vite.config.js ./
+COPY web/src ./src
+COPY web/public ./public
+COPY shared /app/shared
EXPOSE 5173
diff --git a/web/src/App.jsx b/web/src/App.jsx
index a1beb06..8818afb 100644
--- a/web/src/App.jsx
+++ b/web/src/App.jsx
@@ -1,16 +1,36 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { api } from "./api.js";
import Gauge from "./components/Gauge.jsx";
import TrendChart from "./components/TrendChart.jsx";
+import Sidebar, { SmallFootnote } from "./components/Sidebar.jsx";
+import { AUTO_UNIT, DEFAULT_UNITS as DEFAULT_UNIT_OPTIONS, DIGITAL_UNIT, normalizeUnitSymbol, resolveEngineeringUnit } from "../../shared/engineering-units.mjs";
+import { DEFAULT_CHART_SETTINGS, normalizeTrendChartSettings } from "../../shared/trend-chart-settings.mjs";
+import {
+ DEFAULT_MAX_TREND_SERIES,
+ DEFAULT_TREND_PRESET,
+ MAX_TREND_SERIES,
+ TREND_PRESETS as TREND_PRESET_OPTIONS,
+ normalizeMaxTrendSeries,
+} from "../../shared/trend-preferences.mjs";
const views = [
- { id: "dashboard", label: "Dashboard", short: "D" },
- { id: "trends", label: "Trend", short: "T" },
- { id: "admin", label: "Admin", short: "A" },
- { id: "settings", label: "Einstellungen", short: "E" },
+ { id: "dashboard", label: "Dashboard" },
+ { id: "trends", label: "Trend" },
+ { id: "admin", label: "Admin" },
+ { id: "settings", label: "Einstellungen" },
];
+const CHART_DRAFT_KEY = "seltd:trend-chart";
+
+function loadChartDraft() {
+ try {
+ return normalizeTrendChartSettings(JSON.parse(localStorage.getItem(CHART_DRAFT_KEY)));
+ } catch {
+ return DEFAULT_CHART_SETTINGS;
+ }
+}
+
const adminSections = [
{ id: "aliases", label: "Aliase" },
{ id: "units", label: "Einheiten" },
@@ -23,22 +43,6 @@ const adminSections = [
{ id: "debug", label: "Debug" },
];
-const TREND_PRESET_OPTIONS = [
- { value: "0.0034722222", label: "5 min" },
- { value: "0.0069444444", label: "10 min" },
- { value: "0.0208333333", label: "30 min" },
- { value: "0.0416666667", label: "1 h" },
- { value: "0.0833333333", label: "2 h" },
- { value: "0.25", label: "6 h" },
- { value: "0.5", label: "12 h" },
- { value: "1", label: "24 h" },
- { value: "2", label: "2 Tage" },
- { value: "3", label: "3 Tage" },
- { value: "7", label: "7 Tage" },
- { value: "14", label: "14 Tage" },
- { value: "30", label: "30 Tage" },
-];
-
const SCALE_PRESET_OPTIONS = ["1", "0.1", "0.01", "0.001", "10", "100", "1000"];
const MODBUS_DATA_TYPE_OPTIONS = [
@@ -59,7 +63,7 @@ const MODBUS_DATA_TYPE_OPTIONS = [
];
const emptyTrendRange = {
- presetDays: "1",
+ presetDays: "",
from: "",
to: "",
maxRows: 20000,
@@ -76,7 +80,7 @@ const defaultWidgetDraft = {
type: "chart",
source: "manual",
selectionId: "",
- rangePresetDays: 1,
+ rangePresetDays: "",
min: 0,
max: 100,
};
@@ -94,29 +98,6 @@ const PERMISSION_OPTIONS = [
{ id: "manage_runner", label: "CSV-Runner verwalten" },
];
-const pointColors = [
- "#d62839",
- "#2563eb",
- "#ef4444",
- "#1d4ed8",
- "#f97316",
- "#0f766e",
- "#b91c1c",
- "#1e40af",
- "#dc2626",
- "#0891b2",
-];
-
-const DEFAULT_UNIT_OPTIONS = [
- { symbol: "°C", label: "Grad Celsius", isSystem: true },
- { symbol: "%", label: "Prozent", isSystem: true },
- { symbol: "K", label: "Kelvin", isSystem: true },
- { symbol: "V", label: "Volt", isSystem: true },
- { symbol: "A", label: "Ampere", isSystem: true },
- { symbol: "Pa", label: "Pascal", isSystem: true },
- { symbol: "bool", label: "Digital / Bool", isSystem: true },
-];
-const UNIT_PRESETS = DEFAULT_UNIT_OPTIONS.map((unit) => unit.symbol);
const CUSTOM_UNIT_VALUE = "__custom__";
const PROTOCOL_DEFAULT_PORTS = {
"modbus-tcp": "502",
@@ -178,8 +159,10 @@ function getDefaultPointDataType(protocol) {
return "holding-register";
}
-function getDefaultUnitForKind(kind) {
- return kind === "digital" ? "bool" : "°C";
+function unitForChangedKind(unit, kind) {
+ if (unit === AUTO_UNIT) return unit;
+ if (kind === "digital") return DIGITAL_UNIT;
+ return normalizeUnitSymbol(unit) === DIGITAL_UNIT ? AUTO_UNIT : unit;
}
function getPointDataTypeOptions(protocol) {
@@ -256,7 +239,7 @@ function normalizeDisplayUnit(value) {
if (!collapsed || /^\?C$/i.test(collapsed) || /^Â?°C$/i.test(collapsed) || (/[ÃÂ�]/.test(nextValue) && /(?:°|\?|C)/i.test(nextValue))) {
return "°C";
}
- return nextValue;
+ return normalizeUnitSymbol(nextValue);
}
function formatCollectorValue(value) {
@@ -393,7 +376,7 @@ function buildAliasCsv(aliasEditor) {
const rows = getOrderedPointEntries(aliasEditor).map((point) => [
point.pointIndex,
point.alias,
- point.unit,
+ resolveEngineeringUnit(point.unitAuto ? AUTO_UNIT : point.unit, point.kind, point.alias),
point.factor,
point.kind,
point.min,
@@ -416,29 +399,6 @@ function matchesSearch(filterText, values) {
return values.some((value) => normalizeDisplayText(value).toLowerCase().includes(search));
}
-function hashString(value) {
- return String(value)
- .split("")
- .reduce((sum, char) => sum + char.charCodeAt(0), 0);
-}
-
-function resolvePointColor(point, metadataCache) {
- const color = metadataCache[point.isp]?.points?.[String(point.pointIndex)]?.color;
- if (color) {
- return color;
- }
-
- const key = `${point.isp}:${point.pointIndex}`;
- return pointColors[hashString(key) % pointColors.length];
-}
-
-function resolveLatestColor(value) {
- if (value.color) {
- return value.color;
- }
- return pointColors[hashString(value.key) % pointColors.length];
-}
-
function getUserDisplayName(currentUser) {
if (!currentUser) {
return "";
@@ -453,20 +413,16 @@ function getUserDisplayName(currentUser) {
return name.toLowerCase() === username.toLowerCase() ? name : `${name} · @${username}`;
}
-function SmallFootnote() {
- return
by J.H. | SE Inno GmbH
;
-}
-
-function UnitField({ units, value, onChange }) {
+function UnitField({ units, value, onChange, alias, kind }) {
const options = units?.length ? units : DEFAULT_UNIT_OPTIONS;
const normalizedOptions = options.map((unit) => ({
...unit,
symbol: normalizeDisplayUnit(unit.symbol),
label: normalizeDisplayText(unit.label || unit.symbol, normalizeDisplayUnit(unit.symbol)),
}));
- const normalizedValue = normalizeDisplayUnit(value || "\u00B0C");
+ const normalizedValue = value ? normalizeDisplayUnit(value) : "";
const hasPresetMatch = normalizedOptions.some((unit) => unit.symbol === normalizedValue);
- const selectedValue = hasPresetMatch ? normalizedValue : CUSTOM_UNIT_VALUE;
+ const selectedValue = value === AUTO_UNIT || hasPresetMatch ? normalizedValue : CUSTOM_UNIT_VALUE;
return (
@@ -475,13 +431,14 @@ function UnitField({ units, value, onChange }) {
onChange={(event) => {
const nextValue = event.target.value;
if (nextValue === CUSTOM_UNIT_VALUE) {
- onChange(hasPresetMatch ? "" : normalizedValue);
+ onChange(selectedValue === CUSTOM_UNIT_VALUE ? normalizedValue : "");
return;
}
onChange(nextValue);
}}
>
- {normalizedOptions.map((unit) =>
)}
+
+ {normalizedOptions.map((unit) =>
)}
{selectedValue === CUSTOM_UNIT_VALUE ? (
@@ -520,12 +477,14 @@ function ScaleField({ value, onChange }) {
function ColorField({ value, onChange }) {
const normalizedValue = hslToHexString(value || "");
- const pickerValue = /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(normalizedValue || "") ? normalizedValue : "#d62839";
+ const pickerValue = /^#[0-9a-f]{6}$/i.test(normalizedValue) ? normalizedValue
+ : /^#[0-9a-f]{3}$/i.test(normalizedValue) ? "#" + [...normalizedValue.slice(1)].map((digit) => digit.repeat(2)).join("")
+ : "#000000";
return (
- onChange(event.target.value)} />
- onChange(event.target.value)} />
+ onChange(event.target.value)} />
+ onChange(event.target.value)} />
);
}
@@ -538,19 +497,6 @@ function TrashIcon() {
);
}
-function PinIcon({ pinned }) {
- return pinned ? (
-
- ) : (
-
- );
-}
-
function IconButton({ title, onClick, children, danger = false }) {
return (