google-cloud-platformgoogle-cloud-functionsgoogle-cloud-pubsubgoogle-cloud-iot

How to publish to a GCP pub/sub topic using HTTP Bridge in Python3 & CURL?


I am trying to publish to a pub/sub topic via HTTP Bridge using python3 & CURL.

**Python3**

import json
import logging
import os
import socket
import sys
import time
import requests
URL = 'https://cloudiotdevice.googleapis.com/v1/projects/{}/locations/{}/registries/{}/devices/{}:publishEvent'
JWT = 'JWT'

def main():
    if not URL or not JWT:
        sys.exit("Are the Environment Variables set?")
    get_sensor_data(socket.gethostname())
def get_sensor_data(device_id):
    while True:
        print("in get_sensor data")
        payload = {'device': str('asd'),
                   'type': str('adssaff'),
                   'timestamp': str(time.time()),
                   'data': json.dumps({'temperature': str('23'),
                            'humidity': str('442')})}
        post_data(payload)
        print("data printed")
        time.sleep(5)
def post_data(payload):
    payload = json.dumps(payload)
    headers = {
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': JWT
    }
    try:
        req = requests.post(URL, json=str(payload), headers=headers)
        print("request Successfull "+str(req))
    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?')
if __name__ == '__main__':

This is giving an error 400 because i think i havent described the subfolder. Now i am confuse that where can i define the subfolder(Topic name) in my code? and is there only subfolder is missing? or i am doing something else wrong too?

CURL

i also tried using the CURL command described in

https://cloud.google.com/iot/docs/how-tos/http-bridge

The command is

curl -X POST -H 'authorization: Bearer JWT' -H 'content-type: application/json' --data '{"binary_data": "DATA", "sub_folder": "SUBFOLDER"}' -H 'cache-control: no-cache' 'https://cloudiotdevice.googleapis.com/v1/projects/{project-id}/locations/{cloud-region}/registries/{registry-id}/devices/{device-id}:publishEvent'

It triggers my cloud function which means the authorization works but i am not able to see "DATA" in my logs. which i assume i am not providing the right format for the binary_data. whyt would be the right format if i would like to publish 'payload' described above using curl too?


Solution

  • From this documentation. https://cloud.google.com/iot/docs/reference/cloudiotdevice/rest/v1/projects.locations.registries.devices/publishEvent

    I found out that my payload request body was not correct.

    so payload should look like this below ..

    s= json.jumps('json object')
    payload = {"subFolder": 'Sub_FOLDER_NAME', "binaryData": base64.b64encode(s.encode('utf-8'))}