How to get data from Samsung SmartThings Hub using an API from 3rd party APP?


(Anupam Singh) #1

How to get data from Samsung SmartThings Hub using an API in C#


( I hate Mondays) #2

What kind of data?


(Anupam Singh) #3

like netatmo weather device temrature and CO2 etc


( I hate Mondays) #4

Sure can. You need to build a Web Service SmartApp. Enable OAuth in the IDE and then figure out the URI you need to access it from outside. Then enable an endpoint mapping and provide a method that gets executed. Return data like below. More details here and here. You will need to create an access token - use createAccessToken() as explained here.

mappings {
    path("/test") {
        action: [
            GET: "responseTest",
            POST: "responseTest"
        ]
    }
}

def responseTest() {
    def html = """
    <!DOCTYPE html>
    <html>
        <head><title>Some Title</title></head>
        <body><p>Testing</p></body>
    </html>"""

    render contentType: "text/html", data: html, status: 200
}

In C#, you’ll need to get/post a URL of this form:

https://graph.api.smartthings.com/oauth/initialize?appId=dd6aa9d9-f1e6-4e2d-83d5-603c442016e0&access_token=d45b2a4c-1cc1-42e0-b3ee-73b7e08167a1/test

Note: the GUIDs above are fake

${app.id} is the id of the app, ${state.accessToken} is the security token generated by createAccessToken().

This should get you started:

def initialized() {
    if(!state.accessToken) {
        // the createAccessToken() method will store the access token in state.accessToken
        state.accessToken = createAccessToken()
    }
    log.trace "https://graph.api.smartthings.com/oauth/initialize?appId=${app.id}&access_token=${state.accessToken}"
}

Go to the IDE and go to Live logging - then install or open and save the SmartApp in the ST UI on the phone. The log should give you the URI. Append /endpoint after it, where endpoint is whatever name you define in the mappings. In the example above, you’d be using that URI from the logs followed by /test and responseTest() would be executed for either GET or POST requests. You can always just return a Map, rather than rendering HTML. return [a: value1, b: "string", c: null] - this will return JSON to your C# app.

All the above provides you a way to communicate to ST. Now to get data, you need to use a preference page and use some inputs in there to allow you to select which Things you want data from. Once done, you can use them all in your responseTest() method to build up the response.


(Anupam Singh) #5

I need to install SmartThings App in my phone?


( I hate Mondays) #6

During setup, yes. Once configured, you can uninstall it if you really have to


(Anupam Singh) #7

is there any code sample which is giving data from SmartThings hub using an API?


(Anupam Singh) #8

I dont have any device write now. can i use any DEMO hub that can return data


( I hate Mondays) #9

Here’s one that does it in reverse. It sends data to an API, rather than having the API poll data from it.

/**
 * SmartThings example Code for GroveStreams
 * A full "how to" guide for this example can be found at https://www.grovestreams.com/developers/getting_started_smartthings.html
 *
 * Copyright 2015 Jason Steele
 *
 * 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.
 *
 */

definition(
        name: "GroveStreams QuickStart",
        namespace: "JasonBSteele",
        author: "Jason Steele",
        description: "Log to GroveStreams",
        category: "My Apps",
        iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png",
        iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience@2x.png",
        iconX3Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience@2x.png")

preferences {
    section("Log devices...") {
        input "contacts", "capability.contactSensor", title: "Doors open/close", required: false, multiple: true
        input "powerMeters", "capability.powerMeter", title: "Power meters", required: false, multiple: true
        input "energyMeters", "capability.energyMeter", title: "Energy meters", required: false, multiple: true
        input "temperatures", "capability.temperatureMeasurement", title: "Temperatures", required:false, multiple: true
    }

    section ("GroveStreams Feed PUT API key...") {
        input "channelKey", "text", title: "API key"
    }
}

def installed() {
    initialize()
}

def updated() {
    unsubscribe()
    initialize()
}

def initialize() {
    subscribe(temperatures, "temperature", handleTemperatureEvent)
    subscribe(powerMeters, "power", handlePowerEvent)
    subscribe(energyMeters, "energy", handleEnergyEvent)
    subscribe(contacts, "contact", handleContactEvent)
}

def handleTemperatureEvent(evt) {
    sendValue(evt) { it.toString() }
}

def handlePowerEvent(evt) {
    sendValue(evt) { it.toString() }
}

def handleEnergyEvent(evt) {
    sendValue(evt) { it.toString() }
}

def handleContactEvent(evt) {
    sendValue(evt) { it == "closed" ? "false" : "true" }
}

private sendValue(evt, Closure convert) {
    def compId = URLEncoder.encode(evt.displayName.trim())
    def streamId = evt.name
    def value = convert(evt.value)
    
    log.debug "Logging to GroveStreams ${compId}, ${streamId} = ${value}"
    
    def url = "https://grovestreams.com/api/feed?api_key=${channelKey}&compId=${compId}&${streamId}=${value}"
    def putParams = [
        uri: url,
        body: []]

    httpPut(putParams) { response ->
        if (response.status != 200 ) {
            log.debug "GroveStreams logging failed, status = ${response.status}"
        }
    }
}