Apollo Automation PUMP-1 Native ESPHome Driver

I would like to contribute by pump-1 driver. Is it perfect no. Most things work correctly, I haven’t had a chance to fix the auto refill but that is more for the beta firmware.

Also the firmware flash is not right yet.

Try it out and let me know your thoughts.

 * Apollo Automation PUMP-1 Native ESPHome Driver for Hubitat
 *
 * 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.
 *
 * Protocol Conformed to Official Specifications: https://wiki.apolloautomation.com
 * Revision History:
 * v1.3.1 - Fixed firmware OTA endpoint (/perform). Fixed SSE EventStream timeout handling to catch native Hubitat drop states.
 */

metadata {
    definition (name: "Apollo Automation PUMP-1 ESPHome", namespace: "Languy99", author: "Community") {
        capability "Switch"
        capability "Refresh"
        capability "Initialize"
        capability "Sensor"
        capability "TemperatureMeasurement"

        // Apollo Native Fluid Sensors
        attribute "fluidInput", "string"       // "Wet" or "Dry"
        attribute "fluidOutput", "string"      // "Wet" or "Dry"
        
        // Runtime Variables
        attribute "pumpRunTime", "number"
        attribute "maxSafeRunTime", "number"
        
        // Config Toggles
        attribute "autoRefill", "string"
        attribute "invertWaterLogic", "string"
        attribute "stopPumpWhenInputDry", "string"
        attribute "stopPumpWhenOutputWet", "string"
        attribute "pumpSafetyOverride", "string"
        
        // Onboard LED & System Update Tracking
        attribute "ledPower", "string"         // "on" or "off"
        attribute "firmwareUpdateStatus", "string"
        
        // Diagnostics
        attribute "connectionStatus", "string"
        attribute "rssi", "number"
        attribute "uptime", "number"

        // Custom Apollo Routine Commands
        command "runPump"
        command "runPumpUntilOutputWet"
        command "rebootDevice"
        command "updateFirmware"
        command "setLEDPower", [[name:"state*", type: "ENUM", constraints: ["on", "off"], description: "Toggle Onboard status NeoPixel"]]
        command "setLEDColor", [[name:"red*", type: "NUMBER", description: "Red channel (0-255)"], [name:"green*", type: "NUMBER", description: "Green channel (0-255)"], [name:"blue*", type: "NUMBER", description: "Blue channel (0-255)"]]
        command "setPumpRunTime", [[name:"seconds*", type: "NUMBER", description: "Standard execution runtime in seconds"]]
        command "setMaxSafeRunTime", [[name:"seconds*", type: "NUMBER", description: "Maximum safety cutoff threshold in seconds"]]
        command "setAutoRefill", [[name:"state*", type: "ENUM", constraints: ["on", "off"], description: "Toggle Auto Refill Logic"]]
        command "setInvertWaterLogic", [[name:"state*", type: "ENUM", constraints: ["on", "off"], description: "Toggle Inverted Sensors"]]
        command "setStopPumpWhenInputDry", [[name:"state*", type: "ENUM", constraints: ["on", "off"], description: "Toggle Dry Supply Cutoff"]]
        command "setStopPumpWhenOutputWet", [[name:"state*", type: "ENUM", constraints: ["on", "off"], description: "Toggle Full Destination Cutoff"]]
        command "setPumpSafetyOverride", [[name:"state*", type: "ENUM", constraints: ["on", "off"], description: "Toggle Hardware Protections"]]
    }

    preferences {
        input name: "deviceIp", type: "string", title: "PUMP-1 IP Address", description: "e.g. 192.168.100.22", required: true
        input name: "pumpEntityId", type: "string", title: "Pump Control Entity ID", description: "Default is switch-pump_control", defaultValue: "switch-pump_control", required: true
        input name: "logEnable", type: "bool", title: "Enable debug logging", defaultValue: true
        input name: "txtEnable", type: "bool", title: "Enable descriptionText logging", defaultValue: true
    }
}

def installed() {
    log.info "Apollo PUMP-1 Driver Installed"
    initialize()
}

def updated() {
    log.info "Apollo PUMP-1 Preferences updated"
    unschedule()
    initialize()
}

def initialize() {
    if (!deviceIp) {
        log.warn "IP Address is not configured. Please check device preferences."
        return
    }
    
    if (logEnable) log.debug "Connecting to Apollo PUMP-1 SSE Event Stream at http://${deviceIp}/events"
    sendEvent(name: "connectionStatus", value: "connecting")
    
    try {
        interfaces.eventStream.close()
        interfaces.eventStream.connect("http://${deviceIp}/events")
    } catch (Exception e) {
        log.error "Failed to connect to ESPHome event stream: ${e.message}"
        sendEvent(name: "connectionStatus", value: "disconnected")
        runIn(60, initialize)
    }
}

def refresh() {
    if (logEnable) log.debug "Stream-based refresh triggered. Re-initializing connection socket..."
    initialize()
}

def parse(String description) {
    if (!description) return
    def message = description.trim().replaceAll(/\u001B\[[;\d]*m/, "")
    
    if (message.startsWith("{") && message.endsWith("}")) {
        try {
            def entity = parseJson(message)
            sendEvent(name: "connectionStatus", value: "connected")
            parseEntityData(entity)
        } catch (e) {
            log.error "Failed to parse inline JSON object: ${e}"
        }
    }
    else if (message.startsWith("[") && message.endsWith("]")) {
        if (message.contains('{"id":')) {
            try {
                def entities = parseJson(message)
                if (entities instanceof List) {
                    entities.each { parseEntityData(it) }
                }
            } catch (e) {
                if (logEnable) log.debug "PUMP-1 Log: ${message}"
            }
        }
    }
    else {
        if (logEnable && (message.contains("[D]") || message.contains("[I]") || message.contains("[W]") || message.contains("[E]"))) {
            log.debug "PUMP-1 Log: ${message}"
        }
    }
}

def eventStreamHandler(String message) {
    if (message.startsWith("data:")) {
        parse(message.substring(5))
    } else {
        parse(message)
    }
}

def parseEntityData(entity) {
    if (!entity || !entity.id) return

    switch(entity.id) {
        // Core Pump Relay Switch
        case "switch-pump_control":
        case "switch-pump_relay":
        case settings.pumpEntityId:
            def switchState = (entity.value == true || entity.state == "ON" || entity.state == "on") ? "on" : "off"
            if (device.currentValue("switch") != switchState) {
                if (txtEnable) log.info "Apollo PUMP-1 Physical Switch turned ${switchState.toUpperCase()}"
                sendEvent(name: "switch", value: switchState)
            }
            break

        // Onboard Status LED
        case "light-rgb_light":
            def ledState = (entity.value == true || entity.state == "ON" || entity.state == "on") ? "on" : "off"
            if (device.currentValue("ledPower") != ledState) {
                if (txtEnable) log.info "Apollo PUMP-1 Status LED reported: ${ledState.toUpperCase()}"
                sendEvent(name: "ledPower", value: ledState)
            }
            break

        // Firmware Deployment Tracking
        case "update-firmware":
        case "update-pump_1_firmware":
            def updateState = entity.state ?: (entity.value == true ? "Update Available" : "Up to date")
            sendEvent(name: "firmwareUpdateStatus", value: updateState)
            break

        // Fluid Input Sensor (Supply Bottle)
        case "binary_sensor-fluid_input":
            def inputState = (entity.state == "Wet" || entity.value == true || entity.state == "ON") ? "Wet" : "Dry"
            if (device.currentValue("fluidInput") != inputState) {
                if (txtEnable) log.info "Apollo PUMP-1 Fluid Input Sensor reported: ${inputState.toUpperCase()}"
                sendEvent(name: "fluidInput", value: inputState)
            }
            break

        // Fluid Output Sensor (Target Reservoir)
        case "binary_sensor-fluid_output":
            def outputState = (entity.state == "Wet" || entity.value == true || entity.state == "ON") ? "Wet" : "Dry"
            if (device.currentValue("fluidOutput") != outputState) {
                if (txtEnable) log.info "Apollo PUMP-1 Fluid Output Sensor reported: ${outputState.toUpperCase()}"
                sendEvent(name: "fluidOutput", value: outputState)
            }
            break

        // Configurable Timing Numbers
        case "number-pump_run_time":
            def rTime = entity.value != null ? entity.value.toInteger() : entity.state.toInteger()
            sendEvent(name: "pumpRunTime", value: rTime, unit: "s")
            break

        case "number-max_safe_run_time":
            def mTime = entity.value != null ? entity.value.toInteger() : entity.state.toInteger()
            sendEvent(name: "maxSafeRunTime", value: mTime, unit: "s")
            break

        // On-board Automation State Logic Registers
        case "switch-auto_refill":
            sendEvent(name: "autoRefill", value: (entity.value == true || entity.state == "ON") ? "on" : "off")
            break

        case "switch-invert_water_logic":
            sendEvent(name: "invertWaterLogic", value: (entity.value == true || entity.state == "ON") ? "on" : "off")
            break

        case "switch-stop_pump_when_input_dry":
            sendEvent(name: "stopPumpWhenInputDry", value: (entity.value == true || entity.state == "ON") ? "on" : "off")
            break

        case "switch-stop_pump_when_output_wet":
            sendEvent(name: "stopPumpWhenOutputWet", value: (entity.value == true || entity.state == "ON") ? "on" : "off")
            break

        case "switch-pump_safety_override":
            sendEvent(name: "pumpSafetyOverride", value: (entity.value == true || entity.state == "ON") ? "on" : "off")
            break

        // Core Diagnostics
        case "sensor-rssi":
            def rssiVal = entity.value != null ? entity.value.toInteger() : entity.state.toInteger()
            sendEvent(name: "rssi", value: rssiVal, unit: "dBm")
            break

        case "sensor-esp_temperature":
            def tempVal = entity.value != null ? entity.value.toBigDecimal() : entity.state.toBigDecimal()
            sendEvent(name: "temperature", value: tempVal, unit: "°C")
            break

        case "sensor-uptime":
            def uptimeVal = entity.value != null ? entity.value.toInteger() : entity.state.toInteger()
            sendEvent(name: "uptime", value: uptimeVal, unit: "s")
            break
    }
}

// Main Pump Switches
def on() { 
    def targetId = (settings.pumpEntityId && settings.pumpEntityId != "switch-pump_relay") ? settings.pumpEntityId : "switch-pump_control"
    executeEsphomeCommand(targetId, "turn_on") 
}

def off() { 
    def targetId = (settings.pumpEntityId && settings.pumpEntityId != "switch-pump_relay") ? settings.pumpEntityId : "switch-pump_control"
    executeEsphomeCommand(targetId, "turn_off") 
}

// Onboard LED Management
def setLEDPower(String state) {
    if (logEnable) log.debug "Setting onboard LED state to: ${state}"
    executeEsphomeCommand("light-rgb_light", state == "on" ? "turn_on" : "turn_off")
}

def setLEDColor(BigDecimal red, BigDecimal green, BigDecimal blue) {
    if (logEnable) log.debug "Setting onboard LED color to R:${red} G:${green} B:${blue}"
    executeEsphomeCommand("light-rgb_light", "turn_on", [r: red.toInteger().toString(), g: green.toInteger().toString(), b: blue.toInteger().toString()])
}

// Firmware Maintenance Controls (Updated to ESPHome native /perform endpoint)
def updateFirmware() {
    log.info "Triggering native ESPHome OTA routine via /perform. If update fails to clear, access web flasher at https://flash.apolloautomation.com or update manually at http://${deviceIp}/update"
    executeEsphomeCommand("update-firmware", "perform")
    executeEsphomeCommand("update-pump_1_firmware", "perform")
}

// Custom Execution Commands
def runPump() {
    if (logEnable) log.debug "Executing Action: Run Pump"
    executeEsphomeCommand("button-run_pump", "press")
}

def runPumpUntilOutputWet() {
    if (logEnable) log.debug "Executing Action: Run Pump Until Output Wet"
    executeEsphomeCommand("button-run_pump_until_output_wet", "press")
}

def rebootDevice() {
    if (logEnable) log.debug "Executing Action: ESP Reboot"
    executeEsphomeCommand("button-esp_reboot", "press")
}

def setPumpRunTime(BigDecimal seconds) {
    executeEsphomeCommand("number-pump_run_time", "set", [value: seconds.toString()])
}

def setMaxSafeRunTime(BigDecimal seconds) {
    executeEsphomeCommand("number-max_safe_run_time", "set", [value: seconds.toString()])
}

def setAutoRefill(String state) { executeEsphomeCommand("switch-auto_refill", state == "on" ? "turn_on" : "turn_off") }
def setInvertWaterLogic(String state) { executeEsphomeCommand("switch-invert_water_logic", state == "on" ? "turn_on" : "turn_off") }
def setStopPumpWhenInputDry(String state) { executeEsphomeCommand("switch-stop_pump_when_input_dry", state == "on" ? "turn_on" : "turn_off") }
def setStopPumpWhenOutputWet(String state) { executeEsphomeCommand("switch-stop_pump_when_output_wet", state == "on" ? "turn_on" : "turn_off") }
def setPumpSafetyOverride(String state) { executeEsphomeCommand("switch-pump_safety_override", state == "on" ? "turn_on" : "turn_off") }

// Unified URL construction helper for native ESPHome interactions
private def executeEsphomeCommand(String entityId, String command, Map queryParams = null) {
    def componentType = entityId.split("-")[0]
    def normalizedId = entityId.replace("${componentType}-", "")
    def targetUri = "http://${deviceIp}/${componentType}/${normalizedId}/${command}"
    
    def params = [
        uri: targetUri,
        timeout: 5
    ]
    
    if (queryParams) {
        params.query = queryParams
    }
    
    if (logEnable) log.debug "Sending ESPHome Command to ${targetUri} with query params: ${params.query ?: 'None'}"
    
    def logUri = targetUri
    if (queryParams) {
        def queryString = queryParams.collect { k, v -> "${k}=${v}" }.join("&")
        logUri += "?${queryString}"
    }
    
    asynchttpPost("commandResponseHandler", params, [uri: logUri])
}

def commandResponseHandler(response, data) {
    if (response.hasError()) {
        log.error "PUMP-1 Endpoint Control Failure at [${data?.uri}]: ${response.getErrorMessage()}"
    }
}

// Re-engineered to properly intercept native Hubitat system stream drops
def eventStreamStatus(String status) {
    log.warn "SSE Event Stream Status changed to: ${status}"
    
    if (status && status.startsWith("START")) {
        sendEvent(name: "connectionStatus", value: "connected")
    } else {
        sendEvent(name: "connectionStatus", value: "disconnected")
        unschedule(initialize)
        // Auto-reconnect after 10-second cool down following an error or timeout exception
        runIn(10, initialize)
    }
}

I am having trouble getting values to transfer to Hubitat using this driver. The device provides information to ESPHome and will connect with Hubitat, but the sensor values do not transfer. AI suggested going through Home Assistant but I would prefer connecting directly.

I haven’t had a chance to look at it in a while truthfully. Other things happened and pulled me off of it. If you could provide more detail and maybe screen shots of what you are seeing I can try to help but it might take me a bit

@moderators please split the last 3 posts into a new thread.

Done!