Author: Anna Pawlukiewicz (ap223uu)
Introduction
===
This is a project created for the 1DT305 IoT Summer Course at Linnaeus University (2023).
For the theme I have reused a fairly popular idea in the course, the plant monitor. It seems to be a device that would be actually useful and interesting to possess, therefore it makes a neat project theme.
I haven't counted the time that I spent on the project in detail, however I am confident it would not be a lot. The materials provided by this course are very clear and simply by following the instructions, very satisfying results can be achieved.
Objective
===
I like plants, but it's a one way relationship. I figured a device that could help me take care of them would be useful. The objective of a plant monitor is to become the plant caretaker's assistant. It should display data regarding the environment that the plant lives in, so that the caretaker (me) can ensure that it's optimal.
There are many factors that influence the wellbeing of a plant. Among many, I decided to measure:
- soil moisture
- air temperature
- humidity
- sun exposure
This data should be measured with the help of proper hardware and then displayed for the plant owner to view.
Materials
===
| Name | Price | Link |
| ---- | ----- | ---- |
| Raspberry Pi Pico WH | 109 SEK | [Electrokit](https://www.electrokit.com/produkt/raspberry-pi-pico-wh/)
| M5Stack LoRa module 868MHz | 279 SEK | [Electrokit](https://www.electrokit.com/en/product/lnu-1dt305-addon-kit-2023/)
| DHT11 | 49 SEK | [Electrokit](https://www.electrokit.com/produkt/digital-temperatur-och-fuktsensor-dht11/)
| AZ-Delivery Capacitive Soil Moisture Sensor v1.2 | 58-68* SEK | [Amazon SE](https://www.amazon.se/-/en/dp/B07HJ6N1S4?ref=ppx_yo2ov_dt_b_product_details&th=1) <br /> [AZ-Delivery](https://www.az-delivery.de/en/collections/sensoren/products/bodenfeuchte-sensor-modul-v1-2)
| Jumper Wires | - | -
| Photoresistor | 39 SEK | [Electrokit](https://www.electrokit.com/produkt/ljussensor/)
| Breadboard | 69 SEK | [Electrokit](https://www.electrokit.com/produkt/kopplingsdack-840-anslutningar/)
*Price changes depending on order quantity.

Pi Pico could also be used instead, since connecting to the network is done via LoRa. I simply used the one I already have. There is no need for the microcontroller's Wi-FI capabilities.
If anyone is looking for more accurate measurements than DHT11 can provide, it can also be substituted with DHT22. Personally I find the ±2°C and ±5% readings for temperature and humidity accurate enough when it comes to plant environment.
Computer setup
===
The project was developed on a computer running Windows 10, computer setup may differ on different operating systems.
These the steps I followed for setting up the development environment:
1. Install preferred IDE.
In my case, I used VS Code. Some other options are Atom or Thonny.
3. Install Node.js. (only for VS Code or Atom users)
4. Install Pymakr. (only for VS Code or Atom users)
For VS Code, search for it in the extensions manager.
For Atom, go into settings and search for it in the install packages section.
4. Update firmware on the microcontroller.
You should also run some test code to ensure that it works. A simple print('Hello World') in the console will do.
Server should have Docker installed. Since I am running the server on my computer, I used Docker Desktop. Docker will use the images of Telegraf, Influxdb and Grafana. Unless using the compose script provided [here](https://github.com/iot-lnu/tig-stack), please make sure the images are pulled.
While this is not computer setup strictly, I would recommend setting up The Things Network account and application also before starting the development process.
Circuit diagram
===

In reality the positioning of elements on the breadboard differs slightly (DHT11 mirrors the photoresistor's placement, however that would make the diagram difficult to read), the diagram is meant to clearly represent the connections instead.
Platform
===
Data is collected with the help of **The Things Network**.
As for the visualization platform, I settled for the **TIG-stack** data visualization route. This means that I am self-hosting a server running these components:
- Telegraf, which connects to and collects the data from TTN, sends it to the database. Data is collected from MQTT broker.
- InfluxDB, which stores the data received from Telegraf.
- Grafana, which visualizes the data from the database.
Diagram below portrays the journey of the sensored data through mentioned services.

Code
===
:::info
Contents of the LoRaWAN file referred to in main.py can be found [here](https://github.com/iot-lnu/applied-iot/blob/master/Raspberry%20Pi%20Pico%20(W)%20Micropython/network-examples/N4_LoRaWAN_Connection/LoRaWAN.py).
:::
The code can be separated into parts:
#### 1. Declaring constants
While developing, I needed to calibrate the sensors (the soil moisture and photoresistor) I did that by exposing them to extremes and noting down the minimal and maximal values that they returned. For example, the lowest the soil moisture sensor got while dipped in a water glass was around 12000. This value later on became the WET constant.
This is also where keys for connecting to TTN are placed. (lines 15-17)
#### 2. Setup devices
All sensors are assigned variable names and lora object is created, and assigned keys mentioned before.
#### 3. Connection
Before getting to measuring, a connection to the network must be established. Code will not proceed further if there is no successful connection to TTN.
#### 4. Measuring-Sending Loop
The rest of the code is an infinite loop that repeatedly collects sensors' measurements, packs them into payload and sends it over to TTN.
The read delay value that I settled for is 60 seconds, which means that data is measured and uploaded once every minute.
### main.py
```python=
import struct
import binascii
import dht
import machine
import time
from LoRaWAN import lora
# Constants
WET = 12000
DRY = 43930
BRIGHT = 0
DARK = 7000
READ_DELAY = 60 # delay between readings
DEV_EUI = "XXXXXXXXXXXXXXXX"
APP_EUI = "YYYYYYYYYYYYYYYY"
APP_KEY = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
# Pin setup
soil_sensor = machine.ADC(machine.Pin(28))
photoresistor = machine.ADC(machine.Pin(27))
temp_sensor = dht.DHT11(machine.Pin(26))
# Lora setup
lora = lora()
lora.configure(DEV_EUI, APP_EUI, APP_KEY)
lora.startJoin()
while not lora.checkJoinStatus():
time.sleep(1)
while True:
# Measuring soil moisture & converting to percentage
sensor_val = soil_sensor.read_u16()
moisture = int((DRY - sensor_val) * 100 / (DRY - WET) * 10)
# Measuring DHT11 values
temp_sensor.measure()
temperature = int(temp_sensor.temperature())
humidity = int(temp_sensor.humidity())
# Measuring light level
light = photoresistor.read_u16()
light = int((100 - round(light / DARK * 100, 1)) * 10)
# Payload
payload = struct.pack(">hHhH", temperature, humidity, moisture, light)
payload = binascii.hexlify(payload).decode("utf-8")
lora.sendMsg(payload)
time.sleep(READ_DELAY)
```
As seen, the code is actually very simple. It does its job just fine, there is no need to overcomplicate things. :)
Connectivity
===
For this project I settled on using LoRaWAN technology with The Things Network.
A LoRaWAN module enables both utility and efficiency by providing long range wireless communication combined with low power consumption, which makes it a very attractive component to include in any project requiring connectivity.
The downside is that connectivity to platforms allowing to utilize this module (such as Helium or TTN) is not yet provided in all locations. Luckily in my case, I can reach TTN from my home, therefore I could use LoRa in this project. For comparison, I was unable to connect to Helium from my location.
LoRa transmits measured data to the TTN server, which receives and processes it, making it ready for the next step - processing it.
Presenting the data
===
Data is presented with help of earlier mentioned TIG-stack.
It is first collected from The Things Network MQTT broker via Telegraf, then sent to InfluxDB time-series database. This process ensures efficient data collection and smooth transmission.
The data is stored permanently in the local influxdb database. Grafana can access it and display in the form of user-friendly dashboards, which can be composed according to one's liking. As seen on the picture below, I opted for displaying each measured parameter in two forms: easily readable latest reading with a gauge for scale and measurement history as a graph. Grafana is accessible to the user via browser.

Final design (and thoughts)
===


I had a couple comments and ideas during the development and after finishing it. Among those are:
#### Casing
Personally I often pay attention to the aesthetic side of most things. I think that a casing would be a great addition to this. Preferrably 3D printer, however I have neither the printer nor experience with one. Another reason for not making one is because I imagined, that I would remake this project while using materials that would take less space, these seem to more fit for a training kit (which it basically is). I also imagine that would possibly include some soldering. Basically, the casing would be a whole different project on its own.
#### Portable power source
Another neat improvement that I considered is a battery. As of right now, the power source is a wall outlet. Adding a battery would be simple and a great improvement.
#### Visualization on mobile
While it's useful and handy the way it is now, it would be even better if I could view the data from my phone. Potentially I would like to make a small mobile app to visualize the data rather than using Grafana for that. That would also mean altering the local server/network structure, since as of now the whole TIG-stack is simply run on localhost.
#### Server hosting
As mentioned, the TIG-stack is currently run on my computer whenever I need it. Without it in the background the data cannot be viewed, it is not even being stored. I came up with two solutions for this:
1. Host TIG-stack services on a dedicated server. If I am ever in possession of both time and money, and for some reason expand my entire house with IoT projects everywhere (Actually sounds possible and fun, but I don't have a house and am a full time student which means neither time nor money.) - I would maybe use Raspberry Pi for this.
2. Use something else instead of TIG-stack for visualization. Maybe Adafruit or Datacake. This is what I will likely do after the course is over, since I actually like the plant monitor in the end, but I'm not very keen on the idea of running the TIG-stack in the background at all times.
#### Machine learning
I recently took an introduction to machine learning course. I can imagine how I could put some basic concepts from that course to use with a project such as this one. I could possibly input plant's health once per day and eventually have the app learn to associate particular measurement values with plant's health.
Then I imagine that I would get a notification with something along the lines of "Hey, usually the plant's sick at these values, you sure you don't wanna water it?" or like "I know you can survive without sun for a week, but your plant can't."
#### Future
As can be seen by this needlessly long final section, I am open to potential future projects in the IoT field. I find it both entertaining and useful. 10/10 would do it again :+1: