|
import json |
|
|
|
from mqtt_client import MqttClient |
|
|
|
|
|
class MqttSubscriber(object): |
|
|
|
def __init__(self, topic, deserializer=json.loads): |
|
self.topic = topic |
|
self.deserializer = deserializer |
|
self.mqtt = MqttClient() |
|
self.mqtt.client.on_connect = self.on_connect |
|
self.mqtt.client.on_message = self.message_arrived |
|
|
|
def on_connect(self, client, userdata, flags, rc): |
|
print('connected to client with return code: {rc}'.format(rc=rc)) |
|
client.subscribe(self.topic) |
|
|
|
def message_arrived(self, client, userdata, msg): |
|
# every time a message is published, this method will automatically be called |
|
print('received message: {msg} from topic: {topic}'.format(msg=msg.payload, topic=msg.topic)) |
|
# this is how you decode the json. |
|
# the deserializer here points to json.dumps |
|
deserailized_data = self.deserializer(msg.payload) |
|
# this is how you access the lat and long |
|
# instead of the print put your lcd code here |
|
print('received latiude: {}'.format(deserailized_data['lat'])) |
|
print('received longitude: {}'.format(deserailized_data['long'])) |
|
|
|
def listen_for_messages(self): |
|
print('listening for messages from topic: {topic}'.format(topic=self.topic)) |
|
self.mqtt.connect() |
|
# this is the event loop I was talking about.. |
|
# think of this as a loop that runs forever. |
|
# whener a message is received it calls the on_message method |
|
# which is pointing to message_arrived in our case. |
|
self.mqtt.loop_forever() |
|
|
|
|
|
def start_subscriber(): |
|
subscriber = MqttSubscriber(topic='voith/test') |
|
subscriber.listen_for_messages() |
|
|
|
if __name__ == '__main__': |
|
start_subscriber() |