python_mqtt/pub_mqtt.py
2024-05-16 15:42:43 +08:00

82 lines
2.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import random
import time
from PyJWT.jwt import api_jwt as jwt
from datetime import datetime, timedelta
from paho_mqtt.src.paho.mqtt import client as mqtt_client
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.backends import default_backend
broker = '192.168.219.133'
port = 1883
topic = "/python/mqtt"
client_id = 'python_mqtt_001'
def generate_rsa_jwt(username, private_key_pem, private_key_password=None):
# 加载私钥
private_key = load_pem_private_key(
private_key_pem.encode('utf-8'),
password=private_key_password, # 如果私钥是加密的,提供密码,否则留空
backend=default_backend()
)
payload = {
"sub": username,
"iat": int(time.time()), # 当前时间戳表示JWT的签发时间
}
# 使用RSA算法生成JWT
token = jwt.encode(payload, private_key, algorithm='RS256')
return token
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code:", rc)
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1, client_id)
# 加载公钥
with open("public_key.pem", "r") as pub_file:
public_key_pem = pub_file.read()
jwt_token = generate_rsa_jwt('admin', public_key_pem)
print("JWT Token:", jwt_token)
client.username_pw_set('admin', jwt_token)
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
msg_count = 0
while True:
time.sleep(1)
msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
exit()
msg_count += 1
client = connect_mqtt()
client.loop_start()
publish(client)