Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * \file
- * ESP8266 MQTT Bridge example
- * \author
- * Tuan PM <tuanpm@live.com>
- */
- #include "Config.h"
- #include <SoftwareSerial.h>
- #include <espduino.h>
- #include <mqtt.h>
- #define DEBUG_PORT_RX 2
- #define DEBUG_PORT_TX 3
- #define ESP8266_POWER_DOWN 4
- SoftwareSerial debugPort(DEBUG_PORT_RX, DEBUG_PORT_TX); // RX, TX
- ESP esp(&Serial, &debugPort, ESP8266_POWER_DOWN);
- MQTT mqtt(&esp);
- boolean wifiConnected = false;
- void wifiCb(void* response)
- {
- uint32_t status;
- RESPONSE res(response);
- if(res.getArgc() == 1) {
- res.popArgs((uint8_t*)&status, 4);
- if(status == STATION_GOT_IP) {
- debugPort.println("WIFI CONNECTED");
- mqtt.connect(MQTT_BROKER_IP, MQTT_BROKER_PORT, false);
- wifiConnected = true;
- //or mqtt.connect("host", 1883); /*without security ssl*/
- } else {
- wifiConnected = false;
- mqtt.disconnect();
- }
- }
- }
- void mqttConnected(void* response)
- {
- debugPort.println("Connected");
- mqtt.subscribe(MQTT_SUBSCRIBED_TOPIC); //or mqtt.subscribe("topic"); /*with qos = 0*/
- // mqtt.subscribe("/topic/1");
- // mqtt.subscribe("/topic/2");
- // mqtt.publish("/onoff_tutorial/0", "data0");
- }
- void mqttDisconnected(void* response)
- {
- debugPort.println("Disconnected123");
- }
- void mqttPublished(void* response)
- {
- debugPort.println(F("Published"));
- }
- void mqttData(void* response)
- {
- char words[4];
- RESPONSE res(response);
- debugPort.print("Received: topic=");
- String topic = res.popString();
- debugPort.println(topic);
- debugPort.print("data=");
- String data = res.popString();
- debugPort.println(data);
- data.toCharArray(words,4);
- // words(words);
- }
- void setup() {
- Serial.begin(19200);
- debugPort.begin(19200);
- esp.enable();
- delay(500);
- esp.reset();
- delay(500);
- while(!esp.ready());
- debugPort.println("ARDUINO: setup mqtt client");
- if(!mqtt.begin(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD, 120, 1)) {
- debugPort.println("ARDUINO: fail to setup mqtt");
- while(1);
- }
- // debugPort.println("ARDUINO: setup mqtt lwt");
- // mqtt.lwt("/lwt", "offline", 0, 0); //or mqtt.lwt("/lwt", "offline");
- /*setup mqtt events */
- mqtt.connectedCb.attach(&mqttConnected);
- mqtt.disconnectedCb.attach(&mqttDisconnected);
- mqtt.publishedCb.attach(&mqttPublished);
- mqtt.dataCb.attach(&mqttData);
- /*setup wifi*/
- debugPort.println("ARDUINO: setup wifi");
- esp.wifiCb.attach(&wifiCb);
- esp.wifiConnect(AP_SSID,AP_PASSWORD);
- debugPort.println("ARDUINO: system started");
- }
- void loop() {
- esp.process();
- if(wifiConnected) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement