I am writing code on esp32 to be a MQTT publisher and when I run the program on esp32 I get a message on terminal "success send a data" but when I see on my subscriber program on python I didn't get any message. I think the problem was from token but when you see they have a same token.
Code on esp32 as a publisher :
import network
import json
import time
from umqtt.simple import MQTTClient
net = network.WLAN(network.STA_IF)
net.active(True)
while True:
try:
net.connect('Office_CWG', 'Unais2020')
except OSError as e:
print(e)
time.sleep(1)
if net.isconnected():
print('Connected')
break
broker = 'broker.hivemq.com'
client = MQTTClient('vito', broker)
client.connect()
def send(topic, pesan):
client.publish(topic, data)
print ('success sent a data')
sensor = {
'topic': 'active_1',
'current': '25',
'volt': '220',
'frekuensi': '50',
'activePower': '100',
'energy': '90',
'ambienceTemperature': '36',
'jointTemperature': '36'
}
data = json.dumps(sensor)
topic = 'vito'
send(data, topic)
Code on vscode with python as a subscriber :
import paho.mqtt.client as mqtt
import json
def connect(client, userdata, flags, rc): # rc = return code if 1 = error
if rc == 0:
rc = "success"
else:
rc = "error"
print("Connected to mqtt "+str(rc))
client.subscribe("vito")
def message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# pesan = json.loads(str(msg.payload.decode("utf-8")))
# print(pesan['data'])
# # print(pesan['message']['alertJoint'])
client = mqtt.Client()
client.on_connect = connect
client.on_message = message
client.connect("broker.hivemq.com")
client.loop_forever()
I expected the message would be sent but actual result didn't get anything. d