Hi Sara
I am having difficulty connecting my esp32 to raspi mosquitto server. This is my first time using Raspi but I have manged to get Mosquitto MQTT running on it using PuTTy and Mosquitto seems to be running ok. I am using PlatformIO. The ESP32 is connecting ok to the wifi but I get this error when attempting the Mqtt connection:-
Attempting MQTT connection…[E][WiFiClient.cpp:258] connect(): socket error on fd 56, errno: 104, “Connection reset by peer”
Here is my code:-
//System to monitor temperature humidity and moisture
//Send results to NodeRed dashboard via MQTT
#include <Arduino.h>
#include <DHT.h>
#include <WiFi.h>
#include <OneWire.h>
#include <Wire.h>
#include <DallasTemperature.h>
const char* ssid = “ljhglhlhlhb”; // edited to hide SSID
const char* password = “lhjbljhvbljhvljh”; //edited to hide password
//MQTT Setup Start
#include <PubSubClient.h>
#define mqtt_server “192.168.1.33” // ip address of Pi
WiFiClient espClient;
PubSubClient client(espClient);
#define mqttTemp1 “Kiln/tempAmbient”
#define mqttHum1 “Kiln/HumidityIn”
#define mqttTemp2 “Kiln/tempunderkiln”
#define mqttHum2 “Kiln/HuminidtyExhaust”
#define mqttTemp3 “Kiln/tempGrain”
#define mqttTempOff “Kiln/AirOffTemp”
#define mqttGrainMCTop “Kiln/grainMCTop”
#define mqttGrainMCBtm “Kiln/grainMCBtm”
#define MQTT_SOCKET_TIMEOUT 1
//MQTT Setup End
const int oneWireBus = 18;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
uint8_t sensor1[8] = {0x28, 0x56, 0xD6, 0x95, 0xF0, 0x01, 0x3C, 0x74};//dallas DS temp sensor
uint8_t sensor2[8] = {0x28, 0x40, 0xC2, 0x95, 0xF0, 0x01, 0x3C, 0xFE};//dallas DS temp sensor
uint8_t sensor3[8] = {0x28, 0x69, 0x1D, 0x95, 0xF0, 0x01, 0x3C, 0xEF};//dallas DS temp sensor
#define MoistureProbeBtm 35 //GPIO 35
#define MoistureProbeTop 36 //GP1O 36
float AmbTemp1, Intakehum1, underKilntemp2, exhaustHum2, grainTemp, grainMCBtm, grainMCtop;
void setup() {
Serial.begin(115200);
Serial.println();
// begin Wifi connect
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(2000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
//end Wifi connect
client.setServer(mqtt_server, 1883);
//Start Temp Sensors DS18B20
sensors.begin();
if(sensors.isParasitePowerMode()) Serial.println(“DS18B20 in Parasitic power mode – ON”);
else Serial.println(“DS18B20 in Parasitic power mode – OFF”);
}
void getValues()
{
AmbTemp1 = sensors.getTempC(sensor1); // Gets the values of the temperature
underKilntemp2 = sensors.getTempC(sensor2);
grainTemp = sensors.getTempC(sensor3);
Intakehum1 = 56;//set fixed test value until we humidity sensor
exhaustHum2 = 87; // set fixed test value until we humidity sensor
grainMCtop = analogRead(MoistureProbeTop);
grainMCBtm = analogRead(MoistureProbeBtm);
Serial.print(“AmbientKilnTemp = “);
Serial.print(AmbTemp1);
Serial.println(” *C”);
Serial.print(“underKilntemp2 = “);
Serial.print(underKilntemp2);
Serial.println(” *C”);
Serial.print(“Grain Temp = “);
Serial.print(grainTemp);
Serial.println(” *C”);
Serial.print(“Grain Moisture Content = “);
Serial.print(grainMCtop);
Serial.println(” %”);
Serial.print(grainMCBtm);
Serial.println(” %”);
/*Serial.print(“BME 2 Pressure = “);
Serial.print(bme2.readPressure() / 100.0F);
Serial.println(” hPa”);
Serial.print(“BME 2 Humidity = “);
Serial.print(hum2);
Serial.println(” %”);
*/
}
void reconnect() {
// Loop until we’re reconnected
String clientId = “ESPClient-“;
clientId += String(random(0xffff), HEX);
int counter = 0;
while (!client.connected()) {
if (counter==5){
ESP.restart();
}
counter+=1;
Serial.print(“Attempting MQTT connection…”);
// Attempt to connect
if (client.connect(“KilnEspController”)) {
Serial.println(“connected”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(” try again in 5 seconds”);
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()){
reconnect();
}
getValues();
client.publish(mqttTemp1, String(AmbTemp1).c_str(),true);
client.publish(mqttHum1, String(Intakehum1).c_str(),true);
client.publish(mqttTemp2, String(underKilntemp2).c_str(),true);
client.publish(mqttHum2, String(exhaustHum2).c_str(),true);
client.publish(mqttTemp3, String(grainTemp).c_str(),true);
client.publish(mqttGrainMCTop, String(grainMCtop).c_str(),true);
client.publish(mqttGrainMCBtm, String(grainMCBtm).c_str(),true);
delay(5000);
}
The platformio.ini file is as follows:-
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
arduino-libraries/NTPClient@^3.1.0
Adafruit Unified Sensor@^1.1.4
bblanchon/ArduinoJson@^6.17.3
https://github.com/milesburton/Arduino-Temperature-Control-Library.git
https://github.com/adafruit/DHT-sensor-library.git
knolleary/PubSubClient@^2.8
have you any suggestions of where I am going wrrong?
Many thanks
Paul
Hi.
Have you gotten MQTT working successfully before?
If not, I recommend that you try starting with a minimal code setup, so it will be easier to understand what might be wrong.
Remove all code related to sensors and try to send a simple random value on a single topic. Then, check what happens.
Regards,
Sara
Hi Sara
I have not yet been able to get MQTT working on the ESP32 so far, this is my first MQTT project.
I created a new simple example based on the example provided by Mick O’Leay and I get the same error message.
Attempting MQTT connection…[E][WiFiClient.cpp:258] connect(): socket error on fd 58, errno: 104, “Connection reset by peer”
I have read that the later version of Mosquitto has upgraded its security permissions, but I don’t understand the detail, and so I’m wondering if this is the issue? I suspect I need to modify some Mosquitto setting on the Pi, but I have no idea where to start.
On my Pi, when I run mosquitto, I see this line which might be the issue?
1639217535: Starting in local only mode. Connections will only be possible from clients running on this machine.
Here is the simplified sketch (in PlatformIO):-
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = “**********”;
const char* password = “**********”;
const char* mqtt_server = “192.168.1.33”;
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
randomSeed(micros());
Serial.println(“”);
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
// Create a random client ID
String clientId = “ESPClient-“;
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println(“connected”);
// Once connected, publish an announcement…
client.publish(“outTopic”, “hello world”);
// … and resubscribe
client.subscribe(“inTopic”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(” try again in 5 seconds”);
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now – lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, “hello world #%ld”, value);
Serial.print(“Publish message: “);
Serial.println(msg);
client.publish(“outTopic”, msg);
}
}
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps = knolleary/PubSubClient@^2.8
monitor_speed = 115200
Hi again.
Here are the instructions to make it work.
1) Open an SSH connection with your Raspberry Pi and run the following command:
sudo nano /etc/mosquitto/mosquitto.conf
2) It will open the mosquitto.conf file. Move to the end of the file using the arrow keys and paste the following two lines:
listener 1883
allow_anonymous true
3) Then, press CTRL-X to exit and save the file. Press Y and Enter.
4) Reboot your Raspberry Pi with the following command:
sudo reboot
5) Close putty and open again after a few seconds to run the mosquito broker again.
This time, the ESP should connect to the broker.
I’ll update our tutorials related to the Mosquitto broker soon.
Let me know if this solves the issue.
Regards,
Sara
Thank you Sara – I will try that later this evening and hopefully it will work. I’ll update you when I know. Many thanks, Paul