Hi,
I’m preparing Arduino with ETH shield for CT current sensor, and trying to establish Arduino MQTT client to publish value in MQTT broker. I use mosquitto MQTT HA add on, configured as follows on the picture.
I made Arduino sketch as explained here.
#include <Ethernet.h>
#include <PubSubClient.h>
#include <SPI.h>
#define DEBUG 1
// Device settings
IPAddress deviceIp(192, 168, 100, 30);
byte deviceMac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
char* deviceId = "Arduino"; // Name of the sensor
char* state1Topic = "home-assistant/Arduino/Sensor1"; // MQTT topic where values are published
int sensor1Pin = A0; // Pin to which the sensor is connected to
char buf1[4]; // Buffer to store the sensor value
int updateInterval = 1000; // Interval in milliseconds
// MQTT server settings
IPAddress mqttServer(192, 168, 100, 16); //IP address of RPi where HA and MQTT broker is installed
//const char* mqttServer = "core-mosquitto"; I tried to use MQTT server name, but in that case wasn't able to connect
int mqttPort = 1883;
EthernetClient ethClient;
PubSubClient client(ethClient);
void reconnect() {
while (!client.connected()) {
#if DEBUG
Serial.print("Attempting MQTT connection...");
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
#endif
if (client.connect(deviceId)) {
#if DEBUG
Serial.println("connected");
#endif
} else {
#if DEBUG
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
#endif
delay(5000);
}
}
}
void setup() {
Serial.begin(9600);
client.setServer(mqttServer, mqttPort);
Ethernet.begin(deviceMac, deviceIp);
delay(1500);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
int sensor1Value = analogRead(sensor1Pin);
float power1Value = sensor1Value*(5./1023.)*230;
#if DEBUG
Serial.print("Sensor1 value: ");
Serial.println(sensor1Value);
#endif
client.publish(state1Topic, itoa(power1Value, buf1, 10));
delay(updateInterval);
}
In serial printing I see that analog measurement works fine, MQTT connection was established, value on correct topic is published, but when listening topic in MQTT server in HA, there is no any.
What might be a problem?
Thanks,
DK