From 236598ddcd8f8caa523b32125906a1f0df67fae6 Mon Sep 17 00:00:00 2001 From: Francisco Molina Date: Wed, 4 Nov 2020 16:52:19 +0100 Subject: [PATCH] openvisualizer/rpl/topology.py: publish topology data --- openvisualizer/main.py | 2 +- openvisualizer/rpl/topology.py | 43 +++++++++++++++++++++++++++++++--- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/openvisualizer/main.py b/openvisualizer/main.py index 306486f0..c99af773 100644 --- a/openvisualizer/main.py +++ b/openvisualizer/main.py @@ -174,7 +174,7 @@ def __init__(self, host, port, simulator_mode, debug, vcdlog, self.openlbr = openlbr.OpenLbr(use_page_zero) self.rpl = rpl.RPL() self.jrc = jrc.JRC() - self.topology = topology.Topology() + self.topology = topology.Topology(mqtt_broker) self.mote_probes = [] # create opentun call last since indicates prefix diff --git a/openvisualizer/rpl/topology.py b/openvisualizer/rpl/topology.py index f0e5a173..59f4a78a 100644 --- a/openvisualizer/rpl/topology.py +++ b/openvisualizer/rpl/topology.py @@ -17,6 +17,10 @@ import threading import time +import struct +import json +import paho.mqtt.client as mqtt + from openvisualizer.eventbus.eventbusclient import EventBusClient log = logging.getLogger('Topology') @@ -26,11 +30,11 @@ class Topology(EventBusClient): - def __init__(self): + def __init__(self, mqtt_broker): # log - log.debug('create instance') + log.debug('create instance') # local variables self.data_lock = threading.Lock() self.parents = {} @@ -53,6 +57,39 @@ def __init__(self): ], ) + self.broker = mqtt_broker + self.mqtt_connected = False + + if self.broker: + + # connect to MQTT + self.mqtt_client = mqtt.Client() + self.mqtt_client.on_connect = self._on_mqtt_connect + + try: + self.mqtt_client.connect(self.broker) + except Exception as e: + log.error("failed to connect to {} with error msg: {}".format(self.broker, e)) + else: + # start mqtt client + self.mqtt_thread = threading.Thread(name='mqtt_loop_thread', target=self.mqtt_client.loop_forever) + self.mqtt_thread.start() + + + def publish_topology(self): + payload = {'token': 123} + payload['topology'] = str(self.parents) + + if self.mqtt_connected: + # publish the cmd message + self.mqtt_client.publish(topic='opentestbed/openv-server/topology', payload=json.dumps(payload), qos=2) + + + # ======================== private ========================================= + + def _on_mqtt_connect(self, client, userdata, flags, rc): + self.mqtt_connected = True + # ======================== public ========================================== def get_parents(self, sender, signal, data): @@ -84,7 +121,7 @@ def update_parents(self, sender, signal, data): # data[0] == source address, data[1] == list of parents self.parents.update({data[0]: data[1]}) self.parents_last_seen.update({data[0]: time.time()}) - + self.publish_topology() self._clear_node_timeout() def _clear_node_timeout(self):