## 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 has as its final goal to display temperature data on a discord server but is a good way to being introduced to using the MQTT protocol as well as webhooks along the way.
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 its dry or activating your AC when the room temperature is above a certain level. So this tutorial is 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, one way to use the temperature data is to have a servo connected to a Pycom device that closes the curtains if the temperature reaches above a certain point.
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 proved easier to subscribe via a pycom device, which is also showed in the tutorial so it is a useful guide for anyone that wants to transmit data between devices wirelessly via a MQTT protocol.
As a final touch the webhook connected from discord to Adafruit is another rather easy way to treat your data.
# Material
* Pycom LoPy4 device
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
The Breadboard was used to more easily connect the sensor to the Pycom device.
* MCP9700 TO-92 Temperature sensor
The sensor was used to measure the room temperature and transmit the data to the Pycom device.
* wires
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 but the temperature sensors are incredibly cheap and can be purchased separately for around 15 sek, the rest can probably be purchased for a few hundred as well.
# 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, Python can be downloaded here (https://www.python.org/downloads/).
You also need Node.js in which is a package for running javascripts, it can be found here (https://nodejs.org/en/).
Once everything is up and running you should update the firmware on your Pycom device, instructions on how to do that.
# 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 tutorial 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.
Here is a simple picture of how the connections are made:

# Platform
The platform used is called Adafruit, the main reason for this 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. Still though any platform that works as a broker for the MQTT protocol works and there are several others out there, none of which I have tried. 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 here (https://docs.pycom.io/tutorials/networkprotocols/mqtt/), there is also a code example from where a lot my code was taken since I felt that the documentation was a bit lacking, the code example can be found here: (https://docs.pycom.io/tutorials/networkprotocols/mqtt/).
Something that was a bit bothersome about the code and the library is that when subscribing to a topic there is a function in the library used to get access to the message, this one:
```python
def check_msg(self):
self.sock.setblocking(False)
return self.wait_msg()
```
However it turns out that to use the library you need to create a function that is used in the library in order to treat 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)
```
The problem with this one is that it only prints the message and doesn't give you access to it, and since the function you define is being used in another function you can't simply get access to it with a return statement.
My solution was like this:
```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 you datatype you are sending.
This is the only strange thing using the given library for MQTT on the Pycom. Also worth noting that the main goal of this tutorial isn't to subscribe which I just showed how to do but to publish it.
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.
Another good thing to know is that a formula was used in order to convert the temperature from the temperature sensor to celsius degrees, this code looks like this:
```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 is not guaranteed to show the correct room temperature.
# 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. 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 is that you want to put 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 subscrbed to is being subscribed to.
So what is being done here is that the pycom device (client) is using a library to publish data on Adafruit (broker) through a feed called "roomTemperature" (topic). Then theoretically any device like a fan (another client) can subscribe to this topic and get access to the data.
Then a webhook is being used to further transmit the data from Adafruit to discord.
In this tutorial the temperature is being sent every hour or so. Due to MQTT being very lightweight the energy consumtion for this project shouldn't be that much.
# 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 in 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 give an alarm if the data reaches above some threshold.
# Finalizing the design
The whole code can be found on Github on this link:
https://github.com/hpaldan/IOT_SummerCourseProject_2021
This is the end product hardware:
