Is this supposed to work?
#include <SoftwareSerial.h>
#include <WiFiEsp.h>
#include <ArduinoMqttClient.h>
// ESP8266 wifi board things.
#define RX 6 // blue
#define TX 7 // black
SoftwareSerial Esp8266(RX, TX);
const char AP[] = "ap";
const char PASS[] = "secret";
WiFiEspClient wifi_client;
// mqtt things.
const char mqtt_broker[] = "192.168.0.113";
const int mqtt_port = 1883;
const char mqtt_topic[] = "zigbee2mqtt/lux";
MqttClient mqtt_client(wifi_client);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
Esp8266.begin(9600);
WiFi.init(&Esp8266);
// Check for the presence of the shield.
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
// Connect to WiFi network.
while ( WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(AP);
WiFi.begin(AP, PASS);
}
Serial.println("WIFI connected.");
while (!mqtt_client.connect(mqtt_broker, mqtt_port)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqtt_client.connectError());
delay (3000);
}
mqtt_client.subscribe("zigbee2mqtt/lux");
}
void loop() {
int messageSize = mqtt_client.parseMessage();
if (messageSize) {
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqtt_client.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqtt_client.available()) {
Serial.print((char)mqtt_client.read());
}
Serial.println();
Serial.println();
}
}
It gets stuck in the connection loop saying
MQTT connection failed! Error code = -1
Same problem using test.mosquitto.org
and arduino/simple
.
(Tried PubSubClient
which can connect but doesn't receive any messages.)
Is there a known working MQTT subscriber for Arduino?