<commit_before>/**
 *	Wifi 104 Integration (Local)
 *
 *	Copyright 2017 <NAME>
 *
 *	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.
 *
 */

def version() {
    return "1.0\n© 2017 <NAME>"
}

preferences {
    section {
        input("mac", "string", title: "MAC Address (no colons)", required: true, displayDuringSetup: true)
        paragraph "Version: ${version()}"
    }
}

metadata {
    definition (name: "Wifi 104 (local)", namespace: "bluesliverx", author: "<NAME>") {
        capability "Color Control"
        capability "Switch"
        capability "Refresh"

//        attribute "energy_str", "string"
//        attribute "energy_yesterday", "string"
//        attribute "energy_last7days", "string"
//        attribute "energy_life", "string"
//        attribute "power_details", "string"
//        attribute "efficiency", "string"
//        attribute "efficiency_yesterday", "string"
//        attribute "efficiency_last7days", "string"
    }

    simulator {
        // TODO: define status and reply messages here
    }

    tiles(scale: 2) {
        // this tile is used for display in device list (to get correct colorization)
        valueTile(
                "power",
                "device.power") {
            state("power",
                    label: '${currentValue}W',
                    unit: "W",
                    icon: "https://raw.githubusercontent.com/ahndee/Envoy-ST/master/devicetypes/aamann/enlighten-envoy-local.src/Solar.png",
                    backgroundColors: [
                            [value: 0, color: "#bc2323"],
                            [value: 1000, color: "#1e9cbb"],
                            [value: 2000, color: "#90d2a7"]
                    ])
        }
        // this tile is used only to provide an icon in the recent events list
        valueTile(
                "energy",
                "device.energy") {
            state("energy",
                    label: '${currentValue}',
                    unit: "kWh")
        }
        // the following tiles are used for display in the device handler
        multiAttributeTile(name: "switch", type: "lighting", width: 6, height: 4, canChangeIcon: true) {
            tileAttribute("device.switch", key: "PRIMARY_CONTROL") {
                attributeState "on", label: '${name}', action: "lightsOff", icon: "st.Seasonal Winter.seasonal-winter-011",
                        backgroundColor: "#79b821", nextState: "off"
                attributeState "off", label: '${name}', action: "lightsOn", icon: "st.Seasonal Winter.seasonal-winter-011",
                        backgroundColor: "#ffffff", nextState: "on"
            }
            tileAttribute("device.zone1Color", key: "COLOR_CONTROL", label:"Zone 1 Color") {
                attributeState "color", action: "setZone1Color"
            }
            tileAttribute("device.zone2Color", key: "COLOR_CONTROL", label:"Zone 2 Color") {
                attributeState "color", action: "setZone2Color"
            }
        }

        main "switch"
        details(["switch", "refresh"])
    }
}

def updated() {
    log.info("Updated")
//    if (!state.updatedLastRanAt || now() >= state.updatedLastRanAt + 2000) {
//        state.updatedLastRanAt = now()
//        log.trace("$device.displayName - updated() called with settings: ${settings.inspect()}")
//        state.remove('api')
//        state.remove('installationDate')
//        state.maxPower = settings.confNumInverters * settings.confInverterSize
//        // Notify health check about this device with timeout interval equal to 5 failed update requests
//        // (add 30 seconds so we don't collide with the 5th request in case that succeeds)
//        def healthCheckInterval = 5 * settings.pollingInterval.toInteger() * 60 + 30
//        sendEvent(name: "checkInterval", value: healthCheckInterval, data: [protocol: "lan", hubHardwareId: device.hub.hardwareID], displayed: false)
//        log.trace("$device.displayName - setting checkInterval for device health check to ${healthCheckInterval} seconds")
//        pullData()
//    } else {
//        log.trace("$device.displayName - updated() ran within the last 2 seconds - skipping")
//    }
}

private def updateDNI() {
    if (!state.dni || state.dni != device.deviceNetworkId || (settings.mac && settings.mac != device.deviceNetworkId)) {
        device.setDeviceNetworkId(bytesToHex(settings.mac))
        state.dni = device.deviceNetworkId
    }
}

//def toggleOffColorTiles() {
//    sendEvent(name: "zone1Color", value: device.zone1Color, displayed: false, isStateChange: true)
//    sendEvent(name: "zone2Color", value: device.zone2Color, displayed: false, isStateChange: true)
//}

// Return hex-string interpretation of byte array
public String bytesToHex(byte[] bytes) {
    final char[] hexArray = "0123456789ABCDEF".toCharArray();
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}


// Commands to send to the wifi 104

def lightsOn() {
    log.info("Turning lights on")
    sendCommand([0x55,0xaa,0x15,0x0f,0x08,0x11,0x0e,0x59,0xff,0xff,0x02,0x03,0x00,0x00,0x00,0xea])<commit_msg>Reverts settings and change actions<commit_after>/**
 *	Wifi 104 Integration (Local)
 *
 *	Copyright 2017 <NAME>
 *
 *	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.
 *
 */

def version() {
    return "1.0\n© 2017 <NAME>"
}

preferences {
    input("mac", "string", title: "MAC Address (no colons)", required: true, displayDuringSetup: true)
    input(title:"", description: "Version: ${version()}", type: "paragraph", element: "paragraph")
}

metadata {
    definition (name: "Wifi 104 Local", namespace: "bluesliverx", author: "<NAME>") {
        capability "Color Control"
        capability "Switch"
        capability "Refresh"

//        attribute "energy_str", "string"
//        attribute "energy_yesterday", "string"
//        attribute "energy_last7days", "string"
//        attribute "energy_life", "string"
//        attribute "power_details", "string"
//        attribute "efficiency", "string"
//        attribute "efficiency_yesterday", "string"
//        attribute "efficiency_last7days", "string"
    }

    simulator {
        // TODO: define status and reply messages here
    }

    tiles(scale: 2) {
        multiAttributeTile(name:"Zone 1", type: "lighting", width: 6, height: 4) {
            tileAttribute ("device.switch", key: "PRIMARY_CONTROL") {
                attributeState "on", label:'${name}', action:"switch.off", icon:"st.Seasonal Winter.seasonal-winter-011", backgroundColor:"#00a0dc"
                attributeState "off", label:'${name}', action:"switch.on", icon:"st.Seasonal Winter.seasonal-winter-011", backgroundColor:"#ffffff"
            }
            tileAttribute ("device.color", key: "COLOR_CONTROL") {
                attributeState "color", action:"setAdjustedColor"
            }
        }
        multiAttributeTile(name:"Zone 2", type: "lighting", width: 6, height: 4) {
            tileAttribute ("device.switch", key: "PRIMARY_CONTROL") {
                attributeState "on", label:'${name}', action:"switch.on", icon:"st.Seasonal Winter.seasonal-winter-011", backgroundColor:"#00a0dc"
                attributeState "off", label:'${name}', action:"switch.off", icon:"st.Seasonal Winter.seasonal-winter-011", backgroundColor:"#ffffff"
            }
            tileAttribute ("device.color", key: "COLOR_CONTROL") {
                attributeState "color", action:"setAdjustedColor"
            }
        }

        main "switch"
        details(["refresh"])
    }
}

def updated() {
    log.info("Updated")
//    if (!state.updatedLastRanAt || now() >= state.updatedLastRanAt + 2000) {
//        state.updatedLastRanAt = now()
//        log.trace("$device.displayName - updated() called with settings: ${settings.inspect()}")
//        state.remove('api')
//        state.remove('installationDate')
//        state.maxPower = settings.confNumInverters * settings.confInverterSize
//        // Notify health check about this device with timeout interval equal to 5 failed update requests
//        // (add 30 seconds so we don't collide with the 5th request in case that succeeds)
//        def healthCheckInterval = 5 * settings.pollingInterval.toInteger() * 60 + 30
//        sendEvent(name: "checkInterval", value: healthCheckInterval, data: [protocol: "lan", hubHardwareId: device.hub.hardwareID], displayed: false)
//        log.trace("$device.displayName - setting checkInterval for device health check to ${healthCheckInterval} seconds")
//        pullData()
//    } else {
//        log.trace("$device.displayName - updated() ran within the last 2 seconds - skipping")
//    }
}

private def updateDNI() {
    if (!state.dni || state.dni != device.deviceNetworkId || (settings.mac && settings.mac != device.deviceNetworkId)) {
        device.setDeviceNetworkId(bytesToHex(settings.mac))
        state.dni = device.deviceNetworkId
    }
}

def parse(String description) {
    log.info("Parse ${description}")
}

//def toggleOffColorTiles() {
//    sendEvent(name: "zone1Color", value: device.zone1Color, displayed: false, isStateChange: true)
//    sendEvent(name: "zone2Color", value: device.zone2Color, displayed: false, isStateChange: true)
//}

// Return hex-string interpretation of byte array
public String bytesToHex(byte[] bytes) {
    final char[] hexArray = "0123456789ABCDEF".toCharArray();
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}


// Commands to send to the wifi 104

def lightsOn() {
    log.info("Turning lights on")
    sendCommand([0x55,0xaa,0x15,0x0f,0x08,0x11,0x0e,0x59,0xff,0xff,0x02,0x03,0x00,0x00,0x00,0xea])
{'fraction_non_alphanumeric': 0.13365437034344904, 'fraction_numerical': 0.023986916227512266, 'mean_word_length': 2.737521222410866, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 17, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '677869', 'n_tokens_mistral': 3379, 'n_tokens_neox': 3169, 'n_words': 881}