MQTT Subscribe esp8266


mqtt pub sub esp8266

Nambah catatan aja semoga bermanfaat juga buat yang membutuhkan cara subscribe ke mqtt server dengan esp8266

Pertama tama download dan pasang plugin ini di arduino libraries, lalu sesuaikan coding dibawah dengan alamat server dan topic yang anda gunakan

/*
 MQTT subscriber example

- connects to an MQTT server
 - subscribes to the topic "inTopic"
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char *ssid = "ssid"; // cannot be longer than 32 characters!
const char *pass = "pass"; //

// Update these with values suitable for your network.
IPAddress server(xx,xx,xx,xx);

#define BUFFER_SIZE 100

void callback(const MQTT::Publish& pub) {
 Serial.print(pub.topic());
 Serial.print(" => ");
 if (pub.has_stream()) {
 uint8_t buf[BUFFER_SIZE];
 int read;
 while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
 Serial.write(buf, read);
 }
 pub.payload_stream()->stop();
 Serial.println("");
 } else
 Serial.println(pub.payload_string());
}

WiFiClient wclient;
PubSubClient client(wclient, server);

void setup() {
 // Setup console
 Serial.begin(115200);
 delay(10);
 Serial.println();
 Serial.println();
}

void loop() {
 if (WiFi.status() != WL_CONNECTED) {
 Serial.print("Connecting to ");
 Serial.print(ssid);
 Serial.println("...");
 WiFi.begin(ssid, pass);

if (WiFi.waitForConnectResult() != WL_CONNECTED)
 return;
 Serial.println("WiFi connected");
 }

if (WiFi.status() == WL_CONNECTED) {
 if (!client.connected()) {

if (client.connect(MQTT::Connect("arduinoClient")
 .set_auth("username mqtt", "pass mqtt"))) {
 
 client.set_callback(callback);
 client.subscribe("topic");
 }
 }

if (client.connected())
 client.loop();
 }
}

 

Udah gitu aja, semoga bermanfaat

Happy coding !!!

Advertisement

Author: susiloharjo

Khoirunnas anfa'ahum linnas A Father, Husband and love to learn person Love my Family, Electronics, Photography, Robot, Dreaming, Programming

Ditunggu komennya ...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: