python - 如何将文本数据和文件从 IoT 设备发送到 Cloud IoT Core?

标签 python google-cloud-storage mqtt google-cloud-iot

我正在将图像从 Raspberry Pi 发送到 Cloud IoT Core。这是可行的,但我现在意识到,当将其存储在 Google Cloud Storage 中时,我还需要文件的文件名(或我添加到文件名中的数据),但据我所知,它只是内容发送的文件的名称。我尝试使用下面的代码摘录来完成此操作,但这似乎不起作用,我想这是可以理解的,因为它是 JSON 对象内的字节数组..?

有办法吗?通过云功能发送到存储时,文件名是否可以以某种方式检索?

with open(filename, 'rb') as f:
    imagestring = f.read()
byteArray = bytes(imagestring)

now = datetime.datetime.now()
datetime_formatted = now.strftime("%Y-%m-%d_%H:%M:%S")
filename = 'img_GM4_' + datetime_formatted +'.jpg'

payload = '{{ "ts": {}, filename: {}, "image": {}}}'.format(int(time.time()), filename, byteArray)

client.publish(_MQTT_TOPIC, payload, qos=1)
# Previously: client.publish(_MQTT_TOPIC, byteArray, qos=1)

最佳答案

为了将图像保存在 Cloud Storage 中,您需要使用 Cloud Function with a Cloud Pub/Sub trigger

云功能应包含以下步骤:

  1. 以与 PubSubMessage 类似的方式从 this function 的 data 属性中解码数据。
  2. 从文件名字段中提取值并转换 value string from the image field to an actual image
  3. 使用其中一种可用方法将图像上传到 Cloud Storage。例如 Google Cloud Client Libraries for Python 或 REST API 以及任何可用的请求库(例如 requests )。您可以在文档中找到编码示例 here

最后,请注意,根据 best practices for Cloud Storage,您应该避免使用基于时间戳的文件名(这会限制您的吞吐量)。在云存储上下文中,建议在 following manner 中创建文件名。因此,如果您发现应用程序中存在性能问题,请考虑最后一条消息。

关于python - 如何将文本数据和文件从 IoT 设备发送到 Cloud IoT Core?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59990595/

相关文章:

使用 Pandas 数据读取器进行 Python 回归建模

python - 如何在 Pandas 中打开文件

firebase - 是否可以从 Firebase 存储提供 Brotli 压缩文件?

java - 如何从谷歌存储下载文件夹

batch-file - 为什么此 gsutil 调用在 FinalBuilder 网站上不起作用,但在 FinalBuilder 应用程序中运行时有效?

java - Azure IOT 中心上的 MQTT : Error initializing MQTT connection:Not authorized to connect

python - 元素在模态窗口中不可见 - Selenium Python

python - 如何在python docx中更改句子的字体样式

javascript - 使用 IP 地址作为主机名时,Paho MQTT 主机参数无效?

node.js - var mqtt = 需要 ('mqtt' );导致错误