Running on OpenHab 2.x via Linux Mint
Hey Everyone!
So, I’ve run into an issue again, and I think it’s due to lack of experience or full understanding, but I really need some extra eyes and some advice to help determine A. if I’m diagnosing the issue properly, and B. how to solve the issue. Game Development’s what I’m used to, so working with Arduino and going through the debugging process has been entirely different from that of a video game. I’m struggling to determine what the issues are when the console says everything is fine & my code compiles.
Goal:
Using a NodeMCU ESP8266 with code I made on Arduino, I’m trying to send over the soil moisture percentage from my capacitive sensor to the embedded broker on OpenHab.
Eventually, I would like to program OpenHab to do stuff with the data once it receives the message, but that comes -after- I figure out how to send it to the broker in the first place.
The Problems:
- On occassion there’ll be intermittent network connection failures, so every minute or so the ESP will have to reconnect to the broker, and I have no clue why this is happening nor if I can prevent it. This isn’t the biggest priority so long as I can get the client to successfully send a message to the broker so that OpenHab can reasonably use it. and yes the clientid is unique to my knowledge.
- At least in every step of my Arduino code and the output console, it says it successfully sent the message, but neither MQTT Explorer nor MQTT.fx receives the message when they’re subscribed to the topic that my ESP is supposed to be publishing to. Essentially, my ESP is telling me it’s sending messages fine but it’s as if the broker is never actually receiving these messages.
When I publish to the same topic via MQTT.fx however, those messages appear fine.
I thought setting the client.publish to send retain messages that would resolve it but still nothing.
and PubSubClient on Arduino appears to only be able to send QoS 0 messages so if it’s not appearing because of that then I have no clue how to solve this problem, but I don’t feel like that’s the cause of the issue either.
Here’s my code:
#include <SPI.h>
#include <Wire.h>
#include <WiFiClient.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//WiFi Credentials (probably should include these in a secret .h file later)
char ssid[] = "XXXXXX"; // IoT devices can only connect to 2.4 GHz wifi, DO NOT connect to 5GHz it will fail
char pass[] = "XXXXXXXX";
int SensorPin = A0;
int SoilValue = 0;
int SoilPercent = 0; //this takes SoilValue, and converts it to a 0-100% based on AirValue & WaterValue
int AirValue = 866; //These two values are HAND MEASURED to determine air (no water) vs. full count of water.
int WaterValue = 540;
String Data;
WiFiClient wifiClient;
PubSubClient client(wifiClient);
const char broker[] = "XXXXXXXX";
int port = 1883;
const char topic[] = "tele/SoilSensor01";
const char clientID[] = "SoilSensor01";
const long interval = 1000;
unsigned long previousMillis = 0;
int count = 0;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println("You're connected to the network");
Serial.println();
Serial.print("Attempting to connect to the MQTT broker: ");
Serial.println(broker);
Serial.println("...");
client.setServer(broker, port);
client.setCallback(callback);
client.connect(clientID);
client.subscribe(topic);
Serial.println("Connection Status: " + String(client.state()));
if (!client.connected()) {
reconnect();
}
Serial.println("You're connected to the MQTT broker!");
Serial.println();
}
void loop() {
client.loop();
if (!client.connected()) {
reconnect();
}
// avoid having delays in loop, we'll use the strategy from BlinkWithoutDelay
// see: File -> Examples -> 02.Digital -> BlinkWithoutDelay for more info
unsigned long currentMillis = millis();
SoilValue = analogRead(SensorPin);
SoilPercent = map(SoilValue, AirValue, WaterValue, 0, 100);
if (currentMillis - previousMillis >= interval) {
// save the last time a message was sent
previousMillis = currentMillis;
Data = String(SoilPercent);
Serial.print("Sending message to topic: ");
Serial.println(topic);
Serial.println("Percent Value: " + Data + "%");
//This allows the OpenHAB broker to read the message
const char* buffer = Data.c_str();
String JSONconverter = String("{\"moisture\": ") + String(buffer) + String("}");
const char* ToJSON = JSONconverter.c_str();
if(client.publish(topic, ToJSON, true) == true) {
Serial.println("Message Succeeded!");
}
else if(client.publish(topic, ToJSON, true) == false) {
Serial.println("Message Failed to Send!");
}
Serial.println();
count++;
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientID)) {
Serial.println("connected");
client.subscribe(topic);
} else {
Serial.print("failed, state: ");
Serial.println(client.state());
Serial.println("attempting reconnection...");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
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();
}
The thing is, if my code’s fine, then what exactly is going on? Why don’t the messages appear on MQTT.fx when I subscribe to the topic “tele/SoilSensor01”, or why don’t they appear anywhere for that matter? Am I not looking in the right place, or is this an issue with the embedded broker?
If you all think this is an issue due to the broker’s configuration, that’s already a huge step for me to figure this out! I’m not posting this on the server itself but my main computer that I use program with, so let me know if you need to see some of the openhab files and I can log in there and post it here.
Best,
-MTX