Build a Home Security Dapp with Vue + Iotapp
Tags: vue, blockchain, serverless, iot
Published: 2020-08-07 09:29:51

### <b>Preamble</b> ###
Today, Im happy to release <a href="https://iotapp.network">Iotapp Beta </a>, a IoT platform for helping developers build decentralized IoT applications and software. In the following tutorial, we'll use Vue.js and Iotapp to build a simple home security Dapp that will demonstrate the technology behind Iotapp and show how it can be used to build a new kind of decentralized application. So without further ado, lets get started!

### <b>Dependencies </b>###

<ul>
<li><a href="https://www.npmjs.com/get-npm">NPM</a></li>
<li><a href="https://cli.vuejs.org/">Vue CLI</a></li>
<li><a href="https://www.arduino.cc/en/main/software"> Arduino IDE</a></li>
</ul>

### <b>Hardware</b> ###
To make the sensor, we're gonna need some hardware. All these components listed below can be found for a few dollars on Ebay, Amazon and similar monoliths. 

<ul>
<li>ESP8266 or ESP32 Board </li>
<li>Generic PIR Motion Sensor</li>
<li>Jumper Wires</li>
<li>Micro USB C</li>
</ul>

### <b>Building the Motion Sensor</b> ###

#### <b>ESP8266 Wiring</b> ####
<img src="https://i.imgur.com/AlVXHAB.png" alt="esp8266 wiring schema">

<table class="table table-striped" style="width: 300px; margin-top: -120px;">
<thead>
  <tr>
    <th class="">PIR Sensor</th>
    <th class="">ESP8266</th>
  </tr>
</thead>
<tbody>
  <tr>
<td class="tg-0lax"><v-chip color="red" style="color: white; font-weight: 700">VCC <b id="red">(Red)</b></v-chip></td>
    <td>3.3v <b></b></v-chip></td>
  </tr>
  <tr>
    <td class="tg-0lax"><v-chip color="yellow" style="color: black; font-weight: 700">Data <b>(Yellow)</b></v-chip></td>
    <td class="tg-0lax"><v-chip color="yellow" style="color: black; font-weight: 700">D7</v-chip></td>
  </tr>
    <tr>
    <td class="tg-0lax"><v-chip color="black" style="color: white; font-weight: 700">Ground <b>(Black)</b></v-chip></td>
    <td class="tg-0lax"><v-chip color="black" style="color: white; font-weight: 700">Ground</v-chip></td>
  </tr>
</tbody>
</table>
<hr>

</style>

#### <b>ESP32 Wiring</b> ####
<img src="https://i.imgur.com/QMBAAku.png" alt="esp32 wiring schema">
<table class="table table-striped" style="width: 300px; margin-top: -120px;">
<thead>
  <tr>
    <th class="">PIR Sensor</th>
    <th class="">ESP32</th>
  </tr>
</thead>
<tbody>
  <tr>
<td class="tg-0lax"><v-chip color="red" style="color: white; font-weight: 700">VCC <b>(Red)</b></v-chip></td>
    <td class="tg-0lax"><v-chip color="red" style="color: white; font-weight: 700">5V</v-chip></td>
  </tr>
  <tr>
    <td class="tg-0lax"><v-chip color="yellow" style="color: black; font-weight: 700">Data <b>(Yellow)</b></v-chip></td>
    <td class="tg-0lax"><v-chip color="yellow" style="color: black; font-weight: 700">P12</v-chip></td>
  </tr>
    <tr>
    <td class="tg-0lax"><v-chip color="black" style="color: white; font-weight: 700">Ground <b>(Black)</b></v-chip></td>
    <td class="tg-0lax"><v-chip color="black" style="color: white; font-weight: 700">Ground</v-chip></td>
  </tr>
</tbody>
</table>
<hr>

### <b>Console Signup</b> ###
The <a href="https://iotapp.network/#/Console">Iotapp web console</a> is a backend tool that saves your device data to the Iotapp Blockchain. 

First, <a href="https://iotapp.network/#/Register">sign up for a new account</a>. Then, <a href="https://iotapp.network/#/Login">log in</a> to the console. You'll see two channels. These channels are used to capture and display incoming device data. They also contain one-click functions that will automatically save your device data to the blockchain. 

For now, notice the channel URL.

<img src="https://i.imgur.com/o3jxIbo.png" alt="Channel URL">

We'll use this URL to make POST requests to the channel and save any incoming movement data. 

### <b>Uploading the Device Code</b> ###
First, open <a href="https://www.arduino.cc/en/main/software"> Arduino IDE</a>

If you haven't already done so, you'll need to install the binaries for ESP8266 or ESP32. Dont worry, its easy. Here's a guide for each board below:
<ul>
<li><a href="https://randomnerdtutorials.com/how-to-install-esp8266-board-arduino-ide/">ESP8266 IDE Install</a></li>

<li><a href="https://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-windows-instructions/">ESP32 IDE Install</a></li>
<i>Credit and Thanks to Random Nerd Tutorials</i>
</ul>
There's just one more dependency and then we can get cookin'. The 'Arduino JSON' library will format our data to JSON. In the IDE, simply go to <b>Tools -> Manage Libraries</b>.

