# How to use MQTT to publish temperature data as well as displaying it on discord using webhook.
By: Henrik Paldán, hp222mg
## Introduction
This tutorial shows how to display temperature data on a discord server by using the MQTT protocol to publish data on Adafruit and then transmit it to Discord using webhook.
The MQTT protocol is a fairly simple way of having devices communicate with each other via a publish/subscribe system. Being able to send and receive data between devices is a first step of actually using data to not only measure the surroundings but actually use these measurements as inputs to other devices to perform various tasks, this could as an example be to signal a watering system to water when the moisture sensor signals that the soil is dry or activating your AC when the room temperature is above a certain level. So this tutorial can be seen as a first step in starting to actually use measurement data as inputs to other devices.
Webhook is also another way of sending data which can be useful for example if the goal is to publish it to several people in an easy way or having it more easily available on your phone.
Completing this whole tutorial will take approximately 3 hours assuming that all hardware and software works exactly as planned (which it rarely does).
## Objective
This project is useful for anyone that is interested in collecting their room temperature data and want the possibility to allow other devices to subscribe to that data in order to control them in someway.
The intended end goal for the project was to connect a smart wifi plug to a fan and having the smart wifi plug subscribe to temperature sensor data, then during the night while everyone is asleep the fan would switch off once the room temperature goes below a certain point saving energy as well as reducing fan noise giving a better nights sleep, however it proved harder than expected to get access to the chosen wifi plug.
While it was difficult to subscribe from a wifi plug it is easier to subscribe via a pycom device, which is also showed in the tutorial.
As a final touch the webhook connected from discord to Adafruit is another rather easy way to treat your data to make it more accessible.
## Material
* [Pycom LoPy4 device](https://pycom.io/product/lopy4/) (38 EU)
The Pycom device was used to gather data from the temperature sensor and connect to internet via wifi in order to send the data. It is a good general purpose device for gathering in sensor data and transmit it via different channels like wifi, bluetooth, LoRa and SigFox.
* [Breadboard](https://www.electrokit.com/produkt/experimentkort-breadboard-400-hal/) (3 EU)
The Breadboard was used to more easily connect the sensor to the Pycom device.
* [MCP9700 TO-92 Temperature sensor](https://www.electrokit.com/produkt/mcp9700-e-to-to-92-temperaturgivare/) (1 EU)
The sensor was used to measure the room temperature and transmit the data to the Pycom device.
* [wires](https://www.electrokit.com/produkt/labsladd-1-pin-hane-hona-150mm-10-pack/) (3 EU)
The wires were used to connect all components.
All of the material was purchased on electrokit.se as a part of a bundle that cost in total 949 SEK bought separately it would cost around 44 Euros.
## Computer setup
* IDE:
The chosen IDE was VS Code since it is easy to get acquinted with and have a plugin called Pymakr that is used to upload code directly to the Pycom device which is incredibly useful.
How to get started:
First of all download VS code from the internet (https://code.visualstudio.com/Download) and install it.
Then install pymakr as an extension.
Then you also need to install Python since the Pycom device runs on micropython (https://www.python.org/downloads/).
You also need Node.js in which is a package for running javascripts (https://nodejs.org/en/).
Once everything is up and running you should update the firmware on your Pycom device, information on how to that can be found in the following link https://docs.pycom.io/updatefirmware/device/.
## Putting everything together
The only hardware connections that are needed to make is to connect the Pycom device to the temperature measurement board and connect the Pycom to a power source, during the setup of the code and the hardware the easiest is to connect it to a computer where the code is uploaded from since it also works as a powersource but once the code has been uploaded to the device any usb connection works as a power source. The breadboard is used to make the connections easier but isn't directly necessary.
Here is a simple picture of how the connections are made:

## Platform
The platform used is called adafruit.io, the main reason for using adafruit.io is that it was used in a example found on a webpage about MQTT for Pycom devices (https://docs.pycom.io/tutorials/networkprotocols/mqtt/). It is very user friendly with different choices for graphical representation. However any platform that works as a broker for the MQTT protocol works and there are several others out there. Other bonuses with Adafruit is that it is also free and has a simple way of connecting to the data feed via webhooks. A downside is that there is a limitation on the frequency of which you can send data to it. If you wish to scale up with multiple clients that publish and subscribe to data it is possible to upgrade to Adafruit+ but then it will no longer be free.
## The code
The most important code part is the library for MQTT protocol for the Pycom device. This can be found on the Github library for Pycom devices (https://docs.pycom.io/tutorials/networkprotocols/mqtt/), there is also a code example from where a lot my code was copied the code example can be found here (https://docs.pycom.io/tutorials/networkprotocols/mqtt/).
One of the most important parts of subscribing to a topic is to get access to the data in order to use it. However in the code example it only prints the message in the terminal. Getting access to it proved a bit tricky.
This function is used to call the topic in order to get the latest data:
```python=
def check_msg(self):
self.sock.setblocking(False)
return self.wait_msg()
```
However it turns out that you need to create a function that is then used in the library in order to handle the message, in the example it looks like this:
```python=
def sub_cb(topic, msg):
print(msg)
# and then further below this line of code:
client.set_callback(sub_cb)
```
```c++=
int hej = 100;
```
So you define a function which is used in the MQTTClient class in the library to handle the data. This means that simply change the "print(msg)" to "return msg" won't work since that variable then only will be available in the MQTTClient class.
This is how i solved it:
```python=
Q = b'0'
def sub_cb(topic, msg):
global Q
Q = msg
# And then further below where it receives the data:
client.check_msg()
Q = float(Q)
```
Here it creates a float variable from a byte object but the byte object can really be converted to anything depending on what datatype you want.
The purpose of this tutorial is not however to access the data via a Client that subscribes to the topic this was simply a detour for a better understanding of the MQTT library for Pycom.
When publishing data the only thing worth noting is that the format needs to be a string so any other datatype needs to be converted to a string before being sent.
In order to convert the voltage to a celsius value the formula below was used:
```python=
celsius = (milliVal - 500.0) / 10.0 + 62
```
Please note that because of the cheapness of the temperature sensor the correct temperature can sometimes be a bit off and should be taken with a pinch of salt.
## Transmitting the data / connectivity
Transmitting the data is the most interesting part of this project, as previouslyt mentioned it was done using the MQTT protocol via Wifi. The MQTT protocol is a very simple lightweight protocol that is very commonly used to send data, in this project it is done through wifi but it would probably be just as easy to send it through some other channel.
There are a few terms that is good to know with the MQTT protocol:
* Subscribe/publish
Subscribe means that you want to get data from a topic and publish means that you want to send data to a topic.
* Client
A client is an entity (usually a computer of some sort) that can either publish data to a topic or subscribe for data from a topic.
* Topic
A topic is a channel where data is being transferred, so a client can either publish to a topic or subscribe to a topic.
* Broker
A broker is a program that handles all of these topics and clients and makes sure that everything that is suppose to be published is published and everything that is supposed to be subscribed to is being subscribed to. It also ensures that data is being sent in proper ways.
So what is being done here is that the pycom device (client) is using a library to publish data on a feed called "roomTemperature" (topic) which is handled by Adafruit (broker). Then theoretically any device like a electric fan (another client) can subscribe to this topic on Adafruit and get access to the data.
Then finally a webhook is being used to further transmit the data from Adafruit to discord. In order to learn more about how to implement webhooks on Adafruit follow this link: (https://learn.adafruit.com/all-the-internet-of-things-episode-four-adafruit-io/webhooks):
In this tutorial the temperature is being sent every hour or so. Due to MQTT being very lightweight the energy consumtion for this project is likely low.
## Presenting the data
The data is displayed both on Adafruit and on discord. On discord for being able to monitor the temperature remotely in an easy way and on Adafruit because it has better ways of presenting it in a graphically appealing way.
Here is the temperature on discord:

This picture is taken from when trials still are being made and thats why it sends every 10 minutes.
Here is a picture of the more graphical presentation from Adafruit:
This picture is also taken at a time where everything wasn't quite in place hence the wild data values. The data is stored on Adafruit for 24 hours before being discarded.
In Adafruit it is also easy to condition the webhook messages, as for an example it could send values to discord if the data reaches above some threshold.
## Finalizing the design
### Improvements/Continuations
The next goal is to have som kind of receiver that subscribes to the topic and give different output depending on sensor values for example a fan that goes on and off depending on the temperature.
Another less relevant thing would be too include the standby functions from the machine library when the pycom device is not being used in order to reduce energy consumption. This would be even more relevant if the device was powered by battery instead of connected to the power grid directly.
The entire code can be found on Github on this link:
https://github.com/hpaldan/IOT_SummerCourseProject_2021
This is the end product hardware:
