3
votes

According to boto3 documentation here: https://boto3.readthedocs.org/en/latest/reference/services/iot-data.html#client the update_thing_shadow method takes the thingName & JSON payload as parameters. Currently it reads:

    client = boto3.client('iot-data', region_name='us-east-1')
    data = {"state" : { "desired" : { "switch" : "on" }}}
    mypayload = json.dumps(data)
    response = client.update_thing_shadow(
        thingName = 'MyDevice', 
        payload = b'mypayload'
    )

When I use the command line there's no problem but can't seem to get it right from within the lamba function. I've called it with numerous versions of code (json.JSONEncoder, bytearray(), etc..) without any luck. The errors range from syntax to (ForbiddenException) when calling the UpdateThingShadow operation: Bad Request: ClientError. Has anyone had success calling this or a similar method from within a AWS lambda function? Thanks.

2
What exactly is payload = b'mypayload' supposed to do here? - garnaat
update 'MyDevice' with a desired state, in this case set a switch to the 'on' position - JC23
But that is just a string constant containing "mypayload". It's not the actual payload you have stored in the variable called mypayload. That's why I'm confused. - garnaat
For clarification see above as stated in initial post "I've called it with numerous versions of code .... without any luck." What's there currently is the latest as all previous attempts failed. - JC23
Well, the example you show above would not appear to be correct. As I stated above, you are supposed to be passing a JSON payload but you are passing a string constant "mypayload". I would suggest fixing that issue and then updating the question with the new code and the exact response you are getting from the service. - garnaat

2 Answers

5
votes

This code is working fine for me:

def set_thing_state(thingName, state):
    # Change topic, qos and payload
    payload = json.dumps({'state': { 'desired': { 'property': state } }})

    logger.info("IOT update, thingName:"+thingName+", payload:"+payload)
    #payload = {'state': { 'desired': { 'property': state } }}


    response = client.update_thing_shadow(
        thingName = thingName, 
        payload =  payload
        )

    logger.info("IOT response: " + str(response))  
    logger.info("Body:"+response['payload'].read())


def get_thing_state(thingName):

    response = client.get_thing_shadow(thingName=thingName)

    streamingBody = response["payload"]
    jsonState = json.loads(streamingBody.read())

    print jsonState
    #print jsonState["state"]["reported"]

Good luck

0
votes

garnaat is right. Just replace payload = b'mypayload' with payload = mypayload and it should work.