Aiham
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Interactive Home Assistant based on a discord-bot and LoPy4 tags: discord-bot, assistance, Home assistant image: <img src="https://i.ibb.co/8r7Ytc4/Robot-icon-Bot-sign-design-Chatbot-symbol-concept-Voice-support-service-bot-Online-support-bot-Vecto.jpg" alt="Robot-icon-Bot-sign-design-Chatbot-symbol-concept-Voice-support-service-bot-Online-support-bot-Vecto" border="0"></a><br /><a target='_blank' href='https://imgbb.com/'> --- # Interactive Home Assistant based on a discord-bot and LoPy4 ###### Made by: Aiham Altahan aa226as <a href="https://github.com/itsAiham/home_assistant"><img src="https://i.ibb.co/jLDsmf6/githun.png" alt="githun" width="40px" border="0"></a> <br> In this tutorial we are going to create a simple home assistant. The scope of this kind of assistance is to inform you about the surroundings based on a bunch of sensors you can get data from using Lopy4 from pycom. All sensors’ data are sent to you through a discord-bot to keep you up with changes. One of the used sensors is a movement detector to trace any motion. The bot's mission is to send you a notification to your discord server, this can be used as anti-stealing or even auto-lighting in the future. Following this tutorial can get you rid of security companies and the monthly fees! If you are planning to follow this tutorial, you may need less than ten hours (starting from scratch!) to connect all things together. Notice that you need some hardware before starting to follow, as shown below. As you are going to see soon, I'm running all things locally where the bot we create lives on your computer while it is running <br> ## Objective! I choose to work on this project to get a view on my place while I’m out. Since the long-standing idea of IoT is to make our houses smarter with low cost. Being out of home for a long time may cause anxiety for some. The nice and maybe tricky thing about this project is that there is no limitation! In each corner, each function could be added to be smart in your house in a way or another. So, this project may be a cornerstone for many ideas you can come up with! After finishing this project, you will be able to communicate with the bot on your server, asking it about the temperature, humidity in your place. You are going to have long term data regarding the daily sun-lighting. After analyze it you can get a view about the lightness of the day. In addition, you can add your partner and children to this server to be informed all at once! <br> __________________________________ ## **Material** ### **basic material**: <br> - **LoPy4 + expansion board 3.0 (or 3.1)** <img src="https://i.ibb.co/0KrZB5r/tJ8JuRo.png" width="300px" alt="photoresistor" border="0" style="display: block; margin: 0 auto"> <br> - **Wiring, breadboard, resistors** <img src="https://i.ibb.co/LYGTq4S/DXHbOao.jpg" width="300px" alt="Wiring, breadboard" border="0" style="display: block; margin: 0 auto"> <br> <br> <br> ### **Sensors**: <br> #### **Tempreture**: I'm using two types of temperature sensors - **DHT:** Ultra low-cost digital temperature and humidity sensor, it measures the environment inside my place. <img scr="https://ibb.co/zGBYRNV"><img src="https://i.ibb.co/pJM8znj/49343902-69720380-11453-org.webp" width="300px" alt="photoresistor" border="0" style="display: block; margin: 0 auto"> - **MCP9700:** Linear Active Thermistor™ Integrated Circuit (IC) is an analog temperature sensor that converts temperature. I'm using it to measure the temperature outside. <br> <img scr="https://ibb.co/wMVcrmx"><img src="https://i.ibb.co/wMVcrmx/ds1820-sensor-thickbox-default-12x.jpg" width="300px" alt="photoresistor" border="0" style="display: block; margin: 0 auto"> <br> - **PIR Motion detector:** Used to detect whether a human has moved in the sensor's range. It is small, inexpensive, low-power, easy to use and doesn't wear out. <img scr="https://ibb.co/NyG04bK"><img src="https://i.ibb.co/jrjCpsD/1c29d091-e689-4a4f-aea3-904e341269cb-JPG.webp" width="250px" alt="photoresistor" border="0" style="display: block; margin: 0 auto"> <br> - **photoresistor:** Also known as LDR (light-dependent resistors), used to measure the light intensity. <img src="https://i.ibb.co/RTjHvsV/51py-U-gyv8-L-SL1001.jpg" width="200px" alt="photoresistor" border="0" style="display: block; margin: 0 auto"> \ &nbsp; List and prices: <br> <center> | IoT Thing | Price (approximately) | Description | | :---: | :----: | :---: | | [LoPy4 Multipack](https://pycom.io/product/lopy4-multipack/)| €62.04 | 1x LoPy4, 1x Expansion Board, 1x LoRa/Sigfox Antenna| | [PIR motion sensor HC-SR501](https://www.electrokit.com/produkt/pir-rorelsedetektor-hc-sr501/)| €5 | To detect the heat for humans and animals| | [Photoresistor](https://www.m.nu/sensorer-matinstrument/photo-cell-cds-photoresistor?gclid=CjwKCAjwuvmHBhAxEiwAWAYj-EwZZJBLXmTLrn8YjVEzYRRmUgefOMfwIDSC0TDIUQpdVgOqqnVABxoC9fMQAvD_BwE)| €2 | To detect the lightness| | [MCP9700](https://www.electrokit.com/produkt/mcp9700a-to-92-temperaturgivare/)| €1.61 | To detect the temperature outside| | [10m Wiring](https://www.biltema.se/bil---mc/elsystem/kontakter-och-uttag/kopplingsledning-2000018077) | €3.5 | The amount of wiring depends on the distance between sensors | | [(Optional) Battery holder 3xAAA](https://www.electrokit.com/en/product/battery-holder-3xaaa-with-switch-and-jst-connector/) | €2.5 | To allow pycom working without having it connected to a computer| | [(Optional) Multimeter](https://www.hornbach.se/shop/Multimeter-MALMBERGS-digital-Compact-Cat-III-600V/6153937/artikel-detaljer.html) | €11 | To measure voltage, current and resistance. | </center> Notice that you can buy a bundle kit which includes wiring, breadboard, resistors and bunch of sensors for €28-32 such as [THIS](https://www.amazon.se/Miuzei-kompatibelt-LCD1602-modul-str%C3%B6mf%C3%B6rs%C3%B6rjning-handledning/dp/B07CXKP3R3/ref=pd_sim_11/257-5092432-4016929?pd_rd_w=IKdvk&pf_rd_p=6469eaa9-63e0-4609-99c0-ff67d019cf87&pf_rd_r=QWS7CHH7EWNSQPVT8Q4N&pd_rd_r=90cef712-28e9-4c16-b360-387073b89111&pd_rd_wg=cEQPZ&pd_rd_i=B07CXKP3R3&psc=1) or [THIS](https://www.electrokit.com/produkt/sensor-kit-26-moduler/) __________________________________ \ &nbsp; ## **Computer setup** <br> The following table shows the apps and platforms I used, their type and whether there is need to create an account: <center> | Software | Type | Description | | :--------: | :--------: | :--------: | | [Visual Studio Code](https://code.visualstudio.com/) | Open source app | Code editor made by Microsoft. We use it to write our code and upload it to device. | | [Node.js](https://nodejs.org/en/) | Open source cross-platform | Runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. | | [Updating Device Firmware](https://docs.pycom.io/updatefirmware/device/) | Open source tool | After upgrading, we can use the Pymakr Plugins to upload and run programs in our devices. | | [Node-red](https://nodered.org/) | Open source development tool | Programming tool for wiring hardware devices together. | | [Pybytes](https://pybytes.pycom.io/) | Free cloud platform | a device management platform that empowers you by giving you full control over your Pycom devices. **(Account required)** | | [Datacake](https://app.datacake.de/) | Limited platform for non-commercial purposes | where the data is saved and resend it to node-red to be handled by the bot. **(Account required)** | | [(Optional) Fritzing](https://fritzing.org/download/) | €8 | To draw circle diagram | </center> \ &nbsp; __________________________________ \ &nbsp; ### Connecting your pycom <ol> <li>Connected your device to the expansion board as shown bellow, and connect it via USB to your computer <img src="https://i.ibb.co/ygP1K7P/Website-Product-Shots-Exp-B-Right-Side-Fi-Py.png" width="300px" alt="Lopy4 and the expansion board" border="0" style="display: block; margin: 0 auto"></li> <li> [Update firmware from here](https://docs.pycom.io/updatefirmware/device/) Remember to close VSCode before running the firmware updater. </li> <li> Installing VSCode and Node.js: [Follow this tutorial to go step-by-step to make the installation.](https://hackmd.io/a1Nq_9kqR0CZBrYL1xNJDg) </li> <li> Connect to Wi-Fi: There is several ways to connect to Wi-Fi: - Change ssid to your network name, and your password and run the code: <br> ``` python= from network import WLAN import machine wlan = WLAN(mode=WLAN.STA) wlan.connect(ssid='ssid', auth=(WLAN.WPA2, 'password')) while not wlan.isconnected(): machine.idle() print("WiFi connected succesfully") print(wlan.ifconfig()) ``` <br> - Easy way of doing it is by pressing “download” in your IDE and accept all new files. Then a new file pybytes_config.json will appear (if you’ve done the Pybytes firmware update). There you can check the SSID and password you entered in Pybytes. Update your SSID/password if needed, save and upload the project again [ read more](https://hackmd.io/@lnu-iot/r1bGPUOhu/). <br> <img src="https://i.ibb.co/0FMRWVV/Screenshot-2021-07-27-121208.png" width="700px" alt="Show download choice" border="0" style="display: block; margin: 0 auto"> and then change the following: <img src="https://i.ibb.co/PjZH2fb/FZMk3lf.png" alt="project" border="0" width="750px" alt="show pymkr.config.json" border="0" style="display: block; margin: 0 auto"> </li> </ol> \ &nbsp; **OBS** In some cases you will keep losing the communication with your device for no reson! Where the address faile finding the device. To solve this, click on -> All commands -> Global settings and change json file as the following: ``` json= .. // You may have another port than 4, click on List Serial Ports "address": "COM4", .. "auto_connect": false, .. ``` \ &nbsp; __________________________________ \ &nbsp; ## **Putting everything together** <br> The connection between LoPy4 and sensors looks like the following. A small notice that the DHT sensor I have had 3 pins not 4 where it includes a resistor already inside it. Each breadboard is placed in a different corner in the house, you can play with this the way you want even if you plan to put all together. **Be careful of the voltage!** Most sensors need 3.3V. The only one that requires 5V is the movement sensor and the wire has a purple color and is connected separately to its own cell. <img src="https://i.ibb.co/k8Hdr9M/project.png" alt="project" border="0" width="750px" alt="connecting diagram" border="0" style="display: block; margin: 0 auto" > \ &nbsp; \ &nbsp; <!-- ### Electrical Calculatuins: | | Conditions | Minimum |Typical | Maximum | | :--------: | :--------: | :--------: | :--------: | :--------: | |Power Supply| DC | 3V |5V | 5.5V | |Current Supply| Measuring| 0.5mA | | 2.5mA | | | Average | 0.2mA | | 1mA | | | Standby | 100uA | | 150uA | |Sampling period| Second | 1 | | 2.5mA | --> \ &nbsp; __________________________________ \ &nbsp; ## **Platform** As the following figure shows, here are steps to reach the final result. Getting a callable bot where it interacts with us requires some configuration and platforms' communication. <img src="https://i.ibb.co/2g2SDqt/Presentation1.png" alt="project steps" border="0" width="750px" alt="connecting diagram" border="0" style="display: block; margin: 0 auto" > <br> Let's follow the figure and configure each step by step. I'm assuming that your device is connected to Wi-Fi at this stage. \ &nbsp; ### Pybytes: As mentioned earlier, you need to create an account on pybyte platform to send your data on. [Create an account from here, ](https://sso.pycom.io/register/) and login to the website. To add a device: <img src="https://i.ibb.co/6DcdpkC/Presentation2.png" alt="project steps" border="0" width="750px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto" > <br> SSID presents your network name password is your router password <img src="https://i.ibb.co/B3dMSJV/Presentation3.png" alt="project steps" border="0" width="750px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto" > by now, your device is connected, lets send some data. As shown earlier the diagram of how sensors are connected. make sure that you are done of this step before jumping to the next step. By clicking on device name -> SIGNALS -> Define New Signal. Each signal presents a value received from the device, the number of the signal must match on both sides. In our project we are sending 5 signals as the following <br> <central> | Signal| Description | | :--------: | :-------- | | 1 | Temperature Inside | | 2 | Humidity Inside | | 3 | light-sensor | | 4 | Movement | | 5 | Temperature Outside | </central> \ &nbsp; Turning to the code, where all code snippets are shared on a repository. [You can easily access it from here](https://github.com/itsAiham/home_assistant/). If you are not familiar with code hosting that is fine. click on **Download ZIP** After **uncompressing the folder** , open a new window of VSCode and **find the folder on VSCode** <br> <img src="https://i.ibb.co/k8XJZLj/Presentation3.png" alt="project steps" border="0" width="750px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto" > Inside the uncompressed folder, there is another folder that has name **src/** stands for *source code*. This folder must be uploaded on pycom device by clicking on **$\triangle$Upload**, [`as shown in point four`](#Connecting-your-pycom) By now, your terminal should be running and sending the data to Pybytes platform. You might check that your account is pumped up with updates. \ &nbsp; __________________________________ \ &nbsp; ### Datacake <br> Moving to the next configuration in our way to get our interactive bot we need to visualize our data. According to their definition, Datacake is a multi-purpose, low-code IoT platform that requires no programming skills which fits us for this project. In this section, we are going create a communication between Pybytes platform and Datacake, first you need to [create an account.](https://app.datacake.de/signup/) After you login, you need to add a Workspace. by following those steps: - Click arrows besides your email - Choose **Add Workspace** - Give your workspace a name. - Switch to the created workspace. You notice more feilds come to your menu. - Click on **Devices**, and then the button **Add Device** to add you pycom. <br> <img src="https://i.ibb.co/DVfHZrW/Presentation13.png" alt="Config Datacake" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> <img src="https://i.ibb.co/dQST5QY/Presentation13b.png" alt="Config Datacake" border="0" width="800px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> By clicking on next, you will get a chance to choose a name and a serial number for your device. It is written in the field that the serial number is Auto-Generate, however, in our case and to get connection between those platforms we are going to use the device ID from Pybytes as the following: <br> <img src="https://i.ibb.co/qMqRzXG/Presentation5.png" alt="project steps" border="0" width="750px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> You will get a payment choice, notice that Datacake provides full functionality for limited devices for free. Let's stick with this choice and click on **Add 1 Device**. You can see your device added, by clicking on it you see your signals that have been created earlier on Pybytes available. The data is still Null so far and we are going to fix this next. On Datacake, copy your endpoint URL as the following: <br> <img src="https://i.ibb.co/VmB8Qjx/Presentation6.png" alt="project steps" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> Moving to Pybytes: <img src="https://i.ibb.co/2PnSDV5/Presentation7.png" alt="project steps" border="0" width="700px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> Be careful with step 4. after pasting your URL you need to add **/pycom** to the end of it. The reason beyond that is Pybytes deletes the slash at the end. Scroll down, check the box besides the device name and click on **CREATE.** Now, your data is synchronized across Pybytes and Datacake. You can play around your dashboard, add widgets and change visualization the way you want. <br> <img src="https://i.ibb.co/5jQySFg/Presentation8.png" alt="project steps" border="0" width="700px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> \ &nbsp; __________________________________ \ &nbsp; ### Node-Red and Discord At this stage, our device sends data to Pybytes and Datacake take a piece of this cake. Reaching this point means that you have a look on your surrounding and IoT device we created work as it should. Still, we cannot get messages with news rather than we must be connected to those platforms and watching. Now it is time to involve our bot in this case! First, we are going to create bot we need and make them ready to work, then we turn to play with Node-Red. <br> #### Bots Our bot circle-live is locally, so we are not going to deploy it in this tutorial. To keep our bot alive, our computer must be ON and running Node-Red server. I'm using two bots, one to read messages and the one to send me reactions. - [Create a discord account if you don't have.](https://discord.com/) - [Create your own server.](https://www.howtogeek.com/318890/how-to-set-up-your-own-discord-chat-server/) - Login to [Discord Developer and click on Application.](https://discord.com/developers/applications/) Let's start preparing our bots for the mission. \ &nbsp; ##### Create reader bot: <br> <img src="https://i.ibb.co/SN0bCCK/Presentation20.png" alt="project steps" border="0" width="700px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> <img src="https://i.ibb.co/Syzgzvw/Presentation21.png" alt="project steps" border="0" width="700px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> After You copied the URL in step 10, open a new browser window and paste the URL you copied. You will get a discord window where you can invite your bot to the server you want. Now the first bot is one of the members! One last thing for this bot. We need his TOKEN to add it to our Node-Red later on: <br> <img src="https://i.ibb.co/kGV8N3C/Presentation22.png" alt="Bot token" border="0" width="700px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> Save the token from step 12. \ &nbsp; ##### Create sender bot: <br> Assuming your server called Home: <img src="https://i.ibb.co/m0BJTGw/Presentation10.png" alt="project steps" border="0" width="700px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> In step 5, Click on **Copy webhook URL** and save it somewhere. We are going to need it in later steps. \ &nbsp; \ &nbsp; #### Node-Red Node-RED is a programming tool for wiring together hardware devices. In our tutorial, we are wiring data with discord bot. <br> ##### Downloading and Running Node-Red requires Node.js which we already have from an earlier step. There are multiple ways of running Node-Red. If you are familier with Docker, you can simply run it on a container [Check this Doc for more.](https://nodered.org/docs/getting-started/docker) Another way of running it, is by download Node-Red which can be down easilly by running a command line [check this Doc for downloading and running](https://nodered.org/docs/getting-started/windows) After starting node-red you can [click here to open a new browser window.](http://localhost:1880/) ##### Extra Nodes Our project requires extra nodes that are not included by default. We need to download three extra nodes as the following: <br> <img src="https://i.ibb.co/Mk1V5sc/Presentation9.png" alt="project steps" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> You need to search for those three nodes and install them: ```bash= node-red-contrib-datacake node-red-new-discord node-red-contrib-chatbot-discord ``` \ &nbsp; ##### Configure Datacake node: Each node requires a configuration to do its job. Drag a Datacake-node-in node and double click on it as the following: <br> <img src="https://i.ibb.co/KqBFfSC/Presentation12.png" alt="project steps" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> To find the API-Token, we need to go back to Datacake: <br> <img src="https://i.ibb.co/6RjvPz4/Presentation13.png" alt="datacake api-token-1" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> <img src="https://i.ibb.co/fSkj6RF/Presentation14.png" alt="datacake api-token-2" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> Switching back to Node-Red, you can paste new_API in Datacake-node. When you do that, you get the Workspace name <br> <img src="https://i.ibb.co/2smg6TS/Presentation15.png" alt="config datacake-node" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> After clicking on **Add**, you will get your Datacake connected. Notice that we even choose the field. In my case, I add one node for each signal in Pybytes. You can swap one Datacake-node for each signal and make sure they are connected. __________________________________ \ &nbsp; ##### Configure Discord node: <br> <img src="https://i.ibb.co/3TRvqqB/Presentation16.png" alt="config discord-node" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> Do you remember the TOKEN we saved for our reader bot [in step 12?](###Create-reader-bot), now it is time to paste it here. and click on **Add**. Your bot is not connected! \ &nbsp; ##### Configure request node: <br> <img src="https://i.ibb.co/fNxZtr9/Presentation17.png" alt="config discord-node" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> Step 5 was an older step from sender bot, [As in HERE.](###Create-sender-bot) Paste the URL and click on **Done**. \ &nbsp; __________________________________ ##### Node-Red Diagram: It is time to create our diagram using in Node-Red. Follow the next schema to create the connections between nodes: <br> <img src="https://i.ibb.co/fF7xTcP/node-red.png" alt="project steps" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> The fact that function-nodes must be filt. I pushed all code that I used to a repo. Following the same name for each function on Node-Red and the equivalent one on the repo. Paste the code and click on Done for each function [Follow Code On Repo](https://github.com/itsAiham/home_assistant/tree/main/node-red/). I used limit messages to avoid too many messages from bot or directly from Datacake. You can play with this the way you want. However, it is an important to use the limit 1 msg/2s for discord node to avoid many message with the same content in very short time from the bot. At the end of creating the diagram, you need to **Deploy** the diagram with new changes. Time to some DEMO! [Click here to watch.](https://youtu.be/Ks9MIsQYBEU/) \ &nbsp; ______________________________________ \ &nbsp; ## **The code** All code used in this project is published in [this repository](https://github.com/itsAiham/home_assistant/). However, I would like to highlight some parts. ### Initialize fields <br> ``` javascript= flow.set("temp_inside", msg.payload); var temp = flow.get("temp_inside") ; msg.headers = {} msg.method = "POST" msg.headers["content-type"] = "application/json" if (temp > 24){ msg.payload = {"content": "It's even hot inside home! " + temp + " C"}; } else if (23 >= temp > 19){ msg.payload = {"content": "The temp inside in pretty normal" + temp + " C"}; } return msg ``` <br> Each function-node is placed after Datacale-node to work as an initializer for a variable to be used in all the flow as in the first line. I can simply retrieve the value of the same variable in any other function node as the following: ```javascript= var temp = flow.get("temp_inside") ``` temp variable gets the new value for that field each time datacake sends a request. \ &nbsp; ### Multiple thread The way our project works requires a different timing for reading. While the movement detector sends a value when it detects a move, so basically it reads each second. The other sensors can send the data each 3-5 hours to catch changes in the temperature. Multiple threads have been used to make each loop run in separate time. <br> ```python= MIN = 60 HOURE = 60 * MIN def long_sleep(): # inside th = DHT(Pin('P22', mode=Pin.OPEN_DRAIN), 0) # outside adc = machine.ADC() apin = adc.channel(pin='P15') light_sensor = Photoresistor('P16') while True: result = th.read() print('Temperature Inside:', result.temperature) print('Humidity Inside:', result.humidity) millivolts = apin.voltage() celsius = (millivolts - 500.0) / 10.0 print("Temp outside", celsius) print("Light Value", light_sensor.get_value()) print("_____________") pybytes.send_signal(1, result.temperature) pybytes.send_signal(2, result.humidity) pybytes.send_signal(3, light_sensor.get_value()) pybytes.send_signal(5, celsius) utime.sleep(HOURE * 3) if not stop_threads: break def short_sleep(): movment_sensor = HCSR501('P13') while True: movment_sensor.start() if movment_sensor.get_status(): print("Motion Detected") pybytes.send_signal(4, 1) utime.sleep(5) pybytes.send_signal(4, 0) utime.sleep(1) def run_threads(): _thread.start_new_thread(long_sleep, ()) _thread.start_new_thread(short_sleep, ()) if __name__ == "__main__": run_threads() ``` \ &nbsp; ______________________________________ \ &nbsp; ## **Transmitting the data** Two things work as a factor when it comes to timing. First, when we talk about sending data from sensors and pycom device. In python, or as we should say MicroPython We used time functionality to stop the loops we used for a certain time. Since we use multiple threads as described in [The Code](##The-code"), though, when it comes to the data that has some kind of stabil data such as temperature or humidity, it makes sense to send data a couple of times a day. This also supports the principle of sustainability where we do not save the temperature twice hourly! Since I'm using the movement sensor as a security thing and not as a normal detector e.g for turning a light on, it is important in this case to send data each second or even a part of it. However, we used another approach where we send a signal only when a movement detect which saves data on hosting server. In other word, each movement takes 16 Bytes to be saved. From the other side, on the Node-Red server which runs locally. Datacake get a signal from PyBytes, movement_detector functions written to send data only of the value is not zero *inactive*: <br> <img src="https://i.ibb.co/6yTdWZc/Screenshot-2021-07-30-151118.png" alt="sending requist node-red" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> The code used in function-node works as the follwoing: <br> ```javascript= if (movement_value != 0 && flow.get("larm_status")){ msg.payload = {"content": "Move detected!!"}; count += 1; flow.set('alarm_count', count); } return msg ``` When datacake get a value higher than zero which is the default, it changes the content of the msg which is returned anyway. The limited node can be changed based on how many times you want to be notified after movement detecting. Notice that we can turn off the alarm and this will stop the messages from the bot, however, the data is still sent under the hood. \ &nbsp; _______________________ \ &nbsp; ## **Presenting the data** Datacake provides an attractive dashboard to visual the data as it shown: <br> <img src="https://i.ibb.co/Y2CVH1L/datacake-inside.png" alt="sending requist node-red" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> <img src="https://i.ibb.co/qBxH6bz/datacake-outside.png" alt="sending requist node-red" border="0" width="900px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> Our bot also gives a kind of visualization! Check this out: <br> <img src="https://i.ibb.co/Vjh8psT/bot.png" alt="sending requist node-red" border="0" width="600px" alt="pybytes steps" border="0" style="display: block; margin: 0 auto"> <br> \ &nbsp; _______________ ## **Finalizing the design** <br> At the end of this tutorial, we wend throw all steps and how all have been configured together. We reached our goal by setting up a simple bot assistant which can be improved in the future. <br> Things could be done differently? Developing this project under containers such as [Docker](https://www.docker.com/) will improve many aspects and here are my thoughts of how the project may look like. Node-Red may be faster to use for any new user. Easier to follow the tutorial where a beginner can do less work when it comes to downloading new nodes or creating the diagram. Using Docker will allow us to create our bot on python. With creating communication between containers (Node-Red and Python) and by applying some machine learning on the bot, we will end up with a smarter bot. \ &nbsp; _______________ \ &nbsp;

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully