Noob question about Device Handler and JSON over URL on LAN


(Spinn360) #1

Update I just figured out I must use a smart app alongside my device. Sorry folks please ignore my ramblings I’m but a poor noob.

Sorry if this is in the wrong place or I am coming off as the biggest noob ever, but I have been searching and coding for days and cannot figure out how to do what I need to.

Basically I have a device running on Wifi, that when I access its web page all it shows is JSON.

I have written code that runs on my computer in groovy that grabs the information and returns the specific data in the JSON. It runs just fine.

However, I have no idea how to implement it in a device handler. Below is the simple code I used just to test out that this works. I understand it isn’t exactly the best coded, but I am new to groovy, and haven’t done a lot of coding in the past couple of years since I learned Java.

import groovy.json.JsonSlurper
def i=100;
//create thread to handle timer between instances of while loop
		Thread y = new Thread();

while(i>0){
      def jsonSlurper = new JsonSlurper()
      def object = jsonSlurper.parseText('http://192.168.1.109:3003/getData?authToken=filvhe'.toURL().text)

      println("Motion: " + object.movement);
      println("Temp: "+ object.temperature);
      println("LightValue: " + object.lightValue);
     
 //timer run for 0.5 seconds
				y.sleep(500);
				i--;
				println "\n";
       
}

How do I change states of the tiles?
How do I access the URL and receive the JSON data in SmartThings?
Is there a tutorial for noobs? I have read a lot of SmartThings documentation, but I feel like they skipped over some basic things… or I am just completely overlooking something. I get that the def parse(String description) is where I handle the data receieved from the device, but how does that even get the data?

If I could just get an example for the capability of say the motion sensor that would be worth a million hours of trying to decipher partial posts of peoples code. Or if someone could just point out what I am doing wrong, missing, etc that would be awesome.

So right now I have been just trying to get one thing to work. Searching for motion. The JSON object I get back shows true or false for movement, when there is motion or none, but I cannot seem to get anything at all to do anything at all in SmartThings.

I have this so far… and I feel bad that it is all I have, but I have tried many other forms to no avail, and I am positive I need to sit down and read all the documents again and again and again for about a year…

metadata {
	definition (name: "Wifi Motion", namespace: "spinn360", author: "Me") {
		capability "Motion Sensor"
       
       
	}


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

	tiles {
		standardTile("motion", "device.motion", width: 1, height: 1) {
            
            state "inactive", label:'no motion', icon:"st.motion.motion.inactive", backgroundColor:"#ffffff"
            state "active", label:'motion', icon:"st.motion.motion.active", backgroundColor:"#53a7c0"
        }
}


def result = new physicalgraph.device.HubAction(
		method: "GET",
		path: "/getData?authToken=filvhe",   //I feel like this is wrong
		headers: [
			HOST: 'http://192.168.1.109:3003'  // and this is wrong too
		]
	)


def parse(String description) {
	log.debug "Parsing '${description}'"
    
   def msg = parseLanMessage(description)

    def headersAsString = msg.header // => headers as a string
    def headerMap = msg.headers      // => headers as a Map
    def body = msg.body              // => request body as a string
    def status = msg.status          // => http status code of the response
    def json = msg.json              // => any JSON included in response body, as a data structure of lists and maps
    def xml = msg.xml                // => any XML included in response body, as a document tree structure
    def data = msg.data  			// => either JSON or XML in response body (whichever is specified by content-type header in response)
  
    def slurper = new groovy.json.JsonSlurper()
    def result = slurper.parseText(json)
    assert result.movement =="false"
 
log.debug("Json received: ${object}") 

    
}

(Spinn360) #2

Okay so after getting some rest I thought I would try this again.

Okay I have the capability of motion sensor.

I have the states in the tiles section of active and inactive.
(Do I need to define the states or the capability?)

I added definition for motion…
def motion(){
log.debug “Executing ‘motion’”

    def hubAction = new physicalgraph.device.HubAction(
        method: "GET",
        path: "/getData?authToken=filvhe",
        headers: [HOST: "http://192.168.1.109:3003", Accept: "application/json"])
    log.debug hubAction
    return hubAction

}

I modified the parse section…

def parse(String description) {
	log.debug "Parsing '${description}'"
    
   def msg = parseLanMessage(description)

    def headersAsString = msg.header // => headers as a string
    def headerMap = msg.headers      // => headers as a Map
    def body = msg.body              // => request body as a string
    def status = msg.status          // => http status code of the response
    def json = msg.json              // => any JSON included in response body, as a data structure of lists and maps
    def xml = msg.xml                // => any XML included in response body, as a document tree structure
    def data = msg.data  			// => either JSON or XML in response body (whichever is specified by content-type header in response)
  
    def slurper = new groovy.json.JsonSlurper()
    def result = slurper.parseText(json)
  switch (json.movement){
  		case"true":
        sendEvent(name:"motion", value: "active", isStateChange: true)
        log.debug "Motion detected"
        break;
        case"false":
        sendEvent(name:"motion", value: "inactive", isStateChange: true)
        log.debug "No Motion detected"
        break;
  }
 
//log.debug("Json received: ${object}") 

    
}

But I still am seeing nothing at all happen… no log info in simulator, nothing in the app for the device… nothing… Any help would be great.


(Spinn360) #3

Not sure if I am making this better or worse.

metadata {
	definition (name: "Wifi Motion", namespace: "spinn360", author: "Me") {
		capability "Motion Sensor"
        //capability "Temperature Measurement"
        //capability "Refresh"
       
	}


	simulator {
		// TODO: define status and reply messages here
       // status "active": "zone report :: type: 19 value: 0031"
	//	status "inactive": "zone report :: type: 19 value: 0030"
	}

	tiles {
		standardTile("motion", "device.motion", width: 1, height: 1) {
            
            state "inactive", label:'No Motion', icon:"st.motion.motion.inactive", backgroundColor:"#ffffff"
            state "active", label:'Motion', icon:"st.motion.motion.active", backgroundColor:"#53a7c0"
        }
        
        main "motion"
        details "motion"
       // standardTile("Temperature", "device.temperature", key:"VALUE_CONTROL", width: 1, height: 1){
       // 	
       // }
       // standardTile("Refresh", "device.connection", width: 1, height: 1, decoration: "flat") {
    	//	state "default", icon:"st.secondary.refresh", backgroundColor:"#FFFFFF", action:"refresh.refresh", defaultState:true
        //    state "connected", icon:"st.secondary.refresh", backgroundColor:"#44b621", action:"refresh.refresh"
        //    state "disconnected", icon:"st.secondary.refresh", backgroundColor:"#ea5462", action:"refresh.refresh"   	
       // }
	}
}













def parse(String description) {
	log.debug "Parsing '${description}'"
    def name = null
    def value = description
    def descriptionText = null
    
   def msg = parseLanMessage(description)

    def headersAsString = msg.header // => headers as a string
    def headerMap = msg.headers      // => headers as a Map
    def body = msg.body              // => request body as a string
    def status = msg.status          // => http status code of the response
    def json = msg.json              // => any JSON included in response body, as a data structure of lists and maps
    def xml = msg.xml                // => any XML included in response body, as a document tree structure
    def data = msg.data  			// => either JSON or XML in response body (whichever is specified by content-type header in response)
  
    def slurper = new groovy.json.JsonSlurper()
    def results = slurper.parseText(json)
  switch (results.movement){
  		case"true":
        sendEvent(name:"motion", value: "active", isStateChange: true)
        log.debug "Motion detected"
        break;
        case"false":
        sendEvent(name:"motion", value: "inactive", isStateChange: true)
        log.debug "No Motion detected"
        break;
  }
  if (results.movement == ('true')){
  	name = "motion"
    def isActive = 'true'
    value = isActive ? "active" : "inactive"
    descriptionText = isActive ? "${device.displayName} detected motion" : "${device.displayName} motions has stopped"
  }
 
 def result = createEvent(
		name: name,
		value: value,
		descriptionText: descriptionText
	)
log.debug "Parse returned ${result?.desciptionText}"
return result    
}
def inactive(){

}

def active(){

}

def motion(){
log.debug "Executing 'motion'"
	
    def hubAction = new physicalgraph.device.HubAction(
        method: "GET",
        path: "/getData?authToken=filvhe",
        headers: [HOST: "http://192.168.1.109:3003", Accept: "application/json"])
    log.debug hubAction
    return hubAction

}