• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

Basic MQTT question

Q&A Forum › Category: ESP32 › Basic MQTT question
0 Vote Up Vote Down
Jack Douglas asked 2 years ago

I am following the RNT MQTT chapter, but instead of LoRA I’m using a RPi P2P with mosquitto broker/subscriber and esp32 publisher.   The RPi is showing the data as expected, but I want to publish an acknowledgment back to the esp32 from the callback.  It seems simple enough but I am getting stuck. The esp32 code is too complex for me to reproduce as a publisher example in the RPi.  Looking for some help to get me going.

This is the RPi code used without u/n and p/w credentials:

import paho.mqtt.client as mqtt
import time
import datetime

MQTT_ADDRESS = ”
MQTT_USER = ”
MQTT_PASSWORD = ”
MQTT_TOPIC = ‘home/+’

def on_connect(client, userdata, flags, rc):
“”” The callback for when the client receives a CONNACK response from the server.”””
print(‘Connected with result code ‘ + str(rc))
if rc==0:
print(“connected OK”)
client.subscribe(MQTT_TOPIC)
else:
print(“bad connetion returned code=”, rc)

def on_message(client, userdata, msg):
“””The callback for when a PUBLISH message is received from the server.”””
s = str(msg.payload)
s = s.replace(“‘”,”)
s =s.replace(‘b’,”)
print(msg.topic + ‘ ‘ + s)
file=open(“sensor_data.txt”,’a’)
if s != 999:
file.write(s)
file.write(“\n”)
else:
# close file

def main():
mqtt_client = mqtt.Client()
mqtt_client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.connect(MQTT_ADDRESS, 1883)
mqtt_client.loop_forever()

if __name__ == ‘__main__’:
print(‘MQTT to InfluxDB bridge’)
main()

Question Tags: MQTT
5 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 2 years ago

Hi.
I’m not very familiar with Python code to control the RPi.
But I found this tutorial that shows how to subscribe and publish with the Pi: https://www.digikey.com/en/maker/blogs/2019/how-to-use-mqtt-with-the-raspberry-pi
You need to take a look at the sections that refer to publish and then insert it on your callback.
Regards,
Sara

0 Vote Up Vote Down
Jack Douglas answered 2 years ago

Thanks Sara.   Then to add a subscription to the acknowledgment in the esp32, how would that be written?  I am not totally familiar working with c++ and pointers.  Presently the code shows

(sorry I cannot figure out how to copy/paste the code here with the appropriate indents) –

// MQTT
const char* mqtt_server = “x.x.x.x”; // IP of the MQTT broker
const char* battlevel_topic = “home/battlevel”;
const char* moisture_topic = “home/moisture”;
const char* temperature_topic = “home/temperature”;
const char* ID_topic = “home/ID”;
const char* mqtt_username = “xx”; // MQTT username
const char* mqtt_password = “xx”; // MQTT password
const char* clientID = “esp32_client1”; // MQTT client ID

void loop() {
while (millis() < wake){
Serial.print(“Time(s) = “);
Serial.println(millis()/1000);

displayTime(); // display the real-time clock data on the Serial Monitor,

connect_MQTT();
Serial.setTimeout(5000);
getReadings();

Serial.print(“soilMoisture: “);
Serial.println(soilMoisture);
Serial.print(“Moisture: “);
Serial.print(h);
Serial.println(” %”);
Serial.print(“Temperature: “);
Serial.print(t);
Serial.println(” *F”);

// MQTT can only transmit strings
String hs=”Hum: “+String((float)h)+” % “;
String ts=”Temp: “+String((float)t)+” F “;

// PUBLISH to the MQTT Broker (topic = Temperature, defined at the beginning)
if (client.publish(temperature_topic, String((float)t).c_str())) {
Serial.println(“Temperature sent!”);
}

// Again, client.publish will return a boolean value depending on whether it succeded or not.
// If the message failed to send, we will try again, as the connection may have broken.
else {
Serial.println(“Temperature failed to send. Reconnecting to MQTT Broker and trying again”);
client.connect(clientID, mqtt_username, mqtt_password);
delay(10); // This delay ensures that client.publish doesn’t clash with the client.connect call
client.publish(temperature_topic, String(t).c_str());
}

0 Vote Up Vote Down
Sara Santos Staff answered 2 years ago

Hi.
To receive the message sent by the Raspberry Pi, the ESP32 needs to subscribe to the same topic that the Rpi is publishing in.
What specific project are you following?
Regards,
Sara

0 Vote Up Vote Down
Jack Douglas answered 2 years ago

I was trying to combine Project 4 modified without LoRa and the chapter on MQTT so I can transmit data from the weather station directly to another device.  But I forgot the MQTT code above I borrowed from somewhere else, so apologies for that.

0 Vote Up Vote Down
Sara Santos Staff answered 2 years ago

Take a look at the MQTT section again and check the parts of the code that are responsible for subscribing and the parts of the code that are responsible for publishing.
Isolate those sections and try to apply them to your project.
Without further information, it is very difficult to understand what you’re trying to achieve and what issues you’re facing.

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.