WeMOS: MQTT
Sumber: https://techtutorialsx.com/2017/04/09/esp8266-connecting-to-mqtt-broker/
Code
#include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "o"; const char* password = ""; const char* mqttServer = "192.168.0.192"; const int mqttPort = 1883; # pastikan MQTT allow user anonymous const char* mqttUser = ""; const char* mqttPassword = ""; WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network"); client.setServer(mqttServer, mqttPort); client.setCallback(callback); while (!client.connected()) { Serial.println("Connecting to MQTT..."); // if (client.connect("ESP8266Client", mqttUser, mqttPassword )) { if (client.connect("ESP8266Client" )) { Serial.println("connected"); } else { Serial.print("failed with state "); Serial.print(client.state()); delay(2000); } } client.publish("test", "Hello from ESP8266"); client.subscribe("test"); } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived in topic: "); Serial.println(topic); Serial.print("Message:"); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); Serial.println("-----------------------"); } void loop() { client.loop(); }
ERROR: Publish
Check code di bawah ini,
void reconnect() { while (!client.connected()) { debugI("Reconnecting"); if (!client.connect(HOST_NAME, MQTT_USER, MQTT_PW)) { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" retrying in 5 seconds"); debugV("failed, rc=%d retrying in 5 seconds",client.state()); delay(5000); } } } void loop() { // put your main code here, to run repeatedly: StaticJsonDocument<200> doc; ArduinoOTA.handle(); Debug.handle(); if (!client.connected()) { reconnect(); } client.loop(); sleepcount+=1; if(sleepcount >= 60) { // code to build pubMsg removed client.publish("sensors/bme680", pubMsg); digitalWrite(LED, LOW); //Led port ausschalten delay(500); //500ms Pause digitalWrite(LED, HIGH); //Led port einschalten sleepcount=0; } delay(sleeptime); }
Ubuntu
Untuk Subscribe
mosquitto_sub -h 192.168.0.163 -t test
Untuk Posting
mosquitto_pub -h 192.168.0.163 -t test -m "coba echo"