Answer the question
In order to leave comments, you need to log in
How to set up an MQTT server in Google IoT Core?
How to organize data collection using Google IoT Core using the MQTT protocol? How to raise a server that would be connected to Pub/Sub?
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
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"))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question