首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我不能使用Python将图像发送到(使用此代码)?

为什么我不能使用Python将图像发送到(使用此代码)?
EN

Stack Overflow用户
提问于 2020-01-28 14:55:26
回答 1查看 519关注 0票数 0

下面是我用MQTT向Google Core发送图像的尝试。我读过以下文章,这些文章对我有所帮助,但我的代码仍然不起作用:如何使用Python中的Mosquitto将文件发布到AWS- IoT如何在python中使用Mosquitto发布文件?

我想我的错误可能与client.publish中的client.publish有关,也可能与我如何使用循环有关,但恐怕我对这些因素的实验到目前为止并没有帮助我(尝试qos = 0/1/2和例如client.loop_forever())。据我所知,我的图像是1.2MB,所以这不应该是一个问题。

代码语言:javascript
复制
#!/usr/bin/python

from picamera import PiCamera
import datetime
import time
import jwt
import paho.mqtt.client as mqtt
from time import sleep

# Define some project-based variables to be used below. This should be the only
# block of variables that you need to edit in order to run this script

ssl_private_key_filepath = 'FILE1.pem'
ssl_algorithm = 'RS256' # Either RS256 or ES256
root_cert_filepath = 'FILE2.PEM'
project_id = 'PROJECT_ID'
gcp_location = 'LOCATION'
registry_id = 'REG_ID'
device_id = 'DEVICE_ID'

# end of user-variables

run = True
cur_time = datetime.datetime.utcnow()

def create_jwt():
  token = {
      'iat': cur_time,
      'exp': cur_time + datetime.timedelta(minutes=60),
      'aud': project_id
  }

  with open(ssl_private_key_filepath, 'r') as f:
    private_key = f.read()

  return jwt.encode(token, private_key, ssl_algorithm)

_CLIENT_ID = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(project_id, gcp_location, registry_id, device_id)
_MQTT_TOPIC = '/devices/{}/events'.format(device_id)

client = mqtt.Client(client_id=_CLIENT_ID)
# authorization is handled purely with JWT, no user/pass, so username can be whatever
client.username_pw_set(
    username='unused',
    password=create_jwt())

def error_str(rc):
    return '{}: {}'.format(rc, mqtt.error_string(rc))

def on_connect(unusued_client, unused_userdata, unused_flags, rc):
    print('on_connect', error_str(rc))

def on_publish(unused_client, unused_userdata, unused_mid):
    print('on_publish')
    run = False


client.on_connect = on_connect
client.on_publish = on_publish

client.tls_set(ca_certs=root_cert_filepath) # Replace this with 3rd party cert if that was used when creating registry
client.connect('mqtt.googleapis.com', 8883)


camera = PiCamera()
camera.start_preview()
sleep(5)
camera.capture('/tmp/picture.jpg')
camera.stop_preview()

with open("/tmp/picture.jpg", 'rb') as f:
    imagestring = f.read()
byteArray = bytes(imagestring)


try:
    client.publish(_MQTT_TOPIC, byteArray, qos=2)
except:
    print('Error')

while run:
    client.loop()

client.disconnect()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-30 18:57:51

答案是由阿伦提供的。

“1.2毫巴太大了.”

遥测事件有效载荷限制为256 KB,不能增加

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59951444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档