Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <EEPROM.h>
- #include <PubSubClient.h>
- #include <WiFiUdp.h>
- #include <NTPClient.h>
- #include <time.h>
- const char* ssid = "";
- const char* password = "";
- const char* mqttServer = "";
- const int mqttPort = 1883;
- const char* mqttUser = "";
- const char* mqttPassword = "";
- unsigned long lastSend;
- WiFiClient espClient;
- PubSubClient client(espClient);
- char buffer[100] = {0};
- char message_buff[100];
- String msgString = "";
- unsigned long time_second;
- void setup() {
- Serial.begin(115200);
- client.setServer(mqttServer, mqttPort);
- client.setCallback(callback);
- setup_wifi();
- }
- void setup_wifi() {
- delay(10);
- Serial.printf("Connecting to %s ", ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED)
- {
- Serial.print(".");
- delay(5000);
- }
- if(client.connect("ESP8266Client", mqttUser, mqttPassword )){
- Serial.println("connected");
- Serial.println(WiFi.localIP());
- randomSeed(micros());
- }else{
- Serial.print("failed with state ");
- Serial.print(client.state());
- delay(2000);
- }
- }
- void loop()
- {
- send_mqtt ();
- client.loop();
- if (!client.connected())
- {
- reconnect();
- }
- if (WiFi.status() != WL_CONNECTED)
- {
- setup_wifi();
- }
- delay(250);
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- int i = 0;
- for (int i=0;i<length;i++) {
- char receivedChar = (char)payload[i];
- message_buff[i] = payload[i];
- }
- }
- void reconnect() {
- while (!client.connected()) {
- Serial.print("Connecting...");
- if (client.connect("ESP8266 Client")) {
- Serial.println("connected");
- client.subscribe("ledStatus");
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println("try again");
- delay(10000);
- }
- }
- }
- void send_mqtt (){
- if(millis()- lastSend > 5000){
- //Serial.println("kirim status");
- String json_strg = "{\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\",\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\",\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\",\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\",\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\",\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\",\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\",\"type\":\"HOME0001\",\"id\":\"HOME\",\"status\":\"OK\"}";
- char *stat = const_cast<char*>(json_strg.c_str());
- client.publish("IOT/STATUS", stat);
- lastSend = millis();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement