Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. [Vorlage] Skript: Erstellen von User-Datenpunkten

    NEWS

    • [erledigt] 15. 05. Wartungsarbeiten am ioBroker Forum

    • ioBroker goes Matter ... Matter Adapter in Stable

    • Monatsrückblick - April 2025

    [Vorlage] Skript: Erstellen von User-Datenpunkten

    This topic has been deleted. Only users with topic management privileges can see it.
    • paul53
      paul53 @xbow42 last edited by

      @xbow42 sagte:

      mit unterschiedlichen "Arrayfüllungen" wiederverwenden

      Eine manuelle "Füllung" ist konstant bezogen auf das Script.

      1 Reply Last reply Reply Quote 0
      • X
        xbow42 last edited by

        ah ja👍 , nix mit gretalike variablenrecycling 🔁

        paul53 1 Reply Last reply Reply Quote 0
        • paul53
          paul53 @xbow42 last edited by

          @xbow42
          Übrigens: Der Inhalt von Arrays und Objekten kann auch dann zur Laufzeit geändert werden, wenn das Array/Objekt als Konstante deklariert wurde.

          1 Reply Last reply Reply Quote 0
          • X
            xbow42 last edited by xbow42

            bin echt verblüfft, sehr inkonsequente Programmiersprache.
            musste ich glatt mal ausprobieren.

            const arrAnysting = ['0','8','15'];
            
            console.log(arrAnysting[2]);
            arrAnysting[2] = '42';
            console.log(arrAnysting[2]);
            arrAnysting[1] = '10';
            console.log(arrAnysting[1]);  //10
            console.log(arrAnysting[2]);  //42
            arrAnysting[0] = '000000000000000000000000000000000000000000000000000000000000000000000000000000';
            console.log(arrAnysting[0]); //000000000000000000000000000000000000000000000000000000000000000000000000000000
            console.log(arrAnysting[1]); //10
            arrAnysting = ['0','8','15'];//ungültige Zuweisung
            arrAnysting.unshift('neu an pos 0');
            console.log(arrAnysting[0]); //neu an pos 0  // das geht komischer Weise wieder
            

            Also wird das "konstante" Array wild im Arbeitsspeicher gehalten/verschoben/vergrößert, welches man mit Daten des gleichen Typs vollmüllen kann bis der Speicher voll ist -> und das script/der Rechner abschmiert. richtig?
            Austesten werde ich das sicher nicht!☠

            paul53 1 Reply Last reply Reply Quote 0
            • paul53
              paul53 @xbow42 last edited by

              @xbow42 sagte:

              Also wird das "konstante" Array wild im Arbeitsspeicher gehalten

              Konstant ist nur der Bezeichner arrAnysting; es kann keine neue Zuweisung erfolgen. Der Inhalt des Arrays kann beliebig verändert werden, denn Objekte werden nur referenziert (Zeiger). Das ist in anderen Programmiersprachen nicht anders.

              1 Reply Last reply Reply Quote 0
              • X
                xbow42 last edited by

                @paul53 ok danke für die kleine Nachhilfe. Werde mich weiter einlesen. ... geht ja eigentlich um UserDP, da will ich mal hier nicht weiter abschweifen.
                wünsche eine gute Nacht!

                1 Reply Last reply Reply Quote 0
                • Mic
                  Mic Developer last edited by Mic

                  Hier übrigens der Vollständigkeit halber das Github Issue für den JS-Adapter: createState in 0_userdata.0 ermöglichen #429

                  Bitte fleißig dort voten, wäre viel besser, wenn der JS-Adapter das "out of the box" liefert 🙂

                  J 1 Reply Last reply Reply Quote 0
                  • X
                    xbow42 last edited by xbow42

                    klicks sind gemacht👍 gute Idee bitte alle mitmachen.

                    B 1 Reply Last reply Reply Quote 1
                    • B
                      BoehserWolf @xbow42 last edited by

                      @xbow42 said in [[Vorlage] Skript: bitte alle mitmachen.

                      Done

                      1 Reply Last reply Reply Quote 1
                      • Patchwork 3001
                        Patchwork 3001 last edited by

                        sorry bin neu in der Sache.
                        aber hier ist soviel durch einander und wollte frage ob es auch eine Anleitung für Anfänger gibt weil ich hier nicht raus lesen kann wo wie und was jetzt kopiert oder selber erstellt werden muss.
                        Sorry wehre aber ne große Hilfe

                        X 1 Reply Last reply Reply Quote 0
                        • X
                          xbow42 @Patchwork 3001 last edited by

                          @Patchwork-3001 die Frage, ist was du machen willst?

                          1. ein paar eigene Datenpunkte anlegen die du in deinen Scripten verwenden will.
                            Da würde ich den Weg über ioBroker/Objekte gehen und diese unter dem Pfad "0_userdata.0" selbst anlegen.

                          2. du willst in deinen Scripten eigene DP erstellen und kennst dich schon mit den {common}-Eigenschaften der DP aus.
                            erst mal die Doku von @Mic lesen und am besten auch hier abstimmen, damit die Funktion schnell zum ioBroker-Standard wird 😉
                            <wenn du gleich loslegen willst, um die Funktion->
                            2.1 in einem eigenen Script zu verwenden: JScript im Scripte-Ordner anlegen (nicht unter global), Code in dein Javascript kopieren, weiter bei 2..
                            2.2 in vielen eigenen Scripten zu verwenden: unter dem Scripte-Ordner global ein JS-Script anlegen z.B. mit dem Namen createUserStates und den Code dort abspeichern
                            2.. Im eigenen Script kannst du nun mit dem Funktionsaufruf createUserStates(...); deine DP anlegen. Bsp s. Doku.

                          Patchwork 3001 1 Reply Last reply Reply Quote 1
                          • Patchwork 3001
                            Patchwork 3001 @xbow42 last edited by

                            @xbow42 sagte in [Vorlage] Skript: Erstellen von User-Datenpunkten:

                            ein paar eigene Datenpunkte anlegen die du in deinen Scripten verwenden will.
                            Da würde ich den Weg über ioBroker/Objekte gehen und diese unter dem Pfad "0_userdata.0" selbst anlegen.

                            du willst in deinen Scripten eigene DP erstellen und kennst dich schon mit den {common}-Eigenschaften der DP aus.
                            erst mal die Doku von @Mic lesen und am besten auch hier abstimmen, damit die Funktion schnell zum ioBroker-Standard wird
                            <wenn du gleich loslegen willst, um die Funktion->
                            2.1 in einem eigenen Script zu verwenden: JScript im Scripte-Ordner anlegen (nicht unter global), Code in dein Javascript kopieren, weiter bei 2..
                            2.2 in vielen eigenen Scripten zu verwenden: unter dem Scripte-Ordner global ein JS-Script anlegen z.B. mit dem Namen createUserStates und den Code dort abspeichern
                            2.. Im eigenen Script kannst du nun mit dem Funktionsaufruf createUserStates(...); deine DP anlegen. Bsp s. Doku.

                            danke schön

                            1 Reply Last reply Reply Quote 0
                            • marcuskl
                              marcuskl last edited by marcuskl

                              Ich habe mit dem Skript ein Datenpunkt erstellt, aber ich kann den Datenpunkt nicht auf true setzen, der bleibt immer auf false?
                              Warum ? Was mach ich falsch ?

                              let statesToCreate = [
                                  ['Astro.sonnenuntergang', {'name':'Sonnenuntergang', 'type':'boolean', 'read':true, 'write':true, 'role':'switch' }],
                              ];
                              createUserStates('0_userdata.0', false, statesToCreate, function(){
                                  log('Jetzt sind alle States abgearbeitet und wir können nun fortfahren, z.B. nächste Funktion main() aufrufen.');
                                  main();
                              });
                              
                              function main() {
                                  // Hier dann alles weitere.
                                  log('Nun sind wir in der main()-Funktion.')
                              
                                  // Hier der weitere Code...
                                  
                              };
                              /**
                               * Create states under 0_userdata.0 or javascript.x
                               * Current Version:     https://github.com/Mic-M/iobroker.createUserStates
                               * Support:             https://forum.iobroker.net/topic/26839/
                               * Autor:               Mic (ioBroker) | Mic-M (github)
                               * Version:             1.1 (26 January 2020)
                               * Example:             see https://github.com/Mic-M/iobroker.createUserStates#beispiel
                               * -----------------------------------------------
                               * PLEASE NOTE: Per https://github.com/ioBroker/ioBroker.javascript/issues/474, the used function setObject() 
                               *              executes the callback PRIOR to completing the state creation. Therefore, we use a setTimeout and counter. 
                               * -----------------------------------------------
                               * @param {string} where          Where to create the state: '0_userdata.0' or 'javascript.x'.
                               * @param {boolean} force         Force state creation (overwrite), if state is existing.
                               * @param {array} statesToCreate  State(s) to create. single array or array of arrays
                               * @param {object} [callback]     Optional: a callback function -- This provided function will be executed after all states are created.
                               */
                              function createUserStates(where, force, statesToCreate, callback = undefined) {
                               
                                  const WARN = false; // Only for 0_userdata.0: Throws warning in log, if state is already existing and force=false. Default is false, so no warning in log, if state exists.
                                  const LOG_DEBUG = false; // To debug this function, set to true
                                  // Per issue #474 (https://github.com/ioBroker/ioBroker.javascript/issues/474), the used function setObject() executes the callback 
                                  // before the state is actual created. Therefore, we use a setTimeout and counter as a workaround.
                                  const DELAY = 50; // Delay in milliseconds (ms). Increase this to 100, if it is not working.
                              
                                  // Validate "where"
                                  if (where.endsWith('.')) where = where.slice(0, -1); // Remove trailing dot
                                  if ( (where.match(/^((javascript\.([1-9][0-9]|[0-9]))$|0_userdata\.0$)/) == null) ) {
                                      log('This script does not support to create states under [' + where + ']', 'error');
                                      return;
                                  }
                              
                                  // Prepare "statesToCreate" since we also allow a single state to create
                                  if(!Array.isArray(statesToCreate[0])) statesToCreate = [statesToCreate]; // wrap into array, if just one array and not inside an array
                              
                                  // Add "where" to STATES_TO_CREATE
                                  for (let i = 0; i < statesToCreate.length; i++) {
                                      let lpPath = statesToCreate[i][0].replace(/\.*\./g, '.'); // replace all multiple dots like '..', '...' with a single '.'
                                      lpPath = lpPath.replace(/^((javascript\.([1-9][0-9]|[0-9])\.)|0_userdata\.0\.)/,'') // remove any javascript.x. / 0_userdata.0. from beginning
                                      lpPath = where + '.' + lpPath; // add where to beginning of string
                                      statesToCreate[i][0] = lpPath;
                                  }
                              
                                  if (where != '0_userdata.0') {
                                      // Create States under javascript.x
                                      let numStates = statesToCreate.length;
                                      statesToCreate.forEach(function(loopParam) {
                                          if (LOG_DEBUG) log('[Debug] Now we are creating new state [' + loopParam[0] + ']');
                                          let loopInit = (loopParam[1]['def'] == undefined) ? null : loopParam[1]['def']; // mimic same behavior as createState if no init value is provided
                                          createState(loopParam[0], loopInit, force, loopParam[1], function() {
                                              numStates--;
                                              if (numStates === 0) {
                                                  if (LOG_DEBUG) log('[Debug] All states processed.');
                                                  if (typeof callback === 'function') { // execute if a function was provided to parameter callback
                                                      if (LOG_DEBUG) log('[Debug] Function to callback parameter was provided');
                                                      return callback();
                                                  } else {
                                                      return;
                                                  }
                                              }
                                          });
                                      });
                                  } else {
                                      // Create States under 0_userdata.0
                                      let numStates = statesToCreate.length;
                                      let counter = -1;
                                      statesToCreate.forEach(function(loopParam) {
                                          counter += 1;
                                          if (LOG_DEBUG) log ('[Debug] Currently processing following state: [' + loopParam[0] + ']');
                                          if( ($(loopParam[0]).length > 0) && (existsState(loopParam[0])) ) { // Workaround due to https://github.com/ioBroker/ioBroker.javascript/issues/478
                                              // State is existing.
                                              if (WARN && !force) log('State [' + loopParam[0] + '] is already existing and will no longer be created.', 'warn');
                                              if (!WARN && LOG_DEBUG) log('[Debug] State [' + loopParam[0] + '] is already existing. Option force (=overwrite) is set to [' + force + '].');
                                              if(!force) {
                                                  // State exists and shall not be overwritten since force=false
                                                  // So, we do not proceed.
                                                  numStates--;
                                                  if (numStates === 0) {
                                                      if (LOG_DEBUG) log('[Debug] All states successfully processed!');
                                                      if (typeof callback === 'function') { // execute if a function was provided to parameter callback
                                                          if (LOG_DEBUG) log('[Debug] An optional callback function was provided, which we are going to execute now.');
                                                          return callback();
                                                      }
                                                  } else {
                                                      // We need to go out and continue with next element in loop.
                                                      return; // https://stackoverflow.com/questions/18452920/continue-in-cursor-foreach
                                                  }
                                              } // if(!force)
                                          }
                              
                                          // State is not existing or force = true, so we are continuing to create the state through setObject().
                                          let obj = {};
                                          obj.type = 'state';
                                          obj.native = {};
                                          obj.common = loopParam[1];
                                          setObject(loopParam[0], obj, function (err) {
                                              if (err) {
                                                  log('Cannot write object for state [' + loopParam[0] + ']: ' + err);
                                              } else {
                                                  if (LOG_DEBUG) log('[Debug] Now we are creating new state [' + loopParam[0] + ']')
                                                  let init = null;
                                                  if(loopParam[1].def === undefined) {
                                                      if(loopParam[1].type === 'number') init = 0;
                                                      if(loopParam[1].type === 'boolean') init = false;
                                                      if(loopParam[1].type === 'string') init = '';
                                                  } else {
                                                      init = loopParam[1].def;
                                                  }
                                                  setTimeout(function() {
                                                      setState(loopParam[0], init, true, function() {
                                                          if (LOG_DEBUG) log('[Debug] setState durchgeführt: ' + loopParam[0]);
                                                          numStates--;
                                                          if (numStates === 0) {
                                                              if (LOG_DEBUG) log('[Debug] All states processed.');
                                                              if (typeof callback === 'function') { // execute if a function was provided to parameter callback
                                                                  if (LOG_DEBUG) log('[Debug] Function to callback parameter was provided');
                                                                  return callback();
                                                              }
                                                          }
                                                      });
                                                  }, DELAY + (20 * counter) );
                                              }
                                          });
                                      });
                                  }
                              }
                              
                              Mic-M created this issue in ioBroker/ioBroker.javascript

                              closed setObject() function: callback not working as intended. #474

                              Mic-M created this issue in ioBroker/ioBroker.javascript

                              closed setObject() function: callback not working as intended. #474

                              Mic-M created this issue in ioBroker/ioBroker.javascript

                              closed 0_userdata.0: existsState() vs. $-Selector $().length after state deletion #478

                              X C 2 Replies Last reply Reply Quote 0
                              • X
                                xbow42 @marcuskl last edited by

                                @marcuskl dieses seltsame Verhalten hatte ich auch mal. Lade mal die Objekte-Seite neu, kontolliere mal ob ['write':true] passt oder starte ggf. den iobroker mal neu. Bei mir ging es dann aufeinmal.
                                Ich nehme mal an dass es auch im Script funktioniert und nur bei der Darstellung im Browser der neue Wert nicht anzeigt wird.

                                1 Reply Last reply Reply Quote 0
                                • C
                                  CruziX @marcuskl last edited by

                                  @marcuskl Ist doch glaube beim Alias Skript auch so.
                                  Admin neustarten (wichtig, neustarten nicht aus und wieder einschalten) oder iobroker neustart

                                  1 Reply Last reply Reply Quote 0
                                  • marcuskl
                                    marcuskl last edited by

                                    Ok danke, versuche ich später mal 🙂

                                    1 Reply Last reply Reply Quote 0
                                    • marcuskl
                                      marcuskl last edited by

                                      @CruziX @xbow42 Den Admin Adapter neu zu starten hatte nichts geändert, ich musste Iobroker komplett neu starten, danach hat es funktioniert

                                      1 Reply Last reply Reply Quote 0
                                      • O
                                        oFbEQnpoLKKl6mbY5e13 @paul53 last edited by

                                        @paul53 sagte in [Vorlage] Skript: Erstellen von User-Datenpunkten:

                                        @dslraser sagte:

                                        Es wird jedenfalls dann nicht mit "noch leer" initialisiert ?

                                        Initialisierung mit "noch leer" erfolgt nur, wenn kein common.def vorhanden ist (undefined).

                                        Was ist der Grund dafür?

                                        1 Reply Last reply Reply Quote 0
                                        • D3ltoroxp
                                          D3ltoroxp last edited by D3ltoroxp

                                          Kann ich mit diesem Script, solche Einträge irgendwie mit wenig Aufwand erstellen lassen ?

                                          createState('javascript.0.Rasemmaeher.07_Sonntag_Kantenschnitt', {name: "07_Sonntag_Kantenschnitt"});
                                          
                                          Mic 1 Reply Last reply Reply Quote 0
                                          • Mic
                                            Mic Developer @D3ltoroxp last edited by

                                            @D3ltoroxp

                                            Klar, geht einfach, siehe:
                                            https://github.com/Mic-M/iobroker.createUserStates

                                            Aber:

                                            Hinweis (für alle 🙂 )

                                            Mit JavaScript-Adapter ab Version 4.6.1 können mittels createState() auch Datenpunkte unterhalb 0_userdata.0 angelegt werden.

                                            https://github.com/ioBroker/ioBroker.javascript#461-2020-05-11
                                            add support for 0_userdata.0 to createState and deleteState

                                            1 Reply Last reply Reply Quote 2
                                            • First post
                                              Last post

                                            Support us

                                            ioBroker
                                            Community Adapters
                                            Donate

                                            788
                                            Online

                                            31.6k
                                            Users

                                            79.5k
                                            Topics

                                            1.3m
                                            Posts

                                            16
                                            86
                                            13874
                                            Loading More Posts
                                            • Oldest to Newest
                                            • Newest to Oldest
                                            • Most Votes
                                            Reply
                                            • Reply as topic
                                            Log in to reply
                                            Community
                                            Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
                                            The ioBroker Community 2014-2023
                                            logo