Create Attributes Outside of Metadata Block

I am new to hubitat driver coding, so I try stuff that sometimes puts me in the correct direction and other times leads me to a dead end.

For example:
I am working on a device driver with a long list of attributes for each model, and each device model has different JSON key names. I used keyset() to pull all the keys from my JSON script. I then used a string array variable nested into my attribute command
>> (attribute "${keystring[attindex]}", "number") <<
and inside the sendEvent command to write to the device.

(sendEvent(name: "${keystring[attindex]}", value: jsonpl.data."${keystring[attindex]}") <<

I was excited when the device states loaded without me having to hardcode them. But - the attributes were not loaded into memory and only appeared in the HTML device status section. A refresh of the screen, and they were all gone. My lesson for the day is: attributes must be created inside the metadata block.

Is it feasible to get Hubitat to allow the attribute definitions to run outside the Metadata block?
I think not having to hardcode all the device attributes would be a plus.

Variations on this question have been asked in the past, and the answer — as you have likely discovered now — is that "dynamic" capabilities, commands, and attributes are not supported. Further, there are currently (or at least as of the last time they addressed this question) no plans to change that. Among other discussions, see: Eliminating driver code mess - #8 by mike.maxwell

I'm not exactly sure what your use case is, but one thing that might help you with creating similar drivers for different-but-similar devices is libraries. This allows you to re-use code in drivers or apps. So, while your attribute list might be statically defined, if the way you handle most of these attributes is re-usable, you could move that out to a library and share that among a few device-specific drivers.

1 Like

One of the ways I’ve gotten around this issue:

https://raw.githubusercontent.com/thebearmay/hubitat/main/dynAttribute.groovy

2 Likes

Yup - every so often a new guy shows up and asks one of the overly-discussed topics. My turn today. :stuck_out_tongue:

I have not played around with libraries. I'll have a look.

Thanks!

I think it may be worth exploring why you want to dynamically create the attributes and how you intend to use them. Is it simply that you want to reflect what is a dynamic or at least variable list of attributes in data being sent for the device? Even if that is the case, how you intend to use the attributes may not work the way you expect.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.