Permalink
Cannot retrieve contributors at this time
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?
INDIVIDUAL_MQTT/mqtt_subscriber.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
46 lines (35 sloc)
1.21 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |