Skip to content
  • Home
  • Recent
  • Tags
  • 0 Unread 0
  • Categories
  • Unreplied
  • Popular
  • GitHub
  • Docu
  • Hilfe
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
ioBroker Logo

Community Forum

donate donate
  1. ioBroker Community Home
  2. Deutsch
  3. Skripten / Logik
  4. JavaScript
  5. [Vorlage] Skript: Erstellen von User-Datenpunkten

NEWS

  • Monatsrückblick Januar/Februar 2026 ist online!
    BluefoxB
    Bluefox
    16
    1
    225

  • Jahresrückblick 2025 – unser neuer Blogbeitrag ist online! ✨
    BluefoxB
    Bluefox
    17
    1
    4.5k

  • Neuer Blogbeitrag: Monatsrückblick - Dezember 2025 🎄
    BluefoxB
    Bluefox
    13
    1
    1.3k

[Vorlage] Skript: Erstellen von User-Datenpunkten

Scheduled Pinned Locked Moved JavaScript
86 Posts 16 Posters 20.1k Views 30 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • X xbow42

    danke für die Info, das mit dem let_statt_var werde ich mir angewöhnen!

    also im ersten states2Create fehlt das var weil ich die Variable schon vorher deklariert habe. Sorry sieht man leider nur im kompletten code s. Spoiler
    Ich hab var genommen weil die die Variable mehrfach mit unterschiedlichen "Arrayfüllungen" wiederverwenden wollte, in der Hoffung dass es weniger Speicher braucht als wenn ich mehrere Konstantenarrays deklariere.
    Quatsch?

    paul53P Offline
    paul53P Offline
    paul53
    wrote on last edited by
    #51

    @xbow42 sagte:

    mit unterschiedlichen "Arrayfüllungen" wiederverwenden

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

    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

    1 Reply Last reply
    0
    • X Offline
      X Offline
      xbow42
      wrote on last edited by
      #52

      ah ja:+1: , nix mit gretalike variablenrecycling :repeat:

      paul53P 1 Reply Last reply
      0
      • X xbow42

        ah ja:+1: , nix mit gretalike variablenrecycling :repeat:

        paul53P Offline
        paul53P Offline
        paul53
        wrote on last edited by
        #53

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

        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

        1 Reply Last reply
        0
        • X Offline
          X Offline
          xbow42
          wrote on last edited by xbow42
          #54

          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!:skull_and_crossbones:

          paul53P 1 Reply Last reply
          0
          • X 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!:skull_and_crossbones:

            paul53P Offline
            paul53P Offline
            paul53
            wrote on last edited by
            #55

            @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.

            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

            1 Reply Last reply
            0
            • X Offline
              X Offline
              xbow42
              wrote on last edited by
              #56

              @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
              0
              • MicM Offline
                MicM Offline
                Mic
                Developer
                wrote on last edited by Mic
                #57

                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 :-)

                ? 1 Reply Last reply
                0
                • X Offline
                  X Offline
                  xbow42
                  wrote on last edited by xbow42
                  #58

                  klicks sind gemacht:+1: gute Idee bitte alle mitmachen.

                  B 1 Reply Last reply
                  1
                  • X xbow42

                    klicks sind gemacht:+1: gute Idee bitte alle mitmachen.

                    B Offline
                    B Offline
                    BoehserWolf
                    wrote on last edited by
                    #59

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

                    Done

                    1 Reply Last reply
                    1
                    • Patchwork 3001P Offline
                      Patchwork 3001P Offline
                      Patchwork 3001
                      wrote on last edited by
                      #60

                      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
                      0
                      • Patchwork 3001P Patchwork 3001

                        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 Offline
                        X Offline
                        xbow42
                        wrote on last edited by
                        #61

                        @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 3001P 1 Reply Last reply
                        1
                        • X xbow42

                          @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 3001P Offline
                          Patchwork 3001P Offline
                          Patchwork 3001
                          wrote on last edited by
                          #62

                          @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
                          0
                          • marcusklM Offline
                            marcusklM Offline
                            marcuskl
                            wrote on last edited by marcuskl
                            #63

                            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) );
                                            }
                                        });
                                    });
                                }
                            }
                            

                            Host: Intel Nuc6cayh (16GB Ram, 240GB SSD) mit Proxmox.

                            Iobroker VM, InfluxDB LXC, Pihole LXC, Tasmoadmin LXC, Easy2connect VM

                            X C 2 Replies Last reply
                            0
                            • marcusklM 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) );
                                              }
                                          });
                                      });
                                  }
                              }
                              
                              X Offline
                              X Offline
                              xbow42
                              wrote on last edited by
                              #64

                              @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
                              0
                              • marcusklM 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) );
                                                }
                                            });
                                        });
                                    }
                                }
                                
                                C Offline
                                C Offline
                                CruziX
                                wrote on last edited by
                                #65

                                @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
                                0
                                • marcusklM Offline
                                  marcusklM Offline
                                  marcuskl
                                  wrote on last edited by
                                  #66

                                  Ok danke, versuche ich später mal :)

                                  Host: Intel Nuc6cayh (16GB Ram, 240GB SSD) mit Proxmox.

                                  Iobroker VM, InfluxDB LXC, Pihole LXC, Tasmoadmin LXC, Easy2connect VM

                                  1 Reply Last reply
                                  0
                                  • marcusklM Offline
                                    marcusklM Offline
                                    marcuskl
                                    wrote on last edited by
                                    #67

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

                                    Host: Intel Nuc6cayh (16GB Ram, 240GB SSD) mit Proxmox.

                                    Iobroker VM, InfluxDB LXC, Pihole LXC, Tasmoadmin LXC, Easy2connect VM

                                    1 Reply Last reply
                                    0
                                    • paul53P paul53

                                      @dslraser sagte:

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

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

                                      O Away
                                      O Away
                                      oFbEQnpoLKKl6mbY5e13
                                      wrote on last edited by
                                      #68

                                      @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
                                      0
                                      • D3ltoroxpD Offline
                                        D3ltoroxpD Offline
                                        D3ltoroxp
                                        wrote on last edited by D3ltoroxp
                                        #69

                                        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"});
                                        
                                        MicM 1 Reply Last reply
                                        0
                                        • D3ltoroxpD 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"});
                                          
                                          MicM Offline
                                          MicM Offline
                                          Mic
                                          Developer
                                          wrote on last edited by
                                          #70

                                          @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
                                          2
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          Support us

                                          ioBroker
                                          Community Adapters
                                          Donate

                                          325

                                          Online

                                          32.7k

                                          Users

                                          82.5k

                                          Topics

                                          1.3m

                                          Posts
                                          Community
                                          Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
                                          ioBroker Community 2014-2025
                                          logo
                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Home
                                          • Recent
                                          • Tags
                                          • Unread 0
                                          • Categories
                                          • Unreplied
                                          • Popular
                                          • GitHub
                                          • Docu
                                          • Hilfe