Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <PubSubClient.h>
- #include <ESP8266WiFi.h>
- #include <SoftwareSerial.h>
- // Update these with values suitable for your network.
- //const char* ssid = "Automation";
- //const char* password = "1234567890";
- const char* ssid = "Office";
- const char* password = "Office2018";
- const char* mqtt_server = "192.168.16.141";
- char msg[50];
- WiFiClient espClient;
- PubSubClient client(espClient);
- byte mac[6];
- String MACAddress;
- const int LED = D5;
- void setup() {
- pinMode(LED, OUTPUT);
- Serial.begin(115200);
- setup_wifi();
- printMACAddress();
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- }
- void setup_wifi() {
- delay(10);
- // We start by connecting to a WiFi network
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- String mac2String(byte ar[]) {
- String s;
- for (byte i = 0; i < 6; ++i)
- {
- char buf[3];
- sprintf(buf, "%2X", ar[i]);
- s += buf;
- if (i < 5) s += ':';
- }
- return s;
- }
- void printMACAddress() {
- WiFi.macAddress(mac);
- MACAddress = mac2String(mac);
- Serial.println(MACAddress);
- }
- 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();
- // Switch on the LED if an 1 was received as first character
- if ((char)payload[0] == "On") {
- digitalWrite(LED, HIGH); // Turn the LED on (Note that HIGH is the voltage level
- }
- if ((char)payload[0] == "Off") {
- digitalWrite(LED, LOW); // Turn the LED off by making the voltage LOW
- }
- }
- void reconnect() {
- // Loop until we're reconnected
- printMACAddress();
- const char* CL;
- CL = MACAddress.c_str();
- Serial.println(CL);
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (client.connect(CL)) {
- Serial.println("connected");
- client.subscribe("terima");
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- ESP.restart();
- delay(5000);
- }
- }
- }
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement