Minostan MP21ZD/MP31ZD driver

I used ChatGPT and Claude to fix this base driver for the MP21ZD/MP31ZD. Seems to work well and exposes parameters for easy changes. Feel free to copy/use/modify. (updated to add ability to easily set any configuration parameter and also list parameter names versus just numbers) - just updated from 1.5.3 to 1.5.6 removing 'sensor' capability that was confusing alexa and implementing a 'on/off/ status check each hour (default) to assure no missed on/off status get out of synch with Hubitat.

/**
 *      Minoston Smart Plug Dimmer v1.5.6 (Hubitat, MP21ZD/MP31ZD firmware 8.0)
 *
 *  	Models: MP21ZD/MP31ZD
 *
 *  Author:
 *   winnie (sky-nie)
 *
 *	Documentation:
 *
 *  Original driver: winnie (sky-nie), 2022.
 *  Hubitat compatibility revisions: OpenAI ChatGPT, October 2026; Claude (Anthropic), October 2026.
 *  These are independent modifications, not an official Minoston release.
 *
 *  Changelog:
 *    1.5.6-test (10/20/2026) - Claude (Anthropic)
 *      - On/off state check is on by default: a blank interval now means 60 minutes (only an
 *        explicit 0 disables it), and it is scheduled when the device is first installed.
 *      - Removed the Health Check capability and ping(); nothing scheduled ping(), and the
 *        periodic on/off check now does that job.
 *    1.5.5-test (10/20/2026) - Claude (Anthropic)
 *      - Removed the generic "Sensor" capability. It has no attributes for this plug-in dimmer, and
 *        the Amazon Alexa skill was treating the device as a temperature sensor and logging
 *        "Alexa.TemperatureSensor.temperature ... attribute is uninitialized" warnings.
 *    1.5.4-test (10/19/2026) - Claude (Anthropic)
 *      - New preference "On/Off State Check Interval" (0 disables; 1-1440 minutes). Periodically
 *        asks for the current level/on-off state to correct a missed report.
 *      - First check after hub startup or Save Preferences runs at a random 1-10 minutes, so
 *        devices do not all query at once; later checks follow the interval.
 *      - Added the Initialize capability so the check restarts after a hub reboot.
 *      - A change found by the check is logged and sent as [status check] / type digital,
 *        not [physical], so rules that react to physical presses are not triggered.
 *    1.5.3-test (10/12/2026) - Claude (Anthropic)
 *      - Old "configParamN" state entries are renamed as soon as the driver runs anything
 *        (Save, Configure, Refresh, Read Configuration or any device message), with a log line.
 *    1.5.2-test (10/12/2026) - Claude (Anthropic)
 *      - State variables now show parameter names, e.g. "param02 LED Indicator Mode",
 *        zero-padded so they sort in order. Old "configParamN" entries are converted automatically.
 *      - Values read back for unlisted parameters (via Set Configuration Parameter) are kept in state too.
 *    1.5.1-test (10/12/2026) - Claude (Anthropic)
 *      - Added Set Configuration Parameter command (parameter number, length, value).
 *        Writes the value, reads it back, and logs the result. Parameters 0 and 255 are refused.
 *    1.5.0-test (10/12/2026) - Claude (Anthropic)
 *      - Blank preferences are unmanaged: Configure/Save write only parameters you have set,
 *        never driver defaults. Configure no longer rewrites every parameter on first run.
 *      - Reported parameter values are copied into Preferences, so the page shows the device's
 *        actual settings after Read Configuration (or Configure).
 *      - New "Apply changed settings when saving preferences" option (default on); Configure
 *        still applies pending changes manually and then reads all parameters back.
 *      - Follow-up status queries after on/off/setLevel are now actually sent (sendHubCommand);
 *        commands returned from scheduled methods were previously discarded.
 *      - A Basic Report of 0xFF no longer sets level to 255; device level 99 is shown as 100%.
 *      - setLevel tolerates missing or text durations; duration limited to 0-30 seconds.
 *      - lastCheckIn is updated at most once per hour instead of on every message.
 *      - Added description logging and physical/digital event types.
 *      - Debug/trace logging turns off automatically after 30 minutes.
 *      - One-time upgrade step: preferences saved by v1.4 (which held driver defaults) are
 *        cleared and reloaded from the device; nothing is written during the upgrade.
 *      - Removed SmartThings-only metadata, checkInterval events and the unused multi-channel handler.
 *    1.4.0-test (10/07/2026) - OpenAI ChatGPT
 *      - Added parameter 12 (maximum brightness) to editable preferences.
 *      - Verified 800-series manual: 1 byte, 0 disables limit, 1-99 sets limit.
 *      - Set parameter 12 initial preference to 0 to match tested device.
 *      - Kept manual-only Configure and read-only Read Configuration.
 *      - Preserved original author credit and earlier revisions.
 *    1.3.0-test (10/07/2026) - OpenAI ChatGPT
 *      - Documented successful user testing on MP21ZD firmware 8.0, S2.
 *      - Added read-only query of parameter 12 (maximum brightness),
 *        without assuming its size/range or exposing a write control.
 *      - Retained separate optional debug/trace logging controls.
 *      - Retained read-only configuration inspection and manual-only writes.
 *    1.2.0-test (10/07/2026) - OpenAI ChatGPT
 *      - Added configurable debug/trace logging, default off.
 *      - Added Read Configuration without writing device parameters.
 *      - Stopped automatic configuration writes on preference save.
 *    1.1.0-test (10/07/2026) - OpenAI ChatGPT
 *      - Revised S0/S2 command encapsulation and Supervision handling.
 *      - Added multichannel parsing, refreshed state reporting and version query.
 *      - Corrected undefined supervision parsing reference.
 *
 *    1.0.1 (06/18/2022)
 *      - fix a bug: the switch status is not fresh when it is controlled on the device
 *
 *    1.0.0 (03/19/2022)
 *      - Initial Release
 *
 * Reference:
 *    https://github.com/krlaframboise/SmartThings/blob/master/devicetypes/krlaframboise/eva-logik-in-wall-smart-dimmer.src/eva-logik-in-wall-smart-dimmer.groovy
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

import groovy.transform.Field

@Field static final String DRIVER_VERSION = "1.5.6"
// A state change reported within this window after a periodic check is attributed to the check.
@Field static final long SWITCH_CHECK_WINDOW_MS = 15000L
@Field static final int DEFAULT_SWITCH_CHECK_MINUTES = 60
// Names shown in State Variables. Parameters not listed here appear as "(unknown)".
@Field static final Map PARAM_STATE_NAMES = [
    2: "LED Indicator Mode",
    4: "Auto Turn-Off Timer",
    6: "Auto Turn-On Timer",
    7: "Night Light",
    8: "Power Failure Recovery",
    9: "Push Dimming Duration",
    10: "Hold Dimming Duration",
    11: "Minimum Brightness",
    12: "Maximum Brightness"
]
// Bump only if preferences ever need clearing again; a normal version bump must not clear them.
@Field static final int PREF_SCHEMA = 2

metadata {
    definition (
            name: "Minoston Smart Plug Dimmer(MP21ZD)",
            namespace: "sky-nie",
            author: "winnie",
            importUrl: "https://raw.githubusercontent.com/sky-nie/hubitat/main/minoston/minoston-smart-plug-dimmer.groovy"
    ) {
        capability "Actuator"
        capability "Switch"
        capability "Switch Level"
        capability "Configuration"
        capability "Refresh"
        capability "Initialize"

        attribute "firmwareVersion", "string"
        attribute "lastCheckIn", "string"
        attribute "syncStatus", "string"
        command "readConfiguration"
        command "setConfigurationParameter", [
            [name: "Parameter number*", type: "NUMBER", description: "1-254"],
            [name: "Parameter length*", type: "ENUM", constraints: ["1", "2", "4"], description: "Size in bytes"],
            [name: "Value*", type: "NUMBER", description: "Value to write"]
        ]

        fingerprint mfr: "0312", prod: "FF00", deviceId: "FF0D", deviceJoinName: "Minoston Smart Plug Dimmer", inClusters:"0x5E,0x55,0x9F,0x6C" //MP21ZD
        fingerprint mfr: "0312", prod: "FF00", deviceId: "FF0D", deviceJoinName: "Minoston Smart Plug Dimmer", inClusters:"0x86,0x26,0x70,0x85,0x8E,0x71,0x31,0x59,0x72,0x5A,0x73,0x7A"
    }

    preferences {
        input "txtEnable", "bool", title: "Enable description logging", defaultValue: true
        input "enableDebugLogging", "bool", title: "Enable debug logging (turns off after 30 minutes)", defaultValue: false
        input "enableTraceLogging", "bool", title: "Enable trace logging (turns off after 30 minutes)", defaultValue: false
        input "applyOnSave", "bool", title: "Apply changed settings when saving preferences (otherwise use Configure)", defaultValue: true
        input "switchCheckInterval", "number", title: "On/Off State Check Interval (0 disables; 1-1440 minutes; blank = 60)",
                description: "Re-reads on/off and level to correct a missed report. First check runs 1-10 minutes after startup or save.",
                required: false, range: "0..1440", defaultValue: 60
        configParams.each {
            // No defaultValue: a blank preference means "leave the device's value alone".
            if (it.range) {
                input "configParam${it.num}", "number", title: "${it.name}:", required: false, range: it.range,
                        description: "Blank = unchanged. Factory default ${it.factoryDefault}"
            } else {
                input "configParam${it.num}", "enum", title: "${it.name}:", required: false, options: it.options,
                        description: "Blank = unchanged"
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------

def installed() {
    logDebug "installed()..."
    state.prefSchema = PREF_SCHEMA
    runIn(5, "readConfiguration")
    scheduleSwitchCheck()
}

def updated() {
    if (isDuplicateCommand(state.lastUpdated, 5000)) return []
    state.lastUpdated = new Date().time
    logDebug "updated()..."
    unschedule("logsOff")
    if (enableDebugLogging || enableTraceLogging) runIn(1800, "logsOff")
    scheduleSwitchCheck()
    migrateParamStateKeys()
    if (migrateIfNeeded()) return []
    if (applyOnSave != false) {
        sendConfigChanges()
    } else {
        refreshSyncStatus()
    }
    return []
}

// Runs at hub startup (Initialize capability), so the periodic check survives reboots.
def initialize() {
    logDebug "initialize()..."
    scheduleSwitchCheck()
}

// ---------------------------------------------------------------------------
// Periodic on/off state check (preference "switchCheckInterval", minutes; 0 = disabled).
// One Switch Multilevel Get per check; the report updates both switch and level.
// ---------------------------------------------------------------------------

private int switchCheckMinutes() {
    def raw = settings?.switchCheckInterval
    // Hubitat applies a preference's defaultValue only when Preferences are saved, so a blank
    // (never-saved) setting means the default here. Only an explicit 0 disables the check.
    if (raw == null || "${raw}".trim() == "") return DEFAULT_SWITCH_CHECK_MINUTES
    int m = safeToInt(raw, -1)
    if (m < 0 || m > 1440) {
        log.warn "${device.displayName}: On/off check interval must be 0-1440 minutes; received ${raw}. Check disabled."
        return 0
    }
    return m
}

// First run lands at a random 1-10 minutes so devices started together do not all query at once.
private void scheduleSwitchCheck() {
    unschedule("switchStateCheck")
    int m = switchCheckMinutes()
    if (m > 0) {
        int first = 60 + new Random().nextInt(541)   // 60-600 seconds
        runIn(first, "switchStateCheck")
        logDebug "On/off check every ${m} min; first check in ${first} s"
    } else {
        logDebug "On/off check disabled"
    }
}

def switchStateCheck() {
    int m = switchCheckMinutes()
    if (m <= 0) return
    try {
        state.switchCheckAt = new Date().time
        logDebug "Periodic on/off check (switch is ${device.currentValue('switch')}, level ${device.currentValue('level')})"
        sendCommands([switchMultilevelGetCmd()])
    } catch (e) {
        log.warn "${device.displayName}: periodic on/off check failed: ${e.message}"
    } finally {
        runIn(m * 60, "switchStateCheck")
    }
}

def logsOff() {
    device.updateSetting("enableDebugLogging", [value: "false", type: "bool"])
    device.updateSetting("enableTraceLogging", [value: "false", type: "bool"])
    log.info "${device.displayName}: debug and trace logging disabled"
}

// Applies pending changes (only preferences you have set), then reads every parameter back.
def configure() {
    logDebug "configure()..."
    migrateParamStateKeys()
    if (migrateIfNeeded()) return []
    List cmds = configChangeCommands()
    cmds.addAll(configReadCommands())
    sendCommands(cmds, 300)
    runIn(Math.max(8, (int)(cmds.size() * 0.3) + 4), "refreshSyncStatus", [overwrite: true])
    return []
}

// Read only: requests the current values without modifying the device.
def readConfiguration() {
    logDebug "Reading configuration parameters (no writes)"
    migrateParamStateKeys()
    sendCommands(configReadCommands(), 300)
    runIn(8, "refreshSyncStatus", [overwrite: true])
    return []
}

private void sendConfigChanges() {
    List cmds = configChangeCommands()
    if (cmds) {
        logDebug "Writing ${cmds.size() / 2} changed parameter(s)"
        sendCommands(cmds, 300)
        runIn(Math.max(6, (int)(cmds.size() * 0.3) + 4), "refreshSyncStatus", [overwrite: true])
    } else {
        refreshSyncStatus()
    }
}

private List configChangeCommands() {
    List cmds = []
    configParams.each { param ->
        if (param.value == null) return            // blank preference: unmanaged
        def storedVal = getParamStoredValue(param.num)
        if (storedVal != null && storedVal == param.value) return
        if (txtEnable) log.info "${device.displayName}: setting ${param.name} (#${param.num}) to ${param.value}"
        cmds << secureCmd(zwave.configurationV1.configurationSet(parameterNumber: param.num, size: param.size, scaledConfigurationValue: param.value))
        cmds << secureCmd(zwave.configurationV1.configurationGet(parameterNumber: param.num))
    }
    return cmds
}

private List configReadCommands() {
    return configParams.collect { secureCmd(zwave.configurationV1.configurationGet(parameterNumber: it.num)) }
}

// One-time upgrade from v1.4 and earlier. Those versions saved every preference with a
// driver default, so the stored preferences may not reflect anything you chose. Clear them
// and read the real values from the device, which then fill Preferences.
// Returns true when the migration ran (callers should not write configuration this time).
private boolean migrateIfNeeded() {
    if (state.prefSchema == PREF_SCHEMA) return false
    state.prefSchema = PREF_SCHEMA
    state.remove("resyncAll")
    configParams.each { device.removeSetting("configParam${it.num}") }
    log.warn "${device.displayName}: upgraded to v${DRIVER_VERSION}; parameter preferences cleared and are being " +
             "reloaded from the device. Nothing was written. Review Preferences, then change and save as needed."
    runIn(2, "readConfiguration", [overwrite: true])
    return true
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

// Writes any configuration parameter, then reads it back. The readback is logged and,
// for parameters listed in Preferences, copied into the matching preference.
def setConfigurationParameter(parameterNumber, parameterLength, value) {
    try {
        int p = safeToInt(parameterNumber, -1)
        int n = safeToInt(parameterLength, -1)
        if (value == null || !"${value}".trim().matches(/-?\d+(\.0+)?/)) throw new IllegalArgumentException("value must be a whole number")
        long v = new BigDecimal("${value}".trim()).longValue()
        if (p == 255) throw new IllegalArgumentException("parameter 255 is commonly a reset parameter and is blocked by this driver")
        if (p < 1 || p > 254) throw new IllegalArgumentException("parameter number must be 1-254")
        if (!(n in [1, 2, 4])) throw new IllegalArgumentException("length must be 1, 2 or 4 bytes")
        long min = -(1L << (8 * n - 1))
        long max = (1L << (8 * n)) - 1
        if (v < min || v > max) throw new IllegalArgumentException("value must be ${min} to ${max} for ${n} byte(s)")
        // Unsigned values above the signed range are sent as their two's-complement equivalent (same bytes).
        long signedMax = (1L << (8 * n - 1)) - 1
        int wire = (int) (v > signedMax ? v - (1L << (8 * n)) : v)
        log.info "${device.displayName}: writing parameter #${p}, length ${n}, value ${v}"
        sendCommands([
            secureCmd(zwave.configurationV1.configurationSet(parameterNumber: p, size: n, scaledConfigurationValue: wire)),
            secureCmd(zwave.configurationV1.configurationGet(parameterNumber: p))
        ], 500)
    } catch (e) {
        log.error "${device.displayName}: parameter write rejected: ${e.message}"
    }
}

def refresh() {
    logDebug "refresh()..."
    migrateParamStateKeys()
    refreshSyncStatus()
    sendCommands([switchMultilevelGetCmd(), secureCmd(zwave.versionV1.versionGet())], 300)
}

// Scheduled follow-up after a digital command; must send its own commands because
// values returned from scheduled methods are not transmitted.
def refreshSwitch() {
    sendCommands([switchMultilevelGetCmd()])
}

def on() {
    logDebug "on()..."
    markDigital()
    runIn(2, "refreshSwitch", [overwrite: true])
    return [ basicSetCmd(0xFF) ]
}

def off() {
    logDebug "off()..."
    markDigital()
    runIn(2, "refreshSwitch", [overwrite: true])
    return [ basicSetCmd(0x00) ]
}

def setLevel(level) {
    logDebug "setLevel($level)..."
    return setLevel(level, 1)
}

def setLevel(level, duration) {
    logDebug "setLevel($level, $duration)..."
    int durationVal = validateRange(duration, 1, 0, 30)
    markDigital()
    runIn(Math.max(2, durationVal + 1), "refreshSwitch", [overwrite: true])
    return [ switchMultilevelSetCmd(level, durationVal) ]
}

private switchMultilevelGetCmd() {
    return secureCmd(zwave.switchMultilevelV3.switchMultilevelGet())
}

private basicSetCmd(val) {
    return secureCmd(zwave.basicV1.basicSet(value: val))
}

private switchMultilevelSetCmd(level, int durationVal) {
    // Z-Wave levels are 0-99; 100% is sent as 99.
    int levelVal = validateRange(level, 99, 0, 99)
    return secureCmd(zwave.switchMultilevelV3.switchMultilevelSet(dimmingDuration: durationVal, value: levelVal))
}

private void markDigital() {
    state.lastDigitalCmd = new Date().time
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

def parse(String description) {
    def result = []
    try {
        migrateIfNeeded()
        migrateParamStateKeys()
        def cmd = zwave.parse(description, commandClassVersions)
        if (cmd) {
            result.addAll(zwaveEvent(cmd) ?: [])
        } else {
            logDebug "Unable to parse description: $description"
        }
        updateLastCheckIn()
    } catch (e) {
        log.error "${device.displayName}: parse error: $e"
    }
    return result
}

private void updateLastCheckIn() {
    long nowMs = new Date().time
    Long last = state.lastCheckInMs as Long
    if (last == null || nowMs - last >= 60 * 60 * 1000L) {
        state.lastCheckInMs = nowMs
        sendEvent(name: "lastCheckIn", value: convertToLocalTimeString(new Date()))
    }
}

def zwaveEvent(hubitat.zwave.commands.securityv1.SecurityMessageEncapsulation cmd) {
    logTrace "SecurityMessageEncapsulation: ${cmd}"
    def encapCmd = cmd.encapsulatedCommand(commandClassVersions)
    def result = []
    if (encapCmd) {
        result.addAll(zwaveEvent(encapCmd) ?: [])
    } else {
        log.warn "${device.displayName}: unable to extract encapsulated cmd from $cmd"
    }
    return result
}

def zwaveEvent(hubitat.zwave.commands.supervisionv1.SupervisionGet cmd) {
    logTrace "SupervisionGet: ${cmd}"
    def inner = cmd.encapsulatedCommand(commandClassVersions)
    if (inner) {
        zwaveEvent(inner)
    } else {
        log.warn "${device.displayName}: unable to extract supervised command: ${cmd}"
    }
    def report = zwave.supervisionV1.supervisionReport(
        sessionID: cmd.sessionID, reserved: 0, moreStatusUpdates: false,
        status: inner ? 0xFF : 0x00, duration: 0
    )
    sendHubCommand(new hubitat.device.HubAction(secureCmd(report), hubitat.device.Protocol.ZWAVE))
    return []
}

def zwaveEvent(hubitat.zwave.commands.supervisionv1.SupervisionReport cmd) {
    logTrace "SupervisionReport: ${cmd}"
    return []
}

def zwaveEvent(hubitat.zwave.commands.configurationv1.ConfigurationReport cmd) {
    logTrace "ConfigurationReport: ${cmd}"
    sendEvent(name: "syncStatus", value: "Syncing...")
    runIn(4, "refreshSyncStatus", [overwrite: true])
    def param = configParams.find { it.num == cmd.parameterNumber }
    def val = cmd.scaledConfigurationValue
    if (param) {
        if (txtEnable) log.info "${device.displayName}: ${param.name} (#${param.num}) = ${val}"
        setParamStoredValue(param.num, val)
        syncPreference(param, val)
    } else {
        // Unlisted parameter (e.g. from Set Configuration Parameter): keep and always log the readback.
        setParamStoredValue(cmd.parameterNumber, val)
        log.info "${device.displayName}: parameter #${cmd.parameterNumber} (size ${cmd.size}) = ${val}"
    }
    return []
}

// Copy the device's reported value into Preferences so the page reflects the device.
private void syncPreference(Map param, val) {
    try {
        String name = "configParam${param.num}"
        if ("${settings[name]}" == "${val}") return
        if (param.options) {
            if (!param.optionKeys.contains("${val}")) {
                log.warn "${device.displayName}: ${param.name} reported unlisted value ${val}; preference left unchanged"
                return
            }
            device.updateSetting(name, [value: "${val}", type: "enum"])
        } else {
            device.updateSetting(name, [value: val, type: "number"])
        }
        logDebug "Preference ${name} synchronized to ${val}"
    } catch (e) {
        log.warn "${device.displayName}: could not synchronize preference for #${param.num}: ${e.message}"
    }
}

def refreshSyncStatus() {
    def changes = pendingChanges
    sendEvent(name: "syncStatus", value: (changes ? "${changes} Pending Changes" : "Synced"))
}

def zwaveEvent(hubitat.zwave.commands.versionv1.VersionReport cmd) {
    logTrace "VersionReport: ${cmd}"
    def subVersion = String.format("%02d", cmd.applicationSubVersion)
    def fullVersion = "${cmd.applicationVersion}.${subVersion}"
    sendEvent(name: "firmwareVersion", value: fullVersion)
    return []
}

def zwaveEvent(hubitat.zwave.commands.basicv1.BasicReport cmd) {
    logTrace "BasicReport: ${cmd}"
    sendSwitchEvents(cmd.value)
    return []
}

def zwaveEvent(hubitat.zwave.commands.switchmultilevelv3.SwitchMultilevelReport cmd) {
    logTrace "SwitchMultilevelReport: ${cmd}"
    sendSwitchEvents(cmd.value)
    return []
}

def zwaveEvent(hubitat.zwave.Command cmd) {
    logDebug "Unhandled zwaveEvent: $cmd"
    return []
}

private void sendSwitchEvents(rawVal) {
    int raw = safeToInt(rawVal, 0)
    if (raw == 0xFE) {          // "unknown" per Z-Wave spec
        logDebug "Device reported unknown level"
        return
    }
    long nowMs = new Date().time
    Long lastDigital = state.lastDigitalCmd as Long
    Long lastCheck = state.switchCheckAt as Long
    boolean fromCommand = lastDigital != null && nowMs - lastDigital < 5000
    boolean fromCheck = lastCheck != null && nowMs - lastCheck < SWITCH_CHECK_WINDOW_MS
    // A correction found by the periodic check is not a button press: send it as digital.
    String type = (fromCommand || fromCheck) ? "digital" : "physical"
    String source = fromCommand ? "digital" : (fromCheck ? "status check" : "physical")
    // One report answers one check; clear the marker so a later button press is still "physical".
    if (fromCheck) state.remove("switchCheckAt")

    String switchVal = raw ? "on" : "off"
    if (device.currentValue("switch") != switchVal) {
        String desc = "${device.displayName} was turned ${switchVal} [${source}]"
        if (txtEnable) log.info desc
        sendEvent(name: "switch", value: switchVal, type: type, descriptionText: desc)
    }
    // Only real levels (1-99) update level; 0xFF means "on" without a level.
    if (raw >= 1 && raw <= 99) {
        int levelPct = (raw == 99) ? 100 : raw
        if (safeToInt(device.currentValue("level"), -1) != levelPct) {
            String desc = "${device.displayName} level is ${levelPct}% [${source}]"
            if (txtEnable) log.info desc
            sendEvent(name: "level", value: levelPct, unit: "%", type: type, descriptionText: desc)
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

private String secureCmd(hubitat.zwave.Command cmd) {
    return zwaveSecureEncap(cmd.format())
}

private void sendCommands(List cmds, Integer delay = 300) {
    def valid = cmds?.findAll { it }
    if (valid) sendHubCommand(new hubitat.device.HubMultiAction(delayBetween(valid, delay), hubitat.device.Protocol.ZWAVE))
}

private static getCommandClassVersions() {
    [
        0x20: 1,	// Basic
        0x26: 3,	// Switch Multilevel
        0x55: 1,	// Transport Service
        0x59: 1,	// AssociationGrpInfo
        0x5A: 1,	// DeviceResetLocally
        0x5E: 2,	// ZwaveplusInfo
        0x71: 3,	// Notification
        0x6C: 1,	// Supervision
        0x70: 1,	// Configuration
        0x7A: 2,	// FirmwareUpdateMd
        0x72: 2,	// ManufacturerSpecific
        0x73: 1,	// Powerlevel
        0x85: 2,	// Association
        0x86: 1,	// Version (2)
        0x8E: 2,	// Multi Channel Association
        0x98: 1,	// Security S0
        0x9F: 1		// Security S2
    ]
}

// Counts only preferences you have set that differ from (or have not yet been confirmed by) the device.
private getPendingChanges() {
    return configParams.count { it.value != null && it.value != getParamStoredValue(it.num) }
}

private getParamStoredValue(paramNum) {
    migrateParamStateKeys()
    return safeToInt(state[paramStateKey(paramNum)], null)
}

private void setParamStoredValue(paramNum, val) {
    migrateParamStateKeys()
    state[paramStateKey(paramNum)] = val
}

// e.g. "param02 LED Indicator Mode"; zero-padded so State Variables sort numerically.
private static String paramStateKey(paramNum) {
    int n = safeToInt(paramNum, 0)
    String name = PARAM_STATE_NAMES[n] ?: "(unknown)"
    return String.format("param%02d %s", n, name)
}

// Converts entries from v1.5.1 and earlier ("configParam2") to the named form.
private void migrateParamStateKeys() {
    def oldKeys = state.keySet().findAll { "${it}" ==~ /configParam\d+/ }
    if (!oldKeys) return
    log.info "${device.displayName}: renaming ${oldKeys.size()} parameter state entries to named form"
    oldKeys.each { key ->
        int n = "${key}".substring("configParam".length()).toInteger()
        def val = state[key]
        String newKey = paramStateKey(n)
        if (state[newKey] == null) state[newKey] = val
        state.remove(key)
    }
}

// Configuration Parameters
private getConfigParams() {
    [
        ledModeParam,
        autoOffIntervalParam,
        autoOnIntervalParam,
        nightLightParam,
        powerFailureRecoveryParam,
        pushDimmingDurationParam,
        holdDimmingDurationParam,
        minimumBrightnessParam,
        maximumBrightnessParam
    ]
}

private getLedModeParam() {
    return getParam(2, "LED Indicator Mode", 1, 0, ledModeOptions)
}

private getAutoOffIntervalParam() {
    return getParam(4, "Auto Turn-Off Timer(0, Disabled; 1 - 65535 minutes)", 4, 0, null, "0..65535")
}

private getAutoOnIntervalParam() {
    return getParam(6, "Auto Turn-On Timer(0, Disabled; 1 - 65535 minutes)", 4, 0, null, "0..65535")
}

private getNightLightParam() {
    return getParam(7, "Night Light Settings(1 - 10:10% - 100%)", 1, 2, null, "1..10")
}

private getPowerFailureRecoveryParam() {
    return getParam(8, "Power Failure Recovery", 1, 2, powerFailureRecoveryOptions)
}

private getPushDimmingDurationParam() {
    return getParam(9, "Push Dimming Duration(0, Disabled; 1 - 10 Seconds)", 1, 2, null, "0..10")
}

private getHoldDimmingDurationParam() {
    return getParam(10, "Hold Dimming Duration(1 - 10 Seconds)", 1, 4, null, "1..10")
}

private getMinimumBrightnessParam() {
    return getParam(11, "Minimum Brightness(0, Disabled; 1 - 99:1% - 99%)", 1, 10, null,"0..99")
}

private getMaximumBrightnessParam() {
    // 800-series manual: size=1, 0 disables maximum limit, 1..99 limits maximum brightness.
    // Manufacturer factory default is 99; a tested MP21ZD (firmware 8.0) reported 0.
    return getParam(12, "Maximum Brightness (0 = Disabled; 1-99 = Limit)", 1, 99, null, "0..99")
}

// value is null when the preference is blank (unmanaged).
private getParam(num, name, size, factoryDefault, options = null, range = null) {
    def val = safeToInt((settings ? settings["configParam${num}"] : null), null)
    def map = [num: num, name: name, size: size, value: val, factoryDefault: factoryDefault]
    if (options) {
        map.valueName = options?.find { k, v -> "${k}" == "${val}" }?.value
        map.options = setDefaultOption(options, factoryDefault)
        map.optionKeys = options.keySet().collect { "${it}" }
    }
    if (range) {
        map.range = range
    }
    return map
}

private static setDefaultOption(options, defaultVal) {
    return options?.collect{ k, v ->
        if ("${k}" == "${defaultVal}") {
            v = "${v} [FACTORY DEFAULT]"
        }
        ["$k": "$v"]
    }
}

private static getLedModeOptions() {
    return [
        "0":"Off When On",
        "1":"On When On",
        "2":"Always Off",
        "3":"Always On"
    ]
}

private static getPowerFailureRecoveryOptions() {
    return [
        "0":"Turn Off",
        "1":"Turn On",
        "2":"Restore Last State"
    ]
}

private static int validateRange(val, int defaultVal, int lowVal, int highVal) {
    int v = safeToInt(val, defaultVal)
    return Math.max(lowVal, Math.min(highVal, v))
}

// Accepts integers, decimals ("5.0", 5.0) and numeric strings; anything else returns defaultVal.
private static safeToInt(val, defaultVal = 0) {
    if (val == null) return defaultVal
    if (val instanceof Number) return ((Number) val).intValue()
    String s = "${val}".trim()
    if (s.isInteger()) return s.toInteger()
    if (s.isBigDecimal()) return new BigDecimal(s).intValue()
    return defaultVal
}

private convertToLocalTimeString(dt) {
    def timeZoneId = location?.timeZone?.ID
    if (timeZoneId) {
        return dt.format("MM/dd/yyyy hh:mm:ss a", TimeZone.getTimeZone(timeZoneId))
    } else {
        return "$dt"
    }
}

private static isDuplicateCommand(lastExecuted, allowedMil) {
    !lastExecuted ? false : (lastExecuted + allowedMil > new Date().time)
}

private logDebug(msg) {
    if (settings?.enableDebugLogging == true) log.debug "${device.displayName}: $msg"
}

private logTrace(msg) {
    if (settings?.enableTraceLogging == true) log.trace "${device.displayName}: $msg"
}

Thanks for posting this...you might consider adding a screen show of the Device page Command and Preferences tabs, so people can easily get an idea of what this driver offers. :slight_smile:

It's easy enough for someone to install it quickly and see what it does. I'm just frustrated that I can't post it as a file in the form.