Type in <b>"ArduinoJson"</b> and install the package by that name.
<hr>

Now, plug in your board with the Micro USB, and open a new Arduino sketch.
Depending on which board you have, open the URL below and copy in the code.
<ul>
<li>
<b>ESP8266 Code</b>: - <a href="https://github.com/FlynnDerek/iotapp-device-library/blob/master/ESP8266/ESP8266_home_security_app.ino">https://github.com/FlynnDerek/iotapp-device-library/blob/master/ESP8266/ESP8266_home_security_app.ino</a>
</li>

<li>
<b>ESP32 Code</b>: - <a href="https://github.com/FlynnDerek/iotapp-device-library/blob/master/ESP32/ESP32_home_security_app.ino">https://github.com/FlynnDerek/iotapp-device-library/blob/master/ESP32/ESP32_home_security_app.ino</a>
</li>
</ul>

<b>Troubleshooting: </b><i>If your board wont connect, make sure that your Micro USB has Data I/O capability. Some Micro USB cables are for charging only. Generally, if the cable is thin, then you may have problems connecting the board. A thicker, high quality cable is recommended.</i>
<hr>

Paste in the code to a blank sketch. We just need to make 3 changes to the code:

<img src="https://i.imgur.com/ucSTjjw.png" alt="code1"/>
<ul><li><code>wifiName</code> - Your wifi network name</li>
<li><code>wifiPass</code>  - Your wifi password</li>
<li><code>YOUR_IOTAPP_CHANNEL_URL</code> - The URL you copied from your channel earlier. </li>
</ul>
<hr>

We can now upload the code. Click the little arrow button in the top left corner of the IDE. 
<img src="https://i.imgur.com/tEmIeh1.png" alt="upload_button"/>

<b>Note:</b><i> On ESP32 boards, you may need to hold down the "boot" button in order for the sketch to upload. The boot button is the tiny black button next to the USB connector on the board.</i>
 <img src="https://i.imgur.com/AeosGMV.jpg" alt="boot button"/>

###<b>Hardware Testing</b>###

After the sketch has finished compiling, open up the serial monitor in the IDE: <b>Tools -> Serial Monitor</b>. </p>

Pass Your hand over the PIR sensor bulb. Every time movement is detected in the sensor, a function called <code>pushToConsole()</code> is called. The function response will show up in the serial monitor. The function also pushes the data <code>"Movement Detected"</code> to the console via an HTTPS POST request.  

Return to the console and activate your channel by clicking the switch at the top. You should now see the incoming data being shown in the channel's readout section. Click on the <code>streamData()</code> function at the bottom. All incoming data will now be automatically saved to the iotapp Blockchain. 

<img src="https://i.imgur.com/wAhAEVq.gif" />

## <b>The Application</b> ##
<a href="https://security-dapp.surge.sh/">Demo</a>
Now that we have built, configured and integrated the hardware, we can now begin building the Dapp itself. To build the application, we are going to use Vue.js, Vue CLI and the <a href="https://www.npmjs.com/package/iotapp-api">iotapp API</a>.

We'll start by creating a new Vue app with the Vue CLI: 

```
vue create iotapp-security-dapp
```

I'd recommended you simply select the default options. (Just hit enter each time). Then, change directory to the new Vue app. 

```
cd iotapp-security-dapp
```

First, we'll start by installing the<a href="https://www.npmjs.com/package/iotapp-api"> Iotapp API package</a>.

```
npm i iotapp-api
```

Before we start coding, we'll need to get your channel's API key from the console. You can find it by clicking on the key symbol at the top-right corner of the console toolbar. 

<img src="https://i.imgur.com/Hco51zi.png" />

We're going to use the API functions to query the blockchain for your saved movement data. This is done by passing your API key into the function as an argument. 

For example, the API has a function called <code>getPrivateChain()</code>. Doing this will return all data that was saved under that channel key.

```javascript
iotapp.getPrivateChain("cCtRMrdvzMvghIBgnxeRE7LperQnfvLb");
```

### <b>The Code</b> ###

Open the project in your favorite code editor, mine is VS Code. For the sake of simplicity, Ill be writing the code in the <code>HelloWorld.vue</code> component. 

We'll start by importing the API. Then, we'll declare an array called <code>chainData</code> where we'll store the saved movement data. 

```javascript
import as iotapp from "iotapp-api";

export default {
data () {
    return {
      chainData: [],
    }
}, 
```

Then, in the mounted section, we'll call our first function, <code>getPrivateChain()</code>.

```javascript
 mounted() {
// Returns all movement history.
iotapp.getPrivateChain("YOUR_CHANNEL_API_KEY")
  .then(data => this.chainData = data)
  .catch(err => console.log("Error occurred:", err))
  },
}
```
First the response data is declared and passed to the <code>chainData</code> array. Then, we'll make a table to display it. 

