Задать вопрос
@dodo101000101

Как поднять MQTT сервер в Google IoT Core?

Как организовать сбор данных с помощью Google IoT Core по протоколу MQTT? Как поднять сервер который был бы связан с Pub/Sub?

Вот мой python клиент:
import time
import paho.mqtt.client as mqtt
broker="mqtt.googleapis.com"

device_id = 'my-devic-1'
project_id = '****'
cloud_region = '***'
registry_id = '***'
private_key_file = 'rsa_private.pem'
client = mqtt.Client(
            client_id=('projects/{}/locations/{}/registries/{}/devices/{}'
                       .format(
                               project_id,
                               cloud_region,
                               registry_id,
                               device_id)))

print("connecting to broker ",broker)

client.username_pw_set(
            username='unused',
            password=create_jwt(
                    project_id, private_key_file, algorithm))
client.connect(broker, port=8883)#connect
client.loop_start() #start loop to process received messages
print("publishing ")
time.sleep(2)
client.publish("projects/****/topics/pub1",payload="test1", qos=1)
time.sleep(4)
client.disconnect() #disconnect
client.loop_stop() #stop loop


Про create_jwt
import argparse
import datetime
import os
import random
import ssl
import time

import jwt
import paho.mqtt.client as mqtt

def create_jwt(project_id, private_key_file, algorithm):
    """Creates a JWT (https://jwt.io) to establish an MQTT connection.
        Args:
         project_id: The cloud project ID this device belongs to
         private_key_file: A path to a file containing either an RSA256 or
                 ES256 private key.
         algorithm: The encryption algorithm to use. Either 'RS256' or 'ES256'
        Returns:
            An MQTT generated from the given project_id and private key, which
            expires in 20 minutes. After 20 minutes, your client will be
            disconnected, and a new JWT will have to be generated.
        Raises:
            ValueError: If the private_key_file does not contain a known key.
        """

    token = {
            # The time that the token was issued at
            'iat': datetime.datetime.utcnow(),
            # The time the token expires.
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
            # The audience field should always be set to the GCP project id.
            'aud': project_id
    }

    # Read the private key file.
    with open(private_key_file, 'r') as f:
        private_key = f.read()

    print('Creating JWT using {} from private key file {}'.format(
            algorithm, private_key_file))

    return jwt.encode(token, private_key, algorithm=algorithm)
print(create_jwt("project_id", "rsa_private.pem", "RS256"))
  • Вопрос задан
  • 1142 просмотра
Подписаться 1 Средний Комментировать
Пригласить эксперта
Ответы на вопрос 1
AndyKorg
@AndyKorg
Кнопконажиматель и припоерасплавлятель
В облаке уже есть сервер на отдельной тучке.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы