{"id":1265,"date":"2019-01-22T12:22:02","date_gmt":"2019-01-22T06:52:02","guid":{"rendered":"http:\/\/www.mka.in\/wp\/?p=1265"},"modified":"2019-03-02T09:33:58","modified_gmt":"2019-03-02T04:03:58","slug":"smart-iot-enabled-doorbell","status":"publish","type":"post","link":"https:\/\/www.mka.in\/wp\/smart-iot-enabled-doorbell\/","title":{"rendered":"IoT enabled Smart doorbell"},"content":{"rendered":"\n<p>How useful would it be if you are notified on phone with the photo of visitor on door moment doorbell rings \ud83d\ude42<\/p>\n\n\n\n<figure class=\"wp-block-embed-youtube wp-block-embed\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"IoT enabled smart doorbell\" width=\"640\" height=\"360\" src=\"https:\/\/www.youtube.com\/embed\/auYsxAOTdMg?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p>Let us build a low cost and simple solution without intercepting anything on 220v supply of doorbell.<\/p>\n\n\n\n<p>Things you need<\/p>\n\n\n\n<p>1) NodeMCU board.<br> 2) sound sensor with digital output(it a simple mic hooked on a small PCB).<br> 3) MQTT broker, you can use any cloud MQTT service or build your own on raspberry pi or another Linux machine.<br> 4) MQTT client on raspberry pi. You can also configure MQTT broker and client on same raspberry.<br> 5) Webcam.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"960\" height=\"720\" src=\"http:\/\/www.mka.in\/wp\/wp-content\/uploads\/2019\/01\/bellbang-1-960x720.jpg\" alt=\"\" class=\"wp-image-1267\" srcset=\"https:\/\/www.mka.in\/wp\/wp-content\/uploads\/2019\/01\/bellbang-1-960x720.jpg 960w, https:\/\/www.mka.in\/wp\/wp-content\/uploads\/2019\/01\/bellbang-1-595x446.jpg 595w, https:\/\/www.mka.in\/wp\/wp-content\/uploads\/2019\/01\/bellbang-1-768x576.jpg 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/figure>\n\n\n\n<p>I have my own MQTT broker on Raspberry.<\/p>\n\n\n\n<p>How does it works ?<\/p>\n\n\n\n<p>1) When someone presses doorbell, sound sensor installed close to bell detects sound and sends message &#8220;1&#8221; on topic &#8220;bellbang&#8221; to MQTT network. You should tune sensitivity of sensor with the screw on board to make sure it does not catches noise from other sources and is just enough to detect only doorbell sound.<\/p>\n\n\n\n<p>2) MQTT client on raspberry subscribed to topic &#8220;bellbang&#8221; receives &#8220;1&#8221; message and which triggers webcam to take a snap and then sends this photo to your twitter handle and telegram account.<\/p>\n\n\n\n<p><strong>Let us take deep dive in implementation<\/strong><\/p>\n\n\n\n<p>Connect sound VCC (+), GND, D0 to VCC, GND and D5 of NodeMCU board.<\/p>\n\n\n\n<p>Then flash following code on NodeMCU. Make some noise close to sound sensor mic and see output on serial monitor. You can also run MQTT client with subscription to &#8220;bellbang&#8221; topic on a linux machince to ensure NodeMCU is transmitting messages on MQTT network.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\nmanish@iotbox:~ $ mosquitto_sub -h mqtt_broker_ip_host -p 1883 -t \"bellbang\" -u mqtt_user -P mqtt_password\n1<\/code><\/pre>\n\n\n\n<p>Code for NodeMCU<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n#include \"ESP8266WiFi.h\"\n#include \"Adafruit_MQTT.h\"\n#include \"Adafruit_MQTT_Client.h\"\n\n\/************************* WiFi Access Point *********************************\/\n\n#define WLAN_SSID       \"your_wifi_ssid\"\n#define WLAN_PASS       \"your_wifi_password\"\n\n\/************************* Adafruit.io Setup *********************************\/\n\n#define MQTT_SERVER      \"Your MQTT broker host\/IP\"\n#define MQTT_SERVERPORT  1883                   \/\/ use 8883 for SSL\n#define MQTT_USERNAME    \"your MQTT username\"\n#define MQTT_KEY         \"your MQTT password\"\n\n\/************ Global State (you don't need to change this!) ******************\/\n\n\/\/ Create an ESP8266 WiFiClient class to connect to the MQTT server.\nWiFiClient client;\n\/\/ or... use WiFiFlientSecure for SSL\n\/\/WiFiClientSecure client;\n\n\/\/ Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.\nAdafruit_MQTT_Client mqtt(&amp;client, MQTT_SERVER, MQTT_SERVERPORT, MQTT_USERNAME, MQTT_KEY);\n\n\/****************************** Feeds ***************************************\/\n\nAdafruit_MQTT_Publish bellbang = Adafruit_MQTT_Publish(&amp;mqtt, \"bellbang\");\n\n\/*************************** Sketch Code ************************************\/\n\n\/\/ Bug workaround for Arduino 1.6.6, it seems to need a function declaration\n\/\/ for some reason (only affects ESP8266, likely an arduino-builder bug).\nvoid MQTT_connect();\n\nint soundSensor=D5;\n\nvoid setup() {\n  pinMode(soundSensor,INPUT);\n  Serial.begin(115200);\n  delay(10);\n\n  Serial.println(F(\"Door bell alert....\"));\n\n  \/\/ Connect to WiFi access point.\n  Serial.println(); Serial.println();\n  Serial.print(\"Connecting to \");\n  Serial.println(WLAN_SSID);\n\n  WiFi.begin(WLAN_SSID, WLAN_PASS);\n  while (WiFi.status() != WL_CONNECTED) {\n    delay(500);\n    Serial.print(\".\");\n  }\n  Serial.println();\n\n  Serial.println(\"WiFi connected\");\n  Serial.println(\"IP address: \"); Serial.println(WiFi.localIP());\n}\n\nvoid loop() {\n  \/\/ Ensure the connection to the MQTT server is alive (this will make the first\n  \/\/ connection and automatically reconnect when disconnected).  See the MQTT_connect\n  \/\/ function definition further below.\n  MQTT_connect();\n\n\/\/read data from sensor\nint SensorData=digitalRead(soundSensor);\n\n  \/\/ Now we can publish when sensor value becomes high\n  \/\/Serial.print(SensorData);\n  \/\/Serial.println(F(\"\\n\"));\n  delay(50);\n\n  if(SensorData==1)\n  {\n    if (! bellbang.publish(1))\n    {\n      Serial.println(F(\"\\nBellbang publish Failed\"));\n    }\n    else\n    {\n    Serial.println(F(\"\\nBellbang publish OK\"));\n    }\n    delay(3000);\n  }\n}\n\n\/\/ Function to connect and reconnect as necessary to the MQTT server.\n\/\/ Should be called in the loop function and it will take care if connecting.\nvoid MQTT_connect() {\n  int8_t ret;\n\n  \/\/ Stop if already connected.\n  if (mqtt.connected()) {\n    return;\n  }\n\n  Serial.print(\"Connecting to MQTT... \");\n\n  uint8_t retries = 3;\n  while ((ret = mqtt.connect()) != 0) { \/\/ connect will return 0 for connected\n       Serial.println(mqtt.connectErrorString(ret));\n       Serial.println(\"Retrying MQTT connection in 3 seconds...\");\n       mqtt.disconnect();\n       delay(5000);  \/\/ wait 5 seconds\n       retries--;\n       if (retries == 0) {\n         \/\/ basically die and wait for WDT to reset me\n         while (1);\n       }\n  }\n  Serial.println(\"MQTT Connected!\");\n}<\/code><\/pre>\n\n\n\n<p>Client code subcribing to the &#8220;bellbang&#8221; topic and clicking snap, sending message on tweet and telegram. I found telethon available only for python3 so make sure you have installed tweepy and opencv for python3.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n#!\/usr\/bin\/python3\n\nimport paho.mqtt.client as paho\nfrom telethon import TelegramClient, sync\nimport tweepy\nimport time\nimport cv2\nimport logging\n\n# Populate the Twitter API keys below\nconsumer_key = 'Your_twitter_consumer_key'\nconsumer_secret = 'your_twitter_consumber_secret'\naccess_token_key = 'your_twitter_token_key'\naccess_token_secret = 'your_twitter_token_secret'\n\n# Telegram API Keys\ntele_api_id = your_telegram_api_id\ntele_api_hash = 'your_telegram_api_hash'\n\nbroker=\"Your MQTT broker host\/IP\"\nport=1883\ntopic=\"bellbang\"\nusername=\"your_mqtt_username\"\npassword=\"your_mqtt_password\"\n\n#do some basic logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler('\/var\/log\/bellbang.log')  # create a file handler\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # create a logging format\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)# add the handlers to the logger\n\ndef on_subscribe(client, userdata, mid, granted_qos):\n#       print(\"Subscribed: \"+str(mid)+\" \"+str(granted_qos))\n    print(\"Waiting for message bellbang topic...\")\n\ndef on_message(client, userdata, mqttmsg):\n    print(mqttmsg.topic+\" \"+str(mqttmsg.qos)+\" \"+mqttmsg.payload.decode(\"utf-8\"))\n\n    if mqttmsg.topic == 'bellbang' and mqttmsg.payload.decode(\"utf-8\") == '1':\n        # authentication\n        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n        auth.set_access_token(access_token_key, access_token_secret)\n\n        t=time.strftime(\"%d-%m-%Y %H:%M:%S\", time.gmtime())\n\n        logmessage=\" bellbang \"+mqttmsg.payload.decode(\"utf-8\")\n        logger.info(logmessage)\n        print(\"Capturing image of person at door....\")\n        camera = cv2.VideoCapture(0)\n        return_value, image = camera.read()\n        cv2.imwrite('\/tmp\/doorperson'+'.png', image)\n        del(camera)\n\n        print(\"Sending image capture on telegram\")\n        teleclient = TelegramClient('session_name', tele_api_id, tele_api_hash).start()\n        teleclient.send_message('your_telegram_id', 'Someone on door')\n        teleclient.send_file('your_telegram_id', '\/tmp\/doorperson.png')\n\n        print(\"Sending image capture on twitter\")\n        api = tweepy.API(auth)\n        tweet = \"@your_twitter_handle Some one at door at \" + t\n        image_path =\"\/tmp\/doorperson.png\"\n        status = api.update_with_media(image_path, tweet)\n#       api.update_status(status = tweet)\n\nclient = paho.Client()\nclient.username_pw_set(username, password)\nclient.on_subscribe = on_subscribe\nclient.on_message = on_message\nclient.connect(broker, port)\nclient.subscribe(topic)\n\nclient.loop_forever()<\/code><\/pre>\n\n\n\n<p>Now I am planning to extend this to trigger video call to my phone so that I can talk to person on door over some video client like skype, Google duo etc.<br><\/p>\n","protected":false},"excerpt":{"rendered":"<p>How useful would it be if you are notified on phone with the photo of visitor on door moment doorbell rings \ud83d\ude42 Let us build a low cost and simple solution without intercepting anything on 220v supply of doorbell. Things you need 1) NodeMCU board. 2) sound sensor with digital output(it a simple mic hooked [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1266,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[35,36,38,41],"class_list":["post-1265","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tech-bytes","tag-iot","tag-mqtt","tag-nodemcu","tag-smarthome"],"_links":{"self":[{"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/posts\/1265","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/comments?post=1265"}],"version-history":[{"count":10,"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/posts\/1265\/revisions"}],"predecessor-version":[{"id":1418,"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/posts\/1265\/revisions\/1418"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/media\/1266"}],"wp:attachment":[{"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/media?parent=1265"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/categories?post=1265"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mka.in\/wp\/wp-json\/wp\/v2\/tags?post=1265"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}