<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Virtual Devices]]></title><description><![CDATA[<p dir="auto">Ich weiß, es gibt schon Adapter wie Scene und andere, um Geräte zu gruppieren usw.</p>
<p dir="auto">Ich möchte mit diesem Skript deutlich weiter gehen und damit eine Vielzahl an Problemen beseitigen, welche bei mir beim Arbeiten mit ioBroker häufig auftreten. Eigentlich würde sich das Skript sogar gut eignen, um daraus einen Adapter zu bauen, allerdings fehlt mir dafür ein GUI. Das Skript ist ganz neu und evtl. nicht frei von Bugs, funktioniert bei mir aber sehr zuverlässig.</p>
<p dir="auto">Damit das Script lauffähig ist muss der Javascript Adapter "Nicht auf alle Zustände beim Start abonnieren" ausgeschaltet haben und "Erlaube das Kommando setObject" muss eingschaltet sein.</p>
<p dir="auto"><strong><strong>Problem:</strong></strong></p>
<p dir="auto">Bei der Arbeitsteilung zwischen Adaptern, History, Vis usw. kommt es häufig zu Unklarheiten, an welcher Stelle überhaupt gewisse Funktionalität erbracht werden soll. So hat z. B. ein Dimmer in Homematic einen Datenpunkt "LEVEL", welcher Werte von 0-100 annehmen kann. Bei HUE ist es "bri" mit 0-254 und bei Z-Wave sind es 0-99. Bei Hue habe ich vor einiger Zeit in den Adapter den Wert "level" mit der Homematic-Logik hinzugefügt, diesen gibt es in HUE eigentlich nicht. Und eigentlich halte ich es für falsch, solche Logiken in Geräte-Adapter einzubauen, diese sollten die Daten so zur Verfügung stellen, wie es die Geräte tun. Spätestens bei Vis würde ich aber gerne jede Lampe mit Werten 0-100 steuern. Manche Widgets versuchen auch mit möglichst vielen Werten klar zu kommen. Oft reicht das nicht und ich stehe wieder vor dem Problem, dass ich kein passendes Widget finde, um eine gewisse Funktion auszuführen. Dimmer sind hier nur ein Beispiel, wo ich Geräte verschiedener Hersteller auf einen Standard bringen möchte. Wer schonmal versucht hat, den Betriebsmodus eines Homematic-Thermostat mit einem Knopf zu steuern, weiß wovon ich rede. Das Thermostat besitzt nämlich gleich 5 States um den Betriebsmodus zu wechseln und einen weiteren um diesen anzuzeigen. Hier kommt dieses Skript als Vermittler ins Spiel.</p>
<p dir="auto"><strong><strong>Skriptbeschreibung:</strong></strong></p>
<p dir="auto">Das Skript eignet sich, um Geräte zu virtualisieren bzw. ganz neue Geräte zu erstellen. Soll heißen, es werden States in einem Namespace unter <strong>javascript.x.virtualDevice.*</strong> erstellt. Jeder dieser States kann Werte von mehreren Geräten erhalten und auch wieder in mehrere andere Geräte schreiben. Dabei können bedarfsweise Konvertierungen oder andere Funktionen ausgeführt werden. Das Skript ist so universell gehalten und dabei vergleichsweise einfach zu steuern, dass ich damit alle meine Probleme lösen konnte. Wenn man schon viel mit ioBroker gearbeitet hat, werden einem die Vorteile einer Geräte-Virtualisierung schnell klar. Besonders bei der Arbeit mit History und Vis sowie der Verwaltung von Zugriffsrechten bietet es eine Menge Vorteile, weswegen ich mittlerweile alle Geräte virtualisiert habe. So geht mir nie eine History verloren, wenn ich einen Aktor austausche und ich muss auch nichts an den Views in Vis ändern.</p>
<p dir="auto"><strong><strong>Beispiel:</strong></strong></p>
<p dir="auto">Hier erstelle ich eine "Kopie" einer Hue-Lux Lampe, also nur dimmbar, keine Farben. Dabei benötige ich nur den Dimm-Wert, alle anderen States aus dem Adapter brauche ich für mein virtuelles Gerät nicht. Um auf das oben genannte Beispiel einzugehen nutze ich hier den 'bri'-Wert aus dem HUE-Adapter:</p>
<pre><code>new VirtualDevice({
    namespace: 'Hue',
    name: 'Wohnzimmer', //das Gerät wird unter javascript.0.virtualDevice.Hue.Wohnzimmer erstellt
    states: {
        //welche States sollen erstellt werden?
        'level': {
            //State Konfiguration
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                //von welchen States sollen Werte eingelesen werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.floor(val * 100 / 254);
                    }
                },
            },
            write: {
                //in welche States sollen Werte geschrieben werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.ceil(val * 254 / 100);
                    },
                    delay: 1500 // schreibe Werte erst nach 1,5 Sekunden in den Adapter (Puffer)
                },
            }
        },
    }
});
</code></pre>
<p dir="auto">Damit erstelle ich ein Gerät unter <strong>javascript.0.virtualDevice.Hue.Wohnzimmer</strong>, welches eine Datenpunkt <strong>level</strong> hat. Dieser Datenpunkt nimmt Werte zwischen 0 und 100 entgegen und konvertiert diese zu 0-254 und umgekehrt.</p>
<p dir="auto">Man sieht hier auch, dass man unter level.read und level.write weitere States einfügen kann, so dass gleich mehrere Lampen gesteuert werden. Diese müssten auch nicht alle vom HUE-Adapter kommen und können ganz unterschiedliche Werte erwarten.</p>
<p dir="auto">Es ist aber noch mehr möglich:</p>
<p dir="auto">Ich habe im Wandschalter für die Hue-Lampe ein Z-Wave Relay verbaut. So kann ich die Hue-Lampe klassisch an der Wand ein und ausschalten, aber auch über ioBroker vom Aus-Zustand einschalten. Ich möchte aber nicht erst umständlich das Relay schalten und dann die Hue-Lampe. Ich möchte, dass das Relay ganz automatisch einschaltet, wenn ich <strong>level</strong> auf einen Wert größer 0 setze. Dazu löse ich vor dem Schreiben von level in den Hue-Adapter eine Funktion aus:</p>
<pre><code>new VirtualDevice({
    namespace: 'Hue',
    name: 'Wohnzimmer', //das Gerät wird unter javascript.0.virtualDevice.Hue.Wohnzimmer erstellt
    states: {
        //welche States sollen erstellt werden?
        'level': {
            //State Konfiguration
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                //von welchen States sollen Werte eingelesen werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.floor(val * 100 / 254);
                    }
                },
            },
            write: {
                //in welche States sollen Werte geschrieben werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.ceil(val * 254 / 100);
                    },
                    delay: 1500, // schreibe Werte erst nach 1,5 Sekunden in den Adapter (Puffer)
                    before: function (device, value, callback) {
                        if (value &gt; 0 &amp;&amp; getState('zwave.0.NODE10.SWITCH_BINARY.Switch_1').val === false) {
                            //if switch is off and value is greater 0 turn on switch and set long delay
                            setStateDelayed(switchId, true, false, 1500, true, function () {
                                callback(value, 3500);
                            });
                        } else if (value &lt;= 0) {
                            //if level is set to 0 turn off switch and set level 0
                            setStateDelayed(switchId, false, false, 1500, true, function () {
                                callback(0, 0);
                            });
                        } else {
                            callback();
                        }
                    }
                },
            }
        },
    }
});
</code></pre>
<p dir="auto">Ich hoffe anhand dieses Beispiels werden einige Funktionen des Skripts deutlich. Bei Lampen mit Farbtemperatur habe ich den ct-Wert in Kelvin konvertiert, so dass ich die mir bekannte Weißtemperatureinheit eingeben kann, z. B. 2700k für Warmweiß.</p>
<p dir="auto">Homematic-Thermostate habe ich zusammen mit Stellantrieb in ein einziges virtuelles Gerät zusammengefügt und dabei die Moduswahl auf einen Datenpunkt reduziert.</p>
<p dir="auto"><strong><strong>Skript</strong></strong></p>
<pre><code>`/*
VirtualDevice v0.3

Structure of config:
{
    name: 'name', //name of device
    namespace: '', //create device within this namespace (device ID will be namespace.name)
    common: {}, //(optional)
    native: {}, //(optional)
    copy: objectId, //(optional) ID of device or channel to copy common and native from
    onCreate: function(device, callback) {} //called once on device creation
    states: {
        'stateA': { //State Id will be namespace.name.stateA
            common: {}, //(optional)
            native: {}, //(optional)
            copy: stateId,
            read: {
                //(optional) states which should write to "stateA"
                'stateId1': {
                    trigger: {ack: true, change: 'any'} //(optional) see https://github.com/ioBroker/ioBroker.javascript#on---subscribe-on-changes-or-updates-of-some-state
                    convert: function(val) {}, //(optional) functions should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                    validFor: //(optional) ms, to ignore old data which did not change for a long time.  
                },
                ...
            },
            readLogic: 'last' || 'max' || 'min' || 'average', //(optional) default: last (only last implemented)
            write: {
                //(optional) states which "stateA" should write to 
                'stateId1': {
                    convert: function(val) {}, //(optional) functions should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                },     
                'stateId3': {
                    convert: function(val) {}, //(optional) functions should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                },
                ...
            },
        },
        ...
    }
}
*/

//generic virtual device        
function VirtualDevice(config) {
    //sanity check
    if (typeof config !== 'object' || typeof config.namespace !== 'string' || typeof config.name !== 'string' || typeof config.states !== 'object') {
        log('sanity check failed, no device created', 'warn');
        return;
    }

    this.config = config;
    this.namespace = 'virtualDevice.' + config.namespace + '.' + config.name;
    this.name = config.name;

    //create virtual device
    log('creating virtual device ' + this.namespace)
    this.createDevice(function () {
        this.createStates(function () {
            log('created virtual device ' + this.namespace)
        }.bind(this));
    }.bind(this));
}

VirtualDevice.prototype.createDevice = function (callback) {
    log('creating object for device ' + this.namespace, 'debug');
    //create device object
    var obj = this.config.copy ? getObject(this.config.copy) : {common: {}, native: {}};
    delete obj.common.custom;
    if (typeof this.config.common === 'object') {
        obj.common = Object.assign(obj.common, this.config.common);
    }
    if (typeof this.config.native === 'object') {
        obj.native = Object.assign(obj.native, this.config.native);
    }
    extendObject('javascript.' + instance + '.' + this.namespace, {
        type: "device",
        common: obj.common,
        native: obj.native
    }, function (err) {
        if (err) {
            log('could not create virtual device: ' + this.namespace, 'warn');
            return;
        }
        log('created object for device ' + this.namespace, 'debug');
        if (typeof this.config.onCreate === 'function') {
            this.config.onCreate(this, callback);
        } else {
            callback();
        }
    }.bind(this));
}

VirtualDevice.prototype.createStates = function (callback) {
    "use strict";
    log('creating states for device ' + this.namespace, 'debug');
    var stateIds = Object.keys(this.config.states);
    log('creating states ' + JSON.stringify(stateIds), 'debug');
    var countCreated = 0;
    for (var i = 0; i &lt; stateIds.length; i++) {
        let stateId = stateIds[i];
        this.normalizeState(stateId);
        var id = this.namespace + '.' + stateId;
        log('creating state ' + id, 'debug');
        var obj = this.config.states[stateId].copy ? getObject(this.config.states[stateId].copy) : {
            common: {},
            native: {}
        };
        delete obj.common.custom;
        if (typeof this.config.states[stateId].common === 'object') {
            obj.common = Object.assign(obj.common, this.config.states[stateId].common);
        }
        if (typeof this.config.states[stateId].native === 'object') {
            obj.native = Object.assign(obj.native, this.config.states[stateId].native);
        }
        createState(id, obj.common, obj.native, function (err) {
            if (err) {
                log('skipping creation of state ' + id, 'debug');
            } else {
                log('created state ' + id, 'debug');
            }
            this.connectState(stateId);
            countCreated++;
            if (countCreated &gt;= stateIds.length) {
                log('created ' + countCreated + ' states for device ' + this.namespace, 'debug');
                callback();
            }
        }.bind(this));
    }
}

VirtualDevice.prototype.normalizeState = function (state) {
    log('normalizing state ' + state, 'debug');
    if (typeof this.config.states[state].read !== 'object') {
        this.config.states[state].read = {};
    }
    if (typeof this.config.states[state].write !== 'object') {
        this.config.states[state].write = {};
    }

    var readIds = Object.keys(this.config.states[state].read);
    for (var i = 0; i &lt; readIds.length; i++) {
        var readId = this.config.states[state].read[readIds[i]];
        if (typeof readId.before !== 'function') {
            this.config.states[state].read[readIds[i]].before = function (device, value, callback) {
                callback()
            };
        }
        if (typeof readId.after !== 'function') {
            this.config.states[state].read[readIds[i]].after = function (device, value) {
            };
        }
    }
    var writeIds = Object.keys(this.config.states[state].write);
    for (i = 0; i &lt; writeIds.length; i++) {
        var writeId = this.config.states[state].write[writeIds[i]];
        if (typeof writeId.before !== 'function') {
            this.config.states[state].write[writeIds[i]].before = function (device, value, callback) {
                callback()
            };
        }
        if (typeof writeId.after !== 'function') {
            this.config.states[state].write[writeIds[i]].after = function (device, value) {
            };
        }
    }
    log('normalized state ' + state, 'debug');
}

VirtualDevice.prototype.connectState = function (state) {
    log('connecting state ' + state, 'debug');
    var id = this.namespace + '.' + state;

    //subscribe to read ids
    var readIds = Object.keys(this.config.states[state].read);
    for (var i = 0; i &lt; readIds.length; i++) {
        if (getState(readIds[i]).notExist === true) { //check if state exists
            log('cannot connect to not existing state: ' + readIds[i], 'warn');
            continue;
        }
        var readObj = this.config.states[state].read[readIds[i]];
        var trigger = readObj.trigger || {change: 'any'};
        trigger.ack = true;
        trigger.id = readIds[i];
        this.subRead(trigger, readObj, state);
        log('connected ' + readIds[i] + ' to ' + id, 'debug');
    }

    //subscribe to this state and write to write ids
    var writeIds = Object.keys(this.config.states[state].write);
    var trigger = {id: 'javascript.' + instance + '.' + this.namespace + '.' + state, change: 'any', ack: false};
    on(trigger, function (obj) {
        "use strict";
        log('detected change of ' + state, 'debug');
        for (var i = 0; i &lt; writeIds.length; i++) {
            let writeObj = this.config.states[state].write[writeIds[i]];
            let val = this.convertValue(obj.state.val, writeObj.convert);
            let writeId = writeIds[i];
            log('executing function before for ' + writeId, 'debug');
            writeObj.before(this, val, function (newVal, newDelay) {
                if (newVal !== undefined &amp;&amp; newVal !== null) val = newVal;
                var delay = writeObj.delay;
                if (newDelay !== undefined &amp;&amp; newDelay !== null) delay = newDelay;
                log(newVal + 'writing value ' + val + ' to ' + writeId + ' with delay ' + delay, 'debug');
                setStateDelayed(writeId, val, false, delay || 0, true, function () {
                    log('executing function after for ' + writeId, 'debug');
                    writeObj.after(this, val);
                }.bind(this));
            }.bind(this));
        }
    }.bind(this));
    log('connected ' + state + ' to ' + JSON.stringify(writeIds), 'debug');
}

VirtualDevice.prototype.subRead = function (trigger, readObj, state) {
    var func = function (obj) {
        var val = this.convertValue(obj.state.val, readObj.convert);

        //@todo aggregations

        log('executing function before for ' + trigger.id, 'debug');
        readObj.before(this, val, function (newVal, newDelay) {
            if (newVal !== undefined &amp;&amp; newVal !== null) val = newVal;
            if (newDelay !== undefined &amp;&amp; newDelay !== null) writeObj.delay = newDelay;
            log('reading value ' + val + ' to ' + this.namespace + '.' + state, 'debug');
            setStateDelayed(this.namespace + '.' + state, val, true, readObj.delay || 0, true, function () {
                log('executing function after for ' + trigger.id, 'debug');
                readObj.after(this, val);
            }.bind(this));
        }.bind(this));
    }.bind(this);
    func({state: getState(trigger.id)});
    on(trigger, func);
}

VirtualDevice.prototype.convertValue = function (val, func) {
    if (typeof func !== 'function') {
        return val;
    }
    return func(val);
}`[/i][/i][/i][/i][/i][/i]
</code></pre>
]]></description><link>https://forum.iobroker.net/topic/7751/virtual-devices</link><generator>RSS for Node</generator><lastBuildDate>Wed, 19 Aug 2026 00:25:22 GMT</lastBuildDate><atom:link href="https://forum.iobroker.net/topic/7751.rss" rel="self" type="application/rss+xml"/><pubDate>Mon, 25 Sep 2017 00:25:30 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Virtual Devices on Sun, 13 Jul 2025 08:49:53 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/johannes-t%C3%A4uber" aria-label="Profile: johannes-täuber">@<bdi>johannes-täuber</bdi></a> Das hängt davon ab ob du neue, also nicht existente Datenpunkte für das Gerät brauchst oder ob du nur existente Bündeln möchtest.</p>
<p dir="auto">Mit dem devices Adapter lassen sich bestehende Datenpunkte bündeln, diese werden dann als Alias in einer gemeinsamen Objekt Struktur angelegt.</p>
<p dir="auto">Sobald man eigene Datenpunkte hinzufügen möchte muss man sich das selber Bauen, da es keinen Alias geben kann der mit keinem anderen Datenpunkte verknüpft ist.</p>
]]></description><link>https://forum.iobroker.net/post/1282968</link><guid isPermaLink="true">https://forum.iobroker.net/post/1282968</guid><dc:creator><![CDATA[Jey Cee]]></dc:creator><pubDate>Sun, 13 Jul 2025 08:49:53 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Sun, 13 Jul 2025 08:31:07 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/johannes-t%C3%A4uber" aria-label="Profile: johannes-täuber">@<bdi>johannes-täuber</bdi></a> sagte in <a href="/post/1282953">Virtual Devices</a>:</p>
<blockquote>
<p dir="auto">ob das immer noch die beste Lösung fuer <strong>das virtualisieren von devices</strong> ist</p>
</blockquote>
<p dir="auto">was verstehst du darunter?</p>
<p dir="auto">Vermutlich alias?</p>
]]></description><link>https://forum.iobroker.net/post/1282958</link><guid isPermaLink="true">https://forum.iobroker.net/post/1282958</guid><dc:creator><![CDATA[Homoran]]></dc:creator><pubDate>Sun, 13 Jul 2025 08:31:07 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Sun, 13 Jul 2025 08:04:12 GMT]]></title><description><![CDATA[<p dir="auto">Hallo zusammen, dieser Thread ist ziehmlich alt. Ich würde gerne wissen ob das immer noch die beste Lösung fuer das virtualisieren von devices ist oder ob es inzwischen andere Sachen gibt! Danke!</p>
]]></description><link>https://forum.iobroker.net/post/1282953</link><guid isPermaLink="true">https://forum.iobroker.net/post/1282953</guid><dc:creator><![CDATA[Johannes Täuber]]></dc:creator><pubDate>Sun, 13 Jul 2025 08:04:12 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Sat, 11 Dec 2021 12:43:46 GMT]]></title><description><![CDATA[<p dir="auto">Mit Bezug auf die letzte Frage zum Skript möchte ich euch nicht eine neuere Version des Skripts vorenthalten, welche dieses und weitere Probleme einfacher lösen kann.  Unter dem Skript noch ein Beispiel, wie man die neue Logik-Funktion nutzen kann.<br />
<strong>Achtung</strong>: Grundsätzlich sollte das Skript mit der alten Version kompatibel sein, allerdings werden die Geräte nun standardmäßig unter "0_userdata.0.virtualDevice" angelegt. Um dies rückgängig zu machen siehe im Skript Zeile 57.<br />
Wie immer: <strong>vorher dem Update ein Backup machen</strong>.</p>
<pre><code>/*
VirtualDevice v1.0
 
Structure of config:
{
    name: 'name', //name of device
    namespace: '', //create device within this namespace (device ID will be namespace.name)
    common: {}, //(optional)
    native: {}, //(optional)
    copy: objectId, //(optional) ID of device or channel to copy common and native from
    onCreate: function(device, callback) {} //called once on device creation
    states: {
        'stateA': { //State Id will be namespace.name.stateA
            common: {}, //(optional)
            native: {}, //(optional)
            copy: stateId,
            read: {
                //(optional) states which should write to "stateA"
                'stateId1': {
                    trigger: {ack: true, change: 'any'} //(optional) see https://github.com/ioBroker/ioBroker.javascript#on---subscribe-on-changes-or-updates-of-some-state
                    convert: function(val) {}, //(optional) function should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                },
                ...
            },
            logic: { //(optional), default type: last
                type, //can be one of: 'last' || 'number.sum' || 'number.max' || 'number.min' || 'number.average' || 'string.concat'
                parameters //(optional) depends on type: number {decimals: 1} / string {separator: " "} / 
            }, 
            write: {
                //(optional) states which "stateA" should write to 
                'stateId1': {
                    convert: function(val) {}, //(optional) function should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                },     
                ...
            },
        },
        ...
    }
}
*/

