# Presenting the temperature, humidity and moisture of my greenhouse in a cloud service
ver. 1.01 - added picture of the gateway and added link to presentation - See bottom of doc.
Kalle Friberg, km222tv
The project is about learning hands-on, how to build an end-to-end Internet of Things solution.
In short, I have built a device with the Pycom LoPy4 microcontroller and two sensors for measuring the temperature, humidity and moisture in my greenhouse.
The next part was to connect the device via WiFi to Pycom Pybytes, then integrate from there to Datacake, to display the data in a dashboard and triggering alerts when values exceed predefined thresholds.
Finally, I bought and set up a Pycom Pygate LoRaWAN gateway, to be able to connect the sensor device to The Things Stack (TTS), from which I set up a new integration to Datacake.
![](https://i.imgur.com/vvUZA3P.png)
Fig. 1. Overview of the project’s alternative networks for transmitting sensor data to Datacake; over WiFi to Pybytes, and via the LoRaWAN gateway to The Things Stack.
All things which are needed are explained in detail in this tutorial.
The time needed to replicate the project is roughly estimated to:
* Set up the development environment on the computer and assemble the device: 2 h
* Code and connect via WiFi to Pybytes (code available on GitHub): 1-2 h
* Integrate to Datacake from Pybytes, build dashboard and create a mail trigger: 1-2 h
* Set up, and program, my own Pygate LoRaWAN gateway (see GitHub): 1-2 h
* Code and connect via LoRaWAN to The Things Stack (see GitHub): 1-2 h
* Integrate to Datacake from TTS and build a dashboard: 1 h
A comment on the Pygate is that you should first try to connect to LoRaWAN (The Things Stack or Helium) first, and only buy your own gateway if you need it.
## Objective
As part of the summer course at Linnaeus University, 1DT305 - Applied Internet of Things, I chose to build a device using the recommended LoPy4 microcontroller from Pycom, to read and send multiple sensor data streams and present the data in the Datacake cloud service.
The purpose was to understand Internet of Things from end to end, by building an IoT solution to keep track of my greenhouse environment, and use this knowledge to build more IoT solutions for my house.
I aim to give me and others the experience and insights on both which areas are necessary for building a complete solution, which different alternatives are available for each area, and which of these I would like to focus on in the future:
- Sensors and device logic for different use cases,
- Choice of network/s and how to connect, or
- Platforms for storage, visualisation and alerts
## Material
In this project I have chosen to work with the Pycom LoPy4 microcontroller.
![LoPy!](https://i.imgur.com/jCUp2Vx.png)
Fig. 2. LoPy4, without the expansion board. Pycom.io
The LoPy4 is the "brain", which you can program and connect to networks, using external or built-in antennas, while the expansion board is used to connect to the sensors, using wires for voltage and data.
For the second part, I have bought a Pycom Pygate for use as my own LoRaWAN gateway, connected to The Things Stack.
You should first try to connect to The Things Stack or Helium first, and only buy your own gateway if you need it.
To build the device, I am using two sensors:
#### Temperature and humidity sensor
From the documentation ([Link to PDF](https://www.electrokit.com/uploads/productfile/41015/41015728_-_Digital_Temperature_Humidity_Sensor.pdf)):
>The DHT-11 Temperature and humidity sensor provides a digital serial interface to measure humidity and temperature.
#### Soil Moisture Sensor
From the documentation ([Link to PDF](https://www.electrokit.com/uploads/productfile/41015/41015738_-_Soil_Moisture_Sensor.pdf)):
>The FC-28 Soil Moisture Sensor will measure the humidity in the soil. It works by measuring the resistance across the two legs and convert it to a voltage that can be read by a microcontroller.
Please see below, in the 'Putting everything together' section, how the items are connected.
### List of material
| IoT Thing | Cost | Where to buy |
| --------- | ---------------- | -- |
| LoPy4 bundle, incl. Pycom expansion board, LoRa antennae, breadboard, USB cable, LEDs, resistors, wiring, etc. | ~1000 SEK | electrokit.com |
| Sensor kit 25 modules (optional) | 325 SEK | electrokit.com |
| Pygate, incl. WiPy, Ethernet module, case and antennae (optional) | ~1600 SEK incl. customs | pycom.io |
## Computer setup
In order for the LoPy4 to read data from your sensors and send them to the server of choice, you need to be able to program it with MicroPython. By following the following steps, you should have the development environment in place to program your device.
### Update the Pycom firmware
It is both good practice to ensure that the firmware is updated with the latest version, to avoid spending time on already fixed bugs, and ensuring the microcontroller has the libraries needed.
1. Start by plugging the LoPy4 board into a Pycom Expansion board and connecting it to your computer with a Data USB cable.
![](https://i.imgur.com/qLHZNb3.png)
Fig. 3. LoPy4 mounted on the Pycom Expansion board and a Data USB cable.
2. Download the Pycom Firmware Updater from https://pycom.io/downloads and follow the instructions when installing it on your computer.
3. When installed, start the Pycom Firmware Update app. In the Communication step, the app should have found the port connected to the device, e.g., COM3. Check the 'Show Advanced Settings' before clicking Continue.
4. In the Advanced Settings step, check the 'Erase during update' option so old files and configurations on the LoPy4 don't interupt your work going forward. Then choose Continue.
![](https://i.imgur.com/Qt7hIqo.png)
Fig. 4. Check the 'Erase during update' option.
5. Wait while the app is upgrading, until it displays 'Result', then copy the unique 'Device ID' for use later.
You should now have ensured the LoPy4 has the latest firmware version.
### Installing VS Code as IDE
As IDE I have chosen Microsoft VS Code, because I have used it before and because of the extension support for working with Azure, which I think I will use for my IoT devices in the future.
1. Download from https://code.visualstudio.com/Download.
2. Start the Installer, accept the agreement and click Next until you reach the 'Ready to Install' page, where you click Install and wait for it to finish.
### Installing Node.js
To use the Pymakr extension in VS Code, you need node.js installed on your computer, and it's recommended that you do this first.
1. Download the Long-Term Support version of Node.js from https://nodejs.org/en/
2. Start the installation (Setup Wizard) and click Next until you reach the 'Ready to Install' page, where you click Install and wait for it to finish.
### Installing the Pymakr VSCode Extension
Pycom supports Microsoft’s Visual Studio Code IDE platform with the Pymakr extension, as mentioned [on their site](https://docs.pycom.io/gettingstarted/software/vscode/):
> Pymakr enables you to communicate to your Pycom board using the build in command line REPL. The Pymakr Plugin adds a REPL console to the terminal within VS Code, that connects to your Pycom board.
1. Open VS Code and go to the Extensions tab.
2. Search for, and install, Pymakr.
![](https://i.imgur.com/dMr86OJ.png)
Fig. 5. Install the Pycom Pymakr extension in VS Code, after installing Node.js.
Now everything you need is in place for you to start writing and uploading programs to the device.
### Test the device
Before you write and upload your own program to the LoPy4, you can test the device by trying out the 'RGB LED' code from [this link at Pycom](https://docs.pycom.io/tutorials/basic/rgbled/):
```python=
import pycom
import time
pycom.heartbeat(False)
for cycles in range(10): # stop after 10 cycles
pycom.rgbled(0x007f00) # green
time.sleep(5)
pycom.rgbled(0x7f7f00) # yellow
time.sleep(1.5)
pycom.rgbled(0x7f0000) # red
time.sleep(4)
```
1. Connect the Data USB cable to your computer.
2. Open the Command Prompt on your computer and create a folder on your computer (mkdir) and change into that folder (cd), in my example C:\repos\pymakr\rgb.
3. Write "code ." and press Enter, to open VS Code in that folder. This assumes you have added VS Code to the PATH.
![](https://i.imgur.com/J5iGuKL.png)
Fig. 6. Create a folder and open VS Code in that folder, using Command Prompt.
4. In VS Code, ensure that the Pymakr extension loads the Pymakr Console, and that the device is connected to a COM port.
![](https://i.imgur.com/IFHaJqm.png)
Fig. 7. VS Code with Pymakr Console loaded and COM3 connected, displaying the REPL '>>>'.
5. Click on 'Download' in the status bar, and **answer 'Yes' in top of VS Code** to create two empty files in the RGB folder:
-- boot.py
-- main.py
These files were created when you updated the Pycom firmware with the 'Erase during update' option.
Note: If you get an error in the Pymakr Console, e.g., *"Download failed.: timeout Please reboot your device manually."*, remove and attach the USB cable, and try again.
6. Paste in the code from above in main.py, and don't forget to save it!
7. In the status bar, this time click on 'Upload', to write the updated files back to the LoPy4.
The program should automatically start and you should see the light on the microcontroller change colour between green, yellow and red.
8. After a while, the program will stop, and the red colour is turned on permanently, since that is the last colour in the loop.
## Putting everything together
Since the project includes two sensors; a Humidity & temperature sensor (DHT11), and a Soil moisture sensor (FC-28), I have used a breadboard, which '+' and '–' rows are connected to the 3V3 (power) and the GND (ground), respectively.
In the circuit diagram below, the power wires (red), the ground wires (purple) and the data wires (yellow) are visible.
![](https://i.imgur.com/fA3nlPT.png)
Fig. 8. Circuit diagram using Fritzing.
1. For each sensor, connect the power pin to the + row, and the ground pin to the – row, on the breadboard.
2. Connect pin P15 on the Pycom to 'A0' on the sensor, to get the data from the Soil Moisture.
3. Connect pin P23 on the Pycom to the left-most pin on the sensor, to get the data from the DHT.
4. Finally, connect the 3V3 (current) to the lower '+' row on the breadboard, and the GND (ground) to the '–' row.
I have not done electrical calculations or used resistors, because this solution is only for a development setup, and both sensors already have built-in resistors and do not require separate ones, looking at the specifications:
- DHT11, for temperature and humidity ([Link to PDF](https://www.electrokit.com/uploads/productfile/41015/41015728_-_Digital_Temperature_Humidity_Sensor.pdf))
- Moisture sensor, for moisture level in soil ([Link to PDF](https://www.electrokit.com/uploads/productfile/41015/41015738_-_Soil_Moisture_Sensor.pdf))
## Platform
In this project I have successfully set up two routes:
* Connection via WiFi to Pybytes, and an integration to Datacake.
* Connection using LoRa and my own LoRaWAN gateway connected to The Things Stack, and a second integration to Datacake.
In the following sections, I will go through how these are set up and discuss them.
### Connect to Pybytes via WiFi
First off is the connection to Pybytes using the microcontroller's WiFi functionality.
Programming the LoPy4 to connect to your WiFi, and send sensor data to Pybytes, is relatively easy, but Pybytes has limited support to store and visualise the data.
Another drawback from selecting Pybytes to connect your devices is the lack of an efficient support for scaling your solution, e.g., if you want to deploy hundreds of devices there will be much manual work.
However, Pybytes supports integrations directly to several known IoT solutions, e.g., Microsoft Azure, and using webhooks to whichever endpoint you want, in this project - Datacake, as described below.
#### How to connect via WiFi to Pybytes
Follow these steps to be able to send data to Pybytes over your WiFi.
1. Create an account with [Pybytes](https://pybytes.pycom.io/devices) and login.
![](https://i.imgur.com/PGGHTpU.png)
Fig. 9. Pybytes landing page after logging in.
2. Add your WiFi credentials to Pybytes using 'Configure Networks'.
![](https://i.imgur.com/S7yOrSf.png)
Fig. 10. WiFi credentials are needed for the configuration file created in step 5.
3. Choose 'Add device' and select the WiFi option.
![](https://i.imgur.com/lpXG2gx.png)
Fig. 11. After adding the the device, copy the Activation Token from the 'Provisioning' / 'Offline Firmware Updater' tab.
If you do this later, i.e. if the device is already added in Pybytes, you can use the 'Generate New Activation Token' button and copy that.
4. Connect the device to your computer using a Data USB cable.
5. Run the Pycom Firmware Updater app, but this time you should check both 'Force update Pybytes registration' and 'Enable Pybytes / SmartConfig support' options, in the Communication step.
![](https://i.imgur.com/m148tjV.png)
Fig. 12. Check both options below the 'Pybytes' dropdown.
6. In the Pybytes registration step, enter the Activation Token copied earlier, and click 'Continue' to finish the update of the LoPy4.
![](https://i.imgur.com/8dchlL2.png)
Fig. 13. Paste the Activation Token from step 3.
Now, you should successfully have registered your device in Pybytes and created a configuration file (pybytes_config.json), to connect via WiFi to Pybytes, on the device.
#### Try out the connection to Pybytes
Next, open VS Code in an empty folder, and download the created files from the device:
1. Connect the device to your computer using a Data USB cable.
2. Create a new folder using the Command prompt and change into that folder, e.g., C:\repos\pymakr\pybytes
3. Write "code ." to start VS Code in that folder.
4. Ensure Pymakr Console is starting and the connection is working, then click on 'Download' and answer 'Yes' to download the files into the folder:
![](https://i.imgur.com/jjTAlEU.png)
Fig. 14. When having downloaded the files to your computer, you should see in the Pymakr Console that the device tries to automatically connect to Pybytes via your Wifi.
#### Upload the code to read and send sensor data
Now that you have tested that the device can connect to Pybytes, it's time to upload the code for sending the actual sensor data.
1. Configure the device with the sensors as described in the 'Putting everything together' section, and attach the Data USB cable.
2. Use the code available in [the repository](https://github.com/km222tv/Applied-Internet-of-Things/tree/main/pybytes), for the two sensors, DHT and Moisture sensor, and add the files to the 'pybytes' folder:
* lib/dht.py (place the dht.py file in a folder called 'lib')
* main.py (replace the empty file from previous section)
* boot.py (empty, unchanged from previous section)
* pybytes_config.json (unchanged from previous section)
3. Be sure to save the files and click 'Upload' in the status bar in VS Code. The device should automatically connect, and run the program.
4. Go to Pybytes to see the result, which should be showing three signals:
-- 1 = Temperature from DHT
-- 2 = Humidity from DHT
-- 3 = Soil moisture from the Moisture sensor.
![](https://i.imgur.com/nBwQaaR.png)
Fig. 15. You should now see three signals showing up in Pybytes; temperature, humidity and moisture.
As the storage and the presentation of data are limited, we need to integrate Pybytes to a better IoT solution platform for storing long time series and present it, in this development project - to Datacake.
### Integrate to Datacake
This section explains how to set up Datacake for integration from Pybytes, and display the three signals, originating from the device.
Datacake has an [overview guide](https://docs.datacake.de/integrations/webhook) for integrating, but for the project you can follow these steps:
1. Create an account with Datacake and login.
2. Add a new device, and in step 1 (Product), choose API -> New product from template -> Pycom Pybytes base template.
3. In step 2 (Devices), add the Device token (GUID) which shown under the name of the device in Pybytes, in the 'Serial number' field in Datacake.
![](https://i.imgur.com/O9Makyh.jpg)
Fig. 16. Use the device token from Pybytes when adding a device in Datacake.
4. In step 3 (Plan), choose Free, and click on 'Add 1 device'.
5. When the API has been created in Datacake, go to the device's API configuration page and **copy** the 'HTTP Endpoint URL'.
6. Go back to Pybytes and create a new Webhook integration the Integration section.
7. In the 'URL' field, **paste** the HTTP Endpoint URL from Datacake.
![](https://i.imgur.com/Y0GPKgE.png)
Fig. 17. There is a known error in Pybytes, which strips the URL so the last forward slash "/" is removed when saving. To resolve this, add "/ignore" in the end of it before saving.
8. Choose a 'Webhook Event Name' and, **in the bottom of the page**, check the checkbox of your device before clicking on Create.
The integration to Datacake should now be successfully created, and you can run your device to see the data received in Datacake.
![](https://i.imgur.com/dQdKTAj.png)
Fig. 18. With some tweeking, you can easily confgure your own dashboard in Datacake.
### My own LoRa gateway
The second part of the tutorial is about LoRa, and since I can't currently reach any public gateway to connect via LoRaWAN to The Things Stack, I have bought and assembled my own Pycom Pygate.
It's of course a bit expensive, but once you have it, there are some benefits:
* The connection to The Things Stack is very fast
* The so called 'Spread factor' should be in the very low end (7) as it is close, which saves battery on the devices you have in or around your house.
#### Setting the Pygate up
When I ordered Pygate from Pycom, it arrives in 4-5 pieces, which should be assembled:
* The Pygate itself, which is a type of expansion board.
* A microcontroller, I chose the least expensive - WiPy 3.0 with headers, which you attach to the Pygate board.
* A LoRa (868MHz/915MHz) & Sigfox Antenna Kit.
* A Pygate case, to assemble everything in.
* And, optionally, a Power over Ethernet Adapter module, if you want to use an Ethernet wire instead of WiFi.
When assembled, follow these steps:
1. Run the Pycom Firmware Updater to reset the microcontroller on your Pygate, and to create the files boot.py and main.py on the device. In the 'Communication' step, choose "Pygate" instead of "Pybytes" in the dropdown. And in Advanced Settings, check 'Erase during update'.
In the last screen, copy the Device ID, e.g., "2462ACF4E3BC".
![](https://i.imgur.com/x1b1TKc.png)
Fig. 19. Copy the Device ID.
2. Go to The Things Stack, and register your Pygate under Gateways, and in the setting 'Device EUI' enter the first 6 + '**FFFE**' + last 6 of the Device ID copied in the previous step, e.g., "2462AC**FFFE**F4E3BC".
You can read more about the Gateway EUI [here](https://www.thethingsindustries.com/docs/reference/glossary/#gateway-eui).
3. With Atom or VS Code with the Pymakr extension, download the files which were created by the firmware updater on the device; boot.py and main.py, to an empty, local folder on your computer.
4. From [the repository](https://github.com/km222tv/Applied-Internet-of-Things/tree/main/pygate_gw), add the config.json file and replace the main.py file.
5. Change the "Gateway_ID" in config.json to you own value, e.g., "2462AC**FFFE**F4E3BC", and - if you use WiFi - enter the SSID and password in the main.py file, save the files and upload to the device.
The code should run automatically, and if 'Live data' is successfully showing up for the gateway in The Things Stack, you can now move your Pygate to any USB-C cable to start it up.
![](https://i.imgur.com/NXWvaoS.png)
Fig 20. Live data showing up in TTS when the gateway runs the code you uploaded.
As a comment, I did once get stuck when trying to connect to the Pygate, so the Pymakr Console never could display the '>>>' for the device to receive commands, despite removing and plugging in the USB-C cable.
To resolve this, I closed the IDE and started the Pycom Firmware Updater to update the Pygate again. In the Advanced step I checked both Erase and the two RESET checkboxes, which solved the connection problen so I could upload the files.
### Connect to The Things Stack via LoRaWAN
To be able to forward the data packets from the gateway to Datacake, you need to create an application and an 'End device' in The Things Stack (TTS), which represents your sensor device.
Alternatively, when using LoRaWAN, you could connect to Helium instead of TTS, but the cost-free TTS is easier to set up and enough for my purposes, with lower requirements for e.g., security.
Follow these steps to program your sensor device with the LoPy4 for use with LoRa to connect to The Things Stack:
:::warning
Please note, before you program your device to use LoRa, to remember to attach the LoRa antennae. Without having it attached you might brake the microcontroller.
:::
1. Run the Pycom Firmware Updater to reset the microcontroller (e.g., LoPy4) and to create the files boot.py and main.py on the device. In the 'Communication' step, do not check the Pybytes checkboxes, but in the Advanced Settings, check 'Erase during update' and in the last screen, copy the 'LoRa MAC', e.g., "70B3D5400412CFBC"
3. In The Things Stack, create an application, e.g., "greenhouse", with a descriptive name.
4. Register an end device and choose the 'Manually' tab, 'Over the air activation (OTAA)' and 'MAC v1.0.2' LoRaWAN version.
5. In step 1 (Basic), enter an ID, e.g., "sensor-device", App EUI (can be just zeros), the Dev EUI using the LoRa MAC from when you updated the firmware above.
6. In step 2 (Network), use the recommended 'Frequency plan' and the REV A as 'Regional parameters version'.
7. In step 3 (Join), generate a new 'App Key', and click 'Add end device'.
8. When registered, copy the 'App Key' from the 'Overview' tab.
9. With Atom or VS Code with the Pymakr extension, download the files which were created on the device; boot.py and main.py, to an empty, local folder on your computer.
10. From [the repository](https://github.com/km222tv/Applied-Internet-of-Things/tree/main/lorawan), **add** the lib/dht.py and **replace** both the boot.py and main.py files.
11. Use the 'App Key' from earlier and paste it into the boot.py file, and save the files.
12. **After having ensured the antennae is correctly attached**, upload the code for the LoPy4 to the device and test that it sends data to The Things Stack.
![](https://i.imgur.com/XpYZ4MJ.png)
Fig. 21. Live data from the sensor device showing up in The Things Stack.
### Integrate to Datacake, again
To present the data in Datacake using LoRa and The Things Stack (TTS), you need to create a new integration to Datacake.
As long as you keep the devices in Datacake to two, it's free.
Follow these steps:
1. Login to Datacake, where you should create your second device with the Device EUI from previous section.
2. When created, go to the Configuration tab and add the following 3 fields:
![](https://i.imgur.com/LxB83zH.png)
Fig. 22. Add Temperature, Humidity and Moisture as fields in the Datacake device configuration tab.
3. Add the Decoder javascript code from the [GitHub repository](https://github.com/km222tv/Applied-Internet-of-Things/datacake_decoder), into the Payload decoder section, on the same tab.
Note, that the field identifiers, e.g., "MOISTURE" in previous step correspond to the field names in the 'Payload decoder' javascript.
5. Before going to TTS to set up the integration, you need to create an API token in Datacake, which you do on under the 'Members' menu and 'API Users' tab. Be sure to check 'Devices' and under Permissions: 'Can record measurements'! Then copy the API token.
6. In TTS, go to the 'Integrations'/'Webhooks' menu and add a new Webhook of the type 'Datacake'. Fill in a Webhook ID, e.g., "datacake-webhook" and paste in the API token from previous step.
Now, all sensor data should be forwarded to Datacake.
6. As before, when integrating from Pybytes, you can now set up your dashboard for displaying what the three sensors are reading.
## The code
All code is found in my [GitHub repository](https://github.com/km222tv/Applied-Internet-of-Things).
Instructions on how it should be used are found in the [readme.md file](https://github.com/km222tv/Applied-Internet-of-Things/blob/main/README.md).
## Transmitting the data / connectivity
In the sections above, there are detailed step-by-step descriptions for how to transmit both via WiFi to Pybytes and using a webhook to integrate to Datacake, and via LoRaWAN using my own gateway connected to The Things Stack and integrating to Datacake, also with a webhook.
Regarding transmitting data, there is no need to send more often than how much you want to keep in the database. In development, I have chosen once a minute, but in production there is no need to send more often than once per hour, or even less.
As seen in the code, currently the only way of controlling how often data is sent, is the delay in each loop:
```python=
time.sleep(3600)
```
The chosen delay has consequences both for how much data needs to be stored, but also for the battery consumption. So, if your application doesn't need to have data for every minute, then every hour might be enough, which would also save batteries.
### Suggested changes for better logic in the end device
But, to both be able to store as little as is needed AND also be alerted when something happens, I would opt for having two loops when programming the LoPy4:
* One loop which is iterating e.g., every hour, to send the latest or the average value.
* One loop inside which runs every ten minutes, or so, to read the sensor values and breaks the inner loop when values exceeding predefined boundaries, so they can be sent immediately.
This is not implemented, but the non-tested code for this would be to add an inner 'while' loop and two lines of code to break the inner loop if the moisture shows that the soil is too dry.
The two changes of the main.py file in the lorawan folder are commented below with CAPITAL letters:
```python=
while True:
# INNER LOOP START, MAX 6 TIMES (1 hour)
for inner_loop in range(6):
# Get the temp and humidity from the DHT sensor
result = humid_temp_sensor(DHT_PIN)
temperature = (result[0] * 100) # Needs to be divided by 100 when displaying
humidity = result[1]
# Get the moisture from the moisture sensor
result = moist_sensor(ADC_PIN) # Grabs the sensor value
moisture = ((result / 4096) * 100) # Moisture = 100 % would be completely dry
check_plant(moisture) # Check plant reading and display information
#Prints all sensor values
print('Moisture: ' + str(moisture))
print('Temperature:' + str(temperature/100))
print('Humidity: ' + str(humidity))
# ADDED LOGIC START
# Break inner loop if soil is too dry, to transmit immediately
if moisture > 70:
BREAK
# ADDED LOGIC END
# INNER LOOP DELAY 10 MINUTES
time.sleep(600)
# INNER LOOP END
# Sends the values in a structure
package = struct.pack('>Bhh', int(humidity), int(temperature), int(moisture))
# LoRa socket
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
s.setblocking(False)
s.send(package)
# OUTER LOOP DELAY IS NOT NEEDED
# time.sleep(3600)
```
### Battery life and choice of communication
In my project, I am using both WiFi and LoRa. The main pros and cons are these:
| | WiFi | LoRa |
| - | - | - |
| Pros | High data rate | Long range and Low battery consumption|
| Cons | Short range and High battery consumption | Low data rate |
Since the project is only using small amounts of data, and the need for sending the data is not continuous, the primary choice is LoRa, as it has also a low battery consumption.
But, it could be useful to program a fallback to WiFi in your device, when the LoRaWAN network is (temporarily) not available. Especially if the device is in range of your WiFi router and powered by a solar charger.
## Presenting the data
In the project, I have chosen to use the cloud service Datacake. One of the reasons for this is the easy way of creating a dashbord with widgets to present the data as diagrams, numbers, etc.
In this development project I needed two devices in Datacake, one for showing data via Pybytes and one via The Things Stack, and - as it happens - Datacake offers two devices for free. This gives you 500 Datapoints / Day
and 1 Weeks Data Retention (https://datacake.co/pricing). Otherwise you pay 1€ per month and device, having the possibility to export raw data. To keep your data longer, the price also goes up.
As mentioned earlier, you can set up integrations from both Pybytes and The Things Stack to e.g., Microsoft Azure's IoT Hub, where the possibilities are very extensive, and this is probably a good alternative, although more complicated than Datacake, for a production environment.
To introduce you to Datacake, I recommend watching this 5 minute video by Simon Kemper from Datacake "An overview of Data Storage options in the Datacake IoT Platform". https://www.youtube.com/watch?v=ysBGCc6RGGI
### Create a dashboard in Datacake
Try the different widgets out, available in Datacake, and configure them for the signals received from Pybytes.
![](https://i.imgur.com/YcAemph.png)
Fig. 23. This is my dashboard in Datacake, displaying the sensor data.
By clicking in the top right corner of the dashboard, it goes into editing mode, and you can edit and add from a large variety of widgets for different ways of presenting the data.
Using Datacake simplyfies storage too, as the data sent to the service is automatically stored in the fields you define, in this project; Temperature, Humidity and Moisture.
Also, this means that every time the data is successfully transmitted, it will be stored. See above for discussion in the "Transmitting the data / connectivity" secion, about the chosen frequency of sending data.
### Create a rule in Datacake
The last piece is setting up a rule which sends an email triggered by the soil being too dry.
Follow these steps:
1. Go to the Rules section of Datacake and create a new rule.
2. Add a name, conditions and (in this case) what should be included in the mail.
![](https://i.imgur.com/7RxeLNL.png)
Fig. 24. A rule in Datacake which is triggered when the moisture of the soil is over the value of 3000.
NOTE: 'Hysteresis' means that the measurement must come below that value (in this case 2800) in order for the rule to be triggered a second time.
3. Take the moisture sensor out of the soil to fake a very dry value, and see if you get an email.
![](https://i.imgur.com/F4WO0cm.png)
Fig. 25. An email received from Datacake when my "soil" was too dry.
## Finalizing the design
For the IoT solution to work with low power consumption over time, LoRa is preferable to WiFi, and using The Things Stack works very well to forward packages to your platform of choice.
In this development setup, the two free devices work fine using Datacake, and as it's a reasonable fee for a production environment, I will probably compare Datacake and MS Azure IoT Hub for my future solutions.
I have decided to use cloud solutions such as Pybytes, The Things Stack and Datacake, to be able to focus on the functionalities and not having to operate my own environment such as the TIG stack.
Regarding the devices, building and programming your own device has been very instructive, but unless I can't find the device I need, I will look at off-the-shelf sensor and actuating products to set up and configure.
Finally regarding the gateway, the Pygate will be useful for now, and it might be I will prefer having my own even when public gateways become available where I live, to keep having control over the infrastructure. However, as with many things cloud services will most probably be more reliable over time, so we will see about that.
![](https://i.imgur.com/HiIowhy.png)
Fig. 26. The setup in real life, powered by my Dormy Solar charger.
## Added 2021-08-06
* [Link to presentation](https://lnu-ftk.instructuremedia.com/embed/16843622-6eb1-46f1-8d55-b9266ca8101c)
* Picture of my gateway running in the electric cabinet.
![](https://i.imgur.com/qMtEM0T.png)
Fig. 27. Picture of my gateway, installed in the electric cabinet.