[Request]Plaato Keg API App/Driver

Oh I see how that works now. The example in the documentation confused me, but your example helps me understand what is going on and why my attempts failed. Thank you.

1 Like

Ok, next hurdle...

Some of the calls return something like...

["23.850"]

...as a string. Looks like a really simple JSON object with the data at index 0. So what's the simplest way to grab that out as a number?

Something like this should work:

respData = '["23.850"]'
fVal = respData.substring(3,9).toFloat()

oh.. duh. Skip the json object entirely and just grab the characters in the middle.

Sometimes it's just simpler...

I would do this, just in case the data format changes (less digits or whatever):

def resp = '["23.850"]'
def map = new groovy.json.JsonSlurper().parseText(resp)
log.debug "${map}"
log.debug "${map?.getAt(0)?.toFloat()}"
1 Like

OK! I think I got it doing exactly what I want. Open to suggestions for improvements or otherwise cleaning it up. This is my first attempt at anything quite like this for Hubitat. Thank you both for all the help.

What are the limits with runIn for something like this? I don't want to bog down the hub, but if I could do a shorter runIn without worry I would add the Pouring Status to the driver. But that would have to be run every minute or use runInMillis() to make that even worth it. Not really a big deal. Party trick at best to have something happen when someone's pouring a beer.

/*
 * 
 *
 *  Licensed Virtual 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.
 *
 *  Change History:
 *
 *    Date        Who            What
 *    ----        ---            ----
 *    
 *
 */

static String version()	{  return '0.0.1'  }


metadata {
    definition (
		name: "Plaato Keg", 
		namespace: "thebearmay", 
		author: "Jean P. May, Jr.",
	        importUrl:""
	) {
        capability "Sensor"
       
        attribute "vpinReturn", "string"
		attribute "beerLeft", "decimal"
		attribute "temperature", "decimal"
		attribute "leakDetected", "bool"
        
		command "configure"
		command "refresh"
		//command "getPin",[[name:"pin*", type:"STRING", description:"Pin to retrieve"]]
    }   
}

preferences {
    input("auth_token","string", title: "Auth Token", required:true, submitOnChange:true)
	input("timer_pref","number", title: "Refresh Timer", description: "In minutes 1-60", required:false, defaultValue: 5, range: 1..60, submitOnChange:true)
    input("debugEnable", "bool", title: "Enable debug logging?")
    input("security", "bool", title: "Hub Security Enabled", defaultValue: false, submitOnChange: true)
    if (security) { 
        input("username", "string", title: "Hub Security Username", required: false)
        input("password", "password", title: "Hub Security Password", required: false)
    }
}


def installed() {
	log.trace "installed()"
}

def configure() {
    if(debugEnable) log.debug "configure()"
    refresh()
}

def updateAttr(aKey, aValue){
    sendEvent(name:aKey, value:aValue)
}

def updateAttr(aKey, aValue, aUnit){
    sendEvent(name:aKey, value:aValue, unit:aUnit)
}

def initialize(){

}


def refresh(){
		if(debugEnable) log.debug "Fetching data..."
		getRemaining()
		getTemp()
		getLeak()
		//updateAttr("vpinReturn"," ")
		timer = (timer_pref * 60)
		if(debugEnable) log.debug "Running refresh in ${timer} seconds"
		runIn(timer, refresh)
}


def getPin(pin){    
        makeGetHandler("$pin", "vpinReturn")	//Returns a string
}

def getRemaining(){    
        makeGetHandler("v48", "beerLeft")	//Returns a number
}

def getTemp(){    
        makeGetHandler("v56", "temperature")	//Returns a string
}

def getLeak(){    
        makeGetHandler("v83", "leakDetected")	//Returns a string; 0 if no leak, 1 if leak
}


def makeGetHandler(pin, attrName){
    if(security) {
		if(debugEnable) log.debug "Security enabled..."
        httpPost(
                [
                    uri: "http://remoteaccess.aws.hubitat.com",
                    path: "/login",
                    query: [ loginRedirect: "/" ],
                    body: [
                        username: username,
                        password: password,
                        submit: "Login"
                    ]
                ]
            ) { resp -> cookie = resp?.headers?.'Set-Cookie'?.split(';')?.getAt(0) }
     }    
        params = [
            uri: "http://plaato.blynk.cc",
            path: "/$auth_token/get/$pin",
            headers: [ "Cookie": cookie ],
        ]  
	
        asynchttpGet("sendGetHandler", params, [name: attrName])
}


def sendGetHandler(resp, data) {
    try {
        if(resp.getStatus() == 200) {
			if(data.name == "beerLeft") {
				pltoResp = resp.data.toFloat()
			} else if(data.name == "temperature"){
				strWork = resp.data.toString()
				pltoResp = strWork.substring(2,8).toFloat()
			} else if(data.name == "leakDetected"){
				strWork = resp.data.toString()
				intWork = strWork.substring(2,3).toInteger()
				if(intWork > 0){
					pltoResp = true
				} else
					pltoResp = false
			} else{
				pltoResp = resp.data.toString()
			}
    		if(debugEnable) log.debug "${data.name} returned ${pltoResp}"
	        updateAttr(data.name,pltoResp)
  	    } else
            updateAttr(data.name,"Return Status: ${resp.getStatus()}")
			if(debugEnable) log.debug "${data.name} returned Error ${resp.getStatus()}"
    } catch(Exception ex) { 
        updateAttr(data.name, ex)
    } 
}

def updated(){
	log.trace "updated()"
	if(debugEnable) runIn(1800,logsOff)
}

void logsOff(){
     device.updateSetting("debugEnable",[value:"false",type:"bool"])
}

Congratulations you are now a developer😆.

Every minute could work, lot of variables though based on app and device mix. Need to watch memory as there seems to be a small memory leak with doing http calls - normally not an issue (my Hub Information driver uses several and It’s usually a couple months before I need to reboot) but something to keep in mind.

2 Likes

Perhaps not a developer.. but this exercise taught me a lot about drivers code. In fact, I was finally able to fix up a buggy driver I got from SmarthomeDB that kept spewing groovy errors into the debug log.

3 Likes

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