1

I'm using paho-MQTT and I'm able to receive messages. When I receive a message, I want to display the data in a template, but am unable to do so. Below is the code I have.

import paho.mqtt.client as mqtt
import json

def on_connect(client, userdata, flags, rc):
     print("Connected with result code "+str(rc))


client.subscribe("mhub/hr")


def on_message(client, userdata, msg):
   x = (msg.payload)
   print(x)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt.eclipseprojects.io", 1883, 60)

I have been following the tutorial.

How can I show new data from MQTT in the html template I have created?

Rod
  • 57
  • 5
  • 1
    You've just posted the classic python paho example, what have you already tried with Django? Also since mqtt is asynchronous and http is not, what do you actually expect to show in the template? – hardillb Apr 14 '22 at 06:37

1 Answers1

1

It's the wrong way, but if it helps someone...

from django.shortcuts import render
import paho.mqtt.client as mqtt

import json

valor_mqtt = 0

def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))

client.subscribe("mhub/hr")


def on_message(client, userdata, msg):
  global valor_mqtt
  valor_mqtt = (msg.payload)
  print(valor_mqtt)

def print_on_m(request):
  global valor_mqtt
  message = str(valor_mqtt)
  return render(request, 'home/index.html',{'context':message})



client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message


client.connect("mqtt.eclipseprojects.io", 1883, 60)

I'm saying it's the wrong way because it doesn't update the value in the template(.html) in real time when you get a message

Rod
  • 57
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 21 '22 at 14:06