//generic virtual device        
function VirtualDevice(config) {
    //sanity check
    if (typeof config !== 'object' || typeof config.namespace !== 'string' || typeof config.name !== 'string' || typeof config.states !== 'object') {
        log('sanity check failed, no device created', 'warn');
        return;
    }

    this.config = config;
    this.globalNamespace = '0_userdata.0'; //old: 'javascript.' + instance + '.';
    this.sandboxNamespace = 'virtualDevice.' + config.namespace + '.' + config.name;
    this.namespace = this.globalNamespace + '.' + this.sandboxNamespace;
    this.name = config.name;
    this.data = {};
    

    //create virtual device
    log('creating virtual device ' + this.sandboxNamespace)
    this.createDevice(function () {
        this.createStates(function () {
            log('created virtual device ' + this.namespace)
        }.bind(this));
    }.bind(this));
}

VirtualDevice.prototype.createDevice = function (callback) {
    log('creating object for device ' + this.sandboxNamespace, 'debug');
    //create device object
    var obj = this.config.copy ? getObject(this.config.copy) : {common: {}, native: {}};
    // @ts-ignore
    delete obj.common.custom;
    if (typeof this.config.common === 'object') {
        obj.common = Object.assign(obj.common, this.config.common);
    }
    if (typeof this.config.native === 'object') {
        obj.native = Object.assign(obj.native, this.config.native);
    }
    extendObject(this.namespace, {
        type: 'device',
        common: obj.common,
        native: obj.native
    }, function (err) {
        if (err) {
            log('could not create virtual device: ' + this.namespace, 'warn');
            return;
        }
        log('created object for device ' + this.namespace, 'debug');
        if (typeof this.config.onCreate === 'function') {
            this.config.onCreate(this, callback);
        } else {
            callback();
        }
    }.bind(this));
}

VirtualDevice.prototype.createStates = function (callback) {
    "use strict";
    log('creating states for device ' + this.sandboxNamespace, 'debug');
    var stateIds = Object.keys(this.config.states);
    log('creating states ' + JSON.stringify(stateIds), 'debug');
    var countCreated = 0;
    for (var i = 0; i &lt; stateIds.length; i++) {
        let stateId = stateIds[i];
        this.normalizeState(stateId);
        var id = this.sandboxNamespace + '.' + stateId;
        log('creating state ' + id, 'debug');
        var obj = this.config.states[stateId].copy ? getObject(this.config.states[stateId].copy) : {
            common: {},
            native: {}
        };
        // @ts-ignore
        delete obj.common.custom;
        if (typeof this.config.states[stateId].common === 'object') {
            obj.common = Object.assign(obj.common, this.config.states[stateId].common);
        }
        if (typeof this.config.states[stateId].native === 'object') {
            obj.native = Object.assign(obj.native, this.config.states[stateId].native);
        }
        // @ts-ignore
        if (!obj.common.type) {
            // @ts-ignore
            obj.common.type = 'mixed';
        }
        // @ts-ignore
        if (!obj.common.role) {
            // @ts-ignore
            obj.common.role = 'state';
        }
        // @ts-ignore
        if (!obj.common.name) {
            // @ts-ignore
            obj.common.name = stateId;
        }
        extendObject(this.globalNamespace + '.' + id, {
            type: 'state',
            common: obj.common,
            native: obj.native
        }, function (err) {
            if (err) {
                log('skipping creation of state ' + id, 'debug');
            } else {
                log('created state ' + id, 'debug');
            }
            setTimeout(() =&gt; {this.connectState(stateId)}, 1000);
            countCreated++;
            if (countCreated &gt;= stateIds.length) {
                log('created ' + countCreated + ' states for device ' + this.namespace, 'debug');
                callback();
            }
        }.bind(this));
    }
}

VirtualDevice.prototype.normalizeState = function (stateId) {
    log('normalizing state ' + stateId, 'debug');
    if (typeof this.config.states[stateId].read !== 'object') {
        this.config.states[stateId].read = {};
    }
    if (typeof this.config.states[stateId].write !== 'object') {
        this.config.states[stateId].write = {};
    }

    this.data[stateId] = {read: {}, write:{}, val: undefined};
    var readIds = Object.keys(this.config.states[stateId].read);
    for (var i = 0; i &lt; readIds.length; i++) {
        this.data[stateId].read[readIds[i]] = null; 
        var readId = this.config.states[stateId].read[readIds[i]];
        if (typeof readId.before !== 'function') {
            this.config.states[stateId].read[readIds[i]].before = function (device, value, callback) {
                callback()
            };
        }
        if (typeof readId.after !== 'function') {
            this.config.states[stateId].read[readIds[i]].after = function (device, value) {
            };
        }
    }
    var writeIds = Object.keys(this.config.states[stateId].write);
    for (i = 0; i &lt; writeIds.length; i++) {
        this.data[stateId].write[writeIds[i]] = null; 
        var writeId = this.config.states[stateId].write[writeIds[i]];
        if (typeof writeId.before !== 'function') {
            this.config.states[stateId].write[writeIds[i]].before = function (device, value, callback) {
                callback()
            };
        }
        if (typeof writeId.after !== 'function') {
            this.config.states[stateId].write[writeIds[i]].after = function (device, value) {
            };
        }
    }
    log('normalized state ' + stateId, 'debug');
}

VirtualDevice.prototype.connectState = function (stateId) {
    log('connecting state ' + stateId, 'debug');
    let id = this.sandboxNamespace + '.' + stateId;

    //subscribe to read ids
    let readIds = Object.keys(this.config.states[stateId].read);
    for (let i = 0; i &lt; readIds.length; i++) {
        //check if state exists
        getObject(readIds[i], function (err, obj) {
            // @ts-ignore
            if (err || obj.type !== 'state') {
                log('cannot connect to not existing state: ' + readIds[i] + '|' + err + '|' + JSON.stringify(obj), 'warn');
                return;
            }
            var readObj = this.config.states[stateId].read[readIds[i]];
            var trigger_temp = readObj.trigger || {change: 'any'};
            trigger_temp.ack = true;
            trigger_temp.id = readIds[i];
            this.subRead(trigger_temp, readObj, stateId);
            log('connected ' + readIds[i] + ' to ' + id, 'debug');
        }.bind(this));
    }

    //subscribe to this state and write to write ids
    var writeIds = Object.keys(this.config.states[stateId].write);
    var trigger = {id: this.namespace + '.' + stateId, change: 'any', ack: false};
    // @ts-ignore
    on(trigger, function (obj) {
        "use strict";
        log('detected change of ' + stateId, 'debug');
        for (var i = 0; i &lt; writeIds.length; i++) {
            let writeObj = this.config.states[stateId].write[writeIds[i]];
            let val = obj.state.val;
            try {
                val = this.convertValue(obj.state.val, writeObj.convert);
            } catch (e) {
                log('device "' + this.name + '" caused an error in write convert function:' + e, 'warn');
                continue;
            }
            let writeId = writeIds[i];
            log('executing function before for ' + writeId, 'debug');
            try {
                writeObj.before(this, val, function (newVal, newDelay) {
                    if (newVal !== undefined &amp;&amp; newVal !== null) val = newVal;
                    var delay = writeObj.delay;
                    if (newDelay !== undefined &amp;&amp; newDelay !== null) delay = newDelay;
                    log('writing value ' + val + ' to ' + writeId + ' with delay ' + delay, 'debug');
                    this.data[stateId].val = val;
                    setStateDelayed(writeId, val, false, delay || 0, true, function () {
                        log('executing function after for ' + writeId, 'debug');
                        writeObj.after(this, val);
                    }.bind(this));
                }.bind(this));
            } catch (e) {
                log('device "' + this.name + '" caused an error in a write function:' + e, 'warn');
                continue;
            }
        }
    }.bind(this));
    log('connected ' + stateId + ' to ' + JSON.stringify(writeIds), 'debug');
}

VirtualDevice.prototype.subRead = function (trigger, readObj, stateId) {
    //function to process read states
    var onRead = function (obj) {
        let val = obj.state.val; 
        try {
            val = this.convertValue(obj.state.val, readObj.convert);
        } catch (e) {
            log('device "' + this.name + '" caused an error in read convert function:' + e, 'warn');
            return;
        }
        log('executing function before for ' + trigger.id, 'debug');
        try {
            readObj.before(this, val, function (newVal, newDelay) {
                if (newVal !== undefined &amp;&amp; newVal !== null) val = newVal;
                if (newDelay !== undefined &amp;&amp; newDelay !== null) readObj.delay = newDelay;
                log('reading value ' + val + ' into ' + this.namespace + '.' + stateId, 'debug');
                this.data[stateId].read[trigger.id] = val; 
                let aggregatedVal = this.aggregateRead(stateId, trigger.id);  
                this.data[stateId].val = aggregatedVal;              
                setStateDelayed(this.namespace + '.' + stateId, aggregatedVal, true, readObj.delay || 0, true, function () {
                    log('executing function after for ' + trigger.id, 'debug');
                    readObj.after(this, aggregatedVal);
                }.bind(this));
            }.bind(this));
        } catch (e) {
            log('device "' + this.name + '" caused an error in a read function:' + e, 'warn');
            return;
        }
    }.bind(this);

    //subscribe to state
    on(trigger, onRead);

    //get state once initially
    getState(trigger.id, function (err, state) {
        if (!err &amp;&amp; state) {
            onRead({state: state});
        }
    });
}

VirtualDevice.prototype.convertValue = function (val, func) {
    if (typeof func !== 'function') {
        return val;
    }
    return func(val);
}

VirtualDevice.prototype.aggregateRead = function (stateId, readId) {
    var aggregatedVal = this.data[stateId].read[readId];
    if (!this.config.states[stateId].logic || !this.config.states[stateId].logic.type) {
        return aggregatedVal;
    }
    switch(this.config.states[stateId].logic.type) {
        case 'last':
            //use value of state that triggered this function
            aggregatedVal = this.data[stateId].read[readId];
            if (this.config.states[stateId].logic.parameters &amp;&amp; typeof this.config.states[stateId].logic.parameters.decimals === 'number') {
                aggregatedVal = Number(aggregatedVal.toFixed(this.config.states[stateId].logic.parameters.decimals));
            }
            break;
        case 'number.sum':
            var values = Object.values(this.data[stateId].read).filter(value =&gt; typeof value === 'number');
            aggregatedVal = values.reduce((accumulator, current) =&gt; accumulator + current);
            if (this.config.states[stateId].logic.parameters &amp;&amp; typeof this.config.states[stateId].logic.parameters.decimals === 'number') {
                aggregatedVal = Number(aggregatedVal.toFixed(this.config.states[stateId].logic.parameters.decimals));
            }
            break;
        case 'number.min':
            var values = Object.values(this.data[stateId].read).filter(value =&gt; typeof value === 'number');
            aggregatedVal = Math.min(...values);
            if (this.config.states[stateId].logic.parameters &amp;&amp; typeof this.config.states[stateId].logic.parameters.decimals === 'number') {
                aggregatedVal = Number(aggregatedVal.toFixed(this.config.states[stateId].logic.parameters.decimals));
            }
            break;
        case 'number.max':
            var values = Object.values(this.data[stateId].read).filter(value =&gt; typeof value === 'number');
            aggregatedVal = Math.max(...values);
            if (this.config.states[stateId].logic.parameters &amp;&amp; typeof this.config.states[stateId].logic.parameters.decimals === 'number') {
                aggregatedVal = Number(aggregatedVal.toFixed(this.config.states[stateId].logic.parameters.decimals));
            }
            break;
        case 'number.average': 
            var values = Object.values(this.data[stateId].read).filter(value =&gt; typeof value === 'number');
            aggregatedVal = values.length ? values.reduce((accumulator, current) =&gt; accumulator + current) / values.length : 0;
            if (this.config.states[stateId].logic.parameters &amp;&amp; typeof this.config.states[stateId].logic.parameters.decimals === 'number') {
                aggregatedVal = Number(aggregatedVal.toFixed(this.config.states[stateId].logic.parameters.decimals));
            }
            break;
        case 'string.concat':
            var values = Object.values(this.data[stateId].read).filter(value =&gt; typeof value === 'string');
            var separator = " ";
            if (this.config.states[stateId].logic.parameters &amp;&amp; typeof this.config.states[stateId].logic.parameters.separator === 'string') {
                separator = this.config.states[stateId].logic.parameters.separator;
            }
            aggregatedVal = values.join(separator);
            break;
        default:
            //use value of state that triggered this function
            aggregatedVal = this.data[stateId].read[readId];
            break;
    }
    return aggregatedVal;
}
</code></pre>
<p dir="auto">Als Beispiel für die neue Funktion bietet sich ein Gruppierungsgerät an, das die Werte mehrerer Geräte zusammenfasst.<br />
In diesem Fall habe ich meine Thermostate zusammengefasst. <em><strong>valveOpen</strong></em> zeigt z.B. die Anzahl der Ventile mit einem Wert &gt; 0 an, <em><strong>maxTemp</strong></em> zeigt die höchste Temperatur an usw.</p>
<pre><code>new VirtualDevice({
    "namespace": "Heizung.Gruppe",
    "name": "alle",
    "states": {
        "valveOpen": {
            "common": {
                "type": "number",
                "min": 0,
                "def": 0,
                "read": true,
                "write": false,
                "unit": "Valves",
                "role": "value.counter"
            },
            "read": {
                "0_userdata.0.virtualDevice.Heizung.Wohnzimmer.valve": {
                    "convert": function(value) {
                        return value ? 1 : 0
                    }
                },
                "0_userdata.0.virtualDevice.Heizung.Badezimmer.valve": {
                    "convert": function(value) {
                        return value ? 1 : 0
                    }
                },
                "0_userdata.0.virtualDevice.Heizung.Schlafzimmer.valve": {
                    "convert": function(value) {
                        return value ? 1 : 0
                    }
                }
            },
            "logic": {
                "type": "number.sum"
            }
        },
        "valveClosed": {
            "common": {
                "type": "number",
                "min": 0,
                "def": 0,
                "read": true,
                "write": false,
                "unit": "Valves",
                "role": "value.counter"
            },
            "read": {
                "0_userdata.0.virtualDevice.Heizung.Wohnzimmer.valve": {
                    "convert": function(value) {
                        return value ? 0 : 1
                    }
                },
                "0_userdata.0.virtualDevice.Heizung.Badezimmer.valve": {
                    "convert": function(value) {
                        return value ? 0 : 1
                    }
                },
                "0_userdata.0.virtualDevice.Heizung.Schlafzimmer.valve": {
                    "convert": function(value) {
                        return value ? 0 : 1
                    }
                }
            },
            "logic": {
                "type": "number.sum"
            }
        },
        "minTemp": {
            "common": {
                "type": "number",
                "unit": "°C",
                "def": 0,
                "min": -10,
                "max": 50,
                "read": true,
                "write": false,
                "role": "value.temperature"
            },
            "read": {
                "0_userdata.0.virtualDevice.Heizung.Wohnzimmer.temperature": {},
                "0_userdata.0.virtualDevice.Heizung.Badezimmer.temperature": {},
                "0_userdata.0.virtualDevice.Heizung.Schlafzimmer.temperature": {}
            },
            "logic": {
                "type": "number.min"
            }
        },
        "maxTemp": {
            "common": {
                "type": "number",
                "unit": "°C",
                "def": 0,
                "min": -10,
                "max": 50,
                "read": true,
                "write": false,
                "role": "value.temperature"
            },
            "read": {
                "0_userdata.0.virtualDevice.Heizung.Wohnzimmer.temperature": {},
                "0_userdata.0.virtualDevice.Heizung.Badezimmer.temperature": {},
                "0_userdata.0.virtualDevice.Heizung.Schlafzimmer.temperature": {}
            },
            "logic": {
                "type": "number.max"
            }
        },
        "avgTemp": {
            "common": {
                "type": "number",
                "unit": "°C",
                "def": 0,
                "min": -10,
                "max": 50,
                "read": true,
                "write": false,
                "role": "value.temperature"
            },
            "read": {
                "0_userdata.0.virtualDevice.Heizung.Wohnzimmer.temperature": {},
                "0_userdata.0.virtualDevice.Heizung.Badezimmer.temperature": {},
                "0_userdata.0.virtualDevice.Heizung.Schlafzimmer.temperature": {}
            },
            "logic": {
                "type": "number.average",
                "parameters": {
                    "decimals": 1
                }
            }
        },
        "test": {
            "common": {
                "type": "string",
                "read": true,
                "write": false,
                "role": "value"
            },
            "read": {
                "0_userdata.0.virtualDevice.Heizung.Wohnzimmer.temperature": {
                    "convert": function(value) {
                        return value + '°C'
                    }
                },
                "0_userdata.0.virtualDevice.Heizung.Badezimmer.temperature": {
                    "convert": function(value) {
                        return value + '°C'
                    }
                },
                "0_userdata.0.virtualDevice.Heizung.Schlafzimmer.temperature": {
                    "convert": function(value) {
                        return value + '°C'
                    }
                }
            },
            "logic": {
                "type": "string.concat",
                "parameters": {
                    "separator": " | "
                }
            }
        }
    }
});
</code></pre>
]]></description><link>https://forum.iobroker.net/post/718181</link><guid isPermaLink="true">https://forum.iobroker.net/post/718181</guid><dc:creator><![CDATA[Pman]]></dc:creator><pubDate>Sat, 11 Dec 2021 12:43:46 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Fri, 10 Dec 2021 17:06:08 GMT]]></title><description><![CDATA[<p dir="auto">War schon etwas länger nicht im Forum aktiv, das Skript scheint noch aktiv genutzt zu werden (läuft bei mir auch im 24/7 Einsatz!).<br />
Um auf die letzte Frage einzugehen <a class="plugin-mentions-user plugin-mentions-a" href="/user/j1s2e3" aria-label="Profile: j1s2e3">@<bdi>j1s2e3</bdi></a> :</p>
<p dir="auto">Dafür reicht die <em>convert</em> Funktion nicht aus, du kannst aber <em>before</em> nutzen, dort hast du als Parameter nicht nur den <em>val</em> sondern auch das virtualDevice selber und eine callback funktion, der dein berechneter Wert übergeben wird, erst dann wird geschrieben. Ein etwas umständlicher Weg wäre es, in der Funktion einfach per getState() (aus dem Javascript Adapter) die jeweils anderen Werte abzufragen und dann den ON wert zu berechnen. Da du aber auch Zugriff auf das virtuelle Gerät bekommst kannst du beliebige Werte direkt im Gerät-Objekt speichern.<br />
Beispiel (nicht getestet, wirst aber die Idee dahinter verstehen):</p>
<pre><code>new VirtualDevice({
            namespace: 'enocean_0',
            name: '03_woz_A5_FRGBW71L',
            onCreate: function (device, callback) {
                device.myStorage = {
                    R: 0,
                    G: 0,
                    B: 0,
                    W: 0,
                };
                callback();
            },
            states: {
                //... rgbw states
                'ON': {
                    common: {type: 'boolean', def: false, read: true, write: false},
                    read: {
                        [id_03_woz_A5_FRGBW71L + ".R"]: {
                            before: function (device, value, callback) {
                                device.myStorage.R = value;
                                callback(device.myStorage.R || device.myStorage.G || device.myStorage.B || device.myStorage.W);
                            }
                        },
                        [id_03_woz_A5_FRGBW71L + ".G"]: {
                            before: function (device, value, callback) {
                                device.myStorage.G = value;
                                callback(device.myStorage.R || device.myStorage.G || device.myStorage.B || device.myStorage.W);
                            }
                        },
                        [id_03_woz_A5_FRGBW71L + ".B"]: {
                            before: function (device, value, callback) {
                                device.myStorage.B = value;
                                callback(device.myStorage.R || device.myStorage.G || device.myStorage.B || device.myStorage.W);
                            }
                        },
                        [id_03_woz_A5_FRGBW71L + ".W"]: {
                            before: function (device, value, callback) {
                                device.myStorage.W = value;
                                callback(device.myStorage.R || device.myStorage.G || device.myStorage.B || device.myStorage.W);
                            }
                        }
                    }
                }
            }
        });
</code></pre>
]]></description><link>https://forum.iobroker.net/post/718150</link><guid isPermaLink="true">https://forum.iobroker.net/post/718150</guid><dc:creator><![CDATA[Pman]]></dc:creator><pubDate>Fri, 10 Dec 2021 17:06:08 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Tue, 07 Dec 2021 15:29:36 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/pman" aria-label="Profile: pman">@<bdi>pman</bdi></a> Ich habe dein Skipt im "einfachen" Einsatz. Funktioniert sehr gut. Danke!</p>
<p dir="auto">Jetzt habe ich einen Anwendungsfall, wo ich erstmal an meine Grenzen stosse. Javascript ist nicht meine Welt, sondern Embedded Linux.</p>
<p dir="auto">Folgendes Setup:</p>
<p dir="auto">Ich habe einen Enocean RGBW Controller. Der geht soweit in ioBroker. Der hat folgende Datenpunkte:<br />
R, G, B, W jeweils 0-1023 als high resolution Dimmwert. 0=aus 1023=max. Helligkeit. Dazu ein DP CMD. Schreibt man dort 0(R), 1(G), 2(B) oder 3(W) rein, dann wird der in R, G, B oder W hinterlegte Dimmwert am LED Strip eingestellt.</p>
<p dir="auto">Ich habe jetzt erstmal einen virtuelles Gerät angelegt, welche die absoluten Dimmwerte 0-1023 in Prozentwerte 0-100% konvertiert. Das geht.</p>
<p dir="auto">Jetzt versuche ich einen DP "ON", welcher nur im virtuellen JS-Gerät existiert, anzulegen. Das klappt erstmal auch.</p>
<p dir="auto">So sieht das Skript aktuell aus:</p>
<pre><code>let id_03_woz_A5_FRGBW71L = "enocean.0.ffb2fd86";

function roundToTwo(num) {
    return +(Math.round(num + "e+2")  + "e-2");
}

new VirtualDevice({
    namespace: 'enocean_0',
    name: '03_woz_A5_FRGBW71L',
    states: {
        'R': {
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                [id_03_woz_A5_FRGBW71L + ".R"]: {
                    convert: function (val) {return roundToTwo((val * 100) / 1023);}
                }
            },
            write: {
                [id_03_woz_A5_FRGBW71L + ".R"]: {
                    convert: function (val) {return Math.round((val * 1023) / 100);}
                }
            }
        },
        'G': {
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                [id_03_woz_A5_FRGBW71L + ".G"]: {
                    convert: function (val) {return roundToTwo((val * 100) / 1023);
                    }
                }
            },
            write: {
                [id_03_woz_A5_FRGBW71L + ".G"]: {
                    convert: function (val) {return Math.round((val * 1023) / 100);}
                }
            }
        },
        'B': {
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                [id_03_woz_A5_FRGBW71L + ".B"]: {
                    convert: function (val) {return roundToTwo((val * 100) / 1023);}
                }
            },
            write: {
                [id_03_woz_A5_FRGBW71L + ".B"]: {
                    convert: function (val) {return Math.round((val * 1023) / 100);}
                }
            }
        },
        'W': {
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                [id_03_woz_A5_FRGBW71L + ".W"]: {
                    convert: function (val) {return roundToTwo((val * 100) / 1023);}
                }
            },
            write: {
                [id_03_woz_A5_FRGBW71L + ".W"]: {
                    convert: function (val) {return Math.round((val * 1023) / 100);}
                }
            }
        },
        'ON': {
            common: {type: 'boolean', def: false, read: true, write: false},
            read: {
                [id_03_woz_A5_FRGBW71L + ".R"]: {
                    convert: function (val) {return val == 0 ? false : true;}
                },
                [id_03_woz_A5_FRGBW71L + ".G"]: {
                    convert: function (val) {return val == 0 ? false : true;}
                },
                [id_03_woz_A5_FRGBW71L + ".B"]: {
                    convert: function (val) {return val == 0 ? false : true;}
                },
                [id_03_woz_A5_FRGBW71L + ".W"]: {
                    convert: function (val) {return val == 0 ? false : true;}
                }
            }
        }
    }
});
</code></pre>
<p dir="auto">Wie kann ich die Werte für R, G, B und W von ON logisch auswerten, kombinieren?</p>
<p dir="auto">D.h. der virtuelle DP "ON" soll true sein, wenn R, oder G, oder B, oder W größer 0 ist, und false wenn R, G, B und W 0 sind, also keine LED leuchtet?</p>
<p dir="auto">So wie oben, werden zwar die DP R, G, B, W vom Enocean Gerät gelesen, richtig nach true/false konvertiert, aber nicht logisch miteinander verküpft. Ich habe keine Idee, wie ich das im Kontext deines Skriptes anstellen soll???</p>
<pre><code>[id_03_woz_A5_FRGBW71L + ".R"]: {
    convert: function (val) {return val == 0 ? false : true;}
},
</code></pre>
<p dir="auto">Wie bekommen ich den Returnwert von diesem Statement in eine Variable z.B. is_R, ditto für G, B und W, um dann sowas wie if (is_R || is_G || is_B || is_W) set ON true; else set ON false;</p>
]]></description><link>https://forum.iobroker.net/post/716335</link><guid isPermaLink="true">https://forum.iobroker.net/post/716335</guid><dc:creator><![CDATA[j1s2e3]]></dc:creator><pubDate>Tue, 07 Dec 2021 15:29:36 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Sat, 27 Nov 2021 08:28:02 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/zerberus" aria-label="Profile: zerberus">@<bdi>zerberus</bdi></a> Danke für das TS Code. Habe das jetzt in Benutzung, so wie Du das für das DECT Thermostat verwendest. Ich nehme es für Dimmer, um auch schnell mehrere virtuelle Geräte anzulegen.</p>
<p dir="auto">Was ich noch nicht hinbekommen habe, ist das after. z.B. bei deiner createVirtualThermostat() Funktion: nehmen wir mal an, immer wenn ich <code>targettemp</code>  schreibe, dann soll nach dem Schreiben noch <code>hkrmode</code> geschrieben werden.</p>
<pre><code>    targettemp: {
        common: { type: 'number', role: 'state', read: true, write: true },
        read: {
            [id + '.tsoll']: {},
        },
        write: {
            [id + '.tsoll']: {
                after: function (device, value) {
                    if (value &gt; 25) {
                       setState(id + 'hkrmode', 2);
                    } else {
                       setState(id + 'hkrmode', 1);
                    }
                },
            },
        },
    },
</code></pre>
<p dir="auto">So auf diese Art... das gleiche kommt dann auch noch für convert etc... D.h. in der Funktion, mit welcher man schnell mehrere virtuelle Geräte anlegt, brauche ich unter read: und write: auch noch convert, after etc.</p>
<p dir="auto">Ein (paar) Beispiel(e) dafür wäre(n) super.</p>
]]></description><link>https://forum.iobroker.net/post/710656</link><guid isPermaLink="true">https://forum.iobroker.net/post/710656</guid><dc:creator><![CDATA[j1s2e3]]></dc:creator><pubDate>Sat, 27 Nov 2021 08:28:02 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Mon, 23 Aug 2021 16:22:13 GMT]]></title><description><![CDATA[<p dir="auto">hi ich habe den Code mal nach TypeScript portiert, macht es einfacher diesen zu verwenden:</p>
<p dir="auto"><a href="https://gist.github.com/many20/3a5b047bd221ec107153c0231b575ca3" rel="nofollow ugc">https://gist.github.com/many20/3a5b047bd221ec107153c0231b575ca3</a></p>
<pre><code>//https://forum.iobroker.net/topic/7751/virtual-devices/2
/*
VirtualDevice v0.3
{1}
Structure of config:
{
    name: 'name', //name of device
    namespace: '', //create device within this namespace (device ID will be namespace.name)
    common: {}, //(optional)
    native: {}, //(optional)
    copy: objectId, //(optional) ID of device or channel to copy common and native from
    onCreate: function(device, callback) {} //called once on device creation
    states: {
        'stateA': { //State Id will be namespace.name.stateA
            common: {}, //(optional)
            native: {}, //(optional)
            copy: stateId,
            read: {
                //(optional) states which should write to "stateA"
                'stateId1': {
                    trigger: {ack: true, change: 'any'} //(optional) see https://github.com/ioBroker/ioBroker.javascript#on---subscribe-on-changes-or-updates-of-some-state
                    convert: function(val) {}, //(optional) functions should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                    validFor: //(optional) ms, to ignore old data which did not change for a long time.  
                },
                ...
            },
            readLogic: 'last' || 'max' || 'min' || 'average', //(optional) default: last (only last implemented)
            write: {
                //(optional) states which "stateA" should write to 
                'stateId1': {
                    convert: function(val) {}, //(optional) functions should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                },     
                'stateId3': {
                    convert: function(val) {}, //(optional) functions should return converted value 
                    before: function(device, value, callback) {}, //(optional) called before writing new state. has to call callback or new value will not be written 
                    delay: 0, //(optional) delay in ms before new value gets written
                    after: function(device, value) {}, //(optional) called after new value has been written
                },
                ...
            },
        },
        ...
    }
}
*/

/*

new VirtualDevice({
    namespace: 'Hue',
    name: 'Wohnzimmer', //das Gerät wird unter javascript.0.virtualDevice.Hue.Wohnzimmer erstellt
    states: {
        //welche States sollen erstellt werden?
        'level': {
            //State Konfiguration
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                //von welchen States sollen Werte eingelesen werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.floor(val * 100 / 254);
                    }
                },
            },
            write: {
                //in welche States sollen Werte geschrieben werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.ceil(val * 254 / 100);
                    },
                    delay: 1500 // schreibe Werte erst nach 1,5 Sekunden in den Adapter (Puffer)
                },
            }
        },
    }
});

new VirtualDevice({
    namespace: 'Hue',
    name: 'Wohnzimmer', //das Gerät wird unter javascript.0.virtualDevice.Hue.Wohnzimmer erstellt
    states: {
        //welche States sollen erstellt werden?
        'level': {
            //State Konfiguration
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},
            read: {
                //von welchen States sollen Werte eingelesen werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.floor(val * 100 / 254);
                    }
                },
            },
            write: {
                //in welche States sollen Werte geschrieben werden?
                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {
                    convert: function (val) { //wert soll konvertiert werden
                        return Math.ceil(val * 254 / 100);
                    },
                    delay: 1500, // schreibe Werte erst nach 1,5 Sekunden in den Adapter (Puffer)
                    before: function (device, value, callback) {
                        if (value &gt; 0 &amp;&amp; getState('zwave.0.NODE10.SWITCH_BINARY.Switch_1').val === false) {
                            //if switch is off and value is greater 0 turn on switch and set long delay
                            setStateDelayed(switchId, true, false, 1500, true, function () {
                                callback(value, 3500);
                            });
                        } else if (value &lt;= 0) {
                            //if level is set to 0 turn off switch and set level 0
                            setStateDelayed(switchId, false, false, 1500, true, function () {
                                callback(0, 0);
                            });
                        } else {
                            callback();
                        }
                    }
                },
            }
        },
    }
});

*/

