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

  • Weihnachtsangebot 2025! 🎄
    BluefoxB
    Bluefox
    21
    1
    837

  • UPDATE 31.10.: Amazon Alexa - ioBroker Skill läuft aus ?
    apollon77A
    apollon77
    48
    3
    9.0k

  • Monatsrückblick – September 2025
    BluefoxB
    Bluefox
    13
    1
    2.3k

[Vorlage] Skript: Erstellen von User-Datenpunkten

Scheduled Pinned Locked Moved JavaScript
86 Posts 16 Posters 19.0k 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.
  • 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
                      • S Offline
                        S Offline
                        Schranzistor
                        wrote on last edited by
                        #71

                        Guten Morgen

                        Ist es dann möglich mit dem Baustein CreateState() auch den Datenpunkt nur zu erstellen,
                        und nicht zu Aktualisieren wen er schon vorhanden ist ? ( wenn zb. 10 drin steht, ihn nicht wieder auf 0 zu setzen Initialwert)

                        Arbeite mit Blockly, habe gelesen es gibt die forceCreation muss ich die deaktivieren ?

                        Wenn es so eine Funktion gibt wie müsste ich das in den Datenpunkt erzeugen Blockly Block schreiben ?

                        Vielen Dank
                        MFG

                        paul53P 1 Reply Last reply
                        0
                        • S Schranzistor

                          Guten Morgen

                          Ist es dann möglich mit dem Baustein CreateState() auch den Datenpunkt nur zu erstellen,
                          und nicht zu Aktualisieren wen er schon vorhanden ist ? ( wenn zb. 10 drin steht, ihn nicht wieder auf 0 zu setzen Initialwert)

                          Arbeite mit Blockly, habe gelesen es gibt die forceCreation muss ich die deaktivieren ?

                          Wenn es so eine Funktion gibt wie müsste ich das in den Datenpunkt erzeugen Blockly Block schreiben ?

                          Vielen Dank
                          MFG

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

                          @Schranzistor sagte:

                          nicht zu Aktualisieren wen er schon vorhanden ist ?

                          Der Javascript-Adapter enthält an dieser Stelle noch einen Fehler (Issue#597).

                          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
                          • S Offline
                            S Offline
                            Schranzistor
                            wrote on last edited by
                            #73

                            Hallo

                            vielen dank für die Info

                            Also wird das Skript von Mic auch nichts helfen da, dort wahrscheinlich der gleiche Fehler greift oder?

                            Mfg

                            paul53P 1 Reply Last reply
                            0
                            • S Schranzistor

                              Hallo

                              vielen dank für die Info

                              Also wird das Skript von Mic auch nichts helfen da, dort wahrscheinlich der gleiche Fehler greift oder?

                              Mfg

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

                              @Schranzistor sagte:

                              Skript von Mic auch nichts helfen

                              Das Skript von @Mic verwendet für Datenpunkte unter "0_userdata.0" nicht createState(), sollte also funktionieren.

                              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
                              1
                              • MicM 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 :-)

                                ? Offline
                                ? Offline
                                A Former User
                                wrote on last edited by
                                #75

                                @Mic @paul53
                                Versuche mich gerade einzulesen, verstehe aber leider (noch) nicht alles, deswegen:
                                Ich suche gerade eine Möglichkeit aus einem Blockly heraus States in 0_userdata.0 zu erzeugen in der Art (number string boolean):
                                0_userdata.0.traccar.{"NAME"}.Zuhause.entry
                                0_userdata.0.traccar.{"NAME"}.Zuhause.lastEnter
                                0_userdata.0.traccar.{"NAME"}.Zuhause.lastLeave
                                0_userdata.0.traccar.{"NAME"}.BatterieLevel
                                0_userdata.0.traccar.{"NAME"}.Position usw.
                                wobei {"NAME"} idealerweise eine Variable sein sollte. Geht das mit dem Script, oder (mittlerweile) auch direkt im Blockly?

                                paul53P 1 Reply Last reply
                                0
                                • ? A Former User

                                  @Mic @paul53
                                  Versuche mich gerade einzulesen, verstehe aber leider (noch) nicht alles, deswegen:
                                  Ich suche gerade eine Möglichkeit aus einem Blockly heraus States in 0_userdata.0 zu erzeugen in der Art (number string boolean):
                                  0_userdata.0.traccar.{"NAME"}.Zuhause.entry
                                  0_userdata.0.traccar.{"NAME"}.Zuhause.lastEnter
                                  0_userdata.0.traccar.{"NAME"}.Zuhause.lastLeave
                                  0_userdata.0.traccar.{"NAME"}.BatterieLevel
                                  0_userdata.0.traccar.{"NAME"}.Position usw.
                                  wobei {"NAME"} idealerweise eine Variable sein sollte. Geht das mit dem Script, oder (mittlerweile) auch direkt im Blockly?

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

                                  @J_Paul sagte:

                                  auch direkt im Blockly?

                                  Beispiel, aber nicht mit einer ID, die aus einer Variablen gebildet wird.

                                  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
                                  • S Offline
                                    S Offline
                                    stan23
                                    wrote on last edited by
                                    #77

                                    Vielen Dank für das Skript!

                                    Gibt es einen eleganten Weg um eine dynamische Anzahl von Datenpunkten zu erstellen?

                                    /* create datapoints once */
                                    for (let region of listRegion) {
                                        let statesToCreate = [
                                            [`${prefixDp}.${region[1]}.${dpToday}`,     {   'name': 'Cases per 100k in the last 7 days, value from today', 
                                                                                            'type': 'number', 
                                                                                            'read': true, 'write': true, 
                                                                                            'min': 0, 'max': 100000}],
                                            [`${prefixDp}.${region[1]}.${dpYesterday}`, {   'name': 'Cases per 100k in the last 7 days, value from yesterday', 
                                                                                            'type': 'number', 
                                                                                            'read': true, 'write': true, 
                                                                                            'min': 0, 'max': 100000}]
                                        ]
                                        createUserStates(prefixUserdata, false, statesToCreate);
                                    }
                                    

                                    Jetzt habe ich das Problem dass ich das globale Skript createUserStates zu schnell hintereinander aufrufe, und mir dadurch der dpYesterday mit 0 überschreiben oder gelöscht und neu erstellt wird (das ich mir nicht klar).

                                    Arrays kann man ja nicht dynamisch in der Schleife enzeugen :(

                                    Viele Grüße
                                    Marco

                                    S 1 Reply Last reply
                                    0
                                    • S stan23

                                      Vielen Dank für das Skript!

                                      Gibt es einen eleganten Weg um eine dynamische Anzahl von Datenpunkten zu erstellen?

                                      /* create datapoints once */
                                      for (let region of listRegion) {
                                          let statesToCreate = [
                                              [`${prefixDp}.${region[1]}.${dpToday}`,     {   'name': 'Cases per 100k in the last 7 days, value from today', 
                                                                                              'type': 'number', 
                                                                                              'read': true, 'write': true, 
                                                                                              'min': 0, 'max': 100000}],
                                              [`${prefixDp}.${region[1]}.${dpYesterday}`, {   'name': 'Cases per 100k in the last 7 days, value from yesterday', 
                                                                                              'type': 'number', 
                                                                                              'read': true, 'write': true, 
                                                                                              'min': 0, 'max': 100000}]
                                          ]
                                          createUserStates(prefixUserdata, false, statesToCreate);
                                      }
                                      

                                      Jetzt habe ich das Problem dass ich das globale Skript createUserStates zu schnell hintereinander aufrufe, und mir dadurch der dpYesterday mit 0 überschreiben oder gelöscht und neu erstellt wird (das ich mir nicht klar).

                                      Arrays kann man ja nicht dynamisch in der Schleife enzeugen :(

                                      S Offline
                                      S Offline
                                      stan23
                                      wrote on last edited by
                                      #78

                                      Jetzt habe ich das Problem dass ich das globale Skript createUserStates zu schnell hintereinander aufrufe, und mir dadurch der dpYesterday mit 0 überschreiben oder gelöscht und neu erstellt wird (das ich mir nicht klar).

                                      Jetzt ist es mir klar: da ist ein Bug im Skript :)

                                      Wenn kann Callback angegeben ist, wird das letzte Element im Array immer neu erstellt und damit überschrieben.

                                      @Mic PR ist gestellt:
                                      https://github.com/Mic-M/iobroker-createUserStates/pull/3

                                      Viele Grüße
                                      Marco

                                      MicM 1 Reply Last reply
                                      0
                                      • S stan23

                                        Jetzt habe ich das Problem dass ich das globale Skript createUserStates zu schnell hintereinander aufrufe, und mir dadurch der dpYesterday mit 0 überschreiben oder gelöscht und neu erstellt wird (das ich mir nicht klar).

                                        Jetzt ist es mir klar: da ist ein Bug im Skript :)

                                        Wenn kann Callback angegeben ist, wird das letzte Element im Array immer neu erstellt und damit überschrieben.

                                        @Mic PR ist gestellt:
                                        https://github.com/Mic-M/iobroker-createUserStates/pull/3

                                        MicM Offline
                                        MicM Offline
                                        Mic
                                        Developer
                                        wrote on last edited by Mic
                                        #79

                                        @stan23

                                        Vielen Dank für deinen PR, ist jetzt drin :)

                                        Ich bin ehrlich gesagt nicht glücklich mit diesem Script, im Zuge meiner zwischenzeitlichen Adapter-Entwicklungen und deutlichem Wissensaufbau auch hinsichtlich Promises usw. steckt da noch sehr viel Potenzial drin (positiv ausgedrückt :grin: ), zumal ja auch mit createState() ab JavaScript-Adapter ab Version 4.6.1 auch Datenpunkte unterhalb 0_userdata.0 angelegt werden können, und auch das ist noch nicht in diesem Script implementiert.

                                        Der Bedarf für dieses Script scheint aber nach wie vor da zu sein, also in eine Routine mal ein paar Hände voll Datenpunkt-Pfade zu werfen, und diese legt diese für uns an, und erst danach machen wir weiter.
                                        Perfekt für async/await eigentlich.

                                        Mir fehlt gerade etwas die Zeit hierfür, aber möchte euch gerne ermuntern, das zu implementieren. Das auch für Einsteiger m.E. sehr gut geeignet, um in die async/await-Welt einzutauchen ;-)

                                        Siehe auch: https://forum.iobroker.net/topic/36999/neu-diverse-async-funktionen-im-javascript-adapter

                                        Falls ein vielfacher Usecase, wäre das auch ein Issue wert für den JavaScript-Adapter selbst. Also dass hier eine Funktion bereit gestellt wird, sofern nicht eh schon über eine simple Schleife abbildbar jetzt dank der neuen Funktionalitäten.

                                        SpegeliS 1 Reply Last reply
                                        0
                                        • MicM Mic

                                          @stan23

                                          Vielen Dank für deinen PR, ist jetzt drin :)

                                          Ich bin ehrlich gesagt nicht glücklich mit diesem Script, im Zuge meiner zwischenzeitlichen Adapter-Entwicklungen und deutlichem Wissensaufbau auch hinsichtlich Promises usw. steckt da noch sehr viel Potenzial drin (positiv ausgedrückt :grin: ), zumal ja auch mit createState() ab JavaScript-Adapter ab Version 4.6.1 auch Datenpunkte unterhalb 0_userdata.0 angelegt werden können, und auch das ist noch nicht in diesem Script implementiert.

                                          Der Bedarf für dieses Script scheint aber nach wie vor da zu sein, also in eine Routine mal ein paar Hände voll Datenpunkt-Pfade zu werfen, und diese legt diese für uns an, und erst danach machen wir weiter.
                                          Perfekt für async/await eigentlich.

                                          Mir fehlt gerade etwas die Zeit hierfür, aber möchte euch gerne ermuntern, das zu implementieren. Das auch für Einsteiger m.E. sehr gut geeignet, um in die async/await-Welt einzutauchen ;-)

                                          Siehe auch: https://forum.iobroker.net/topic/36999/neu-diverse-async-funktionen-im-javascript-adapter

                                          Falls ein vielfacher Usecase, wäre das auch ein Issue wert für den JavaScript-Adapter selbst. Also dass hier eine Funktion bereit gestellt wird, sofern nicht eh schon über eine simple Schleife abbildbar jetzt dank der neuen Funktionalitäten.

                                          SpegeliS Offline
                                          SpegeliS Offline
                                          Spegeli
                                          wrote on last edited by Spegeli
                                          #80

                                          //Edit: Mein Problem hat sich mittlerweile erledigt ;-)

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          Support us

                                          ioBroker
                                          Community Adapters
                                          Donate

                                          398

                                          Online

                                          32.5k

                                          Users

                                          81.6k

                                          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