Weiter zum Inhalt
  • Home
  • Aktuell
  • Tags
  • 0 Ungelesen 0
  • Kategorien
  • Unreplied
  • Beliebt
  • GitHub
  • Docu
  • Hilfe
Skins
  • Hell
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dunkel
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Standard: (Kein Skin)
  • Kein Skin
Einklappen
ioBroker Logo

Community Forum

donate donate
  1. ioBroker Community Home
  2. English
  3. Visualization
  4. Datenpunkt mit Start/ Endzeit in einem Diagramm

NEWS

  • Neuer ioBroker-Blog online: Monatsrückblick März/April 2026
    BluefoxB
    Bluefox
    7
    1
    270

  • Verwendung von KI bitte immer deutlich kennzeichnen
    HomoranH
    Homoran
    9
    1
    250

  • Monatsrückblick Januar/Februar 2026 ist online!
    BluefoxB
    Bluefox
    18
    1
    903

Datenpunkt mit Start/ Endzeit in einem Diagramm

Geplant Angeheftet Gesperrt Verschoben Visualization
25 Beiträge 3 Kommentatoren 160 Aufrufe 3 Beobachtet
  • Älteste zuerst
  • Neuste zuerst
  • Meiste Stimmen
Antworten
  • In einem neuen Thema antworten
