Search code examples
google-cloud-platformgoogle-cloud-functionsgoogle-cloud-pubsubgoogle-cloud-iot

HTTP request to HTTP Cloud Function from Device(Google Cloud IoT Core)?


How can i make a "HTTP requests" to a Google Cloud Function from a device(with CLOUD IOT CORE AUTHORIZATION)?

e.g. right now i have a device which is registered in Cloud IoT core already. In order to communicate i send the data via Pub/Sub Mqtt to the cloud function. It works well but i am not be able to send an acknowledgment message from cloud function to device that wether the response is successfull or not.

But now i would like to e.g. make a HTTP POST/GET Request to a cloud function from the device. So that this HTPP request gets a ack message e.g. "Your data has reached" back from the cloud function.

What i have tried now in my device is ..

def post_data(payload):
    URL='https://cloudiotdevice.googleapis.com/v1/projects/{project-id}/locations/{cloud-region}/registries/{registry-id}/devices/{device-id}:publishEvent'
    payload = json.dumps(payload)
    headers = {
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': JWT
    }
    try:
        requests.post(URL, json=payload, headers=headers)
    except requests.exceptions.ConnectionError:
        logging.error('Error posting data to Cloud Function!')
    except requests.exceptions.MissingSchema:
        logging.error('Error posting data to Cloud Function! Are Environment Variables set?')

But it is returning me back 400 error. I also have sub folder as a topic but i also dont know where should i define it?

payload format is like this below

payload = {'device': device_id,
           'type': TYPE,
           'timestamp': time.time(),
           'data': {'temperature': temperature,
                    'humidity': humidity}}

Solution

  • When you send a telemetry event from your device to Cloud IoT using HTTP, the payload must be JSON and it must be of the structure described here. Specifically, the payload of the REST POST request must be:

    {
      "binaryData": string
    }
    

    Where the ACTUAL data that you want published is a base 64 encoded representation. Looking at your example code, I'm not seeing you send a REST request with that payload.