Any Groovy Programmers?

I am looking for someone who knows Groovy (better than me :slight_smile: ) to convert the following python to Groovy

try:
    response = requests.post(

        'http://192.168.1.190:8123/api/states/sensor.hem_theperiod',

        headers={'x-ha-access': 'mypassword', 'content-type': 'application/json'},

        data=json.dumps({'state': x, 'attributes': {'hidden': 'true', 'friendly_name': 'the period'}}))
except:
    print ("%%%%%% HA Connection Error %%%%%")

Anyone?

Not groovy but I can turn my hand to Java/Kotlin and theyā€™re not so dissimilar, so I guess it would be something likeā€¦

try {

    response = request.post(
       'http://192.168.1.190:8123/api/states/sensor.hem_theperiod', 
        headers={'x-ha-access': 'mypassword', 'content-type': 'application/json'}, 
        data=json.dumps({'state': x, 'attributes': {'hidden': 'true', 'friendly_name': 'the period'}})
        );

} catch(Exception ex) {

    print "%%%%%% HA Connection Error %%%%%";
     

}

ā€¦ But I donā€™t understand python so Iā€™m guessing at transposing the functions print/print and requests/request :slight_smile:

1 Like

Yeah I am afraid Groovy is quite different in this case anyway. This is what is looks like. I am 99% sure my problem lies with the line data: ["ā€˜attributesā€™: {ā€˜hiddenā€™: ā€˜trueā€™, ā€˜friendly_nameā€™: ā€˜the periodā€™}, ā€˜stateā€™: ā€˜4ā€™" ]

def params = [
    uri: "http://192.168.1.190:8123",
    path: "/api/states/sensor.hem_theperiod",
    headers: ['x-ha-access': 'mypassword','content-type': 'application/json'],
    data: ["'attributes': {'hidden': 'true', 'friendly_name': 'the period'}, 'state': '4'" ]
       ]
       
log.debug "Calling HAS"
httpPostJson(params) { resp ->
        resp.headers.each {
            log.debug "${it.name} : ${it.value}"
        }

        log.debug "response contentType: ${resp.contentType}"
        }
log.debug "HAS called. $response"

Ugh, I get some weird dyslexia thing when I look at code with those weird lambda things in, thatā€™s one part of kotlin I still scratch my head over (amongst many others).

I take it you want the catch block to see why httpPostJson(params) is failing? If so it should just be wrapping it and printing the exception, no?

    def params = [
        uri: "http://192.168.1.190:8123",
        path: "/api/states/sensor.hem_theperiod",
        headers: ['x-ha-access': 'mypassword','content-type': 'application/json'],
        data: ["'attributes': {'hidden': 'true', 'friendly_name': 'the period'}, 'state': '4'" ]
           ]
           
    log.debug "Calling HAS"
    try {
        httpPostJson(params) { resp ->
                resp.headers.each {
                    log.debug "${it.name} : ${it.value}"
                }

                log.debug "response contentType:  ${resp.contentType}"
                }
        log.debug "HAS called. $response"

   } catch(Exception ex) {

        log.debug "Failed " + ex.toString()

   } 

Or perhaps does it want to be like thisā€¦

I am afraid I have hit a wall. I hate Groovy with a passion. Being a ā€œchild of the 60sā€ Groovy is NOT groovy :wink:

Not matter what I try I always get back the error
java.lang.SecurityException: Getting properties on class java.lang.Class is not allowed @line 265 (sendHTTPPost)

I even stripped the params definition down to only the uri and path to see if the error changes. Same thing. I know that the uri and path are correct as I copied it from the working python scripts.

I dont often give up but this one has me stumped. I hope the many proficient Groovy programmer of the Smartthings forum can shed some light.

Anyway, thank you very much for your effort. Stay tuned :slight_smile:

1 Like

Did you see the different method referred to in that stackoverflow answer? I take using that instead doesnā€™t work?

Am afraid not. With this methos I get
java.lang.NullPointerException: Cannot invoke method request() on null object @line 253 (sendHTTPPost)

Grrrrā€¦

Bugger.

I canā€™t be anymore use on this I donā€™t think, groovy is a mystery :smile:

Hope you work it out :+1:

Did you instantiate httpPostJson? Itā€™s difficult to debug when you only share a few lines.

the lines are posted are as far as I can go/show. the httpPosJson() is a library call. Here is the documentation for it:

httpPostJson()

Executes an HTTP POST request with a JSON-encoded body and content type, and passes control to the specified closure. The closure is passed one HttpResponseDecorator argument from which the response content and header information can be extracted.

If the response content type is JSON, the response data will automatically be parsed into a data structure.

Signature:

void httpPostJson(String uri, String body, Closure closure)

void httpPostJson(String uri, Map body, Closure closure)

void httpPostJson(Map params, Closure closure)

Parameters:

String uri - The URI to make the HTTP POST call to

String body - The body of the request

Map params - A map of parameters for configuring the request. The valid parameters are:

Parameter Description
uri Either a URI or URL of of the endpoint to make a request from.
path Request path that is merged with the URI.
query Map of URL query parameters.
headers Map of HTTP headers.
contentType Forced response content type and request Accept header.
requestContentType Content type for the request, if it is different from the expected response content-type.
body Request body that will be encoded based on the given contentType.

Closure closure - The closure that will be called with the response of the request.

@cdikland Oh this is the Samsung SmartThings Geoovy? I donā€™t know how much I can help with that. Did you try copy and pasting the example code for httpPostJson from the docs?

I ā€œsolvedā€ the problem by rewriting the python script into php. From within Groovy I call the webserver/script using Groovy library function httpGet. Not pretty but it works :slight_smile:

1 Like