Anmelden zum Antworten
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
  • WinniW Offline
    WinniW Offline
    Winni
    Most Active
    schrieb am zuletzt editiert von
    #8

    Super, danke 👍

    Es gibt nicht Gutes. Außer man tut es. Erich Kästner

    M 1 Antwort Letzte Antwort
    0
    • WinniW Winni

      Super, danke 👍

      M Online
      M Online
      MCU
      schrieb am zuletzt editiert von MCU
      #9

      @Winni
      https://mcuiobroker.gitbook.io/iobroker-tipps/tipps/scripte-blockly-javascript/flexcharts/beispiel-comparedays
      Ist noch nicht ganz komplett, aber man kann schon anfangen. Falls Fragen sind hier stellen. Danke.

      NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
      Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

      1 Antwort Letzte Antwort
      0
      • WinniW Offline
        WinniW Offline
        Winni
        Most Active
        schrieb am zuletzt editiert von
        #10

        Guten Morgen @mcu habe mal mit dem javascript compareDays angefangen.
        Ich habe unter Allgemeine Scripte einen Ordner Echarts erstellt und das .javascript compareDays mittels copy und past einkopier.
        Nach dem Start kommen bei mir leider eine Reihe von roten Fehlermeldungen:

        javascript.0	09:10:59.227	info	
        Stopping script
        javascript.0	09:10:59.257	info	
        start JavaScript (Javascript/js)
        javascript.0	09:10:59.259	error	
        compile failed at: script.js.common.Echarts.javascript_compareDays:2
        javascript.0	09:10:59.261	error	
        # javascript compareDays
        javascript.0	09:10:59.264	error	
        ^
        javascript.0	09:10:59.265	error	
        SyntaxError: Invalid or unexpected token
        javascript.0	09:10:59.265	error	
            at new Script (node:vm:117:7)
        javascript.0	09:10:59.265	error	
            at JavaScript.createVM (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2179:25)
        javascript.0	09:10:59.265	error	
            at JavaScript.prepareScript (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2481:44)
        javascript.0	09:10:59.265	error	
            at processTicksAndRejections (node:internal/process/task_queues:103:5)
        

        Ich habe allerdings mit javascript 0 Erfahrung, nur bisschen blockly.

        Es gibt nicht Gutes. Außer man tut es. Erich Kästner

        M 1 Antwort Letzte Antwort
        0
        • WinniW Winni

          Guten Morgen @mcu habe mal mit dem javascript compareDays angefangen.
          Ich habe unter Allgemeine Scripte einen Ordner Echarts erstellt und das .javascript compareDays mittels copy und past einkopier.
          Nach dem Start kommen bei mir leider eine Reihe von roten Fehlermeldungen:

          javascript.0	09:10:59.227	info	
          Stopping script
          javascript.0	09:10:59.257	info	
          start JavaScript (Javascript/js)
          javascript.0	09:10:59.259	error	
          compile failed at: script.js.common.Echarts.javascript_compareDays:2
          javascript.0	09:10:59.261	error	
          # javascript compareDays
          javascript.0	09:10:59.264	error	
          ^
          javascript.0	09:10:59.265	error	
          SyntaxError: Invalid or unexpected token
          javascript.0	09:10:59.265	error	
              at new Script (node:vm:117:7)
          javascript.0	09:10:59.265	error	
              at JavaScript.createVM (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2179:25)
          javascript.0	09:10:59.265	error	
              at JavaScript.prepareScript (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2481:44)
          javascript.0	09:10:59.265	error	
              at processTicksAndRejections (node:internal/process/task_queues:103:5)
          

          Ich habe allerdings mit javascript 0 Erfahrung, nur bisschen blockly.

          M Online
          M Online
          MCU
          schrieb zuletzt editiert von
          #11

          @Winni schau ich mir an

          NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
          Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

          M 1 Antwort Letzte Antwort
          1
          • M MCU

            @Winni schau ich mir an

            M Online
            M Online
            MCU
            schrieb zuletzt editiert von
            #12

            Du hast etwas hinzugefügt?
            Zeig mal ein Bild von dem was du wo geschrieben hast.

            NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
            Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

            1 Antwort Letzte Antwort
            0
            • WinniW Offline
              WinniW Offline
              Winni
              Most Active
              schrieb zuletzt editiert von
              #13

              Unter "Allgemeine Scripte" habe ich einen Ordner "Echarts" angelegt. Darin das Script "javascript compareDays"

              # javascript compareDays
              
              ## javascript compareDays
              
              ```js
              /***************************************************************
               * compareDays v1.0.0 
               * Copyright ©MCU
               ***************************************************************/
              
              const CONFIG_BASE = '0_userdata.0.flexCharts.Compare24Times';
              
              const DEFAULT_CURRENT_STYLE = {
                  type: 'line',
                  color: '',
                  lineStyle: 'solid',
                  lineWidth: 2,
                  area: false,
                  smooth: false,
                  symbol: 'none'
              };
              
              const DEFAULT_COMPARE_STYLE = {
                  type: 'line',
                  color: '',
                  lineStyle: 'solid',
                  lineWidth: 2,
                  area: false,
                  smooth: false,
                  symbol: 'none'
              };
              
              const DEFAULT_DELTA_STYLE = {
                  type: 'bar',
                  color: '',
                  lineStyle: 'solid',
                  lineWidth: 1,
                  area: false,
                  smooth: false,
                  symbol: 'none',
                  yAxisIndex: 1
              };
              
              const DEFAULT_COMPARE_DAYS = [1, 2, 3];
              
              const DEFAULTS = {
                  messageName: 'puffervergleich',
                  historyInstance: 'history.0',
                  dpId: '',
                  windowHours: 24,
                  compareDays: DEFAULT_COMPARE_DAYS.join(','),
                  maxCount: 2000,
                  fallbackUnit: '°C',
                  chartTitle: 'Pufferspeicher: aktuell vs. Vortage',
                  valueName: 'Temperatur',
                  urlBase: 'http://192.168.178.150:8082/flexcharts/echarts.html',
                  urlRefresh: 60,
                  generatedUrl: '',
                  deltaEnabled: false,
                  deltaSourceA: 'current',
                  deltaSourceB: 'day1',
                  deltaAreaEnabled: false,
                  deltaSmooth: false,
                  seriesConfig: JSON.stringify(buildDefaultSeriesConfigObject(DEFAULT_COMPARE_DAYS), null, 2)
              };
              
              let restartPending = false;
              let syncPending = false;
              
              start();
              
              function start() {
                  ensureConfigStates(() => {
                      refreshDeltaSourceStates();
                      synchronizeSeriesConfigState();
                      updateGeneratedUrl();
              
                      const config = readConfig();
                      log('flexCharts Compare24Times gestartet. messageName=' + config.messageName, 'info');
              
                      onMessage(config.messageName, (httpParams, callback) => {
                          createComparisonChart(callback);
                      });
              
                      on({ id: CONFIG_BASE + '.compareDays', ack: false, change: 'ne' }, () => {
                          refreshDeltaSourceStates();
                          synchronizeSeriesConfigState();
                          updateGeneratedUrl();
                      });
              
                      on({ id: CONFIG_BASE + '.seriesConfig', ack: false, change: 'ne' }, () => {
                          synchronizeSeriesConfigState();
                      });
              
                      on({ id: CONFIG_BASE + '.deltaSourceA', ack: false, change: 'ne' }, () => {
                          refreshDeltaSourceStates();
                      });
              
                      on({ id: CONFIG_BASE + '.deltaSourceB', ack: false, change: 'ne' }, () => {
                          refreshDeltaSourceStates();
                      });
              
                      on({ id: CONFIG_BASE + '.urlBase', ack: false, change: 'ne' }, () => {
                          updateGeneratedUrl();
                      });
              
                      on({ id: CONFIG_BASE + '.urlRefresh', ack: false, change: 'ne' }, () => {
                          updateGeneratedUrl();
                      });
              
                      on({ id: CONFIG_BASE + '.messageName', ack: false, change: 'ne' }, obj => {
                          if (restartPending) return;
              
                          const newValue = obj && obj.state ? String(obj.state.val || '').trim() : '';
                          updateGeneratedUrl();
              
                          if (!newValue) {
                              log('messageName ist leer, Script wird nicht neu gestartet', 'warn');
                              return;
                          }
              
                          restartPending = true;
                          log('messageName geändert auf "' + newValue + '" -> Script wird neu gestartet', 'info');
              
                          setTimeout(() => {
                              runScript(scriptName);
                          }, 200);
                      });
                  });
              }
              
              function ensureConfigStates(done) {
                  const defs = [
                      {
                          key: 'messageName',
                          def: DEFAULTS.messageName,
                          common: {
                              name: 'flexCharts Message-Name',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'historyInstance',
                          def: DEFAULTS.historyInstance,
                          common: {
                              name: 'History-Instanz',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'dpId',
                          def: DEFAULTS.dpId,
                          common: {
                              name: 'Datenpunkt-ID',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'windowHours',
                          def: DEFAULTS.windowHours,
                          common: {
                              name: 'Sichtbarer Zeitraum in Stunden',
                              type: 'number',
                              role: 'value',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'compareDays',
                          def: DEFAULTS.compareDays,
                          common: {
                              name: 'Vergleichstage, z.B. 1,2,3',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'maxCount',
                          def: DEFAULTS.maxCount,
                          common: {
                              name: 'Maximale Anzahl History-Werte',
                              type: 'number',
                              role: 'value',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'fallbackUnit',
                          def: DEFAULTS.fallbackUnit,
                          common: {
                              name: 'Fallback-Einheit',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'chartTitle',
                          def: DEFAULTS.chartTitle,
                          common: {
                              name: 'Chart-Titel',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'valueName',
                          def: DEFAULTS.valueName,
                          common: {
                              name: 'Name der Messgröße',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'urlBase',
                          def: DEFAULTS.urlBase,
                          common: {
                              name: 'Basis-URL für flexCharts',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'urlRefresh',
                          def: DEFAULTS.urlRefresh,
                          common: {
                              name: 'Refresh in Sekunden',
                              type: 'number',
                              role: 'value',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'generatedUrl',
                          def: DEFAULTS.generatedUrl,
                          common: {
                              name: 'Generierte flexCharts-URL',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: false
                          }
                      },
                      {
                          key: 'deltaEnabled',
                          def: DEFAULTS.deltaEnabled,
                          common: {
                              name: 'Delta aktiv',
                              type: 'boolean',
                              role: 'switch.enable',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'deltaSourceA',
                          def: DEFAULTS.deltaSourceA,
                          common: {
                              name: 'Delta Quelle A',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'deltaSourceB',
                          def: DEFAULTS.deltaSourceB,
                          common: {
                              name: 'Delta Quelle B',
                              type: 'string',
                              role: 'text',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'deltaAreaEnabled',
                          def: DEFAULTS.deltaAreaEnabled,
                          common: {
                              name: 'Delta als Fläche',
                              type: 'boolean',
                              role: 'switch.enable',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'deltaSmooth',
                          def: DEFAULTS.deltaSmooth,
                          common: {
                              name: 'Delta geglättet',
                              type: 'boolean',
                              role: 'switch.enable',
                              read: true,
                              write: true
                          }
                      },
                      {
                          key: 'seriesConfig',
                          def: DEFAULTS.seriesConfig,
                          common: {
                              name: 'Serien-Konfiguration als JSON',
                              type: 'string',
                              role: 'json',
                              read: true,
                              write: true
                          }
                      }
                  ];
              
                  let index = 0;
              
                  function next() {
                      if (index >= defs.length) {
                          done();
                          return;
                      }
              
                      const item = defs[index++];
                      const id = CONFIG_BASE + '.' + item.key;
              
                      if (existsState(id)) {
                          next();
                          return;
                      }
              
                      createState(id, item.def, false, item.common, {}, () => {
                          next();
                      });
                  }
              
                  next();
              }
              
              function refreshDeltaSourceStates() {
                  const compareDays = parseCompareDays(readString(CONFIG_BASE + '.compareDays', DEFAULTS.compareDays));
                  const statesMap = buildDeltaSourceStatesMap(compareDays);
              
                  try {
                      extendObject(CONFIG_BASE + '.deltaSourceA', {
                          common: {
                              states: statesMap
                          }
                      });
                  } catch (e) {
                      log('deltaSourceA common.states konnte nicht aktualisiert werden: ' + e.message, 'warn');
                  }
              
                  try {
                      extendObject(CONFIG_BASE + '.deltaSourceB', {
                          common: {
                              states: statesMap
                          }
                      });
                  } catch (e) {
                      log('deltaSourceB common.states konnte nicht aktualisiert werden: ' + e.message, 'warn');
                  }
              
                  ensureValidDeltaSources(statesMap, compareDays);
              }
              
              function buildDeltaSourceStatesMap(compareDays) {
                  const map = {
                      current: 'Aktuell'
                  };
              
                  for (let i = 0; i < compareDays.length; i++) {
                      const day = compareDays[i];
                      map['day' + day] = 'Vor ' + day + ' Tag' + (day > 1 ? 'en' : '');
                  }
              
                  return map;
              }
              
              function ensureValidDeltaSources(statesMap, compareDays) {
                  const validKeys = Object.keys(statesMap);
              
                  let sourceA = normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceA', DEFAULTS.deltaSourceA));
                  let sourceB = normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceB', DEFAULTS.deltaSourceB));
              
                  if (!validKeys.includes(sourceA)) {
                      sourceA = 'current';
                      setState(CONFIG_BASE + '.deltaSourceA', sourceA, true);
                  }
              
                  if (!validKeys.includes(sourceB)) {
                      sourceB = compareDays.length ? ('day' + compareDays[0]) : 'current';
                      setState(CONFIG_BASE + '.deltaSourceB', sourceB, true);
                  }
              
                  if (sourceA === sourceB) {
                      if (sourceA !== 'current') {
                          sourceA = 'current';
                          setState(CONFIG_BASE + '.deltaSourceA', sourceA, true);
                      } else if (compareDays.length) {
                          sourceB = 'day' + compareDays[0];
                          setState(CONFIG_BASE + '.deltaSourceB', sourceB, true);
                      }
                  }
              }
              
              function synchronizeSeriesConfigState() {
                  if (syncPending) return;
                  syncPending = true;
              
                  setTimeout(() => {
                      try {
                          const compareDays = parseCompareDays(readString(CONFIG_BASE + '.compareDays', DEFAULTS.compareDays));
                          const currentConfig = readSeriesConfig(compareDays);
                          saveSeriesConfigIfChanged(currentConfig);
                      } finally {
                          syncPending = false;
                      }
                  }, 50);
              }
              
              function readConfig() {
                  const compareDays = parseCompareDays(readString(CONFIG_BASE + '.compareDays', DEFAULTS.compareDays));
                  const seriesConfig = readSeriesConfig(compareDays);
              
                  return {
                      messageName: readString(CONFIG_BASE + '.messageName', DEFAULTS.messageName),
                      historyInstance: readString(CONFIG_BASE + '.historyInstance', DEFAULTS.historyInstance),
                      dpId: readString(CONFIG_BASE + '.dpId', DEFAULTS.dpId),
                      windowHours: Math.max(1, readNumber(CONFIG_BASE + '.windowHours', DEFAULTS.windowHours)),
                      compareDays: compareDays,
                      maxCount: Math.max(100, readNumber(CONFIG_BASE + '.maxCount', DEFAULTS.maxCount)),
                      fallbackUnit: readString(CONFIG_BASE + '.fallbackUnit', DEFAULTS.fallbackUnit),
                      chartTitle: readString(CONFIG_BASE + '.chartTitle', DEFAULTS.chartTitle),
                      valueName: readString(CONFIG_BASE + '.valueName', DEFAULTS.valueName),
                      urlBase: readString(CONFIG_BASE + '.urlBase', DEFAULTS.urlBase),
                      urlRefresh: Math.max(0, readNumber(CONFIG_BASE + '.urlRefresh', DEFAULTS.urlRefresh)),
                      deltaEnabled: readBoolean(CONFIG_BASE + '.deltaEnabled', DEFAULTS.deltaEnabled),
                      deltaSourceA: normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceA', DEFAULTS.deltaSourceA)),
                      deltaSourceB: normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceB', DEFAULTS.deltaSourceB)),
                      deltaAreaEnabled: readBoolean(CONFIG_BASE + '.deltaAreaEnabled', DEFAULTS.deltaAreaEnabled),
                      deltaSmooth: readBoolean(CONFIG_BASE + '.deltaSmooth', DEFAULTS.deltaSmooth),
                      seriesConfig: seriesConfig
                  };
              }
              
              function readSeriesConfig(compareDays) {
                  const id = CONFIG_BASE + '.seriesConfig';
                  const fallbackRaw = JSON.stringify(buildDefaultSeriesConfigObject(compareDays), null, 2);
                  const raw = readString(id, fallbackRaw);
              
                  let parsed;
                  try {
                      parsed = JSON.parse(raw);
                  } catch (e) {
                      log('seriesConfig JSON ungültig, setze Default zurück: ' + e.message, 'warn');
                      parsed = buildDefaultSeriesConfigObject(compareDays);
                      setState(id, JSON.stringify(parsed, null, 2), true);
                  }
              
                  const normalized = normalizeSeriesConfig(parsed);
                  const synced = syncStoredSeriesConfigWithCompareDays(normalized, compareDays);
              
                  return synced;
              }
              
              function syncStoredSeriesConfigWithCompareDays(cfg, compareDays) {
                  const result = cloneJson(cfg);
              
                  if (!result.compareByDay || typeof result.compareByDay !== 'object') {
                      result.compareByDay = {};
                  }
              
                  const compareDefault = normalizeSeriesStyle(result.compareDefault, DEFAULT_COMPARE_STYLE);
                  const validDayMap = {};
              
                  for (let i = 0; i < compareDays.length; i++) {
                      const dayKey = String(compareDays[i]);
                      validDayMap[dayKey] = true;
              
                      if (!result.compareByDay[dayKey] || typeof result.compareByDay[dayKey] !== 'object') {
                          result.compareByDay[dayKey] = cloneJson(compareDefault);
                      }
                  }
              
                  Object.keys(result.compareByDay).forEach(dayKey => {
                      if (validDayMap[dayKey]) {
                          return;
                      }
              
                      const entry = normalizeSeriesStyle(result.compareByDay[dayKey], compareDefault);
              
                      if (isJsonEqual(entry, compareDefault)) {
                          delete result.compareByDay[dayKey];
                      }
                  });
              
                  if (!result.delta || typeof result.delta !== 'object') {
                      result.delta = buildDefaultDeltaStyleConfig();
                  }
              
                  return normalizeSeriesConfig(result);
              }
              
              function saveSeriesConfigIfChanged(seriesConfig) {
                  const id = CONFIG_BASE + '.seriesConfig';
                  const currentRaw = readString(id, DEFAULTS.seriesConfig);
                  const nextRaw = JSON.stringify(seriesConfig, null, 2);
              
                  if (normalizeJsonString(currentRaw) !== normalizeJsonString(nextRaw)) {
                      setState(id, nextRaw, true);
                  }
              }
              
              function updateGeneratedUrl() {
                  const messageName = readString(CONFIG_BASE + '.messageName', DEFAULTS.messageName);
                  const urlBase = readString(CONFIG_BASE + '.urlBase', DEFAULTS.urlBase);
                  const urlRefresh = Math.max(0, readNumber(CONFIG_BASE + '.urlRefresh', DEFAULTS.urlRefresh));
              
                  const url = buildFlexUrl(urlBase, messageName, urlRefresh);
                  const id = CONFIG_BASE + '.generatedUrl';
                  const current = readString(id, '');
              
                  if (current !== url) {
                      setState(id, url, true);
                  }
              }
              
              function buildFlexUrl(baseUrl, messageName, refreshSeconds) {
                  const base = String(baseUrl || '').trim();
                  const msg = String(messageName || '').trim();
                  const refresh = Number(refreshSeconds);
              
                  if (!base || !msg) {
                      return '';
                  }
              
                  const separator = base.includes('?') ? '&' : '?';
                  let url = base + separator + 'source=script&message=' + encodeURIComponent(msg);
              
                  if (Number.isFinite(refresh) && refresh > 0) {
                      url += '&refresh=' + encodeURIComponent(String(refresh));
                  }
              
                  return url;
              }
              
              function normalizeSeriesConfig(cfg) {
                  const result = (cfg && typeof cfg === 'object') ? cloneJson(cfg) : {};
              
                  result.current = normalizeSeriesStyle(result.current, DEFAULT_CURRENT_STYLE);
                  result.compareDefault = normalizeSeriesStyle(result.compareDefault, DEFAULT_COMPARE_STYLE);
              
                  if (!result.compareByDay || typeof result.compareByDay !== 'object') {
                      result.compareByDay = {};
                  }
              
                  Object.keys(result.compareByDay).forEach(day => {
                      result.compareByDay[day] = normalizeSeriesStyle(result.compareByDay[day], result.compareDefault);
                  });
              
                  result.delta = normalizeDeltaStyle(result.delta, DEFAULT_DELTA_STYLE);
              
                  return result;
              }
              
              function normalizeSeriesStyle(style, defaults) {
                  const src = (style && typeof style === 'object') ? style : {};
                  const def = defaults || {};
              
                  return {
                      type: normalizeSeriesType(src.type !== undefined ? src.type : def.type),
                      color: String(src.color !== undefined ? src.color : def.color || '').trim(),
                      lineStyle: normalizeLineStyle(src.lineStyle !== undefined ? src.lineStyle : def.lineStyle),
                      lineWidth: Math.max(1, toNumber(src.lineWidth, def.lineWidth || 2)),
                      area: toBoolean(src.area, !!def.area),
                      smooth: toBoolean(src.smooth, !!def.smooth),
                      symbol: normalizeSymbol(src.symbol !== undefined ? src.symbol : def.symbol)
                  };
              }
              
              function normalizeDeltaStyle(style, defaults) {
                  const src = (style && typeof style === 'object') ? style : {};
                  const def = defaults || DEFAULT_DELTA_STYLE;
              
                  const base = normalizeSeriesStyle(src, def);
                  base.yAxisIndex = Math.max(0, parseInt(toNumber(src.yAxisIndex, def.yAxisIndex || 1), 10));
              
                  return base;
              }
              
              function normalizeSeriesType(type) {
                  const t = String(type || '').trim().toLowerCase();
                  if (t === 'line' || t === 'bar' || t === 'scatter') {
                      return t;
                  }
                  return 'line';
              }
              
              function normalizeLineStyle(style) {
                  const s = String(style || '').trim().toLowerCase();
                  if (s === 'solid' || s === 'dashed' || s === 'dotted') {
                      return s;
                  }
                  return 'solid';
              }
              
              function normalizeSymbol(symbol) {
                  const raw = String(symbol || '').trim();
                  const lower = raw.toLowerCase();
              
                  if (!raw || lower === 'none') {
                      return 'none';
                  }
              
                  const allowed = {
                      circle: 'circle',
                      rect: 'rect',
                      roundrect: 'roundRect',
                      roundRect: 'roundRect',
                      triangle: 'triangle',
                      diamond: 'diamond',
                      pin: 'pin',
                      arrow: 'arrow'
                  };
              
                  return allowed[raw] || allowed[lower] || 'none';
              }
              
              function normalizeSeriesRef(ref) {
                  const r = String(ref || '').trim().toLowerCase();
              
                  if (r === 'current') {
                      return 'current';
                  }
              
                  const m = r.match(/^day(\d+)$/);
                  if (m) {
                      return 'day' + parseInt(m[1], 10);
                  }
              
                  return 'current';
              }
              
              function buildDefaultSeriesConfigObject(compareDays) {
                  const compareByDay = {};
                  const days = Array.isArray(compareDays) && compareDays.length ? compareDays : DEFAULT_COMPARE_DAYS;
              
                  for (let i = 0; i < days.length; i++) {
                      compareByDay[String(days[i])] = cloneJson(DEFAULT_COMPARE_STYLE);
                  }
              
                  return {
                      current: cloneJson(DEFAULT_CURRENT_STYLE),
                      compareDefault: cloneJson(DEFAULT_COMPARE_STYLE),
                      compareByDay: compareByDay,
                      delta: buildDefaultDeltaStyleConfig()
                  };
              }
              
              function buildDefaultDeltaStyleConfig() {
                  return {
                      type: DEFAULT_DELTA_STYLE.type,
                      color: DEFAULT_DELTA_STYLE.color,
                      lineStyle: DEFAULT_DELTA_STYLE.lineStyle,
                      lineWidth: DEFAULT_DELTA_STYLE.lineWidth,
                      area: DEFAULT_DELTA_STYLE.area,
                      smooth: DEFAULT_DELTA_STYLE.smooth,
                      symbol: DEFAULT_DELTA_STYLE.symbol,
                      yAxisIndex: DEFAULT_DELTA_STYLE.yAxisIndex
                  };
              }
              
              function isJsonEqual(a, b) {
                  return normalizeJsonString(JSON.stringify(a)) === normalizeJsonString(JSON.stringify(b));
              }
              
              function normalizeJsonString(value) {
                  try {
                      return JSON.stringify(JSON.parse(String(value || '')));
                  } catch (e) {
                      return String(value || '').trim();
                  }
              }
              
              function cloneJson(obj) {
                  try {
                      return JSON.parse(JSON.stringify(obj || {}));
                  } catch (e) {
                      return {};
                  }
              }
              
              function toNumber(value, fallback) {
                  const n = Number(value);
                  return Number.isFinite(n) ? n : Number(fallback);
              }
              
              function toBoolean(value, fallback) {
                  if (value === true || value === false) {
                      return value;
                  }
              
                  if (typeof value === 'string') {
                      const v = value.trim().toLowerCase();
                      if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
                      if (v === 'false' || v === '0' || v === 'no' || v === 'off') return false;
                  }
              
                  if (typeof value === 'number') {
                      return value !== 0;
                  }
              
                  return !!fallback;
              }
              
              function readString(id, fallback) {
                  try {
                      if (!existsState(id)) return fallback;
                      const state = getState(id);
                      if (!state || state.val === null || state.val === undefined) return fallback;
                      const value = String(state.val).trim();
                      return value !== '' ? value : fallback;
                  } catch (e) {
                      return fallback;
                  }
              }
              
              function readNumber(id, fallback) {
                  try {
                      if (!existsState(id)) return fallback;
                      const state = getState(id);
                      if (!state || state.val === null || state.val === undefined) return fallback;
                      const value = Number(state.val);
                      return Number.isFinite(value) ? value : fallback;
                  } catch (e) {
                      return fallback;
                  }
              }
              
              function readBoolean(id, fallback) {
                  try {
                      if (!existsState(id)) return fallback;
                      const state = getState(id);
                      if (!state || state.val === null || state.val === undefined) return fallback;
                      return toBoolean(state.val, fallback);
                  } catch (e) {
                      return fallback;
                  }
              }
              
              function parseCompareDays(value) {
                  const result = [];
                  const used = {};
              
                  String(value || '')
                      .split(',')
                      .map(s => parseInt(String(s).trim(), 10))
                      .forEach(n => {
                          if (Number.isFinite(n) && n > 0 && !used[n]) {
                              used[n] = true;
                              result.push(n);
                          }
                      });
              
                  result.sort((a, b) => a - b);
              
                  if (!result.length) {
                      return [1];
                  }
              
                  return result;
              }
              
              function createComparisonChart(callback) {
                  const config = readConfig();
              
                  saveSeriesConfigIfChanged(config.seriesConfig);
                  updateGeneratedUrl();
              
                  const now = Date.now();
                  const windowMs = config.windowHours * 60 * 60 * 1000;
              
                  const startCurrent = now - windowMs;
                  const endCurrent = now;
              
                  const unit = getUnitFromObject(config.dpId) || config.fallbackUnit;
              
                  getHistorySeries(
                      config.historyInstance,
                      config.dpId,
                      startCurrent,
                      endCurrent,
                      config.maxCount,
                      (errCurrent, currentSeries) => {
                          if (errCurrent) {
                              callback(createErrorOption('Fehler beim Laden der aktuellen History: ' + stringifyError(errCurrent)));
                              return;
                          }
              
                          loadComparisonSeries(
                              config.historyInstance,
                              config.dpId,
                              startCurrent,
                              endCurrent,
                              config.compareDays,
                              config.maxCount,
                              (errCompare, compareSeriesList) => {
                                  if (errCompare) {
                                      callback(createErrorOption('Fehler beim Laden der Vergleichs-History: ' + stringifyError(errCompare)));
                                      return;
                                  }
              
                                  const allSeries = [];
              
                                  allSeries.push(buildSeriesObject(
                                      'Aktuell',
                                      currentSeries,
                                      config.seriesConfig.current,
                                      0
                                  ));
              
                                  for (let i = 0; i < compareSeriesList.length; i++) {
                                      const item = compareSeriesList[i];
                                      const dayStyle = config.seriesConfig.compareByDay[String(item.dayOffset)] || config.seriesConfig.compareDefault;
              
                                      allSeries.push(buildSeriesObject(
                                          'Vor ' + item.dayOffset + ' Tag' + (item.dayOffset > 1 ? 'en' : ''),
                                          item.data,
                                          dayStyle,
                                          0
                                      ));
                                  }
              
                                  const deltaBaseStyle = config.seriesConfig.delta;
                                  let deltaData = [];
              
                                  if (config.deltaEnabled && config.deltaSourceA !== config.deltaSourceB) {
                                      const sourceAData = getSeriesDataByRef(config.deltaSourceA, currentSeries, compareSeriesList);
                                      const sourceBData = getSeriesDataByRef(config.deltaSourceB, currentSeries, compareSeriesList);
              
                                      if (sourceAData.length && sourceBData.length) {
                                          deltaData = buildDeltaSeries(sourceAData, sourceBData);
              
                                          if (deltaData.length) {
                                              const effectiveDeltaStyle = cloneJson(deltaBaseStyle);
              
                                              if (config.deltaAreaEnabled) {
                                                  effectiveDeltaStyle.type = 'line';
                                                  effectiveDeltaStyle.area = true;
                                              }
              
                                              effectiveDeltaStyle.smooth = !!config.deltaSmooth;
              
                                              allSeries.push(buildSeriesObject(
                                                  'Δ ' + getSeriesLabelByRef(config.deltaSourceA) + ' - ' + getSeriesLabelByRef(config.deltaSourceB),
                                                  deltaData,
                                                  effectiveDeltaStyle,
                                                  effectiveDeltaStyle.yAxisIndex
                                              ));
                                          }
                                      }
                                  }
              
                                  const yAxis = [
                                      {
                                          type: 'value',
                                          name: config.valueName + ' [' + unit + ']',
                                          scale: true,
                                          axisLabel: {
                                              formatter: '{value} ' + unit
                                          }
                                      }
                                  ];
              
                                  if (deltaData.length) {
                                      yAxis.push({
                                          type: 'value',
                                          name: 'Δ [' + unit + ']',
                                          scale: true,
                                          axisLabel: {
                                              formatter: '{value} ' + unit
                                          }
                                      });
                                  }
              
                                  const option = {
                                      title: {
                                          text: config.chartTitle,
                                          left: 'center'
                                      },
                                      grid: {
                                          left: 80,
                                          right: 50,
                                          top: 70,
                                          bottom: 90
                                      },
                                      legend: {
                                          top: 35
                                      },
                                      tooltip: {
                                          trigger: 'axis',
                                          axisPointer: {
                                              type: 'cross'
                                          }
                                      },
                                      toolbox: {
                                          feature: {
                                              dataZoom: { yAxisIndex: 'none' },
                                              restore: {},
                                              saveAsImage: {}
                                          }
                                      },
                                      xAxis: {
                                          type: 'time',
                                          min: startCurrent,
                                          max: endCurrent,
                                          name: 'Zeit'
                                      },
                                      yAxis: yAxis,
                                      dataZoom: [
                                          {
                                              type: 'inside',
                                              start: 0,
                                              end: 100
                                          },
                                          {
                                              type: 'slider',
                                              start: 0,
                                              end: 100
                                          }
                                      ],
                                      series: allSeries
                                  };
              
                                  callback(option);
                              }
                          );
                      }
                  );
              }
              
              function buildSeriesObject(name, data, style, yAxisIndex) {
                  const series = {
                      name: name,
                      type: style.type,
                      data: data,
                      yAxisIndex: Number.isFinite(Number(yAxisIndex)) ? Number(yAxisIndex) : 0
                  };
              
                  if (style.type === 'line') {
                      series.showSymbol = style.symbol !== 'none';
                      series.symbol = style.symbol;
                      series.smooth = !!style.smooth;
                      series.connectNulls = false;
                      series.lineStyle = {
                          type: style.lineStyle,
                          width: style.lineWidth
                      };
              
                      if (style.color) {
                          series.lineStyle.color = style.color;
                          series.itemStyle = { color: style.color };
                      }
              
                      if (style.area) {
                          series.areaStyle = {};
                      }
                  }
              
                  if (style.type === 'scatter') {
                      series.symbol = style.symbol === 'none' ? 'circle' : style.symbol;
                      if (style.color) {
                          series.itemStyle = { color: style.color };
                      }
                  }
              
                  if (style.type === 'bar') {
                      if (style.color) {
                          series.itemStyle = { color: style.color };
                      }
                  }
              
                  return series;
              }
              
              function getSeriesDataByRef(ref, currentSeries, compareSeriesList) {
                  if (ref === 'current') {
                      return currentSeries;
                  }
              
                  const m = String(ref || '').match(/^day(\d+)$/);
                  if (!m) {
                      return [];
                  }
              
                  const day = parseInt(m[1], 10);
                  const found = compareSeriesList.find(item => item.dayOffset === day);
              
                  return found ? found.data : [];
              }
              
              function getSeriesLabelByRef(ref) {
                  if (ref === 'current') {
                      return 'Aktuell';
                  }
              
                  const m = String(ref || '').match(/^day(\d+)$/);
                  if (!m) {
                      return String(ref || '');
                  }
              
                  const day = parseInt(m[1], 10);
                  return 'Vor ' + day + ' Tag' + (day > 1 ? 'en' : '');
              }
              
              /**
               * Delta-Berechnung über die Vereinigungsmenge aller Zeitstempel.
               * Dadurch wird die Abweichung auch dann am Anfang gezeigt,
               * wenn nur eine der beiden Kurven dort schon einen Punkt hat.
               */
              function buildDeltaSeries(seriesA, seriesB) {
                  if (!Array.isArray(seriesA) || !Array.isArray(seriesB) || !seriesA.length || !seriesB.length) {
                      return [];
                  }
              
                  const a = seriesA
                      .map(item => [Number(item[0]), Number(item[1])])
                      .filter(item => Number.isFinite(item[0]) && Number.isFinite(item[1]))
                      .sort((x, y) => x[0] - y[0]);
              
                  const b = seriesB
                      .map(item => [Number(item[0]), Number(item[1])])
                      .filter(item => Number.isFinite(item[0]) && Number.isFinite(item[1]))
                      .sort((x, y) => x[0] - y[0]);
              
                  if (!a.length || !b.length) {
                      return [];
                  }
              
                  const timestamps = Array.from(new Set(
                      a.map(item => item[0]).concat(b.map(item => item[0]))
                  )).sort((x, y) => x - y);
              
                  let aIndex = 0;
                  let bIndex = 0;
                  let lastAVal = a[0][1];
                  let lastBVal = b[0][1];
              
                  const result = [];
              
                  for (let i = 0; i < timestamps.length; i++) {
                      const ts = timestamps[i];
              
                      while (aIndex < a.length && a[aIndex][0] <= ts) {
                          lastAVal = a[aIndex][1];
                          aIndex++;
                      }
              
                      while (bIndex < b.length && b[bIndex][0] <= ts) {
                          lastBVal = b[bIndex][1];
                          bIndex++;
                      }
              
                      if (!Number.isFinite(lastAVal) || !Number.isFinite(lastBVal)) {
                          continue;
                      }
              
                      result.push([ts, lastAVal - lastBVal]);
                  }
              
                  return result;
              }
              
              function loadComparisonSeries(historyInstance, dpId, startCurrent, endCurrent, compareDays, maxCount, cb) {
                  const results = [];
                  let index = 0;
              
                  function next() {
                      if (index >= compareDays.length) {
                          cb(null, results);
                          return;
                      }
              
                      const dayOffset = compareDays[index++];
                      const shiftMs = dayOffset * 24 * 60 * 60 * 1000;
              
                      const startPrevious = startCurrent - shiftMs;
                      const endPrevious = endCurrent - shiftMs;
              
                      getHistorySeries(historyInstance, dpId, startPrevious, endPrevious, maxCount, (err, previousSeriesRaw) => {
                          if (err) {
                              cb(err);
                              return;
                          }
              
                          const shifted = previousSeriesRaw.map(item => [item[0] + shiftMs, item[1]]);
              
                          results.push({
                              dayOffset: dayOffset,
                              data: shifted
                          });
              
                          next();
                      });
                  }
              
                  next();
              }
              
              function getHistorySeries(historyInstance, dpId, start, end, maxCount, cb) {
                  getHistory(historyInstance, {
                      id: dpId,
                      start: start,
                      end: end,
                      ack: true,
                      count: maxCount,
                      aggregate: 'none'
                  }, (err, result) => {
                      if (err) {
                          cb(err);
                          return;
                      }
              
                      const series = [];
              
                      if (Array.isArray(result)) {
                          for (let i = 0; i < result.length; i++) {
                              const item = result[i];
                              if (!item) continue;
              
                              const ts = Number(item.ts);
                              const val = Number(item.val);
              
                              if (!Number.isFinite(ts) || !Number.isFinite(val)) {
                                  continue;
                              }
              
                              series.push([ts, val]);
                          }
                      }
              
                      cb(null, series);
                  });
              }
              
              function getUnitFromObject(id) {
                  try {
                      const obj = getObject(id);
                      if (
                          obj &&
                          obj.common &&
                          typeof obj.common.unit === 'string' &&
                          obj.common.unit.trim() !== ''
                      ) {
                          return obj.common.unit.trim();
                      }
                  } catch (e) {
                      // nichts
                  }
                  return '';
              }
              
              function createErrorOption(message) {
                  return {
                      title: {
                          text: 'Fehler',
                          subtext: message,
                          left: 'center',
                          top: 'middle'
                      },
                      xAxis: {
                          type: 'time'
                      },
                      yAxis: {
                          type: 'value'
                      },
                      series: []
                  };
              }
              
              function stringifyError(err) {
                  try {
                      return typeof err === 'string' ? err : JSON.stringify(err);
                  } catch (e) {
                      return String(err);
                  }
              }
              

              Es gibt nicht Gutes. Außer man tut es. Erich Kästner

              M 1 Antwort Letzte Antwort
              0
              • WinniW Winni

                Unter "Allgemeine Scripte" habe ich einen Ordner "Echarts" angelegt. Darin das Script "javascript compareDays"

                # javascript compareDays
                
                ## javascript compareDays
                
                ```js
                /***************************************************************
                 * compareDays v1.0.0 
                 * Copyright ©MCU
                 ***************************************************************/
                
                const CONFIG_BASE = '0_userdata.0.flexCharts.Compare24Times';
                
                const DEFAULT_CURRENT_STYLE = {
                    type: 'line',
                    color: '',
                    lineStyle: 'solid',
                    lineWidth: 2,
                    area: false,
                    smooth: false,
                    symbol: 'none'
                };
                
                const DEFAULT_COMPARE_STYLE = {
                    type: 'line',
                    color: '',
                    lineStyle: 'solid',
                    lineWidth: 2,
                    area: false,
                    smooth: false,
                    symbol: 'none'
                };
                
                const DEFAULT_DELTA_STYLE = {
                    type: 'bar',
                    color: '',
                    lineStyle: 'solid',
                    lineWidth: 1,
                    area: false,
                    smooth: false,
                    symbol: 'none',
                    yAxisIndex: 1
                };
                
                const DEFAULT_COMPARE_DAYS = [1, 2, 3];
                
                const DEFAULTS = {
                    messageName: 'puffervergleich',
                    historyInstance: 'history.0',
                    dpId: '',
                    windowHours: 24,
                    compareDays: DEFAULT_COMPARE_DAYS.join(','),
                    maxCount: 2000,
                    fallbackUnit: '°C',
                    chartTitle: 'Pufferspeicher: aktuell vs. Vortage',
                    valueName: 'Temperatur',
                    urlBase: 'http://192.168.178.150:8082/flexcharts/echarts.html',
                    urlRefresh: 60,
                    generatedUrl: '',
                    deltaEnabled: false,
                    deltaSourceA: 'current',
                    deltaSourceB: 'day1',
                    deltaAreaEnabled: false,
                    deltaSmooth: false,
                    seriesConfig: JSON.stringify(buildDefaultSeriesConfigObject(DEFAULT_COMPARE_DAYS), null, 2)
                };
                
                let restartPending = false;
                let syncPending = false;
                
                start();
                
                function start() {
                    ensureConfigStates(() => {
                        refreshDeltaSourceStates();
                        synchronizeSeriesConfigState();
                        updateGeneratedUrl();
                
                        const config = readConfig();
                        log('flexCharts Compare24Times gestartet. messageName=' + config.messageName, 'info');
                
                        onMessage(config.messageName, (httpParams, callback) => {
                            createComparisonChart(callback);
                        });
                
                        on({ id: CONFIG_BASE + '.compareDays', ack: false, change: 'ne' }, () => {
                            refreshDeltaSourceStates();
                            synchronizeSeriesConfigState();
                            updateGeneratedUrl();
                        });
                
                        on({ id: CONFIG_BASE + '.seriesConfig', ack: false, change: 'ne' }, () => {
                            synchronizeSeriesConfigState();
                        });
                
                        on({ id: CONFIG_BASE + '.deltaSourceA', ack: false, change: 'ne' }, () => {
                            refreshDeltaSourceStates();
                        });
                
                        on({ id: CONFIG_BASE + '.deltaSourceB', ack: false, change: 'ne' }, () => {
                            refreshDeltaSourceStates();
                        });
                
                        on({ id: CONFIG_BASE + '.urlBase', ack: false, change: 'ne' }, () => {
                            updateGeneratedUrl();
                        });
                
                        on({ id: CONFIG_BASE + '.urlRefresh', ack: false, change: 'ne' }, () => {
                            updateGeneratedUrl();
                        });
                
                        on({ id: CONFIG_BASE + '.messageName', ack: false, change: 'ne' }, obj => {
                            if (restartPending) return;
                
                            const newValue = obj && obj.state ? String(obj.state.val || '').trim() : '';
                            updateGeneratedUrl();
                
                            if (!newValue) {
                                log('messageName ist leer, Script wird nicht neu gestartet', 'warn');
                                return;
                            }
                
                            restartPending = true;
                            log('messageName geändert auf "' + newValue + '" -> Script wird neu gestartet', 'info');
                
                            setTimeout(() => {
                                runScript(scriptName);
                            }, 200);
                        });
                    });
                }
                
                function ensureConfigStates(done) {
                    const defs = [
                        {
                            key: 'messageName',
                            def: DEFAULTS.messageName,
                            common: {
                                name: 'flexCharts Message-Name',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'historyInstance',
                            def: DEFAULTS.historyInstance,
                            common: {
                                name: 'History-Instanz',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'dpId',
                            def: DEFAULTS.dpId,
                            common: {
                                name: 'Datenpunkt-ID',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'windowHours',
                            def: DEFAULTS.windowHours,
                            common: {
                                name: 'Sichtbarer Zeitraum in Stunden',
                                type: 'number',
                                role: 'value',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'compareDays',
                            def: DEFAULTS.compareDays,
                            common: {
                                name: 'Vergleichstage, z.B. 1,2,3',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'maxCount',
                            def: DEFAULTS.maxCount,
                            common: {
                                name: 'Maximale Anzahl History-Werte',
                                type: 'number',
                                role: 'value',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'fallbackUnit',
                            def: DEFAULTS.fallbackUnit,
                            common: {
                                name: 'Fallback-Einheit',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'chartTitle',
                            def: DEFAULTS.chartTitle,
                            common: {
                                name: 'Chart-Titel',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'valueName',
                            def: DEFAULTS.valueName,
                            common: {
                                name: 'Name der Messgröße',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'urlBase',
                            def: DEFAULTS.urlBase,
                            common: {
                                name: 'Basis-URL für flexCharts',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'urlRefresh',
                            def: DEFAULTS.urlRefresh,
                            common: {
                                name: 'Refresh in Sekunden',
                                type: 'number',
                                role: 'value',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'generatedUrl',
                            def: DEFAULTS.generatedUrl,
                            common: {
                                name: 'Generierte flexCharts-URL',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: false
                            }
                        },
                        {
                            key: 'deltaEnabled',
                            def: DEFAULTS.deltaEnabled,
                            common: {
                                name: 'Delta aktiv',
                                type: 'boolean',
                                role: 'switch.enable',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'deltaSourceA',
                            def: DEFAULTS.deltaSourceA,
                            common: {
                                name: 'Delta Quelle A',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'deltaSourceB',
                            def: DEFAULTS.deltaSourceB,
                            common: {
                                name: 'Delta Quelle B',
                                type: 'string',
                                role: 'text',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'deltaAreaEnabled',
                            def: DEFAULTS.deltaAreaEnabled,
                            common: {
                                name: 'Delta als Fläche',
                                type: 'boolean',
                                role: 'switch.enable',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'deltaSmooth',
                            def: DEFAULTS.deltaSmooth,
                            common: {
                                name: 'Delta geglättet',
                                type: 'boolean',
                                role: 'switch.enable',
                                read: true,
                                write: true
                            }
                        },
                        {
                            key: 'seriesConfig',
                            def: DEFAULTS.seriesConfig,
                            common: {
                                name: 'Serien-Konfiguration als JSON',
                                type: 'string',
                                role: 'json',
                                read: true,
                                write: true
                            }
                        }
                    ];
                
                    let index = 0;
                
                    function next() {
                        if (index >= defs.length) {
                            done();
                            return;
                        }
                
                        const item = defs[index++];
                        const id = CONFIG_BASE + '.' + item.key;
                
                        if (existsState(id)) {
                            next();
                            return;
                        }
                
                        createState(id, item.def, false, item.common, {}, () => {
                            next();
                        });
                    }
                
                    next();
                }
                
                function refreshDeltaSourceStates() {
                    const compareDays = parseCompareDays(readString(CONFIG_BASE + '.compareDays', DEFAULTS.compareDays));
                    const statesMap = buildDeltaSourceStatesMap(compareDays);
                
                    try {
                        extendObject(CONFIG_BASE + '.deltaSourceA', {
                            common: {
                                states: statesMap
                            }
                        });
                    } catch (e) {
                        log('deltaSourceA common.states konnte nicht aktualisiert werden: ' + e.message, 'warn');
                    }
                
                    try {
                        extendObject(CONFIG_BASE + '.deltaSourceB', {
                            common: {
                                states: statesMap
                            }
                        });
                    } catch (e) {
                        log('deltaSourceB common.states konnte nicht aktualisiert werden: ' + e.message, 'warn');
                    }
                
                    ensureValidDeltaSources(statesMap, compareDays);
                }
                
                function buildDeltaSourceStatesMap(compareDays) {
                    const map = {
                        current: 'Aktuell'
                    };
                
                    for (let i = 0; i < compareDays.length; i++) {
                        const day = compareDays[i];
                        map['day' + day] = 'Vor ' + day + ' Tag' + (day > 1 ? 'en' : '');
                    }
                
                    return map;
                }
                
                function ensureValidDeltaSources(statesMap, compareDays) {
                    const validKeys = Object.keys(statesMap);
                
                    let sourceA = normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceA', DEFAULTS.deltaSourceA));
                    let sourceB = normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceB', DEFAULTS.deltaSourceB));
                
                    if (!validKeys.includes(sourceA)) {
                        sourceA = 'current';
                        setState(CONFIG_BASE + '.deltaSourceA', sourceA, true);
                    }
                
                    if (!validKeys.includes(sourceB)) {
                        sourceB = compareDays.length ? ('day' + compareDays[0]) : 'current';
                        setState(CONFIG_BASE + '.deltaSourceB', sourceB, true);
                    }
                
                    if (sourceA === sourceB) {
                        if (sourceA !== 'current') {
                            sourceA = 'current';
                            setState(CONFIG_BASE + '.deltaSourceA', sourceA, true);
                        } else if (compareDays.length) {
                            sourceB = 'day' + compareDays[0];
                            setState(CONFIG_BASE + '.deltaSourceB', sourceB, true);
                        }
                    }
                }
                
                function synchronizeSeriesConfigState() {
                    if (syncPending) return;
                    syncPending = true;
                
                    setTimeout(() => {
                        try {
                            const compareDays = parseCompareDays(readString(CONFIG_BASE + '.compareDays', DEFAULTS.compareDays));
                            const currentConfig = readSeriesConfig(compareDays);
                            saveSeriesConfigIfChanged(currentConfig);
                        } finally {
                            syncPending = false;
                        }
                    }, 50);
                }
                
                function readConfig() {
                    const compareDays = parseCompareDays(readString(CONFIG_BASE + '.compareDays', DEFAULTS.compareDays));
                    const seriesConfig = readSeriesConfig(compareDays);
                
                    return {
                        messageName: readString(CONFIG_BASE + '.messageName', DEFAULTS.messageName),
                        historyInstance: readString(CONFIG_BASE + '.historyInstance', DEFAULTS.historyInstance),
                        dpId: readString(CONFIG_BASE + '.dpId', DEFAULTS.dpId),
                        windowHours: Math.max(1, readNumber(CONFIG_BASE + '.windowHours', DEFAULTS.windowHours)),
                        compareDays: compareDays,
                        maxCount: Math.max(100, readNumber(CONFIG_BASE + '.maxCount', DEFAULTS.maxCount)),
                        fallbackUnit: readString(CONFIG_BASE + '.fallbackUnit', DEFAULTS.fallbackUnit),
                        chartTitle: readString(CONFIG_BASE + '.chartTitle', DEFAULTS.chartTitle),
                        valueName: readString(CONFIG_BASE + '.valueName', DEFAULTS.valueName),
                        urlBase: readString(CONFIG_BASE + '.urlBase', DEFAULTS.urlBase),
                        urlRefresh: Math.max(0, readNumber(CONFIG_BASE + '.urlRefresh', DEFAULTS.urlRefresh)),
                        deltaEnabled: readBoolean(CONFIG_BASE + '.deltaEnabled', DEFAULTS.deltaEnabled),
                        deltaSourceA: normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceA', DEFAULTS.deltaSourceA)),
                        deltaSourceB: normalizeSeriesRef(readString(CONFIG_BASE + '.deltaSourceB', DEFAULTS.deltaSourceB)),
                        deltaAreaEnabled: readBoolean(CONFIG_BASE + '.deltaAreaEnabled', DEFAULTS.deltaAreaEnabled),
                        deltaSmooth: readBoolean(CONFIG_BASE + '.deltaSmooth', DEFAULTS.deltaSmooth),
                        seriesConfig: seriesConfig
                    };
                }
                
                function readSeriesConfig(compareDays) {
                    const id = CONFIG_BASE + '.seriesConfig';
                    const fallbackRaw = JSON.stringify(buildDefaultSeriesConfigObject(compareDays), null, 2);
                    const raw = readString(id, fallbackRaw);
                
                    let parsed;
                    try {
                        parsed = JSON.parse(raw);
                    } catch (e) {
                        log('seriesConfig JSON ungültig, setze Default zurück: ' + e.message, 'warn');
                        parsed = buildDefaultSeriesConfigObject(compareDays);
                        setState(id, JSON.stringify(parsed, null, 2), true);
                    }
                
                    const normalized = normalizeSeriesConfig(parsed);
                    const synced = syncStoredSeriesConfigWithCompareDays(normalized, compareDays);
                
                    return synced;
                }
                
                function syncStoredSeriesConfigWithCompareDays(cfg, compareDays) {
                    const result = cloneJson(cfg);
                
                    if (!result.compareByDay || typeof result.compareByDay !== 'object') {
                        result.compareByDay = {};
                    }
                
                    const compareDefault = normalizeSeriesStyle(result.compareDefault, DEFAULT_COMPARE_STYLE);
                    const validDayMap = {};
                
                    for (let i = 0; i < compareDays.length; i++) {
                        const dayKey = String(compareDays[i]);
                        validDayMap[dayKey] = true;
                
                        if (!result.compareByDay[dayKey] || typeof result.compareByDay[dayKey] !== 'object') {
                            result.compareByDay[dayKey] = cloneJson(compareDefault);
                        }
                    }
                
                    Object.keys(result.compareByDay).forEach(dayKey => {
                        if (validDayMap[dayKey]) {
                            return;
                        }
                
                        const entry = normalizeSeriesStyle(result.compareByDay[dayKey], compareDefault);
                
                        if (isJsonEqual(entry, compareDefault)) {
                            delete result.compareByDay[dayKey];
                        }
                    });
                
                    if (!result.delta || typeof result.delta !== 'object') {
                        result.delta = buildDefaultDeltaStyleConfig();
                    }
                
                    return normalizeSeriesConfig(result);
                }
                
                function saveSeriesConfigIfChanged(seriesConfig) {
                    const id = CONFIG_BASE + '.seriesConfig';
                    const currentRaw = readString(id, DEFAULTS.seriesConfig);
                    const nextRaw = JSON.stringify(seriesConfig, null, 2);
                
                    if (normalizeJsonString(currentRaw) !== normalizeJsonString(nextRaw)) {
                        setState(id, nextRaw, true);
                    }
                }
                
                function updateGeneratedUrl() {
                    const messageName = readString(CONFIG_BASE + '.messageName', DEFAULTS.messageName);
                    const urlBase = readString(CONFIG_BASE + '.urlBase', DEFAULTS.urlBase);
                    const urlRefresh = Math.max(0, readNumber(CONFIG_BASE + '.urlRefresh', DEFAULTS.urlRefresh));
                
                    const url = buildFlexUrl(urlBase, messageName, urlRefresh);
                    const id = CONFIG_BASE + '.generatedUrl';
                    const current = readString(id, '');
                
                    if (current !== url) {
                        setState(id, url, true);
                    }
                }
                
                function buildFlexUrl(baseUrl, messageName, refreshSeconds) {
                    const base = String(baseUrl || '').trim();
                    const msg = String(messageName || '').trim();
                    const refresh = Number(refreshSeconds);
                
                    if (!base || !msg) {
                        return '';
                    }
                
                    const separator = base.includes('?') ? '&' : '?';
                    let url = base + separator + 'source=script&message=' + encodeURIComponent(msg);
                
                    if (Number.isFinite(refresh) && refresh > 0) {
                        url += '&refresh=' + encodeURIComponent(String(refresh));
                    }
                
                    return url;
                }
                
                function normalizeSeriesConfig(cfg) {
                    const result = (cfg && typeof cfg === 'object') ? cloneJson(cfg) : {};
                
                    result.current = normalizeSeriesStyle(result.current, DEFAULT_CURRENT_STYLE);
                    result.compareDefault = normalizeSeriesStyle(result.compareDefault, DEFAULT_COMPARE_STYLE);
                
                    if (!result.compareByDay || typeof result.compareByDay !== 'object') {
                        result.compareByDay = {};
                    }
                
                    Object.keys(result.compareByDay).forEach(day => {
                        result.compareByDay[day] = normalizeSeriesStyle(result.compareByDay[day], result.compareDefault);
                    });
                
                    result.delta = normalizeDeltaStyle(result.delta, DEFAULT_DELTA_STYLE);
                
                    return result;
                }
                
                function normalizeSeriesStyle(style, defaults) {
                    const src = (style && typeof style === 'object') ? style : {};
                    const def = defaults || {};
                
                    return {
                        type: normalizeSeriesType(src.type !== undefined ? src.type : def.type),
                        color: String(src.color !== undefined ? src.color : def.color || '').trim(),
                        lineStyle: normalizeLineStyle(src.lineStyle !== undefined ? src.lineStyle : def.lineStyle),
                        lineWidth: Math.max(1, toNumber(src.lineWidth, def.lineWidth || 2)),
                        area: toBoolean(src.area, !!def.area),
                        smooth: toBoolean(src.smooth, !!def.smooth),
                        symbol: normalizeSymbol(src.symbol !== undefined ? src.symbol : def.symbol)
                    };
                }
                
                function normalizeDeltaStyle(style, defaults) {
                    const src = (style && typeof style === 'object') ? style : {};
                    const def = defaults || DEFAULT_DELTA_STYLE;
                
                    const base = normalizeSeriesStyle(src, def);
                    base.yAxisIndex = Math.max(0, parseInt(toNumber(src.yAxisIndex, def.yAxisIndex || 1), 10));
                
                    return base;
                }
                
                function normalizeSeriesType(type) {
                    const t = String(type || '').trim().toLowerCase();
                    if (t === 'line' || t === 'bar' || t === 'scatter') {
                        return t;
                    }
                    return 'line';
                }
                
                function normalizeLineStyle(style) {
                    const s = String(style || '').trim().toLowerCase();
                    if (s === 'solid' || s === 'dashed' || s === 'dotted') {
                        return s;
                    }
                    return 'solid';
                }
                
                function normalizeSymbol(symbol) {
                    const raw = String(symbol || '').trim();
                    const lower = raw.toLowerCase();
                
                    if (!raw || lower === 'none') {
                        return 'none';
                    }
                
                    const allowed = {
                        circle: 'circle',
                        rect: 'rect',
                        roundrect: 'roundRect',
                        roundRect: 'roundRect',
                        triangle: 'triangle',
                        diamond: 'diamond',
                        pin: 'pin',
                        arrow: 'arrow'
                    };
                
                    return allowed[raw] || allowed[lower] || 'none';
                }
                
                function normalizeSeriesRef(ref) {
                    const r = String(ref || '').trim().toLowerCase();
                
                    if (r === 'current') {
                        return 'current';
                    }
                
                    const m = r.match(/^day(\d+)$/);
                    if (m) {
                        return 'day' + parseInt(m[1], 10);
                    }
                
                    return 'current';
                }
                
                function buildDefaultSeriesConfigObject(compareDays) {
                    const compareByDay = {};
                    const days = Array.isArray(compareDays) && compareDays.length ? compareDays : DEFAULT_COMPARE_DAYS;
                
                    for (let i = 0; i < days.length; i++) {
                        compareByDay[String(days[i])] = cloneJson(DEFAULT_COMPARE_STYLE);
                    }
                
                    return {
                        current: cloneJson(DEFAULT_CURRENT_STYLE),
                        compareDefault: cloneJson(DEFAULT_COMPARE_STYLE),
                        compareByDay: compareByDay,
                        delta: buildDefaultDeltaStyleConfig()
                    };
                }
                
                function buildDefaultDeltaStyleConfig() {
                    return {
                        type: DEFAULT_DELTA_STYLE.type,
                        color: DEFAULT_DELTA_STYLE.color,
                        lineStyle: DEFAULT_DELTA_STYLE.lineStyle,
                        lineWidth: DEFAULT_DELTA_STYLE.lineWidth,
                        area: DEFAULT_DELTA_STYLE.area,
                        smooth: DEFAULT_DELTA_STYLE.smooth,
                        symbol: DEFAULT_DELTA_STYLE.symbol,
                        yAxisIndex: DEFAULT_DELTA_STYLE.yAxisIndex
                    };
                }
                
                function isJsonEqual(a, b) {
                    return normalizeJsonString(JSON.stringify(a)) === normalizeJsonString(JSON.stringify(b));
                }
                
                function normalizeJsonString(value) {
                    try {
                        return JSON.stringify(JSON.parse(String(value || '')));
                    } catch (e) {
                        return String(value || '').trim();
                    }
                }
                
                function cloneJson(obj) {
                    try {
                        return JSON.parse(JSON.stringify(obj || {}));
                    } catch (e) {
                        return {};
                    }
                }
                
                function toNumber(value, fallback) {
                    const n = Number(value);
                    return Number.isFinite(n) ? n : Number(fallback);
                }
                
                function toBoolean(value, fallback) {
                    if (value === true || value === false) {
                        return value;
                    }
                
                    if (typeof value === 'string') {
                        const v = value.trim().toLowerCase();
                        if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
                        if (v === 'false' || v === '0' || v === 'no' || v === 'off') return false;
                    }
                
                    if (typeof value === 'number') {
                        return value !== 0;
                    }
                
                    return !!fallback;
                }
                
                function readString(id, fallback) {
                    try {
                        if (!existsState(id)) return fallback;
                        const state = getState(id);
                        if (!state || state.val === null || state.val === undefined) return fallback;
                        const value = String(state.val).trim();
                        return value !== '' ? value : fallback;
                    } catch (e) {
                        return fallback;
                    }
                }
                
                function readNumber(id, fallback) {
                    try {
                        if (!existsState(id)) return fallback;
                        const state = getState(id);
                        if (!state || state.val === null || state.val === undefined) return fallback;
                        const value = Number(state.val);
                        return Number.isFinite(value) ? value : fallback;
                    } catch (e) {
                        return fallback;
                    }
                }
                
                function readBoolean(id, fallback) {
                    try {
                        if (!existsState(id)) return fallback;
                        const state = getState(id);
                        if (!state || state.val === null || state.val === undefined) return fallback;
                        return toBoolean(state.val, fallback);
                    } catch (e) {
                        return fallback;
                    }
                }
                
                function parseCompareDays(value) {
                    const result = [];
                    const used = {};
                
                    String(value || '')
                        .split(',')
                        .map(s => parseInt(String(s).trim(), 10))
                        .forEach(n => {
                            if (Number.isFinite(n) && n > 0 && !used[n]) {
                                used[n] = true;
                                result.push(n);
                            }
                        });
                
                    result.sort((a, b) => a - b);
                
                    if (!result.length) {
                        return [1];
                    }
                
                    return result;
                }
                
                function createComparisonChart(callback) {
                    const config = readConfig();
                
                    saveSeriesConfigIfChanged(config.seriesConfig);
                    updateGeneratedUrl();
                
                    const now = Date.now();
                    const windowMs = config.windowHours * 60 * 60 * 1000;
                
                    const startCurrent = now - windowMs;
                    const endCurrent = now;
                
                    const unit = getUnitFromObject(config.dpId) || config.fallbackUnit;
                
                    getHistorySeries(
                        config.historyInstance,
                        config.dpId,
                        startCurrent,
                        endCurrent,
                        config.maxCount,
                        (errCurrent, currentSeries) => {
                            if (errCurrent) {
                                callback(createErrorOption('Fehler beim Laden der aktuellen History: ' + stringifyError(errCurrent)));
                                return;
                            }
                
                            loadComparisonSeries(
                                config.historyInstance,
                                config.dpId,
                                startCurrent,
                                endCurrent,
                                config.compareDays,
                                config.maxCount,
                                (errCompare, compareSeriesList) => {
                                    if (errCompare) {
                                        callback(createErrorOption('Fehler beim Laden der Vergleichs-History: ' + stringifyError(errCompare)));
                                        return;
                                    }
                
                                    const allSeries = [];
                
                                    allSeries.push(buildSeriesObject(
                                        'Aktuell',
                                        currentSeries,
                                        config.seriesConfig.current,
                                        0
                                    ));
                
                                    for (let i = 0; i < compareSeriesList.length; i++) {
                                        const item = compareSeriesList[i];
                                        const dayStyle = config.seriesConfig.compareByDay[String(item.dayOffset)] || config.seriesConfig.compareDefault;
                
                                        allSeries.push(buildSeriesObject(
                                            'Vor ' + item.dayOffset + ' Tag' + (item.dayOffset > 1 ? 'en' : ''),
                                            item.data,
                                            dayStyle,
                                            0
                                        ));
                                    }
                
                                    const deltaBaseStyle = config.seriesConfig.delta;
                                    let deltaData = [];
                
                                    if (config.deltaEnabled && config.deltaSourceA !== config.deltaSourceB) {
                                        const sourceAData = getSeriesDataByRef(config.deltaSourceA, currentSeries, compareSeriesList);
                                        const sourceBData = getSeriesDataByRef(config.deltaSourceB, currentSeries, compareSeriesList);
                
                                        if (sourceAData.length && sourceBData.length) {
                                            deltaData = buildDeltaSeries(sourceAData, sourceBData);
                
                                            if (deltaData.length) {
                                                const effectiveDeltaStyle = cloneJson(deltaBaseStyle);
                
                                                if (config.deltaAreaEnabled) {
                                                    effectiveDeltaStyle.type = 'line';
                                                    effectiveDeltaStyle.area = true;
                                                }
                
                                                effectiveDeltaStyle.smooth = !!config.deltaSmooth;
                
                                                allSeries.push(buildSeriesObject(
                                                    'Δ ' + getSeriesLabelByRef(config.deltaSourceA) + ' - ' + getSeriesLabelByRef(config.deltaSourceB),
                                                    deltaData,
                                                    effectiveDeltaStyle,
                                                    effectiveDeltaStyle.yAxisIndex
                                                ));
                                            }
                                        }
                                    }
                
                                    const yAxis = [
                                        {
                                            type: 'value',
                                            name: config.valueName + ' [' + unit + ']',
                                            scale: true,
                                            axisLabel: {
                                                formatter: '{value} ' + unit
                                            }
                                        }
                                    ];
                
                                    if (deltaData.length) {
                                        yAxis.push({
                                            type: 'value',
                                            name: 'Δ [' + unit + ']',
                                            scale: true,
                                            axisLabel: {
                                                formatter: '{value} ' + unit
                                            }
                                        });
                                    }
                
                                    const option = {
                                        title: {
                                            text: config.chartTitle,
                                            left: 'center'
                                        },
                                        grid: {
                                            left: 80,
                                            right: 50,
                                            top: 70,
                                            bottom: 90
                                        },
                                        legend: {
                                            top: 35
                                        },
                                        tooltip: {
                                            trigger: 'axis',
                                            axisPointer: {
                                                type: 'cross'
                                            }
                                        },
                                        toolbox: {
                                            feature: {
                                                dataZoom: { yAxisIndex: 'none' },
                                                restore: {},
                                                saveAsImage: {}
                                            }
                                        },
                                        xAxis: {
                                            type: 'time',
                                            min: startCurrent,
                                            max: endCurrent,
                                            name: 'Zeit'
                                        },
                                        yAxis: yAxis,
                                        dataZoom: [
                                            {
                                                type: 'inside',
                                                start: 0,
                                                end: 100
                                            },
                                            {
                                                type: 'slider',
                                                start: 0,
                                                end: 100
                                            }
                                        ],
                                        series: allSeries
                                    };
                
                                    callback(option);
                                }
                            );
                        }
                    );
                }
                
                function buildSeriesObject(name, data, style, yAxisIndex) {
                    const series = {
                        name: name,
                        type: style.type,
                        data: data,
                        yAxisIndex: Number.isFinite(Number(yAxisIndex)) ? Number(yAxisIndex) : 0
                    };
                
                    if (style.type === 'line') {
                        series.showSymbol = style.symbol !== 'none';
                        series.symbol = style.symbol;
                        series.smooth = !!style.smooth;
                        series.connectNulls = false;
                        series.lineStyle = {
                            type: style.lineStyle,
                            width: style.lineWidth
                        };
                
                        if (style.color) {
                            series.lineStyle.color = style.color;
                            series.itemStyle = { color: style.color };
                        }
                
                        if (style.area) {
                            series.areaStyle = {};
                        }
                    }
                
                    if (style.type === 'scatter') {
                        series.symbol = style.symbol === 'none' ? 'circle' : style.symbol;
                        if (style.color) {
                            series.itemStyle = { color: style.color };
                        }
                    }
                
                    if (style.type === 'bar') {
                        if (style.color) {
                            series.itemStyle = { color: style.color };
                        }
                    }
                
                    return series;
                }
                
                function getSeriesDataByRef(ref, currentSeries, compareSeriesList) {
                    if (ref === 'current') {
                        return currentSeries;
                    }
                
                    const m = String(ref || '').match(/^day(\d+)$/);
                    if (!m) {
                        return [];
                    }
                
                    const day = parseInt(m[1], 10);
                    const found = compareSeriesList.find(item => item.dayOffset === day);
                
                    return found ? found.data : [];
                }
                
                function getSeriesLabelByRef(ref) {
                    if (ref === 'current') {
                        return 'Aktuell';
                    }
                
                    const m = String(ref || '').match(/^day(\d+)$/);
                    if (!m) {
                        return String(ref || '');
                    }
                
                    const day = parseInt(m[1], 10);
                    return 'Vor ' + day + ' Tag' + (day > 1 ? 'en' : '');
                }
                
                /**
                 * Delta-Berechnung über die Vereinigungsmenge aller Zeitstempel.
                 * Dadurch wird die Abweichung auch dann am Anfang gezeigt,
                 * wenn nur eine der beiden Kurven dort schon einen Punkt hat.
                 */
                function buildDeltaSeries(seriesA, seriesB) {
                    if (!Array.isArray(seriesA) || !Array.isArray(seriesB) || !seriesA.length || !seriesB.length) {
                        return [];
                    }
                
                    const a = seriesA
                        .map(item => [Number(item[0]), Number(item[1])])
                        .filter(item => Number.isFinite(item[0]) && Number.isFinite(item[1]))
                        .sort((x, y) => x[0] - y[0]);
                
                    const b = seriesB
                        .map(item => [Number(item[0]), Number(item[1])])
                        .filter(item => Number.isFinite(item[0]) && Number.isFinite(item[1]))
                        .sort((x, y) => x[0] - y[0]);
                
                    if (!a.length || !b.length) {
                        return [];
                    }
                
                    const timestamps = Array.from(new Set(
                        a.map(item => item[0]).concat(b.map(item => item[0]))
                    )).sort((x, y) => x - y);
                
                    let aIndex = 0;
                    let bIndex = 0;
                    let lastAVal = a[0][1];
                    let lastBVal = b[0][1];
                
                    const result = [];
                
                    for (let i = 0; i < timestamps.length; i++) {
                        const ts = timestamps[i];
                
                        while (aIndex < a.length && a[aIndex][0] <= ts) {
                            lastAVal = a[aIndex][1];
                            aIndex++;
                        }
                
                        while (bIndex < b.length && b[bIndex][0] <= ts) {
                            lastBVal = b[bIndex][1];
                            bIndex++;
                        }
                
                        if (!Number.isFinite(lastAVal) || !Number.isFinite(lastBVal)) {
                            continue;
                        }
                
                        result.push([ts, lastAVal - lastBVal]);
                    }
                
                    return result;
                }
                
                function loadComparisonSeries(historyInstance, dpId, startCurrent, endCurrent, compareDays, maxCount, cb) {
                    const results = [];
                    let index = 0;
                
                    function next() {
                        if (index >= compareDays.length) {
                            cb(null, results);
                            return;
                        }
                
                        const dayOffset = compareDays[index++];
                        const shiftMs = dayOffset * 24 * 60 * 60 * 1000;
                
                        const startPrevious = startCurrent - shiftMs;
                        const endPrevious = endCurrent - shiftMs;
                
                        getHistorySeries(historyInstance, dpId, startPrevious, endPrevious, maxCount, (err, previousSeriesRaw) => {
                            if (err) {
                                cb(err);
                                return;
                            }
                
                            const shifted = previousSeriesRaw.map(item => [item[0] + shiftMs, item[1]]);
                
                            results.push({
                                dayOffset: dayOffset,
                                data: shifted
                            });
                
                            next();
                        });
                    }
                
                    next();
                }
                
                function getHistorySeries(historyInstance, dpId, start, end, maxCount, cb) {
                    getHistory(historyInstance, {
                        id: dpId,
                        start: start,
                        end: end,
                        ack: true,
                        count: maxCount,
                        aggregate: 'none'
                    }, (err, result) => {
                        if (err) {
                            cb(err);
                            return;
                        }
                
                        const series = [];
                
                        if (Array.isArray(result)) {
                            for (let i = 0; i < result.length; i++) {
                                const item = result[i];
                                if (!item) continue;
                
                                const ts = Number(item.ts);
                                const val = Number(item.val);
                
                                if (!Number.isFinite(ts) || !Number.isFinite(val)) {
                                    continue;
                                }
                
                                series.push([ts, val]);
                            }
                        }
                
                        cb(null, series);
                    });
                }
                
                function getUnitFromObject(id) {
                    try {
                        const obj = getObject(id);
                        if (
                            obj &&
                            obj.common &&
                            typeof obj.common.unit === 'string' &&
                            obj.common.unit.trim() !== ''
                        ) {
                            return obj.common.unit.trim();
                        }
                    } catch (e) {
                        // nichts
                    }
                    return '';
                }
                
                function createErrorOption(message) {
                    return {
                        title: {
                            text: 'Fehler',
                            subtext: message,
                            left: 'center',
                            top: 'middle'
                        },
                        xAxis: {
                            type: 'time'
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: []
                    };
                }
                
                function stringifyError(err) {
                    try {
                        return typeof err === 'string' ? err : JSON.stringify(err);
                    } catch (e) {
                        return String(err);
                    }
                }
                
                M Online
                M Online
                MCU
                schrieb zuletzt editiert von MCU
                #14

                @Winni Im Ordner Allgemeine Skripte darf nur etwas stehen , was alle Skripte nutzen. Also dort das compareDays löschen.

                Du musst einen Ordner nicht im Allgemeine Scripte erstellen.
                9299ca0d-998c-4d38-945f-5b4cc61a492f-image.jpeg
                Im Skript selbst darf kein # stehen.

                ab5da5a8-852b-4944-a921-595f7d80b072-image.jpeg

                NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
                Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

                paul53P WinniW 2 Antworten Letzte Antwort
                0
                • M MCU

                  @Winni Im Ordner Allgemeine Skripte darf nur etwas stehen , was alle Skripte nutzen. Also dort das compareDays löschen.

                  Du musst einen Ordner nicht im Allgemeine Scripte erstellen.
                  9299ca0d-998c-4d38-945f-5b4cc61a492f-image.jpeg
                  Im Skript selbst darf kein # stehen.

                  ab5da5a8-852b-4944-a921-595f7d80b072-image.jpeg

                  paul53P Offline
                  paul53P Offline
                  paul53
                  schrieb zuletzt editiert von paul53
                  #15

                  @MCU [sagte]: Im Ordner Allgemeine Skripte darf nur etwas stehen , was alle Skripte nutzen.

                  Nein, das trifft nur auf den Ordner "Globale Skripte (global)" zu.
                  Unter "Allgemeine Skripte" können beliebige Skripte stehen.

                  Bitte verzichtet auf Chat-Nachrichten, denn die Handhabung ist grauenhaft !
                  Produktiv: RPi 2 mit S.USV, HM-MOD-RPI und SLC-USB-Stick mit root fs

                  M 1 Antwort Letzte Antwort
                  0
                  • paul53P paul53

                    @MCU [sagte]: Im Ordner Allgemeine Skripte darf nur etwas stehen , was alle Skripte nutzen.

                    Nein, das trifft nur auf den Ordner "Globale Skripte (global)" zu.
                    Unter "Allgemeine Skripte" können beliebige Skripte stehen.

                    M Online
                    M Online
                    MCU
                    schrieb zuletzt editiert von
                    #16

                    @paul53 Stimmt.

                    NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
                    Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

                    1 Antwort Letzte Antwort
                    0
                    • M MCU

                      @Winni Im Ordner Allgemeine Skripte darf nur etwas stehen , was alle Skripte nutzen. Also dort das compareDays löschen.

                      Du musst einen Ordner nicht im Allgemeine Scripte erstellen.
                      9299ca0d-998c-4d38-945f-5b4cc61a492f-image.jpeg
                      Im Skript selbst darf kein # stehen.

                      ab5da5a8-852b-4944-a921-595f7d80b072-image.jpeg

                      WinniW Offline
                      WinniW Offline
                      Winni
                      Most Active
                      schrieb zuletzt editiert von Winni
                      #17

                      @MCU habe die # entfernt, aber jetzt schaut es so aus:
                      1000019516.jpg

                      javascript.0	10:49:06.505	info	
                      Stopping script
                      javascript.0	10:49:06.512	info	
                      start JavaScript (Javascript/js)
                      javascript.0	10:49:06.515	error	
                      compile failed at: script.js.common.Echarts.javascript_compareDays:1207
                      javascript.0	10:49:06.515	error	
                      log(`registered ${__engine.__subscriptions} subscription${__engine.__subscriptions === 1 ? '' : 's'}, ${__engine.__schedules} schedule${__engine.__schedules === 1 ? '' : 's'}, ${__engine.__subscriptionsMessage} message${__engine.__subscriptionsMessage === 1 ? '' : 's'}, ${__engine.__subscriptionsLog} log${__engine.__subscriptionsLog === 1 ? '' : 's'} and ${__engine.__subscriptionsFile} file subscription${__engine.__subscriptionsFile === 1 ? '' : 's'}`);
                      javascript.0	10:49:06.515	error	
                           ^^^^^^^^^^
                      javascript.0	10:49:06.515	error	
                      SyntaxError: Unexpected identifier 'registered'
                      javascript.0	10:49:06.515	error	
                          at new Script (node:vm:117:7)
                      javascript.0	10:49:06.516	error	
                          at JavaScript.createVM (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2179:25)
                      javascript.0	10:49:06.516	error	
                          at JavaScript.prepareScript (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2481:44)
                      javascript.0	10:49:06.516	error	
                          at processTicksAndRejections (node:internal/process/task_queues:103:5)
                      

                      PS: Danke auch an @paul53 fürs mit schauen.

                      Es gibt nicht Gutes. Außer man tut es. Erich Kästner

                      M 1 Antwort Letzte Antwort
                      0
                      • WinniW Winni

                        @MCU habe die # entfernt, aber jetzt schaut es so aus:
                        1000019516.jpg

                        javascript.0	10:49:06.505	info	
                        Stopping script
                        javascript.0	10:49:06.512	info	
                        start JavaScript (Javascript/js)
                        javascript.0	10:49:06.515	error	
                        compile failed at: script.js.common.Echarts.javascript_compareDays:1207
                        javascript.0	10:49:06.515	error	
                        log(`registered ${__engine.__subscriptions} subscription${__engine.__subscriptions === 1 ? '' : 's'}, ${__engine.__schedules} schedule${__engine.__schedules === 1 ? '' : 's'}, ${__engine.__subscriptionsMessage} message${__engine.__subscriptionsMessage === 1 ? '' : 's'}, ${__engine.__subscriptionsLog} log${__engine.__subscriptionsLog === 1 ? '' : 's'} and ${__engine.__subscriptionsFile} file subscription${__engine.__subscriptionsFile === 1 ? '' : 's'}`);
                        javascript.0	10:49:06.515	error	
                             ^^^^^^^^^^
                        javascript.0	10:49:06.515	error	
                        SyntaxError: Unexpected identifier 'registered'
                        javascript.0	10:49:06.515	error	
                            at new Script (node:vm:117:7)
                        javascript.0	10:49:06.516	error	
                            at JavaScript.createVM (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2179:25)
                        javascript.0	10:49:06.516	error	
                            at JavaScript.prepareScript (/opt/iobroker/node_modules/iobroker.javascript/src/main.ts:2481:44)
                        javascript.0	10:49:06.516	error	
                            at processTicksAndRejections (node:internal/process/task_queues:103:5)
                        

                        PS: Danke auch an @paul53 fürs mit schauen.

                        M Online
                        M Online
                        MCU
                        schrieb zuletzt editiert von MCU
                        #18

                        @Winni Bei dir ist noch eine Zeile drin

                        log(`registered....
                        

                        Diese löschen.
                        Am Besten das Skript neu laden.
                        https://mcuiobroker.gitbook.io/iobroker-tipps/tipps/scripte-blockly-javascript/flexcharts/beispiel-comparedays/javascript-comparedays

                        NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
                        Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

                        WinniW 1 Antwort Letzte Antwort
                        0
                        • M MCU

                          @Winni Bei dir ist noch eine Zeile drin

                          log(`registered....
                          

                          Diese löschen.
                          Am Besten das Skript neu laden.
                          https://mcuiobroker.gitbook.io/iobroker-tipps/tipps/scripte-blockly-javascript/flexcharts/beispiel-comparedays/javascript-comparedays

                          WinniW Offline
                          WinniW Offline
                          Winni
                          Most Active
                          schrieb zuletzt editiert von
                          #19

                          @MCU Jetzt kommen keine Fehlermeldungen mehr 😀

                          javascript.0	11:17:31.101	info	
                          Stopping script
                          javascript.0	11:17:31.109	info	
                          start JavaScript (Javascript/js)
                          javascript.0	11:17:31.114	info	
                          flexCharts Compare24Times gestartet. messageName=puffervergleich
                          javascript.0	11:17:31.114	info	
                          registered 7 subscriptions, 0 schedules, 1 message, 0 logs and 0 file subscriptions
                          

                          Es gibt nicht Gutes. Außer man tut es. Erich Kästner

                          1 Antwort Letzte Antwort
                          0
                          • WinniW Offline
                            WinniW Offline
                            Winni
                            Most Active
                            schrieb zuletzt editiert von
                            #20

                            @mcu Wirklich weiter komme auch jetzt nicht. Ich sehe keine Möglichkeit Diagramme zu erstellen bzw. zu ändern. Vielleicht kannst du mir da nochmal auf die Sprünge helfen.

                            Es gibt nicht Gutes. Außer man tut es. Erich Kästner

                            M 2 Antworten Letzte Antwort
                            0
                            • WinniW Winni

                              @mcu Wirklich weiter komme auch jetzt nicht. Ich sehe keine Möglichkeit Diagramme zu erstellen bzw. zu ändern. Vielleicht kannst du mir da nochmal auf die Sprünge helfen.

                              M Online
                              M Online
                              MCU
                              schrieb zuletzt editiert von MCU
                              #21

                              @Winni Du hast doch jetzt DPs erhalten.
                              Im DP 0_userdata.0.flexCharts.compareDays.dpId gibst du Deine ID ein, von der du jetzt die unterschiedlichen History-Werte vergleichen willst.

                              Im DP 0_userdata.0.flexCharts.compareDays.historyInstance gibst du die Instanz ein, mit der du die History speicherst. also history.0 oder sql.0 oder influxdb.0

                              Im DP 0_userdata.0.flexCharts.compareDays.urlBase musst du die ioBroker-Server-IP und den Port evtl anpassen. (http / https Protocoll)?

                              Im DP 0_userdata.0.flexCharts.compareDays.compareDays gibst du kommagetrennt an, welche Tage du mit heute vergleichen willst. Gestern -> 1, vorgestern -> 2 usw.
                              willst du mehrere Kurven sehen, dann 1,2,3 usw.

                              Wenn das alles passt hast du im DP 0_userdata.0.flexCharts.compareDays.generatedUrl jetzt eine URL die du direkt im Browser nutzen kannst oder als iFrame-Url nutzt.

                              NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
                              Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

                              1 Antwort Letzte Antwort
                              0
                              • WinniW Winni

                                @mcu Wirklich weiter komme auch jetzt nicht. Ich sehe keine Möglichkeit Diagramme zu erstellen bzw. zu ändern. Vielleicht kannst du mir da nochmal auf die Sprünge helfen.

                                M Online
                                M Online
                                MCU
                                schrieb zuletzt editiert von MCU
                                #22

                                @Winni Weiter gekommen?

                                NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
                                Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

                                1 Antwort Letzte Antwort
                                0
                                • WinniW Offline
                                  WinniW Offline
                                  Winni
                                  Most Active
                                  schrieb zuletzt editiert von
                                  #23

                                  Wow, fantastisch 😀, hat funktioniert. Was ich jetzt noch nicht verstanden habe, muss man für jedes neue Diagramm ein neues Script anlegen und entsprechend anpassen?

                                  Es gibt nicht Gutes. Außer man tut es. Erich Kästner

                                  M 1 Antwort Letzte Antwort
                                  0
                                  • WinniW Offline
                                    WinniW Offline
                                    Winni
                                    Most Active
                                    schrieb zuletzt editiert von Winni
                                    #24

                                    Ok, ich glaube ich komme der Sache näher. Habe das Script kopiert und testweise einen Parameter (Zeitraum) geändert. Hat funktioniert. 1000019520.jpgMorgen mach ich weiter. Vielen Dank für deine Unterstützung.

                                    Es gibt nicht Gutes. Außer man tut es. Erich Kästner

                                    1 Antwort Letzte Antwort
                                    0
                                    • WinniW Winni

                                      Wow, fantastisch 😀, hat funktioniert. Was ich jetzt noch nicht verstanden habe, muss man für jedes neue Diagramm ein neues Script anlegen und entsprechend anpassen?

                                      M Online
                                      M Online
                                      MCU
                                      schrieb zuletzt editiert von MCU
                                      #25

                                      @Winni Ja momentan ist das so. Wie viele Diagramme möchtest du denn haben?
                                      Alle mit den gleichen Parametern? Also heute und gestern

                                      Man kann das Programm auch anpassen für mehrere DPs und andere Optionen. man muss halt wissen, was du, wie brauchst.

                                      Man kann es auch so machen,. dass man die DPs (vordefiniert im DP als Array) im Diagramm auswählen kann und dann die Diagramme angezeigt werden zum DP.

                                      NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
                                      Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

                                      1 Antwort Letzte Antwort
                                      0

                                      Hey! Du scheinst an dieser Unterhaltung interessiert zu sein, hast aber noch kein Konto.

                                      Hast du es satt, bei jedem Besuch durch die gleichen Beiträge zu scrollen? Wenn du dich für ein Konto anmeldest, kommst du immer genau dorthin zurück, wo du zuvor warst, und kannst dich über neue Antworten benachrichtigen lassen (entweder per E-Mail oder Push-Benachrichtigung). Du kannst auch Lesezeichen speichern und Beiträge positiv bewerten, um anderen Community-Mitgliedern deine Wertschätzung zu zeigen.

                                      Mit deinem Input könnte dieser Beitrag noch besser werden 💗

                                      Registrieren Anmelden
                                      Antworten
                                      • In einem neuen Thema antworten
                                      Anmelden zum Antworten
                                      • Älteste zuerst
                                      • Neuste zuerst
                                      • Meiste Stimmen


                                      Support us

                                      ioBroker
                                      Community Adapters
                                      Donate

                                      633

                                      Online

                                      32.8k

                                      Benutzer

                                      82.8k

                                      Themen

                                      1.3m

                                      Beiträge
                                      Community
                                      Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
                                      ioBroker Community 2014-2025
                                      logo
                                      • Anmelden

                                      • Du hast noch kein Konto? Registrieren

                                      • Anmelden oder registrieren, um zu suchen
                                      • Erster Beitrag
                                        Letzter Beitrag
                                      0
                                      • Home
                                      • Aktuell
                                      • Tags
                                      • Ungelesen 0
                                      • Kategorien
                                      • Unreplied
                                      • Beliebt
                                      • GitHub
                                      • Docu
                                      • Hilfe