/* Publish RF Doorbell Signal to MQTT */ #include #include #include #define wifi_ssid "YOUR_WIFI_SSID" #define wifi_password "YOUR_WIFI_PASSWORD" #define mqtt_server "192.168.1.1" #define mqtt_user "MQTT_USERNAME" #define mqtt_password "MQTT_PASSWD" // This is the RF message the doorbell sends. // You will need to run this as is first, and get the ID after // the "Unknown signal received!" message #define doorbell_id 5179940 #define doorbell_topic "sensor/doorbell" RCSwitch mySwitch = RCSwitch(); WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin (115200); mySwitch.enableReceive(D2); setup_wifi(); client.setServer(mqtt_server, 1883); Serial.println ("start"); } void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(wifi_ssid); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect // If you do not want to use a username and password, change next line to // if (client.connect("ESP8266Client")) { if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } long lastMsg = 0; void loop() { if (!client.connected()) { reconnect(); } client.loop(); // You get roughly 4-5 messages within a second each time the // button is pressed, so lets add some time contraints. long now = millis(); if (now - lastMsg > 2000) { lastMsg = now; if (mySwitch.available()) { int value = mySwitch.getReceivedValue(); if (value == doorbell_id) { Serial.println("Ding Dong!"); client.publish(doorbell_topic, "front_door"); } else { Serial.println("Unknown signal received!"); Serial.print("Received "); Serial.print( mySwitch.getReceivedValue() ); Serial.print(" / "); Serial.print( mySwitch.getReceivedBitlength() ); Serial.print("bit "); Serial.print("Protocol: "); Serial.println( mySwitch.getReceivedProtocol() ); } mySwitch.resetAvailable(); } } }