interface NumberCommon {
    type: 'number';
    def: number;
    min: number;
    max: number;
    read: boolean;
    write: boolean;
    unit: '%' | string;
}

//https://github.com/ioBroker/ioBroker.docs/blob/master/docs/en/dev/objectsschema.md
interface Common {
    /**
     *  (optional - (default is mixed==any type) (possible values: number, string, boolean, array, object, mixed, file). As exception the objects with type meta could have common.type=meta.user or meta.folder
     */
    type?: 'number' | 'string' | 'boolean' | 'array' | 'object' | 'mixed' | 'file';
    /**
     * (optional)
     */
    min?: number;
    /**
     * (optional)
     */
    max?: number;
    /**
     * (optional) - increase/decrease interval. E.g. 0.5 for thermostat
     */
    step?: number;
    /**
     * (optional) - unit of the value E.g. C°
     */
    unit?: string;
    /**
     * (optional - the default value)
     */
    def?: any;
    /**
     * (optional - if common.def is set this value is used as ack flag, js-controller 2.0.0+)
     */
    defAck?: any;
    /**
     * (optional, string or object) - description, object for multilingual description
     */
    desc?: string | object;
    /**
     * (optional, string or object) - name of the device
     */
    name?: string;
    /**
     * (boolean, mandatory) - true if state is readable
     */
    read: boolean;
    /**
     * (boolean, mandatory) - true if state is writable
     */
    write: boolean;
    /**
     * (string, mandatory) - role of the state (used in user interfaces to indicate which widget to choose, see below)
     * https://github.com/ioBroker/ioBroker.docs/blob/master/docs/en/dev/stateroles.md
     */
    role: 'state' | 'text' | 'button' | string;
    /**
     * (optional) attribute of type number with object of possible states {'value': 'valueName', 'value2': 'valueName2', 0: 'OFF', 1: 'ON'}
     */
    states?: Record&lt;string, string&gt;;
    /**
     * (string, optional) - if this state has helper state WORKING. Here must be written the full name or just the last part if the first parts are the same with actual. Used for HM.LEVEL and normally has value "WORKING"
     */
    workingID?: string;
    /**
     * (optional) - the structure with custom settings for specific adapters. Like {"influxdb.0": {"enabled": true, "alias": "name"}}. enabled attribute is required and if it is not true, the whole attribute will be deleted.
     */
    custom?: any;
}

interface VirtualDeviceConfigStateRead {
    trigger?: { ack: boolean; change: "eq" | "ne" | "gt" | "ge" | "lt" | "le" | "any" };
    convert?: (val: iobJS.StateValue) =&gt; iobJS.StateValue;
    before?: (device: VirtualDevice, value: iobJS.StateValue, triggerId: string, callback: (newVal?: iobJS.StateValue, newDelay?: number) =&gt; void) =&gt; void;
    delay?: number;
    after?: (device: VirtualDevice, value: iobJS.StateValue, triggerId: string) =&gt; void;
    //validFor?: number;
}

interface VirtualDeviceConfigStateWrite {
    convert?: (val: iobJS.StateValue) =&gt; iobJS.StateValue;
    before?: (device: VirtualDevice, value: iobJS.StateValue, triggerId: string, callback: (newVal?: iobJS.StateValue, newDelay?: number) =&gt; void) =&gt; void;
    delay?: number;
    after?: (device: VirtualDevice, value: iobJS.StateValue, triggerId: string) =&gt; void;
}

interface VirtualDeviceConfigState {
    common?: Partial&lt;Common&gt;;
    native?: Record&lt;string, any&gt;;
    copy?: string;
    read?:  Record&lt;string, VirtualDeviceConfigStateRead&gt;; //stateId
    readLogic?: 'last' | 'max' | 'min' | 'average';
    write?: Record&lt;string, VirtualDeviceConfigStateWrite&gt;; //stateId
}

interface VirtualDeviceConfig {
    namespace: string;
    name: string;
    common?: Partial&lt;Common&gt;;
    native?: Record&lt;string, any&gt;;
    copy?: string;
    onCreate?: (device, callback) =&gt; void;
    states: Record&lt;string, VirtualDeviceConfigState&gt;; //stateId will be namespace.name.stateA
}

export declare interface VirtualDevice {
    config: VirtualDeviceConfig;
    namespace: string;
    name: string;
    createDevice: (callback: () =&gt; void) =&gt; void;
    createStates: (callback: () =&gt; void) =&gt; void;
    normalizeState: (state: string) =&gt; void;
    connectState: (state: string) =&gt; void;
    subRead: (trigger: iobJS.SubscribeOptions, readObj: VirtualDeviceConfigStateRead, state: string) =&gt; void;
    convertValue: (val: iobJS.StateValue, func?: (value: iobJS.StateValue) =&gt; iobJS.StateValue) =&gt; iobJS.StateValue;
}

//generic virtual device        
function VirtualDevice(this: VirtualDevice, config: VirtualDeviceConfig): void {
    //sanity check
    if (typeof config !== 'object' || typeof config.namespace !== 'string' || typeof config.name !== 'string' || typeof config.states !== 'object') {
        log('sanity check failed, no device created', 'warn');
        return;
    }
 
    this.config = config;
    this.namespace = 'virtualDevice.' + config.namespace + '.' + config.name;
    this.name = config.name;
 
    //create virtual device
    log('creating virtual device ' + this.namespace)
    this.createDevice(function (this: VirtualDevice, ) {
        this.createStates(function (this: VirtualDevice, ) {
            log('created virtual device ' + this.namespace)
        }.bind(this));
    }.bind(this));
}

VirtualDevice.prototype.createDevice = function (this: VirtualDevice, callback: () =&gt; void): void {
    log('creating object for device ' + this.namespace, 'debug');
    //create device object
    const obj = this.config.copy ? getObject(this.config.copy) : { common: {}, native: {} };

    if ((obj.common as any).custom) delete (obj.common as any).custom;

    if (typeof this.config.common === 'object') {
        obj.common = Object.assign(obj.common, this.config.common);
    }
    if (typeof this.config.native === 'object') {
        obj.native = Object.assign(obj.native, this.config.native);
    }
    extendObject('javascript.' + instance + '.' + this.namespace, {
        type: "device",
        common: obj.common,
        native: obj.native
    }, function (err) {
        if (err) {
            log(err, 'warn');
            log('could not create virtual device: ' + this.namespace, 'warn');
            return;
        }
        log('created object for device ' + this.namespace, 'debug');
        if (typeof this.config.onCreate === 'function') {
            this.config.onCreate(this, callback);
        } else {
            callback();
        }
    }.bind(this));
}

VirtualDevice.prototype.createStates = function (this: VirtualDevice, callback: () =&gt; void): void {
    "use strict";
    log('creating states for device ' + this.namespace, 'debug');
    const stateIds = Object.keys(this.config.states);
    log('creating states ' + JSON.stringify(stateIds), 'debug');
    let countCreated = 0;
    for (let i = 0; i &lt; stateIds.length; i++) {
        let stateId = stateIds[i];
        this.normalizeState(stateId);
        const id = this.namespace + '.' + stateId;
        log('creating state ' + id, 'debug');
        const obj = this.config.states[stateId].copy ? getObject(this.config.states[stateId].copy) : { common: {}, native: {} };

        if ((obj.common as any).custom) delete (obj.common as any).custom;

        if (typeof this.config.states[stateId].common === 'object') {
            obj.common = Object.assign(obj.common, this.config.states[stateId].common);
        }
        if (typeof this.config.states[stateId].native === 'object') {
            obj.native = Object.assign(obj.native, this.config.states[stateId].native);
        }
        createState(id, obj.common, obj.native, function (err) {
            if (err) {
                log('skipping creation of state ' + id, 'debug');
            } else {
                log('created state ' + id, 'debug');
            }
            this.connectState(stateId);
            countCreated++;
            if (countCreated &gt;= stateIds.length) {
                log('created ' + countCreated + ' states for device ' + this.namespace, 'debug');
                callback();
            }
        }.bind(this));
    }
}

VirtualDevice.prototype.normalizeState = function (this: VirtualDevice, state: string): void {
    log('normalizing state ' + state, 'debug');
    if (typeof this.config.states[state].read !== 'object') {
        this.config.states[state].read = {};
    }
    if (typeof this.config.states[state].write !== 'object') {
        this.config.states[state].write = {};
    }
 
    const readIds = Object.keys(this.config.states[state].read);
    for (let i = 0; i &lt; readIds.length; i++) {
        const readId = this.config.states[state].read[readIds[i]];
        if (typeof readId.before !== 'function') {
            this.config.states[state].read[readIds[i]].before = function (device, value, triggerId, callback) {
                callback()
            };
        }
        if (typeof readId.after !== 'function') {
            this.config.states[state].read[readIds[i]].after = function (device, value, triggerId) {
            };
        }
    }
    const writeIds = Object.keys(this.config.states[state].write);
    for (let i = 0; i &lt; writeIds.length; i++) {
        const writeId = this.config.states[state].write[writeIds[i]];
        if (typeof writeId.before !== 'function') {
            this.config.states[state].write[writeIds[i]].before = function (device, value, triggerId, callback) {
                callback()
            };
        }
        if (typeof writeId.after !== 'function') {
            this.config.states[state].write[writeIds[i]].after = function (device, value, triggerId) {
            };
        }
    }
    log('normalized state ' + state, 'debug');
}

VirtualDevice.prototype.connectState = function (this: VirtualDevice, state: string): void {
    log('connecting state ' + state, 'debug');
    const id = this.namespace + '.' + state;
 
    //subscribe to read ids
    const readIds = Object.keys(this.config.states[state].read);
    for (let i = 0; i &lt; readIds.length; i++) {
        if (getState(readIds[i]).notExist === true) { //check if state exists
            log('cannot connect to not existing state: ' + readIds[i], 'warn');
            continue;
        }
        const readObj = this.config.states[state].read[readIds[i]];
        const trigger: iobJS.SubscribeOptions = readObj.trigger || {change: 'any'};
        trigger.ack = true;
        trigger.id = readIds[i];
        this.subRead(trigger, readObj, state);
        log('connected ' + readIds[i] + ' to ' + id, 'debug');
    }
 
    //subscribe to this state and write to write ids
    const writeIds = Object.keys(this.config.states[state].write);
    const trigger: iobJS.SubscribeOptions = {id: 'javascript.' + instance + '.' + this.namespace + '.' + state, change: 'any', ack: false};
    on(trigger, function (this: VirtualDevice, obj: { state: ReturnType&lt;typeof getState&gt; }) {
        "use strict";
        log('detected change of ' + state, 'debug');
        for (let i = 0; i &lt; writeIds.length; i++) {
            const writeObj = this.config.states[state].write[writeIds[i]];
            let val: iobJS.StateValue = this.convertValue(obj.state.val, writeObj.convert);
            const writeId = writeIds[i];
            log('executing function before for ' + writeId, 'debug');
            writeObj.before(this, val, trigger.id.toString(), function (this: VirtualDevice, newVal?: iobJS.StateValue, newDelay?: number) {
                if (newVal !== undefined &amp;&amp; newVal !== null) val = newVal;
                let delay = writeObj.delay;
                if (newDelay !== undefined &amp;&amp; newDelay !== null) delay = newDelay;
                log(newVal + 'writing value ' + val + ' to ' + writeId + ' with delay ' + delay, 'debug');
                setStateDelayed(writeId, val, false, delay || 0, true, function () {
                    log('executing function after for ' + writeId, 'debug');
                    writeObj.after(this, val, trigger.id.toString());
                }.bind(this));
            }.bind(this));
        }
    }.bind(this));
    log('connected ' + state + ' to ' + JSON.stringify(writeIds), 'debug');
}

VirtualDevice.prototype.subRead = function (this: VirtualDevice, trigger: iobJS.SubscribeOptions, readObj: VirtualDeviceConfigStateRead, state: string): void {
    const func = function (this: VirtualDevice, obj: { state: ReturnType&lt;typeof getState&gt; }) {
        let val: iobJS.StateValue = this.convertValue(obj.state.val, readObj.convert);
 
        //@todo aggregations
 
        log('executing function before for ' + trigger.id.toString(), 'debug');
        readObj.before(this, val, trigger.id.toString(), function (this: VirtualDevice, newVal?: iobJS.StateValue, newDelay?: number) {
            if (newVal !== undefined &amp;&amp; newVal !== null) val = newVal;
            if (newDelay !== undefined &amp;&amp; newDelay !== null) readObj.delay = newDelay;
            log('reading value ' + val + ' to ' + this.namespace + '.' + state, 'debug');
            setStateDelayed(this.namespace + '.' + state, val, true, readObj.delay || 0, true, function () {
                log('executing function after for ' + trigger.id, 'debug');
                readObj.after(this, val, trigger.id.toString());
            }.bind(this));
        }.bind(this));
    }.bind(this);
    func({ state: getState(trigger.id.toString()) });
    on(trigger, func);
}

VirtualDevice.prototype.convertValue = function (this: VirtualDevice, val: iobJS.StateValue, func: (value: iobJS.StateValue) =&gt; iobJS.StateValue): iobJS.StateValue {
    if (typeof func !== 'function') {
        return val;
    }
    return func(val);
}

//global
function createVirtualDevice(config: VirtualDeviceConfig): VirtualDevice {
    return new VirtualDevice(config)
}

</code></pre>
<p dir="auto">ich benutzt mehrer DECT Thermostat von Fritz mit dem entspechenden Adapter, dafür habe ich eine Funktion geschrieben mit der ich schnell mehrere VirtualDevice erzeugen kann:</p>
<pre><code>const createVirtualThermostat = (name: string, id: string, isGroup?: boolean) =&gt; createVirtualDevice({
    namespace: 'thermostat',
    name: name,
    common: { name: id },
    states: {
        name: {
            common: { type: 'string', role: 'text', read: true, write: false },
            read: {
                [id + '.name']: {},
            },
        },
        manufacturer: {
            common: { type: 'string', role: 'text', read: true, write: false },
            read: {
                [id + '.manufacturer']: {},
            },
        },     
        id: {
            common: { type: 'string', role: 'text', read: true, write: false },
            read: {
                [id + '.id']: {},
            },
        },
        ...(!isGroup 
            ? {
                productname: {
                    common: { type: 'string', role: 'text', read: true, write: false },
                    read: {
                        [id + '.productname']: {},
                    },
                },
                battery: {
                    common: { type: 'number', role: 'state', read: true, write: false },
                    read: {
                        [id + '.battery']: {},
                    },
                },
                batterylow: {
                    common: { type: 'boolean', role: 'state', read: true, write: false },
                    read: {
                        [id + '.batterylow']: {},
                    },
                },
                batterylow_homekit: {
                    common: { type: 'number', role: 'state', read: true, write: false },
                    read: {
                        [id + '.batterylow']: {
                            convert: d =&gt; d ? 1 : 0,
                        },              
                    },
                },
                actualtemp: {
                    common: { type: 'number', role: 'state', read: true, write: false },
                    read: {
                        [id + '.tist']: {},
                    },
                }
            }
            : {}
        ),
        targettemp: {
            common: { type: 'number', role: 'state', read: true, write: true },
            read: {
                [id + '.tsoll']: {},
            },
            write: {
                [id + '.tsoll']: {},
            },
        },
        windowopenactiv: {
            common: { type: 'boolean', role: 'state', read: true, write: false },
            read: {
                [id + '.windowopenactiv']: {},
            },
        },
        errorcode: {
            common: { type: 'number', role: 'state', read: true, write: false },
            read: {
                [id + '.errorcode']: {},
            },
        },
        error: {
            common: { type: 'boolean', role: 'state', read: true, write: false },
            read: {
                [id + '.errorcode']: {
                    convert: d =&gt; !!d,
                },
            },
        },
        present: {
            common: { type: 'boolean', role: 'state', read: true, write: false },
            read: {
                [id + '.present']: {},
            },
        },
        operationmode: {
            common: { type: 'string', role: 'state', read: true, write: false },
            read: {
                [id + '.operationmode']: {},
            },
        },
        hkrmode: {
            common: { type: 'number', role: 'state', read: true, write: true },
            read: {
                [id + '.hkrmode']: {},
            },
            write: {
                [id + '.hkrmode']: {},
            },
        },        
    }
});
</code></pre>
<p dir="auto">benutzten kann man das dann so:</p>
<pre><code>createVirtualThermostat('temp1', 'fritzdect.0.DECT_099950242551');
createVirtualThermostat('temp2', 'fritzdect.0.DECT_133570009104');
createVirtualThermostat('temp3', 'fritzdect.0.DECT_133570329192');
createVirtualThermostat('temp4', 'fritzdect.0.DECT_133570402960');
createVirtualThermostat('temp5', 'fritzdect.0.DECT_133570404888');
createVirtualThermostat('temp6', 'fritzdect.0.DECT_133570405128');
createVirtualThermostat('temp7', 'fritzdect.0.DECT_140780177080');
createVirtualThermostat('temp8', 'fritzdect.0.DECT_140800051032');
createVirtualThermostat('temp9', 'fritzdect.0.DECT_140800051048');
createVirtualThermostat('temp10', 'fritzdect.0.DECT_140800052056');

createVirtualThermostat('grp-temp1', 'fritzdect.0.DECT_grpC58331-3B9ABD4E9', true);
</code></pre>
]]></description><link>https://forum.iobroker.net/post/668783</link><guid isPermaLink="true">https://forum.iobroker.net/post/668783</guid><dc:creator><![CDATA[Zerberus]]></dc:creator><pubDate>Mon, 23 Aug 2021 16:22:13 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Tue, 15 Oct 2019 13:57:42 GMT]]></title><description><![CDATA[<p dir="auto">Hi ich hab das Gefühl ich bin zu blöd dafür.</p>
<p dir="auto">Hab viele Codes ausporbiert jedoch tut sich bei mir einfach nichts.</p>
<p dir="auto"><img src="/assets/uploads/files/1571147819057-20a60c75-7fda-4df8-a110-f59d85405cc8-image.png" alt="20a60c75-7fda-4df8-a110-f59d85405cc8-image.png" class=" img-fluid img-markdown" /> ```</p>
<p dir="auto">Ich hab diesen Code ohne Fehler bei mir als Javascript Code ausgeführt und in meinen Objekten tut sich einfach gar nichts</p>
<p dir="auto"><img src="/assets/uploads/files/1571147741332-de0eae46-3aa7-4330-87fe-d5f960f44a95-image.png" alt="de0eae46-3aa7-4330-87fe-d5f960f44a95-image.png" class=" img-fluid img-markdown" /></p>
<p dir="auto">Was mache ich falsch?</p>
]]></description><link>https://forum.iobroker.net/post/311415</link><guid isPermaLink="true">https://forum.iobroker.net/post/311415</guid><dc:creator><![CDATA[R1Snake]]></dc:creator><pubDate>Tue, 15 Oct 2019 13:57:42 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Sat, 12 Oct 2019 20:53:52 GMT]]></title><description><![CDATA[<p dir="auto">Nachtrag. Ich habe ein Skript für 2 Tint-Birnen erstellt, damit lassen sich beide als eine Gruppe ansteuern, sowie Farbe, Farbtemperatur und Helligkeit:</p>
<pre><code>new VirtualDevice({

    namespace: 'WC',

    name: 'Deckenlicht', //das Gerät wird unter javascript.0.virtualDevice.'namespace'.'name' erstellt

    states: {

        //welche States sollen erstellt werden?

        'level.colorrgb': {

            //State Konfiguration
           
            common: {type: 'string', def: 000000, read: true, write: true},
           
            read: {
 
                //von welchen States sollen Werte eingelesen werden?
                //Mehrere Geräte müssen innerhalb der Klammern der read-Funktion stehen.
                
                'zigbee.0.000d6ffffe0200fe.color': { function (val) { return (val) ; } },
                'zigbee.0.d0cf5efffefefcaf.color': { function (val) { return (val) ; } },

            },

            write: {

                //in welche States sollen Werte geschrieben werden?
                //Mehrere Geräte müssen innerhalb der Klammern der write-Funktion stehen.
                //delay: xxx - schreibe Werte erst nach xxx msec. in den Adapter (Puffer)

                'zigbee.0.000d6ffffe0200fe.color': { function (val) { return (val); }, delay: 500 },
                'zigbee.0.d0cf5efffefefcaf.color': { function (val) { return (val); }, delay: 500 },

            }

        },

        'level.colortemperature': {

            //State Konfiguration
           
            common: {type: 'number', def: 0, min: 155, max: 555, read: true, write: true},

            read: {
 
                //von welchen States sollen Werte eingelesen werden?
                //Mehrere Geräte müssen innerhalb der Klammern der read-Funktion stehen.
                
                'zigbee.0.000d6ffffe0200fe.colortemp': { function (val) { return (val) ; } },
                'zigbee.0.d0cf5efffefefcaf.colortemp': { function (val) { return (val) ; } },

            },

            write: {

                //in welche States sollen Werte geschrieben werden?
                //Mehrere Geräte müssen innerhalb der Klammern der write-Funktion stehen.
                //delay: xxx - schreibe Werte erst nach xxx msec. in den Adapter (Puffer)

                'zigbee.0.000d6ffffe0200fe.colortemp': { function (val) { return (val); }, delay: 500 },
                'zigbee.0.d0cf5efffefefcaf.colortemp': { function (val) { return (val); }, delay: 500 },

            }

        },

        'level.dimmer': {

            //State Konfiguration
           
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true},

            read: {
 
                //von welchen States sollen Werte eingelesen werden?
                //Mehrere Geräte müssen innerhalb der Klammern der read-Funktion stehen.
                
                'zigbee.0.000d6ffffe0200fe.brightness': { function (val) { return (val) ; } },
                'zigbee.0.d0cf5efffefefcaf.brightness': { function (val) { return (val) ; } },

            },

            write: {

                //in welche States sollen Werte geschrieben werden?
                //Mehrere Geräte müssen innerhalb der Klammern der write-Funktion stehen.
                //delay: xxx - schreibe Werte erst nach xxx msec. in den Adapter (Puffer)

                'zigbee.0.000d6ffffe0200fe.brightness': { function (val) { return (val); }, delay: 500 },
                'zigbee.0.d0cf5efffefefcaf.brightness': { function (val) { return (val); }, delay: 500 },

            }

        },

    }

});
</code></pre>
]]></description><link>https://forum.iobroker.net/post/310147</link><guid isPermaLink="true">https://forum.iobroker.net/post/310147</guid><dc:creator><![CDATA[roughestboy]]></dc:creator><pubDate>Sat, 12 Oct 2019 20:53:52 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Wed, 09 Oct 2019 05:44:38 GMT]]></title><description><![CDATA[<p dir="auto">gibts das script auch in GIT, nur zwecks Versionierung?</p>
]]></description><link>https://forum.iobroker.net/post/308557</link><guid isPermaLink="true">https://forum.iobroker.net/post/308557</guid><dc:creator><![CDATA[homecineplexx]]></dc:creator><pubDate>Wed, 09 Oct 2019 05:44:38 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Sun, 19 May 2019 12:09:34 GMT]]></title><description><![CDATA[<p dir="auto">Entwickle aktuell einen Adapter der einige der Funktionalitäten dieses Skriptes abbilden soll.<br />
Wer interesse hat: <a href="https://forum.iobroker.net/topic/22301/neuer-adapter-linkeddevices">[Neuer Adapter] LinkedDevices</a></p>
]]></description><link>https://forum.iobroker.net/post/262807</link><guid isPermaLink="true">https://forum.iobroker.net/post/262807</guid><dc:creator><![CDATA[Scrounger]]></dc:creator><pubDate>Sun, 19 May 2019 12:09:34 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Mon, 18 Mar 2019 20:06:19 GMT]]></title><description><![CDATA[<p dir="auto">Auch wenn der letzte Beitrag fast schon 1 Jahr her ist...</p>
<p dir="auto">Ich habe die Sache mit dem VirtualDevice nachvollzogen und habe das auch grundsätzlich hinbekommen. Ich möchte 2 Tint E14 Lampen gruppieren und steuern, die können Farbe und Warmweiß bis Kaltweiß. Die Farbsteuerung erfolgt mit Hexadezimalangabe, z.B. #FF0000 für rot.<br />
Mit Scriupten kenne ich nicht quasi gar nicht aus.<br />
Wie würde man in dem 'State' Abschnitt des Skripts</p>
<pre><code>    states: {

        //welche States sollen erstellt werden?

        'level': {

            //State Konfiguration

            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%'},

            read: {

                //von welchen States sollen Werte eingelesen werden?

                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {

                    convert: function (val) { //wert soll konvertiert werden

                        return Math.floor(val * 100 / 254);

                    }

                },

            },

            write: {

                //in welche States sollen Werte geschrieben werden?

                'hue.0.hue_bridge.Wohnzimmer_Decke.bri': {

                    convert: function (val) { //wert soll konvertiert werden

                        return Math.ceil(val * 254 / 100);

                    },

                    delay: 1500 // schreibe Werte erst nach 1,5 Sekunden in den Adapter (Puffer)

                },

            }

        },

    }
</code></pre>
<p dir="auto">die entsprechende Variable in 'common' definieren und wie würde man die Variable (mit return) zurückschreiben ?</p>
]]></description><link>https://forum.iobroker.net/post/243590</link><guid isPermaLink="true">https://forum.iobroker.net/post/243590</guid><dc:creator><![CDATA[roughestboy]]></dc:creator><pubDate>Mon, 18 Mar 2019 20:06:19 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Mon, 30 Apr 2018 20:06:16 GMT]]></title><description><![CDATA[<p dir="auto"><s><a class="plugin-mentions-user plugin-mentions-a" href="/user/hsgev" aria-label="Profile: hsgev">@<bdi>hsgev</bdi></a>:</s></p>
<blockquote>
<p dir="auto">Müssen die Skripte, die die Erstellung der Virtual Devices vornehmen nach der Erstellung weiterlaufen oder kann man die dann stoppen bzw. entfernen? `</p>
</blockquote>
<p dir="auto">weiterlaufen</p>
]]></description><link>https://forum.iobroker.net/post/149939</link><guid isPermaLink="true">https://forum.iobroker.net/post/149939</guid><dc:creator><![CDATA[eumats]]></dc:creator><pubDate>Mon, 30 Apr 2018 20:06:16 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Mon, 30 Apr 2018 13:00:48 GMT]]></title><description><![CDATA[<p dir="auto">Müssen die Skripte, die die Erstellung der Virtual Devices vornehmen nach der Erstellung weiterlaufen oder kann man die dann stoppen bzw. entfernen?</p>
]]></description><link>https://forum.iobroker.net/post/149879</link><guid isPermaLink="true">https://forum.iobroker.net/post/149879</guid><dc:creator><![CDATA[hsgev]]></dc:creator><pubDate>Mon, 30 Apr 2018 13:00:48 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Wed, 03 Jan 2018 23:05:17 GMT]]></title><description><![CDATA[<p dir="auto">Das Sript, was Du meinst, gehört unter "global",</p>
<p dir="auto">da damit die Erstellung der virtuellen Geräte aufgerufen werden.</p>
<p dir="auto">Die anderen Skript stehen bei mir z.B. unter common.virtualDevices.</p>
<p dir="auto">Die Skripte dort regeln dann, wie die virtuelle Geräte erzeugt werden.</p>
<p dir="auto">Diese sind meist selbst zu schreiben um z.B. Anpassungen an sein</p>
<p dir="auto">eigenes System vorzunehmen; oder zu erweitern etc. pp.</p>
<p dir="auto">Die vorgestellen Skripte sind daher nun als Leitfaden zu verstehen,</p>
<p dir="auto">was dann möglich ist.</p>
]]></description><link>https://forum.iobroker.net/post/119084</link><guid isPermaLink="true">https://forum.iobroker.net/post/119084</guid><dc:creator><![CDATA[modmax]]></dc:creator><pubDate>Wed, 03 Jan 2018 23:05:17 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Sat, 30 Dec 2017 20:48:58 GMT]]></title><description><![CDATA[<p dir="auto">Moin Moin,</p>
<p dir="auto">ich habe den Thread bereits mehrmals gelesen, aber so ganz schlau bin ich doch nich draus geworden.</p>
<p dir="auto">Das Schema habe ich soweit verstanden und ich wollte das nun auch bei mir einsetzen, da ich viele Systeme nutze.</p>
<p dir="auto">Homematic, Hue Color, XIAOMI, Milight, Harmony, sonoff, wm-bus.</p>
<p dir="auto">Nun, es stehen hier mehrere Script im Thread, welche davon sollten jetzt genutzt werden, damit ich meine States einheitlich darstellen kann?</p>
<p dir="auto">Die States würde ich auch gerne für mobile.ui sowie cloud nutzen. Hat den schöne, dass nur die Auftauchen die ich wirklich brauche.</p>
<p dir="auto">Wer mal ein Thermostat von Homematic in mobile.ui drin hatte, der weiß was da alles so aufpoppt. :-)</p>
<p dir="auto">Gehört das auch unter Global? Oder steht dieses als einziges Unter global?</p>
<pre><code>/*
VirtualDevice v0.3

Structure of config:
{
    name: 'name', //name of device
    namespace: '', //create device within this namespace (device ID will be namespace.name)
    common: {}, //(optional)
    .................

</code></pre>
]]></description><link>https://forum.iobroker.net/post/117603</link><guid isPermaLink="true">https://forum.iobroker.net/post/117603</guid><dc:creator><![CDATA[ple]]></dc:creator><pubDate>Sat, 30 Dec 2017 20:48:58 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Thu, 28 Dec 2017 20:55:40 GMT]]></title><description><![CDATA[<p dir="auto">Von Adaptern habe ich (bisher) keine Ahnung.</p>
<p dir="auto">Wüßte aktuell auch nicht, wie man sowas umsetzen kann.</p>
<p dir="auto">Da ich den Adapter Broadlink2 im Einsatz habe, habe ich nun einige 433Mhz-Funksteckdosen ebenfalls als virtuelle Geräte eingerichtet,</p>
<p dir="auto">so daß man mit dem STATE eines solchen Geräts auch Funksteckdosen ein/ausschalten kann.</p>
<p dir="auto">Zuerst das globale Skript dazu, um einen Toggle zu erstellen.</p>
<p dir="auto">Hier muß aber der Broadlink-Code angepaßt werden.</p>
<blockquote>
<p dir="auto">! ````<br />
/*<br />
VirtualBroadlinkToggle 0.1<br />
! name       - name of device<br />
namespace  - create state within this namespace (device ID will be <a href="http://namespace.name" rel="nofollow ugc">namespace.name</a>)<br />
onCode     - on-Code<br />
offCode    - off-Code<br />
*/<br />
! // generic virtual broadlink toggle<br />
function VirtualBroadlinkToggle(namespace, name, onCode, offCode) {<br />
this.namespace = 'virtualDevice.' + namespace + '.' + name;<br />
<a href="http://this.name" rel="nofollow ugc">this.name</a> = name;<br />
this.onCode = onCode;<br />
this.offCode = offCode;</p>
</blockquote>
<pre><code>// create virtual device
this.createDevice(function () {
    this.createStates(function () {
        console.log('created virtual device ' + this.namespace);
    }.bind(this));
}.bind(this));
</code></pre>
<p dir="auto">}</p>
<blockquote>
<p dir="auto">! VirtualBroadlinkToggle.prototype.createDevice = function (callback) {<br />
log('creating object for device ' + this.namespace, 'debug');<br />
!     extendObject('javascript.' + instance + '.' + this.namespace, {<br />
type: "device",<br />
common: {"name": <a href="http://this.name" rel="nofollow ugc">this.name</a>, "role": "switch"},<br />
native: {}<br />
}, function (err) {<br />
if (err) {<br />
log('could not create virtual device: ' + this.namespace, 'warn');<br />
return;<br />
}<br />
log('created object for device ' + this.namespace, 'debug');<br />
callback();<br />
}.bind(this));<br />
}<br />
! VirtualBroadlinkToggle.prototype.createStates = function (callback) {<br />
"use strict";<br />
log('creating states for device ' + this.namespace, 'debug');<br />
var id = this.namespace + '.state';</p>
</blockquote>
<pre><code>createState(id, {type: 'boolean', def: false, min: false, max: true, name: this.name+'.state', role: 'state'}, function (err) {
    if (err) {
        log('skipping creation of state ' + id, 'debug');
    } else {
        log('created state ' + id, 'debug');
    }
    this.connectState(id);
    callback();
}.bind(this));
</code></pre>
<p dir="auto">}</p>
<blockquote>
<p dir="auto">! VirtualBroadlinkToggle.prototype.connectState = function (stateId) {<br />
var trigger = {id: 'javascript.' + instance + '.' + stateId, change: 'any', ack: false};<br />
on(trigger, function (obj) {<br />
var code = obj.state.val ? this.onCode : this.offCode;<br />
sendTo('broadlink2.0', 'send_code', 'RM:RMPROSUB-ID.CODE_'+code);<br />
}.bind(this));<br />
}<br />
! ````</p>
</blockquote>
<p dir="auto">Die virtuelle Geräte (die nur einen state haben) kann man dann wie folgt anlegen:</p>
<pre><code>new VirtualBroadlinkToggle("Schalter", "Funksteckdose", "onCode", "offcode");

</code></pre>
<p dir="auto">So kann man die Funksteckdosen auch ohne Skripting steuern und an/aus-schalten.</p>
<p dir="auto">Für Alexa kann man dann die Datenpunkte ebenfalls nehmen, oder je nach Laune verwenden.</p>
]]></description><link>https://forum.iobroker.net/post/116947</link><guid isPermaLink="true">https://forum.iobroker.net/post/116947</guid><dc:creator><![CDATA[modmax]]></dc:creator><pubDate>Thu, 28 Dec 2017 20:55:40 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Tue, 26 Dec 2017 09:18:08 GMT]]></title><description><![CDATA[<p dir="auto">Ich habe das Skript jetzt seit einiger Zeit sehr erfolgreich im Einsatz.</p>
<p dir="auto">Wie geht es nun weiter?</p>
<p dir="auto">Plant jemand einen Adapter daraus zu erstellen?</p>
<p dir="auto">Oder den Adapter ioBroker.wrapper damit zu ergänzen?</p>
<p dir="auto">Oder gleich in ioBroker als zentrale Funktion aufnehmen?</p>
<p dir="auto">Ich habe bislang keine Erfahrung mit der Adapter Entwicklung, würde mich aber beteiligen.</p>
]]></description><link>https://forum.iobroker.net/post/116293</link><guid isPermaLink="true">https://forum.iobroker.net/post/116293</guid><dc:creator><![CDATA[[[global:former-user]]]]></dc:creator><pubDate>Tue, 26 Dec 2017 09:18:08 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Fri, 22 Dec 2017 15:14:32 GMT]]></title><description><![CDATA[<p dir="auto">Da ich das gleiche Problem hatte (da mir gerade wieder ein Fensterkontakt gecrasht ist),</p>
<p dir="auto">hab ich nun die Sensoren und Schalter in virtuelle Devices verpackt.</p>
<p dir="auto">Jedoch hab ich das Skript "VirtualDevice" noch ergänzt, um ggfs. einen eigenes common/native-Gespann ins Device zu bringen.</p>
<blockquote>
<p dir="auto">! <code>    var obj;     if (typeof this.config.copy == 'string') {         obj = getObject(this.config.copy);     } else if (typeof this.config.copy == 'object') {         obj = this.config.copy;     } else {         obj = {common: {}, native: {}};     } !</code></p>
</blockquote>
<p dir="auto">Für meine Homematic-Schalter nutze ich folgendes Skript:</p>
<blockquote>
<p dir="auto">! ````<br />
// virtuelle HM-Schalter<br />
new virtualHomematicSwitch('Wohnzimmer_Lampe', 'hm-rpc.0.ABC1234567');<br />
// virtuelle HM-IP-Schalter<br />
new virtualHomematicIpSwitch('Schlafzimmer_Lampe', 'hm-rpc.1.CBA7654321', 4);<br />
! // -----------------<br />
! function virtualHomematicSwitch(name, deviceId) {<br />
var config = {<br />
namespace: 'Schalter',<br />
name: name,<br />
copy: {common: {"name":name,"role":"switch"}, native: {}},<br />
states: {<br />
'unreachable': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.unreachable', role: 'indicator.unreach'},<br />
read: {<br />
[deviceId + '.0.UNREACH']: {}<br />
}<br />
},<br />
'lowBat': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.lowBat', role: 'indicator.battery'},<br />
read: {<br />
[deviceId + '.0.LOWBAT']: {}<br />
}<br />
},<br />
'dutyCycle': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.dutyCycle', role: 'value'},<br />
read: {<br />
[deviceId + '.0.DUTYCYCLE']: {}<br />
}<br />
},<br />
'working': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.working', role: 'indicator.working'},<br />
read: {<br />
[deviceId + '.1.WORKING']: {}<br />
}<br />
},<br />
'state': {<br />
common: {type: 'boolean', def: false, read: true, write: true, name: name+'.state', role: 'state'},<br />
read: {<br />
[deviceId + '.1.STATE']: {}<br />
} ,<br />
write: {<br />
[deviceId + '.1.STATE']: {}<br />
}</p>
</blockquote>
<pre><code>        }
    }
}
return new VirtualDevice(config);
</code></pre>
<p dir="auto">}</p>
<blockquote>
<p dir="auto">! // -----------------<br />
! function virtualHomematicIpSwitch(name, deviceId, switchState) {<br />
var config = {<br />
namespace: 'Schalter',<br />
name: name,<br />
copy: {common: {"name":name,"role":"switch"}, native: {}},<br />
states: {<br />
'unreachable': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.unreachable', role: 'indicator.unreach'},<br />
read: {<br />
[deviceId + '.0.UNREACH']: {}<br />
}<br />
},<br />
'lowBat': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.lowBat', role: 'indicator.battery'},<br />
},<br />
'dutyCycle': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.dutyCycle', role: 'value'},<br />
read: {<br />
[deviceId + '.0.DUTY_CYCLE']: {}<br />
}<br />
},<br />
'working': {<br />
common: {type: 'boolean', def: false, read: true, write: false, name: name+'.working', role: 'indicator.working'},<br />
},<br />
'state': {<br />
common: {type: 'boolean', def: false, read: true, write: true, name: name+'.state', role: 'state'},<br />
read: {<br />
[deviceId + '.' + switchState + '.STATE']: {}<br />
} ,<br />
write: {<br />
[deviceId + '.' + switchState + '.STATE']: {}<br />
}</p>
</blockquote>
<pre><code>        }
    }
}
return new VirtualDevice(config);
</code></pre>
<p dir="auto">}</p>
<blockquote>
<p dir="auto">! ````</p>
</blockquote>
<p dir="auto">Und für die Sensoren folgendes Skript:</p>
<blockquote>
<p dir="auto">! <code>// Homematic Tür/Fenster Sensoren new virtualHomematicShutterContact('Wohnzimmer_Fenster', 'hm-rpc.0.ABC1234567'); // Homematic Drehgriffkontakte new virtualHomematicRotaryHandleSensor('Schlafzimmer_Fenster', 'hm-rpc.0.CBA7654321'); ! // ----------------- ! function virtualHomematicShutterContact(name, deviceId) {     var config = {         namespace: 'Sensor',         name: name,         copy: {common: {"name":name,"role":"sensor"}, native: {}},         states: {             'unreachable': {                 common: {type: 'boolean', def: false, read: true, write: false, name: name+'.unreachable', role: 'indicator.unreach'},                 read: {                     [deviceId + '.0.UNREACH']: {}                 }                               },             'lowBat': {                 common: {type: 'boolean', def: false, read: true, write: false, name: name+'.lowBat', role: 'indicator.battery'},                 read: {                     [deviceId + '.0.LOWBAT']: {}                 }                               },             'state': {                 common: {type: 'boolean', def: false, read: true, write: false, name: name+'.state', role: 'state'},                 read: {                     [deviceId + '.1.STATE']: {}                 }              }         }     }     return new VirtualDevice(config); } ! function virtualHomematicRotaryHandleSensor(name, deviceId) {     var config = {         namespace: 'Sensor',         name: name,         copy: {common: {"name":name,"role":"sensor"}, native: {}},         states: {             'unreachable': {                 common: {type: 'boolean', def: false, read: true, write: false, name: name+'.unreachable', role: 'indicator.unreach'},                 read: {                     [deviceId + '.0.UNREACH']: {}                 }                               },             'lowBat': {                 common: {type: 'boolean', def: false, read: true, write: false, name: name+'.lowBat', role: 'indicator.battery'},                 read: {                     [deviceId + '.0.LOWBAT']: {}                 }                               },             'state': {                 common: {type: 'boolean', def: false, read: true, write: false, name: name+'.state', role: 'state'},                 read: {                     [deviceId + '.1.STATE']: {                         convert: function(value) {                             return value !== 0;                         }                     }                 }  !             },             'handle': {                 common: {type: 'number', def: 0, read: true, write: false, states: {0: 'closed', 1: 'tilted', 2: 'open'}, name: name+'.handle', role: 'state'},                 read: {                     [deviceId + '.1.STATE']: {}                 }              }                         }     }     return new VirtualDevice(config); } !</code></p>
</blockquote>
<p dir="auto">Für die HUE-Lampen habe ich das Skripot modifiziert, da ich zu jeder HUE-Lampe einen CUxD-Switch habe.</p>
<p dir="auto">Hier wolten ich sowohl über Alexa, als auch HueApp, als auch ioBroker, als auch CUxD-Schalter</p>
<p dir="auto">die komplette Synchronisation übernehmen; so daß alles per ioBroker synchronisiert wird.</p>
<blockquote>
<p dir="auto">! ````<br />
// Hue-Lampen verknüft mit CUxD-Schalter<br />
new virtualHueLamp("hue.0.hue_bridge.Stehlampe", "hm-rpc.2.CUX4001110.1.STATE");<br />
! // -----------------<br />
! function virtualHueLamp(lampId, switchId) {<br />
var lampObj = getObject(lampId);<br />
var lampName = lampObj.common.name.split('.').splice(-1)[0];</p>
</blockquote>
<pre><code>var config = {
    namespace: 'Hue',
    name: lampName,
    copy: {common: {"name":lampName,"role":lampObj.common.role}, native: {type: lampObj.native.type, model: lampObj.native.modelid}},
    states: {
        'unreachable': {
            common: {type: 'boolean', def: false, read: true, write: false, name: lampName+'.unreachable', role: 'indicator.unreach'},
            read: {
                [lampId + '.reachable']: {
                    convert: function(value) {
                        return !value;
                    }
                }
            }                  
        },
        'level': {
            common: {type: 'number', def: 0, min: 0, max: 100, read: true, write: true, unit: '%', name: lampName+'.level', role: 'level.dimmer'},
            read: {
                [lampId + '.bri']: {
                    convert: function(value) {
                        return Math.floor(value*100/254);
                    },
                    before: function (device, value, callback) {
                        if (value &gt; 0) {
                            setState(device.namespace+'.lastLevel', value, true);
                        }
                        callback();
                    }
                }
            },
            write: {
                [lampId + '.bri']: {
                    convert: function(val) {
                        return Math.ceil(val*254/100);
                    },
                    delay: 800
                }
            }
        },
        'lastLevel': {
            common: {type: 'number', def: 100, min: 0, max: 100, read: true, write: false, unit: '%', name: lampName+'.lastLevel', role: 'value'},
            read: {}
        },
        'command': {
            common: {type: 'string', def: '', read: true, write: true, name: lampName+'.command', role: 'command'},
            write: {
                [lampId + '.command']: {
                    delay: 800
                }
            }
        }
    }
}

if (switchId) {
    config.states['switch'] = {
        common: {type: 'boolean', def: false, read: true, write: false, name: lampName+'.switch', role: 'state'},
        read: {
            [switchId]: {
                after: function (device, value) {
                    var level = getState(device.namespace + '.level').val;
                    if (value === false &amp;&amp; level &gt; 0) {
                        setState(device.namespace + '.level', 0);
                    } else if (value === true &amp;&amp; level &lt;= 0) {
                        var lastLevel = getState(device.namespace + '.lastLevel').val;
                        setState(device.namespace + '.level', lastLevel);
                    }
                }
            }
        }
    }
</code></pre>
<blockquote>
<p dir="auto">!         config.states.level.read[lampId + '.bri'].after = function (device, value) {<br />
if (value &gt; 0 &amp;&amp; getState(switchId).val === false) {<br />
setStateDelayed(switchId, true, 200);<br />
} else if (value &lt;= 0) {<br />
setStateDelayed(switchId, false, 200);<br />
}<br />
}<br />
!         config.states.command.write[lampId + '.command'].before = function (device, value, callback) {<br />
var parsed;<br />
try{<br />
parsed = JSON.parse(value);<br />
} catch(e) {<br />
return;<br />
}<br />
if (parsed.level &gt; 0 &amp;&amp; getState(switchId).val === false) {<br />
//if switch is off and level is greater 0 turn on switch<br />
setStateDelayed(switchId, true, false, 800, true, function(){<br />
callback(value, 3500);<br />
});<br />
} else if (parsed.level &lt;= 0){<br />
//if level is set to 0 turn off switch and set level 0<br />
setStateDelayed(switchId, false, false, 800, true, function(){<br />
callback(null, 0);<br />
});<br />
} else {<br />
callback();<br />
}<br />
}<br />
}</p>
</blockquote>
<pre><code>if (lampObj.native &amp;&amp; lampObj.native.type === 'Color temperature light' || lampObj.native.type === 'Extended color light') {
    config.states.ct = {
        common: {min: 2000, max: 6500, unit: 'K', step: 10, name: lampName+'.ct', role: 'level.color.temperature'},
        read: {
            [lampId + '.ct']: {
                convert: function(val) {
                    return Math.max(2000, Math.min(6500, Math.round(Math.pow(10,6)/val)));  
                }
            }
        },
        write: {
            [lampId + '.ct']: {
                convert: function(val) {
                    return Math.max(153, Math.min(500, Math.round(Math.pow(10,6)/val))); 
                },
                delay: 1500
            }              
        }
    }
}

if (lampObj.native &amp;&amp; lampObj.native.type === 'Color light' || lampObj.native.type === 'Extended color light') {
    config.states.xy = {
        common: {read: true, write: true, type: "string", name: lampName+'.xy', role: 'level.color.xy'},
        read: {
            [lampId + '.xy']: {}
        },
        write: {
            [lampId + '.xy']: {
                delay: 800
            }
        }
    }    
}

return new VirtualDevice(config);
</code></pre>
<p dir="auto">}</p>
<blockquote>
<p dir="auto">! ````</p>
</blockquote>
<p dir="auto">Vielleicht gibt es noch weitere Ideen.</p>
]]></description><link>https://forum.iobroker.net/post/115315</link><guid isPermaLink="true">https://forum.iobroker.net/post/115315</guid><dc:creator><![CDATA[modmax]]></dc:creator><pubDate>Fri, 22 Dec 2017 15:14:32 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Fri, 27 Oct 2017 19:19:48 GMT]]></title><description><![CDATA[<p dir="auto">Denke auch an einen Bug im zwave Adapter.</p>
<p dir="auto">Hab mal ein Topic eröffnet dazu mit ein paar mehr Details:</p>
<p dir="auto"><a href="http://forum.iobroker.net/viewtopic.php?f=22&amp;t=8718" rel="nofollow ugc">http://forum.iobroker.net/viewtopic.php?f=22&amp;t=8718</a></p>
]]></description><link>https://forum.iobroker.net/post/103459</link><guid isPermaLink="true">https://forum.iobroker.net/post/103459</guid><dc:creator><![CDATA[[[global:former-user]]]]></dc:creator><pubDate>Fri, 27 Oct 2017 19:19:48 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Thu, 26 Oct 2017 18:46:59 GMT]]></title><description><![CDATA[<p dir="auto">Dann wird der Fehler im ZWave Adapter liegen, der Strings reinschreibt, statt Number.</p>
]]></description><link>https://forum.iobroker.net/post/103283</link><guid isPermaLink="true">https://forum.iobroker.net/post/103283</guid><dc:creator><![CDATA[Pman]]></dc:creator><pubDate>Thu, 26 Oct 2017 18:46:59 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Thu, 26 Oct 2017 18:38:28 GMT]]></title><description><![CDATA[<p dir="auto">Ich verwende zwave Sensoren.</p>
<p dir="auto">Das auslesen des Temperaturwertes ist angeblich ein string:</p>
<pre><code>log (typeof getState("zwave.0.NODE17.SENSOR_MULTILEVEL.Temperature_1").val);

20:39:38.999	[info]	javascript.0 Start javascript script.js.test.dummy
20:39:38.999	[info]	javascript.0 script.js.test.dummy: string
</code></pre>
<p dir="auto">Der Sensor ist ein "FIBARO System FGMS001-ZW5 Motion Sensor":</p>
<pre><code>{
  "common": {
    "name": "Temperature",
    "type": "number",
    "role": "value.temperature",
    "read": true,
    "write": false
  },
  "native": {
    "value_id": "17-49-1-1",
    "type": "decimal",
    "genre": "user",
    "label": "Temperature",
    "units": "C",
    "help": "",
    "node_id": 17,
    "class_id": 49,
    "instance": 1,
    "index": 1,
    "min": 0,
    "max": 0,
    "read_only": true,
    "write_only": false,
    "is_polled": false
  },
  "acl": {
    "object": 1636,
    "owner": "system.user.admin",
    "ownerGroup": "system.group.administrator",
    "state": 1636
  },
  "_id": "zwave.0.NODE17.SENSOR_MULTILEVEL.Temperature_1",
  "type": "state"
}
</code></pre>
<p dir="auto">Alle Adapter sind aktuell:</p>
<p dir="auto">ioBroker.zwave: 0.8.0</p>
<p dir="auto">ioBroker.javascript; 3.4.0</p>
<p dir="auto">ioBroker.js-controller: 1.1.3</p>
]]></description><link>https://forum.iobroker.net/post/103278</link><guid isPermaLink="true">https://forum.iobroker.net/post/103278</guid><dc:creator><![CDATA[[[global:former-user]]]]></dc:creator><pubDate>Thu, 26 Oct 2017 18:38:28 GMT</pubDate></item><item><title><![CDATA[Reply to Virtual Devices on Thu, 26 Oct 2017 11:30:30 GMT]]></title><description><![CDATA[<p dir="auto">Der Fehler  <code>&gt; Wrong type of …: "string". Please fix, while deprecated and will not work in next versions.</code>  tritt auf, wenn in einen State der nicht vom typ "string" ist, ein string <strong><strong><strong>geschrieben</strong></strong></strong> wird, woher auch immer. Analog für andere Datentypen (number =&gt; nicht-number, boolean =&gt; nicht-boolean, etc…).</p>
<p dir="auto">Mit Lesen hat das wenn nur indirekt zu tun.</p>
]]></description><link>https://forum.iobroker.net/post/103151</link><guid isPermaLink="true">https://forum.iobroker.net/post/103151</guid><dc:creator><![CDATA[AlCalzone]]></dc:creator><pubDate>Thu, 26 Oct 2017 11:30:30 GMT</pubDate></item></channel></rss>