2.2.8.133 Libraries

Is there anybody who can point me to an example of how to create a library and what can be done inside one? Specifically, how do you declare the namespace and can you define classes inside the library?

1 Like

Sure.. here is one of mine

library (
        base: "driver",
        author: "bcopeland",
        category: "zwave",
        description: "Motion",
        name: "binarymotion",
        namespace: "zwave",
        documentationLink: ""
)

void zwaveEvent(hubitat.zwave.commands.sensorbinaryv2.SensorBinaryReport cmd) {
    Map evt = [:]
    evt.name = "motion"
    if (cmd.sensorType == 12) {
        if (cmd.sensorValue == 0) {
            evt.value = "inactive"
            evt.descriptionText = "${device.displayName} motion became ${evt.value}"
            eventProcess(evt)
        } else {
            evt.value = "active"
            evt.descriptionText = "${device.displayName} motion became ${evt.value}"
            eventProcess(evt)
        }
    }
}

Then in your app/library it would be:

#include zwave.binarymotion
4 Likes

Can you declare classes in a library?

no

The key is to not overthink the library feature. Basically it's just pasting that code into the other coder where you use the #include statement.

It's a great way to merge common code.

For example I have a library for my logging methods. One for my driver methods that work across all drivers. One for zwave that had the zwave methods that are the same across all my driver's.

My zwave drivers have become so small. You really see how very little they differ.

One bonus is i can instally turn in all logging by editing one line of code if needed.

It's a great feature and really helps to consolidate code.

3 Likes

Then I have a more general question: if I want to store a map of keys to compound values, how would you suggest I represent the values?

Don't over think it.. it's JUST text.

"include" just pastes text in where you place it.

Think of it the other way 'round...

Take 5 nearly identical drivers and grab chunks of purely identical code and put it in a library. The original 5 drivers now shrink to almost just the MetaData portion. :slight_smile: Plus any device specific uniqueness.

In testing, I took a couple of HubConnect's Universal Drivers (Dimmer and Lock) and pulled all the common stuff out into a Library, including "on" and "off" which wouldn't apply to a Lock. The dimmer driver is just MetaData + setLevel related. The Lock is just MetaData + Lock/unlock and Lock Code related methods.

HubConnect Drivers are awfully tiny anyway and since this doesn't reduce out the quantity of them it's not worth investing/publishing in the change BUT the critical element is, it works of course. Even the Lock with extra/unused methods for On and Off works fine.

5 Likes

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