Skip to content
  • Home
  • Aktuell
  • Tags
  • 0 Ungelesen 0
  • Kategorien
  • Unreplied
  • Beliebt
  • 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

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

Community Forum

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

NEWS

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

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

  • Neues Video "KI im Smart Home" - ioBroker plus n8n
    BluefoxB
    Bluefox
    15
    1
    2.5k

[Vorlage] Skript: Erstellen von User-Datenpunkten

Geplant Angeheftet Gesperrt Verschoben JavaScript
86 Beiträge 16 Kommentatoren 18.5k Aufrufe 30 Watching
  • Älteste zuerst
  • Neuste zuerst
  • Meiste Stimmen
Antworten
  • In einem neuen Thema antworten
Anmelden zum Antworten
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
  • X Offline
    X Offline
    xbow42
    schrieb am zuletzt editiert von
    #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 Antwort Letzte Antwort
    0
    • MicM Offline
      MicM Offline
      Mic
      Developer
      schrieb am zuletzt editiert von 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 :-)

      J 1 Antwort Letzte Antwort
      0
      • X Offline
        X Offline
        xbow42
        schrieb am zuletzt editiert von xbow42
        #58

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

        B 1 Antwort Letzte Antwort
        1
        • X xbow42

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

          B Offline
          B Offline
          BoehserWolf
          schrieb am zuletzt editiert von
          #59

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

          Done

          1 Antwort Letzte Antwort
          1
          • Patchwork 3001P Offline
            Patchwork 3001P Offline
            Patchwork 3001
            schrieb am zuletzt editiert von
            #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 Antwort Letzte Antwort
            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
              schrieb am zuletzt editiert von
              #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 Antwort Letzte Antwort
              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
                schrieb am zuletzt editiert von
                #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 Antwort Letzte Antwort
                0
                • marcusklM Offline
                  marcusklM Offline
                  marcuskl
                  schrieb am zuletzt editiert von 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 Antworten Letzte Antwort
                  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
                    schrieb am zuletzt editiert von
                    #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 Antwort Letzte Antwort
                    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
                      schrieb am zuletzt editiert von
                      #65

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

                      1 Antwort Letzte Antwort
                      0
                      • marcusklM Offline
                        marcusklM Offline
                        marcuskl
                        schrieb am zuletzt editiert von
                        #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 Antwort Letzte Antwort
                        0
                        • marcusklM Offline
                          marcusklM Offline
                          marcuskl
                          schrieb am zuletzt editiert von
                          #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 Antwort Letzte Antwort
                          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 Offline
                            O Offline
                            oFbEQnpoLKKl6mbY5e13
                            schrieb am zuletzt editiert von
                            #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 Antwort Letzte Antwort
                            0
                            • D3ltoroxpD Offline
                              D3ltoroxpD Offline
                              D3ltoroxp
                              schrieb am zuletzt editiert von 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 Antwort Letzte Antwort
                              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
                                schrieb am zuletzt editiert von
                                #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 Antwort Letzte Antwort
                                2
                                • S Offline
                                  S Offline
                                  Schranzistor
                                  schrieb am zuletzt editiert von
                                  #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 Antwort Letzte Antwort
                                  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
                                    schrieb am zuletzt editiert von
                                    #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 Antwort Letzte Antwort
                                    0
                                    • S Offline
                                      S Offline
                                      Schranzistor
                                      schrieb am zuletzt editiert von
                                      #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 Antwort Letzte Antwort
                                      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
                                        schrieb am zuletzt editiert von
                                        #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 Antwort Letzte Antwort
                                        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 :-)

                                          J Offline
                                          J Offline
                                          J_Paul
                                          schrieb am zuletzt editiert von
                                          #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 Antwort Letzte Antwort
                                          0
                                          Antworten
                                          • In einem neuen Thema antworten
                                          Anmelden zum Antworten
                                          • Älteste zuerst
                                          • Neuste zuerst
                                          • Meiste Stimmen


                                          Support us

                                          ioBroker
                                          Community Adapters
                                          Donate

                                          416

                                          Online

                                          32.4k

                                          Benutzer

                                          81.4k

                                          Themen

                                          1.3m

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

                                          • Du hast noch kein Konto? Registrieren

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