Skip to content

Instantly share code, notes, and snippets.

@id
Created February 19, 2024 16:48
Show Gist options
  • Save id/f9495a5d1363772d7a9251b0610c1433 to your computer and use it in GitHub Desktop.
Save id/f9495a5d1363772d7a9251b0610c1433 to your computer and use it in GitHub Desktop.
paho.mqtt python publisher
#!/usr/bin/env python3
import asyncio
import random
import string
import json
import paho.mqtt.client as mqtt
broker = 'localhost'
port = 1883
alhabet = string.ascii_lowercase+string.digits
async def connect_mqtt(client_id):
def on_connect(client, userdata, flags, rc, properties):
if rc != 0:
print(f"Failed to connect, result code {rc}\n")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=client_id, protocol=mqtt.MQTTv5)
client.on_connect = on_connect
client.connect(broker, port)
return client
async def publish(client, id):
topic = f'/{''.join(random.sample(alhabet, 10))}/otaa'
msg = json.dumps({'otaUrl': 'mqtt', 'otaBinary': 'latest.bin', 'id': id})
rc = client.publish(topic, msg)
print(f"published to {topic} with message {msg}, rc={rc[0]}")
async def main():
tasks = []
for i in range(1, 51):
client_id = f'python-mqtt-{i}'
client = await connect_mqtt(client_id)
tasks.append(publish(client, i))
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment