# Report
✔ Jakob Aschauer, k12007322
✔ Matthias Heiden, k12104028
✔ Stefan Gabriel, k12008194
✔ Christian Dattinger, k12031039
✔ Mohamad Khabour, k12005283
✔ Victoria Plöckinger, k12108435
✔ Mehmet Tasdemir, k11910284
## Interesting parts of the code
### MQTT Topics
Different services can subscribe to topics that are relevant to them. If there are no subscribers, the data will be thrown away and no error occurs. This is good because we can test software components without actually needing to have the coffee machine right next to us.
- **measurements**: Raw data from the analysis service.
- **air_quality**: A single integer representing the air quality
- **action/brew_coffee**: Command that coffee should be brewed. Sent by the analysis service. Coffee machine subscribes to this topic.
- **action/open_window**: Action to use a servo motor to open a window. Not implemented in our project due to power constraints.
- **configuration/open_window**: Can be used to manually enable/disable opening of the window.
- **configuration/control_fans** Can be used to manually enable/disable fans
- **configuration/control_blinds**: Configures the state of the mitigation (e.g. turning the fan on or off)
### Architecture

Having 7 members in our group, it was important to structure the project into individual services. This way, each person was able to work on their part without interfering with the work of others. The only central component that is required is the **storage service**.

The storage service consists of the MQTT broker and database. It also exposes the GraphQL endpoint. You don't need the measuring service, because you can send mock data via MQTT. You can also leave out the coffee machine and mitigation service, which require hardware. This makes development of the software components incredibly easy.
Most of the services use the MQTT broker:
- Measurement: Send data via `measurements` topic
- Database: Subscribe to `measurements` topic and save to SQLite database
- Analysis: Subscribe to `measurements`, publish `air_quality` or `action/brew_coffee`
- Mitigation: Subscribe to `air_quality` and `configuration/control_fans`
- Coffee machine: Subscribe to `action/brew_coffee`
- Web Interface: Trigger manual actions (e.g. brew coffee `action/brew_coffee`) and send new configuration (e.g. enable/disable automatic opening of window `configuration/open_window`)
Only the website uses the GraphQL endpoint to access historic data.
### Coffee Machine
To interact with the Coffee Machine we use a Raspberry Pi 4 Model B that controls 3 Continuos Rotation Servo Motors. Directly after the Pi has been started, it executes a Python script, that waits until we receive a message over MQTT on the `action/brew_coffee` topic and then does the appropriate actions to brew a coffee.
The order of operations is:
1. Power on the coffee machine
2. Wait for the automatic cleaning mechanism to finish
3. Move the cup under the coffee dispenser
4. Press the touch button to brew a coffee
5. Wait until the coffee has been poured into the cup
6. Turn off the coffee machine
To control the Servo Motors we use the RPi.GPIO Python library. The actual handling of those is rather simple. We initialize them to their respective GPIO pins and a frequency of 50Hz with
```python!
GPIO.setup(pin_number, GPIO.OUT)
servo = GPIO.PWM(pin_number, 50)
```
The direction and speed at which the Servo Motors turn is dependent on their duty cycle. When the script is started the duty cycle of all servos is initially set to 0, which means that they should not be moving. When we then want them to move, we change their duty cycle with `servo.ChangeDutyCycle(duty_cycle)`. To set how long they should be on, we use `time.sleep(sleep_time)` and then change their duty cycle back to 0.
### Coffee Machine Circuit Diagram
The circuit which powers the Servo Motors is rather simple. All of them are connected to power and ground through the same pins on the Pi, but they all are linked to individual GPIO pins on the Pi, so that they can receive their own signal, when they should be turned on.



### Measurement
The Raspberry Pi collects sensor measurements using the Sense HAT module, including temperature, humidity, and pressure (in further updates not included anymore, due to no usage). These measurements are then published as MQTT messages to a broker, specifying a topic called `measurements`.
The Python script running on the Raspberry Pi establishes a connection to the MQTT broker using the paho-mqtt library. It continuously retrieves the sensor measurements, rounds them to the desired number of digits, and packages them into a payload along with a timestamp. The payload is then published to the `measurements` topic using the MQTT client.
### Analysis & Mitigation Circuit Diagram


The 3 LED's are connected to only one ballast resistor because only one of them is on at a time.
The Motor Symbol represents the Fan.
Due to power Limitation the fan would not always start on ists own this could have been mitigate by using a dedicated powersource an just controlling i with a resitor.
### Analysis Algorithm
The code compares the measured temperature and humidity with reference values and calculates an air quality value based on the differences. If the humidity is outside the range of 20-80%, or if the temperature difference exceeds 10 degrees, the air quality value is set to 0. Otherwise, the differences are normalized, and the air quality value is computed as the average of the normalized differences.
### Mock Data
As previously mentioned, we often don't have all the hardware components so having mock data is really important. We created a simple script that sends the following random values:
- Temperature: Between 20.0 and 30.0
- Humidity: Between 40.0 and 60.0
- Brew coffee: Sent in 10% of the cases
- Configuration: Sent in 10% of the cases
### Pass broker address via env variable
We don't want to hard-code the IP address of the broker (especially when running in docker), so we pass it via environment variables.
```python
broker_address = os.getenv("BROKER_ADDRESS", "localhost")
broker_port = 1883
```
### Web Interface
- Display historic data. Get a comprehensive overview of your coffee consumption habits through the intuitive web interface. Dive into the historical data that shows how often you've enjoyed a cup of coffee, helping you track your caffeine intake patterns effortlessly.
- Monitor real-time air quality information right from the comfort of your web interface. Stay informed about the environment where you consume your coffee / (work) and ensure a healthy and refreshing experience every time.
- The web interface allows you to manually trigger various features such as brewing a coffee and opening a window.
- Maintain complete control over the functionality by enabling or disabling specific features as desired. Have the freedom to customize your brewing setup.
The historic data is retrieved from the Storage Service using GraphQL. Commands and configuration are sent using MQTT.
---
## Limitations / Difficulties
### Limited hardware
Since we were 7 people, it was not easy for everyone to get the hardware that one needed all the time, therefore there was significant coordination required.
Unfortunately, we didn't have a CO2 sensor, so we had to only use temperature and humidity. We thought about buying one, but they are quite expensive when bought as a single piece.
We also had problems with energy distribution. For example, when enabling the LEDs, the fan sometimes didn't have enough power to go from 0 to 100. We were able to bypass this by manually pushing it a little bit. Turning off the fan worked flawlessly.
### Currently only one room supported: TODO
Sensor in each room, but only N coffee machines. Work should be distributed between those. Account for distance from office to coffee machine.
### Outdated Raspberry Pi Software
We tried to install Docker, but it wasn't possible because the operating system was from 2018 and not supported anymore. We tried to install a new version, but had many issues with certificates and lack of storage. For some reason, the SD card used 4GB for the root partition, which caused the system update to fail due to lack of space.
We spent a lot of time on this, and decided to switch to use our own SD card with a newer OS version instead.
Apparently the kernel is from 2018 (running debian stretch):

### Software not supported on ARM
It's quite common that newer technologies/software isn't supported on ARM. We tried to use Rust and SurrealDB for the storage first, but setting that up was quite the hassle. We then also realized that SurrealDB is currently not running on ARM devices.
We then switched to Kotlin, which worked fine for a simple Web Server and SQLite database, but there was no easy way to setup a GraphQL server.
After that, we switched to deno where we could use existing Node.js libraries. Turns out, there is no ARM runtime for Deno either. Luckily, porting the code to Node wasn't that hard and that worked, because it's supported on ARM.
### VueJS Wrapper of Highcharts has some bugs and little documentation
The highcharts-vue wrapper seems to support Vue 3, but updating the chart data doesn't trigger a re-rendering of the chart. This is a problem, since there initially is no chart data, as it comes from an asynchronous request to the GraphQL endpoint (storage service). Several attempts to manually trigger a re-rendering also were not successful, so we switched to vue-chartjs, which worked without problems out of the box.
### CORS
When developing software locally on a Raspberry Pi and accessing it through a web browser, a CORS (Cross-Origin Resource Sharing) issue arises. This problem occurs because the web page's origin (ip of the pi) differs from the backend (storage service, 127.0.0.1) running on the Raspberry Pi. As a result, modern browsers enforce CORS restrictions, preventing backend requests and hindering the ability to get data from the GraphQL Service. This requires modifications of the GraphQL Service to send a special header to allow CORS requests. A workaround for this is to run the Webinterface and GraphQL service on same device where the web browser runs.
### Running MQTT in a Browser
Running MQTT in a browser can be a challenge. The latest version of MQTT.js did not start, instead it always had dependency problems when using with Vue 3. While downgrading the version solved that problem, a new one arose. The browser always refused to connect with a generic`error_connection_refused` exception. When running inside a browser you cannot directly use TCP/IP connections (MQTT default), instead you have to run MQTT over Websockets. The mosquitto server on the hand does not expect Websocket connections by default, so we had to configure that.
We used the following mosquitto configuration:
```
persistence true
persistence_location /mosquitto/data/
log_dest stdout
#log_dest file /mosquitto/log/mosquitto.log
connection_messages true
allow_anonymous true
#listener 1883
listener 1883 0.0.0.0
listener 8080
protocol websockets
```
### Coffee Machine Documentation
As for Coffee Machine Documentation, there was none. We tried searching for the documentation of our specific or a similar coffee machine, however we could not find anything useful. This could have substantially reduced the time we would have needed for the pressing/simulating of the "brew coffee" button.
### How to (not) control a coffee machine
When we first started to think about ways we could interact with the coffee machine, we thought we could simply just bypass the touch press of the display and directly send a signal from the Pi to the coffee machine. We did so by naively separating the cable which leads from the touch button to the inner machinations of the coffee machine and simply attaching a cable that leads to the Pi. This astonishingly worked the first few times, but the more we did it this way, the weirder the coffee machine started to behave. When we sent the signal to make a coffee now, simply nothing happened, but after we detached the cable from the Pi to the coffee machine, it started to constantly order a coffee.
After too much troubleshooting, we gathered that the coffee machine would now order a coffee if no or only a very small voltage was applied, however if we tried to manually send only a low voltage nothing happened. To fix this, we now simply connected this cable that would order a small coffee to a 5V output of the Pi, which however meant we couldn't use this functionality of the coffee machine anymore, but there was still the possibility of ordering a big coffee. To achieve this we now simulated the touch press by using a Servo Motor that would move a "hand" which then would activate the touch of the display.
### Simulating human touch
We first assumed the hand to touch the display, would simply need to use enough force and this would then activate the button, however this did not work. We then discovered that if one of us would directly touch the "hand" it would work and also didn't need a lot of force at all. After some more research into how touch displays actually worked, we gathered, that the "hand" needed to be grounded.
### Raspberry Pi Zero W can't change the duty cycle of a servo motor
We are unsure if this was just a problem with our Raspberry Pi Zero W or if this is a general problem, but we tried to use the RPi.GPIO python library to control the servo motor. This means to change the direction the servo is turning, we would need to use the ChangeDutyCycle() function. This however did not work and would crash the Pi without exception. Fortunately, one of our team members had another Raspberry Pi 4 Model B with which ChangeDutyCycle() worked, so in the end this worked out.
### Network
It's quite difficult to connect to a Raspberry Pi when you don't have a separate monitor or mouse/keyboard with you. We had to set a static IP in the DHCP config file. We had to do the same on the client, so that we were able to connect to the Pi via a direct LAN cable.
Once that was done, we got an SSH connection where we configured it to automatically connect to the WLAN 'es2023' with the password 'es2023es2023'. This way, it doesn't matter who creates the WLAN as long as it has the same SSID and password.