Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import asyncio
from gmqtt import Client as MQTTClient
BROKER = '127.0.0.1'
PORT = 1883
CITY = 'city_name'
DISTRICT = 'district_name'
DEVICE_ID = 'device_id'
ALERTS_TOPIC = f'alerts/{CITY}/{DISTRICT}/{DEVICE_ID}'
LOCATION_TOPIC = f'location/{CITY}/{DISTRICT}/{DEVICE_ID}'
STATUS_TOPIC = f'status/{CITY}/{DISTRICT}/{DEVICE_ID}'
RESPONSE_TOPIC = f'response/{CITY}/{DISTRICT}/{DEVICE_ID}'
STOP = asyncio.Event()
def on_connect(client, flags, rc, properties):
print('Connected')
client.subscribe(ALERTS_TOPIC)
client.subscribe(LOCATION_TOPIC)
client.subscribe(STATUS_TOPIC)
client.subscribe(RESPONSE_TOPIC)
def on_message(client, topic, payload, qos, properties):
print(f'Received message from {topic}: {payload.decode()}')
def on_disconnect(client, packet, exc=None):
print('Disconnected')
def on_subscribe(client, mid, qos, properties):
print('Subscribed')
async def main():
client = MQTTClient(DEVICE_ID)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.on_subscribe = on_subscribe
await client.connect(BROKER, PORT)
await STOP.wait()
await client.disconnect()
if __name__ == '__main__':
asyncio.run(main())