Ivanhosa13
Posts: 6
Joined: Mon Feb 03, 2020 6:11 pm

ESP32 and MQTT

Thu Feb 13, 2020 11:22 pm

I am using a raspberry pi 3 and a ESP32. I am trying to make the ESP 32 (the client) communicate wirelessly with the pi being used as a broker. i need some help with a code that will make ESP32 connect automatically with the MQTT.
this is the code i am currently using.

Code: Select all

from time import sleep
from umqtt.simple import MQTTClient
from machine import Pin
from dht import DHT22

SERVER = '192.168.1.22'  # MQTT Server Address (Change to the IP address of your Pi)
CLIENT_ID = 'ESP32_DHT22_Sensor'
TOPIC = b'temp_humidity'

client = MQTTClient(CLIENT_ID, SERVER)
client.connect()   # Connect to MQTT broker

sensor = DHT22(Pin(15, Pin.IN, Pin.PULL_UP))   # DHT-22 on GPIO 15 (input with internal pull-up resistor)

while True:
    try:
        sensor.measure()   # Poll sensor
        t = sensor.temperature()
        h = sensor.humidity()
        if isinstance(t, float) and isinstance(h, float):  # Confirm sensor results are numeric
            msg = (b'{0:3.1f},{1:3.1f}'.format(t, h))
            client.publish(TOPIC, msg)  # Publish sensor data to MQTT topic
            print(msg)
        else:
            print('Invalid sensor readings.')
    except OSError:
        print('Failed to read sensor.')
    sleep(4)
    
credits to https://www.rototron.info/raspberry-pi- ... -tutorial/

DirkS
Posts: 10130
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: ESP32 and MQTT

Fri Feb 14, 2020 3:57 am

You're asking about (Micropython?) code on an ESP32, so it has nothing to do with Pi...

Anyway, what is the problem with your code? Error messages?

Ivanhosa13
Posts: 6
Joined: Mon Feb 03, 2020 6:11 pm

Re: ESP32 and MQTT

Fri Feb 14, 2020 2:42 pm

DirkS wrote:
Fri Feb 14, 2020 3:57 am
You're asking about (Micropython?) code on an ESP32, so it has nothing to do with Pi...

Anyway, what is the problem with your code? Error messages?
I'm not getting errors, but when ever I restart the ESP32. It doesn’t connect back the Mqtt , I have to go back to REPL and import the code that we submit to work so all I want it to do is to connect to the Mqtt by it self.

User avatar
B.Goode
Posts: 9318
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: ESP32 and MQTT

Fri Feb 14, 2020 5:24 pm

Ivanhosa13 wrote:
Fri Feb 14, 2020 2:42 pm
DirkS wrote:
Fri Feb 14, 2020 3:57 am
You're asking about (Micropython?) code on an ESP32, so it has nothing to do with Pi...

Anyway, what is the problem with your code? Error messages?
I'm not getting errors, but when ever I restart the ESP32. It doesn’t connect back the Mqtt , I have to go back to REPL and import the code that we submit to work so all I want it to do is to connect to the Mqtt by it self.


While still noting that this isn't an RPi query...

Does your esp32 board have an association with a wireless access point to allow network connectivity with the mqtt broker at the time your esp32 sensor client runs?

Ivanhosa13
Posts: 6
Joined: Mon Feb 03, 2020 6:11 pm

Re: ESP32 and MQTT

Fri Feb 14, 2020 7:14 pm

B.Goode wrote:
Fri Feb 14, 2020 5:24 pm
Ivanhosa13 wrote:
Fri Feb 14, 2020 2:42 pm
DirkS wrote:
Fri Feb 14, 2020 3:57 am
You're asking about (Micropython?) code on an ESP32, so it has nothing to do with Pi...

Anyway, what is the problem with your code? Error messages?
I'm not getting errors, but when ever I restart the ESP32. It doesn’t connect back the Mqtt , I have to go back to REPL and import the code that we submit to work so all I want it to do is to connect to the Mqtt by it self.


While still noting that this isn't an RPi query...

Does your esp32 board have an association with a wireless access point to allow network connectivity with the mqtt broker at the time your esp32 sensor client runs?
Yes, I am trying to make the pi the wireless access point.
This is the code I'm using on the pi

Code: Select all

import paho.mqtt.client as mqtt
import Adafruit_SSD1306
from PIL import Image, ImageDraw, ImageFont

disp = Adafruit_SSD1306.SSD1306_128_32(rst=0)
disp.begin()
FONT_PATH = '/usr/share/fonts/truetype/piboto/PibotoCondensed-Regular.ttf'
FONT = ImageFont.truetype(FONT_PATH, 22)

def display_data(t, h):
    image = Image.new('1', (disp.width, disp.height))
    draw = ImageDraw.Draw(image)
    # Draw temperature / Humidity values.
    draw.text((0, 8), '{0}°C'.format(t),  font=FONT, fill=255)
    draw.text((71, 8), '{0}%'.format(h), font=FONT, fill=255)
    # Draw bar charts.
    draw.rectangle((0, 0, 50, 8), outline=255, fill=0)
    draw.rectangle((71, 0, 121, 8), outline=255, fill=0)
    draw.rectangle((0, 0, t / 100.0 * 50, 8), outline=255, fill=255)
    draw.rectangle((71, 0, 71 + (h / 100.0 * 50), 8), outline=255, fill=255)
    # Send to OLED display.
    disp.clear()
    disp.image(image)
    disp.display()

	# Callback fires when conected to MQTT broker.
def on_connect(client, userdata, flags, rc):
    print('Connected with result code {0}'.format(rc))
    # Subscribe (or renew if reconnect).
    client.subscribe('temp_humidity')


# Callback fires when a published message is received.
def on_message(client, userdata, msg):
	# Decode temperature and humidity values from binary message paylod.
    t,h = [float(x) for x in msg.payload.decode("utf-8").split(',')]
    print('{0}°C {1}%'.format(t, h))
    display_data(t, h)  # Display data on OLED display.


client = mqtt.Client()
client.on_connect = on_connect  # Specify on_connect callback
client.on_message = on_message  # Specify on_message callback
client.connect('localhost', 1883, 60)  # Connect to MQTT broker (also running on Pi).

# Processes MQTT network traffic, callbacks and reconnections. (Blocking)
client.loop_forever()

User avatar
B.Goode
Posts: 9318
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: ESP32 and MQTT

Fri Feb 14, 2020 7:23 pm

I thought the outstanding substantive question was -
when ever I restart the ESP32. It doesn’t connect back the Mqtt ,

The script that subscribes to the mqtt broker is not relevant if the publisher client on the esp32 does not have a working wireless connection.

Ivanhosa13
Posts: 6
Joined: Mon Feb 03, 2020 6:11 pm

Re: ESP32 and MQTT

Fri Feb 14, 2020 9:00 pm

I do have a code that connects the ESP32 to the WiFi automatically when I reset the ESP32 and it is the same WiFi that the pi is connected too. The code is in a different script and called main.py

Code: Select all

 import network
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect("<your ssid>", "<password>")

User avatar
B.Goode
Posts: 9318
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: ESP32 and MQTT

Fri Feb 14, 2020 9:08 pm

Ivanhosa13 wrote:
Fri Feb 14, 2020 9:00 pm
I do have a code that connects the ESP32 to the WiFi automatically when I reset the ESP32 and it is the same WiFi that the pi is connected too. The code is in a different script and called main.py

Code: Select all

 import network
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect("<your ssid>", "<password>")


1. Does this main.py script run to completion to put the esp32 online before the sensor publisher client script starts running.


2. " it is the same WiFi that the pi is connected too" - I thought you were configuring the RPi to act as an Access Point/Hotspot?

Ivanhosa13
Posts: 6
Joined: Mon Feb 03, 2020 6:11 pm

Re: ESP32 and MQTT

Fri Feb 14, 2020 9:23 pm

Yes sir, the main.py script run to completion to put the esp32 online before the sensor publisher client script starts running.

Another thing, I am using Rshell to access the ESP32 using the raspberry pi. And from there I got REPL and from there I hit the rest bottom and it shows that the ESP32 is connected to the WiFi but I doesn’t connect to the mqtt, so I have to import the dht_publish which is this code

Code: Select all

 from time import sleep
from umqtt.simple import MQTTClient
from machine import Pin
from dht import DHT22

SERVER = '192.168.1.22'  # MQTT Server Address (Change to the IP address of your Pi)
CLIENT_ID = 'ESP32_DHT22_Sensor'
TOPIC = b'temp_humidity'

client = MQTTClient(CLIENT_ID, SERVER)
client.connect()   # Connect to MQTT broker

sensor = DHT22(Pin(15, Pin.IN, Pin.PULL_UP))   # DHT-22 on GPIO 15 (input with internal pull-up resistor)

while True:
    try:
        sensor.measure()   # Poll sensor
        t = sensor.temperature()
        h = sensor.humidity()
        if isinstance(t, float) and isinstance(h, float):  # Confirm sensor results are numeric
            msg = (b'{0:3.1f},{1:3.1f}'.format(t, h))
            client.publish(TOPIC, msg)  # Publish sensor data to MQTT topic
            print(msg)
        else:
            print('Invalid sensor readings.')
    except OSError:
        print('Failed to read sensor.')
    sleep(4)
    
To make it work.

Also , I am new to all these stuff so excuse me if I am making mistakes explaining the stuff

User avatar
B.Goode
Posts: 9318
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: ESP32 and MQTT

Fri Feb 14, 2020 9:31 pm

I will not be providing any further esp32 support in this Raspberry Pi forum.

DirkS
Posts: 10130
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: ESP32 and MQTT

Fri Feb 14, 2020 10:57 pm

B.Goode wrote:
Fri Feb 14, 2020 9:31 pm
I will not be providing any further esp32 support in this Raspberry Pi forum.
Indeed. This is way off topic for this forum

Return to “General discussion”