-
Notifications
You must be signed in to change notification settings - Fork 0
/
group_1_Subscriber.py
50 lines (38 loc) · 1.27 KB
/
group_1_Subscriber.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# GROUP 1
# Benjamin
# Paige
# Harpreet
# Gwen
import threading
import paho.mqtt.client as mqtt
MQTT_BROKER = 'localhost'
PORT = 1883
class Subscriber:
def __init__(self, topic):
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1)
self.topic = topic
self.is_connected = False
def connect(self, topic):
# Update Params
self.topic = topic
# Connect to Broker
self.client.connect(MQTT_BROKER, PORT)
self.client.subscribe(self.topic)
self.is_connected = True
print(f'Subscriber connected to : {self.topic}\n...')
# Start background thread for network loop
self.thread = threading.Thread(target=self.client.loop_forever)
self.thread.daemon = True # Set as daemon for proper program termination
self.thread.start()
def disconnect(self):
if self.is_connected:
self.client.unsubscribe(self.topic)
self.client.disconnect()
self.is_connected = False
print(f'Subscriber disconnected from topic: {self.topic}\n...')
# Wait for the thread to finish
self.thread.join()
if __name__ == '__main__':
topic = 'DEBUG'
sub = Subscriber(topic)
sub.connect()