我正在尝试使用 python3 和 CURL 通过 HTTP Bridge 发布到 pub/sub 主题。
**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__':
这给出了错误 400,因为我认为我没有描述子文件夹。 现在我很困惑,我可以在哪里定义代码中的子文件夹(主题名称(? 是否只缺少子文件夹?还是我也做错了别的事情?
卷曲
我还尝试使用中描述的 CURL 命令
https://cloud.google.com/iot/docs/how-tos/http-bridge
该命令是
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'
它触发了我的云功能,这意味着授权有效,但我无法在我的日志中看到"DATA"。 我假设我没有为binary_data提供正确的格式。 如果我也想使用 curl 发布上述"有效载荷",为什么会是正确的格式?
看起来您正在使用 JSON 有效负载,data
字段设置为对象,而不是二进制string
。尝试在'data'
字段中json.dumps
对象,或将'data'
字段作为字符串发送。
来自本文档。 https://cloud.google.com/iot/docs/reference/cloudiotdevice/rest/v1/projects.locations.registries.devices/publishEvent
我发现我的有效负载请求正文不正确。
所以有效载荷应该如下所示..
s= json.jumps('json object')
payload = {"subFolder": 'Sub_FOLDER_NAME', "binaryData": base64.b64encode(s.encode('utf-8'))}