```html
<template>
 <table>
        <thead>
              <tr>
                <th>Block Height</th>
                <th>Block Hash</th>
                <th>Previous Hash</th>
                <th>Timestamp</th>
                <th>Transactions</th>
              </tr>
         </thead>
            <tbody>
              <tr v-for="alias in chainData" :key="alias.index">
                <td>{{alias.index}}</td>
                <td>{{alias.hash}}</td>
                <td>{{alias.prevHash}}</td>
                <td>{{alias.timestamp}}</td>
                <td>{{alias.transactions[0][1]}}</td> <!-- Show just the data: [0][1][0] -->
              </tr>
            </tbody>
          </table>
</template>
```
In the table we'll use one of my favorite Vue features: the <code>v-for</code> loop. This will loop through each iteration of response data, and display each instance. We have 5 data points we can display: 

<ul><li><code>index</code> - This is the block number that the data was saved to.</li>
<li><code>hash</code>  - The block's hash value</li>
<li><code>prevHash</code> - The previous block's hash.</li>
<li><code>timestamp</code> - The time the transaction was made</li>
<li><code>transactions</code> - The transaction itself. Contains the signed API Key as well as the device data.</li>
</ul>

The API also contains other functions, check out the <a href="https://www.npmjs.com/package/iotapp-api">documentation here</a>. 

<code>getLatestTx()</code> - Returns the latest saved data for a given API key. In this case, it would return the most recent movement. Pass you channel API key(s) as an argument. 

<code>getPublicChain()</code> - Returns a full copy of the blockchain, minus the private transactions. Use this function for blockchain and node validation. 

### <b>Full Code</b> ###
<code>getLatestTx()</code><i> function code is included</i>

<b>HelloWorld.vue</b>
```
<template>
<div>
  <!-- Latest Movement Table -->
 <table>
        <thead>
              <tr>
                <th>Block Height</th>
                <th>Block Hash</th>
                <th>Previous Hash</th>
                <th>Timestamp</th>
                <th>Transactions</th>
              </tr>
         </thead>
            <tbody>
              <tr v-for="alias in latestData" id="tRow" :key="alias.index">
                <td>{{alias.index}}</td>
                <td>{{alias.hash}}</td>
                <td>{{alias.prevHash}}</td>
                <td>{{alias.timestamp}}</td>
                <td>{{alias.transactions[0][1][0]}}</td>
              </tr>
            </tbody>
          </table>

<!-- Movment History Table -->
 <table>
        <thead>
              <tr>
                <th>Block Height</th>
                <th>Block Hash</th>
                <th>Previous Hash</th>
                <th>Timestamp</th>
                <th>Transactions</th>
              </tr>
         </thead>
            <tbody>
              <tr v-for="alias in chainData" id="tRow" :key="alias.index">
                <td>{{alias.index}}</td>
                <td>{{alias.hash}}</td>
                <td>{{alias.prevHash}}</td>
                <td>{{alias.timestamp}}</td>
                <td>{{alias.transactions[0][1][0]}}</td>
              </tr>
            </tbody>
          </table>
</div>
</template>
<script>
import iotapp from "iotapp-api" //Linked NPM module

export default {
data () {
    return {
      chainData: [],
      latestData: []
    }
}, 

  mounted() {
//returns movement history
iotapp.getPrivateChain("YOUR_IOTAPP_APP_KEY(S)")
  .then(data => this.chainData = data)
  .catch(err => console.log("Error occurred:", err))
  
//returns latest movement
iotapp.getLatestTx("YOUR_IOTAPP_API_KEY(S)")
      .then(data => this.latestData = data)
      .catch(err => console.log("Error occurred:", err))
  }
}

</script>
```
Finally, serve the application.
```
npm run serve
```
<img src="https://i.imgur.com/eJX8oCB.png" />
First you'll be able to see the latest movement from the sensor displayed in the first table. Below you can see a history of all movements. 

You can clone the app repo <b><a href="https://github.com/FlynnDerek/iotapp-home-security-dapp">here</a></b>

<b><a href="https://security-dapp.surge.sh/">A demo also exists.</a></b>



## <b>Conclusion</b> ##
Thats a wrap folks! If you made it this far, congratulations!. By now maybe you've noticed that there's no need to configure a blockchain node. The API allows us the build a serverless application, with the web console taking responsibility for blockchain node validation. 

One of the main goals of the project was to make the connection between the device and the application as seamless as possible. By removing the need to spin up a server or a blockchain node, backend configuration has been greatly reduced. This is a concept I've dubbed <b>Blockchain-as-a-Backend</b>. Its a simple enough idea, being that the blockchain itself functions as an application's backend, and a simple API is used to query that backend via API keys. 

The motivation for this type of architecture was made from a desire to lessen the complexity that is often associated with decentralized app development. I believe this approach will allow the developer to focus more on the application itself while still storing data in a secure, immutable and decentralized manner. 

<hr>
More proof-of-concepts and tutorials are on the way! If you'd like to learn more about Iotapp, check out the <a href="https://iotapp.network/#/architecture">Docs</a>.

You can also connect with me on these platforms:

{% twitter 1291254894213713920 %}
###<b><a href="https://discord.gg/VGPwwYd">Discord</a> | <a href="https://github.com/FlynnDerek">Github</a> | <a href="https://www.linkedin.com/in/derek-flynn-a6954a17a/">Linkedin</a></b> ###