# How to monitor the home temperature using a sensor, Wifi, and Node-Red.
This tutorial is created by Hasan Ahmed (ha222tt).
This project aims to monitor the home temperature to receive an instant notification about serverly changes in home temperature via E-mail.
The following sections of the guide, describe the process and the material needed to achieve this goal.
## Objective
To reduce the consumption of the energy used by the radiator, we need a mechanism that can detect the changes in the temperature that helps to determine when to turn off the radiator and reduce the total cost of the energy.
## Material
In order to achieve this project the following material is needed to detect the changes in the temperature and send the changes to email address.
The following table shows the material required for the project.
|Item | Decription | Price |
|----|----|---|
|PyCom ExpansionBoard 3.1|Allow connecting varaity of microcontrollers and sensors|160|
|PyCom Lopy4|Provide different types of communications to the Expansionboard like Wifi, Bluetooth, SigFox, and LoRa |350|
|DHT11 Sensor|This sensor measures the temperature and humidity|7|
|Micro USB-cable|Allow connection between the board and the computer and provide power to the board|32|
|Electrical Wires|Allow connecting the sensor to the board|29|
The total cost is about ~600SEK. The images of the devices is listed below.
#### ExpansionBoard

#### PyCom Lopy4

#### Electrical Wires

#### DHT11 Sensor

## Computer setup
To achieve this project, Windows based computer is used. The version of Windows is 10. Due to the availability of the last firmware in LoPy4, no firmware flashing is executed to it.
In order to communicate and upload the code to the device, Visual Studio Code is used with Node.js.
### Development Environment
Visual Studio Code IDE is used to complete the project. The following pluging are also used to achieve the communication process.
- Pymakr. This is used to allow serial communication to the device using virtual serial port the the device creates when connecting via usb cable.
- Python. This extension is used to edit the micropython code with auto-completion, code navigation and syntax checking.
The version of Visual Studio Code used in this project is 1.46. Furthermore, Python 3.7 is installed on the computer to allow the features that are used in Python extension.
### Hardware Steps
The following steps are followed to connect all parts together.
- First, the LoPy4 is attached with the expansion board.
- The LoRa antenna is connected since it is recommended by Pycom.
- The DHT sensors is connected using the wires.
- Lastly, the USB cable is used to connect the ExpansionBoard to the computer.
#### ExpansionBoard with LoPy4

#### ExpansionBoard, LoPy4, and DHT11 Sensor

### Sofware Steps
The following steps are followed to prepare the environment to upload micropython code to the device.
- Node.js v12 is downloaded from https://nodejs.org/en/ and installed on the computer.
- Visual Studio Code is downloaded from https://code.visualstudio.com/ and installed on the computer.
- After installing and opening Visual Studio Code, the Python, Pymakr extensions are installed.
- At this step, the communication is done via serial port using the Pymakr extension.
### Platform
The aim of this project is to get a notification when the temperature is changed to a certian level. To do this, the Node-red is used to determine the range of the temperature. IBM cloud platform is used to host the Node-red application and this guarantees that the project is running after shutting down the computer. IBM Cloud platform provides free access which is suitable to this project. Other platforms could be use like using a virtual private server on a cloud company to host Node-red.
This project uses MQTT as a message protocol and Node-Red for determining if an email is needed to be sent based on the temperature received from the sensor.
#### Node-Red Installation
To install Node-red, the followin steps are followed:
- Create an account in IBM cloud platform
- Add Node-red app to the account
- Deploy the project
- Using the App link to access Node-red
### Code
The following code is used to get data from the sensor and send data to MQTT broker via MQTT protocol.
```+
import read_dht
import pycom
import json
import time
import _thread
import machine
import ubinascii
import hashlib
from mqtt import MQTTClient
with open('config.json') as f:
config = json.load(f)
def sub_cb(topic, msg):
return
def interval_send(t_):
while True:
send_value()
time.sleep(t_)
def send_value():
try:
dht_T = read_dht.value()
c.publish(topic_pub,'{"home": {"tmp":' + str(dht_T) + '}}')
print('Sensor data sent ..')
except (NameError, ValueError, TypeError):
print('Failed to send!')
topic_pub = 'hasan/home'
topic_sub = 'hasan/home/control'
broker_url = 'sjolab.lnu.se'
client_name = ubinascii.hexlify(hashlib.md5(machine.unique_id()).digest()) # create a md5 hash of the pycom WLAN mac
c = MQTTClient(client_name,broker_url,user=config['user_mqtt'],password=config['pass_mqtt'])
c.set_callback(sub_cb)
c.connect()
c.subscribe(topic_sub)
def listen_command(i_):
while True:
c.check_msg()
time.sleep(i_)
_thread.start_new_thread(interval_send,[10])
_thread.start_new_thread(listen_command,[0.1])
```
The following code is used to setup the Wifi connection.
```+
# boot.py -- run on boot-up
from network import WLAN
import machine
import json
wlan = WLAN(mode=WLAN.STA)
with open('config.json') as f:
config = json.load(f)
nets = wlan.scan()
for net in nets:
if net.ssid == config['ssid']:
print('Network found!')
wlan.connect(net.ssid, auth=(net.sec, config['ssid_pass']), timeout=5000)
while not wlan.isconnected():
machine.idle() # save power while waiting
print('WLAN connection succeeded!')
break
```
### Transmitting the data / connectivity
The devices is programmed to use threads that will trigger every 10 seonds. Once the thread is running, the program obtains the temperature from the sensor and sends the data via MQTT protocol.
Wifi is used in terms of the connectivity between the device and the internet. MQTT, on the other hand, publishes the messages that contain the temperature info to the broker using the topic /hasan/home. The LNU MQTT broker is used to complete this project.
The following image shows the runnging program

## Presenting the data
Since the project is an alarming system, the Node-red is used mainly to get the data from the broker and check if the temperature is high. After checking the temperature, Node-red will send a message if needed as we can see from the following image.

## Finalizing the design
The final result of this project is an email notification that is sent by Node-red. The sending process using Node-red to email via Gmail requires disabling the two factor authentication and allowing less secure apps to use the service.