Почему я не могу отправить изображение в Google Cloud IoT Core с MQTT, используя Python (с этим кодом)? - PullRequest
0 голосов
/ 28 января 2020

Ниже приведена моя попытка отправить изображение в Google Cloud IoT Core с помощью MQTT. Я прочитал следующие посты, которые мне несколько помогли, но мой код все еще не работает: Как я могу опубликовать sh Файл на AWS - IoT с использованием Mosquitto в Python и Как я могу опубликовать sh файл с помощью Mosquitto в python? .

Я бы предположил, что моя ошибка связана с qos в client.publish или как у меня использовал цикл, но я боюсь, что мои эксперименты с этими факторами мне пока не помогли (попытка qos = 0/1/2 и, например, client.loop_forever()). Мой образ 1,2 Мб, так что, насколько я понимаю, это не должно быть проблемой.

#!/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()

1 Ответ

1 голос
/ 30 января 2020

Ответ предоставил @ Aaron.

"1.2Mb слишком велик ..."

Предел полезной нагрузки события телеметрии 256 КБ и не может быть увеличено

...