1+ from paho .mqtt import client as mqtt_client
2+ from random import randint
3+ from decouple import config
4+
5+ # Reading broker credentials
6+ BROKER = config ("BROKER" )
7+ PORT = int (config ("PORT" ))
8+ TOPIC = config ("TOPIC" )
9+ USER = config ("USER" )
10+ PASS = config ("PASS" )
11+
12+ # Create a randdom id for login in MQTT
13+ CLIENT_ID = f'id-mqtt-{ randint (0 ,100 )} '
14+
15+ # Create a client to interact with MQTT
16+ def connectMqtt () -> mqtt_client :
17+ def on_connect (client , userdata , flags , rc ):
18+ if rc == 0 :
19+ print ('[MQTT] Connected to server.' )
20+ else :
21+ print ('[MQTT] Failure to connect.' )
22+
23+ client = mqtt_client .Client (CLIENT_ID )
24+ client .username_pw_set (USER , PASS )
25+ client .on_connect = on_connect
26+ client .connect (BROKER ,PORT )
27+
28+ return client
29+
30+ # Receiving messages sendings with MQTT
31+ def subscribe (client : mqtt_client ):
32+ def on_message (client , userdata , msg ):
33+ print (
34+ f'[MQTT] Received message from { msg .topic } topic:' ,
35+ f'\n { msg .payload .decode ()} '
36+ )
37+
38+ client .subscribe (TOPIC )
39+ client .on_message = on_message
40+
41+ # Publishing messages with MQTT
42+ def publish (client , msg = 'Hello MQTT' ):
43+ result = client .publish (TOPIC ,msg )
44+
45+ if __name__ == '__main__' :
46+ client = connectMqtt ()
47+ subscribe (client )
48+ publish (client )
49+ publish (client , msg = 'Custom Messages Working!' )
50+ client .loop_forever ()
0 commit comments