Skip to content

Instantly share code, notes, and snippets.

@ajangrahmat
Last active February 25, 2023 15:46
Show Gist options
  • Save ajangrahmat/992be6d182c90cf0dda3debfc16786b6 to your computer and use it in GitHub Desktop.
Save ajangrahmat/992be6d182c90cf0dda3debfc16786b6 to your computer and use it in GitHub Desktop.
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "KelasRobot.com";
const char* password = "k3l4sr0b0t";
const char* mqtt_server = "mqtt.ardumeka.com";
int mqtt_port = 11219;
char* topic1 = "/ajang/ardumeka/j9682121213121dwdq/tes1";
char* topic2 = "/ajang/ardumeka/j9682121213121dwdq/tes2";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
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();
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
client.publish(topic1, "hello world");
client.subscribe(topic2);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(topic1, msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment