Hi guys!
Is it possible to create device attributes variables on-the-fly?
Thanks!
Creating device attributes on-the-fly
Hi guys!
Is it possible to create device attributes variables on-the-fly?
Thanks!
@skarcha could you describe what you want to achieve here?
pimatic rocks!
I’m working on a MQTT plugin and I would like to create attributes based on received topics.
Thanks for your answer
@skarcha, I have similar requirements.
Looking at the code pimatic/lib/devices.coffee
it provides a method addAttribute()
which takes a name string and an instance variable. The method can only be called as part of the device constructor, however.
I haven’t tried this yet and as I am busy with other things. I’ll keep you posted.
"It always takes longer than you expect, even when you take into account Hofstadter's Law.", Hofstadter's Law
@skarcha Adding device attributes on the fly is not supported yet. You would have to cache the attributes somehow in the device config and create them after a restart. Dynamically adding/updating attributes needs some work in the framework, that’s currently not done yet.
@skarcha The following works for me, but I am not sure it is any useful for your case, as addAttribute() can only be called inside the constructor before calling super().
constructor: (@config) ->
dynamicAttributes = {
topicA: {
description: "Topic Data",
type: "string"
data: ""
}
};
@addAttribute('topicA', dynamicAttributes['topicA'])
@['getTopicA'] = ()-> Promise.resolve(dynamicAttributes.topicA.data)
# Update 'topicA' with the current date string every five seconds
setInterval(
()=>
dynamicAttributes['topicA'].data = (new Date()).toLocaleString()
@emit 'topicA', dynamicAttributes['topicA'].data
, 5000
)
super(@config)
"It always takes longer than you expect, even when you take into account Hofstadter's Law.", Hofstadter's Law
@skarcha Currently the framework assumes that the attributes do not change after the device was added / created. So if you would add the attributes after device creation (when receiving infos by mqtt) then the framework is not fully aware of them and will for example not create variables for them.
The current workaround is to either add config options to defin the attributes a priori in the config, so the attribute can already be created at device creation or save them to the config after a mqtt message was received so the attributes can be created at the upcoming start / after a restart. That’s not ideal, but attributes are needed for rules and variables at startup.