MQTT Broker IoT Debug and Enhance

Job ID: 38932826

Budget: €8 – €30 EUR

connect to mqtt broker, get some info from the general topic (iotlesson_eventbus/grafeio113/out/#) take all the info. then from the iotlesson_eventbus/grafeio113/out/ZWave_8_Metered_Wall_Plug_Switch_on_desk_Sensor_power/state take the value and show it in a plot as watts on y axis and secs in y axis. show the status (on/off) based from the topics iotlesson_eventbus/grafeio113/out/ZWave_8_Metered_Wall_Plug_Switch_on_desk_LED_ring_colour_when_device_is_on/state 1
iotlesson_eventbus/grafeio113/out/ZWave_8_Metered_Wall_Plug_Switch_on_desk_LED_ring_colour_when_device_is_off/state 0 also create 2 buttons on/off to send the respective values.
i have started the code but it does not work.
```
import paho.mqtt.client as mqtt
import ssl
import os
import sys
import matplotlib.pyplot as plt
import random
import json
from datetime import datetime, timezone
from matplotlib.widgets import Button
from tzlocal import get_localzone
# from dateutil.tz import tzlocal
from threading import Timer




class IoTExample:
def __init__(self):
# self._establish_mqtt_connection()
self.client = mqtt.Client()
self.client.on_connect = self._on_connect
self.client._on_log = self._on_log
self.client._on_message = self._on_message
self.client.tls_set_context(ssl.SSLContext(ssl.PROTOCOL_TLSv1_2))
self.client._client_id = f"iotlession{random.randint(0, 99999)}"
self.client.username_pw_set('iotlesson', 'iotlesson123456!')
self._prepare_graph_window()
print("Class is created")



#This function starts the endless loop
def start(self):
self.client.connect('kube.cs.uowm.gr', 8883)
self.client.loop_start()
print("Starting")
plt.show()



#The following function is called after the connection
def _on_connect(self, client, userdata, flags, rc):
print("Client connected")
client.subscribe('iotlesson_eventbus/grafeio113/out/#')



#The following function is callback for when a new message is received
def _on_message(self, client, userdata, msg):
if msg.topic == 'iotlesson_eventbus/grafeio113/out/ZWave_8_Metered_Wall_Plug_Switch_on_desk_Sensor_power/state':
self._add_value_to_plot(float(msg.payload))
print(msg.topic+' '+str(msg.payload))


#The following function is called when a new log event is created
def _on_log(self, client, userdata, level, buf):
print('log: ', buf)


#Initialize the graph
def _prepare_graph_window(self):
# Variables for plot mapping
plt.rcParams['toolbar'] = 'None'
self.ax = plt.subplot(111)
self.dataX = []
self.dataY = []
self.first_ts = datetime.now()
self.lineplot, = self.ax.plot(
self.dataX, self.dataY, linestyle='--', marker='o', color='b')
self.ax.figure.canvas.mpl_connect('close_event', self.disconnect)
self.finishing = False
self._my_timer()

#This function refreshes the values for new feeds or time update of X axis
def _refresh_plot(self):
if len(self.dataX) > 0:
self.ax.set_xlim(min(self.first_ts, min(self.dataX)), max(max(self.dataX), datetime.now()))
self.ax.set_ylim(min(self.dataY) * 0.8, max(self.dataY) * 1.2)
self.ax.relim()
else:
self.ax.set_xlim(self.first_ts, datetime.now())
self.ax.relim()
print("Opens the plot window to display the graph")
plt.draw()


#This function moves right every 1 sec
def _my_timer(self):
self._refresh_plot()
if not self.finishing:
Timer(1.0, self._my_timer).start()


#This function disconnects from the broker
def disconnect(self, args=None):
self.finishing = True
self.client.disconnect() # disconnects from the MQTT broker


#This function adds values to the variables to create the plot
def _add_value_to_plot(self, value):
print("Starting the plot", value)
value_json = json.loads(value)
# self.dataX.append(datetime.now()) OLD Value, try this is the next line won't work.
# self.dataX.append(datetime.fromisoformat(value_json["timestamp"]))
self.dataX.append(datetime.now())
# self.dataY.append(float(value_json["watt"]))
self.dataY.append(value)
self.lineplot.set_data(self.dataX, self.dataY)
self._refresh_plot()



try:
iot_example = IoTExample()
iot_example.start()
plt.show()
except KeyboardInterrupt:
print("Interrupted")
plt.close(all)
iot_example.disconnect("Keyboard_Interrupt")
try:
sys.exit(0)
except SystemExit:
os._exit(0)




```
Related categories: Python MQTT