Using a raspberry pi, we listen to the coffee machine and count the number of coffee consumption

Overview

maintained by dataroots

Fresh-Coffee-Listener

A typical datarootsian consumes high-quality fresh coffee in their office environment. The board of dataroots had a very critical decision by the end of 2021-Q2 regarding coffee consumption. From now on, the total number of coffee consumption stats have to be audited live via listening to the coffee grinder sound in Raspberry Pi, because why not?

Overall flow to collect coffee machine stats

  1. Relocate the Raspberry Pi microphone just next to the coffee machine
  2. Listen and record environment sound at every 0.7 seconds
  3. Compare the recorded environment sound with the original coffee grinder sound and measure the Euclidean distance
  4. If the distance is less than a threshold it means that the coffee machine has been started and a datarootsian is grabbing a coffee
  5. Connect to DB and send timestamp, office name, and serving type to the DB in case an event is detected ( E.g. 2021-08-04 18:03:57, Leuven, coffee )

Raspberry Pi Setup

  1. Hardware: Raspberry Pi 3b
  2. Microphone: External USB microphone (doesn't have to be a high-quality one). We also bought a microphone with an audio jack but apparently, the Raspberry Pi audio jack doesn't have an input. So, don't do the same mistake and just go for the USB one :)
  3. OS: Raspbian OS
  4. Python Version: Python 3.7.3. We used the default Python3 since we don't have any other python projects in the same Raspberry Pi. You may also create a virtual environment.

Detecting the Coffee Machine Sound

  1. In the sounds folder, there is a coffee-sound.m4a file, which is the recording of the coffee machine grinding sound for 1 sec. You need to replace this recording with your coffee machine recording. It is very important to note that record the coffee machine sound with the external microphone that you will use in Raspberry Pi to have a much better performance.
  2. When we run detect_sound.py, it first reads the coffee-sound.m4a file and extracts its MFCC features. By default, it extracts 20 MFCC features. Let's call these features original sound features
  3. The external microphone starts listening to the environment for about 0.7 seconds with a 44100 sample rate. Note that the 44100 sample rate is quite overkilling but Raspberry Pi doesn't support lower sample rates out of the box. To make it simple we prefer to use a 44100 sample rate.
  4. After each record, we also extract 20 MFCC features and compute the Euclidean Distance between the original sound features and recorded sound features.
  5. We append the Euclidean Distance to a python deque object having size 3.
  6. If the maximum distance in this deque is less than self.DIST_THRESHOLD = 85, then it means that there is a coffee machine usage attempt. Feel free to play with this threshold based on your requirements. You can simply comment out line 66 of detect_sound.py to print the deque object and try to select the best threshold. We prefer to check 3 events (i.e having deque size=3) subsequently to make it more resilient to similar sounds.
  7. Go back to step 3, if the elapsed time is < 12 hours. (Assuming that the code will run at 7 AM and ends at 7 PM since no one will be at the office after 7 PM)
  8. Exit

Scheduling the coffee listening job

We use a systemd service and timer to schedule the running of detect_sound.py. Please check coffee_machine_service.service and coffee_machine_service.timer files. This timer is enabled in the makefile. It means that even if you reboot your machine, the app will still work.

coffee_machine_service.service

In this file, you need to set the correct USER and WorkingDirectory. In our case, our settings are;

User=pi
WorkingDirectory= /home/pi/coffee-machine-monitoring

To make the app robust, we set Restart=on-failure. So, the service will restart if something goes wrong in the app. (E.g power outage, someone plugs out the microphone and plug in again, etc.). This service will trigger make run the command that we will cover in the following sections.

coffee_machine_service.timer

The purpose of this file is to schedule the starting time of the app. As you see in;

OnCalendar=Mon..Fri 07:00

It means that the app will work every weekday at 7 AM. Each run will take 7 hours. So, the app will complete listening at 7 PM.

Setup a PostgreSQL Database

You can set up a PostgreSQL database at any remote platform like an on-prem server, cloud, etc. It is not advised to install it to Raspberry Pi.

  1. Install and setup a PostgreSQL server by following the official documentation

  2. Create a database by typing the following command to the PostgreSQL console and replace DB_NAME with your database name;

    createdb DB_NAME
    

    If you got an error, check here

  3. Create a table by running the following query in your PostgreSQL console by replacing DB_NAME and TABLE_NAME with your own preference;

    CREATE TABLE DB_NAME.TABLE_NAME (
        "timestamp" timestamp(0) NOT NULL,
        office varchar NOT NULL,
        serving_type varchar NOT NULL
    );
    
  4. Create a user, password and give read/write access by replacing DB_USER, DB_PASSWORD, DB_NAME and DB_TABLE

    create user DB_USER with password 'DB_PASSWORD';
    grant select, insert, update on DB_NAME.DB_TABLE to DB_USER;
    

Deploying Fresh-Coffee-Listener app

  1. Installing dependencies: If you are using an ARM-based device like Raspberry-Pi run

    make install-arm

    For other devices having X84 architecture, you can simply run

    make install
  2. Set Variables in makefile

    • COFFEE_AUDIO_PATH: The absolute path of the original coffee machine sound (E.g. /home/pi/coffee-machine-monitoring/sounds/coffee-sound.m4a)
    • SD_DEFAULT_DEVICE: It is an integer value represents the sounddevice input device number. To find your external device number, run python3 -m sounddevice and you will see something like below;
         0 bcm2835 HDMI 1: - (hw:0,0), ALSA (0 in, 8 out)
         1 bcm2835 Headphones: - (hw:1,0), ALSA (0 in, 8 out)
         2 USB PnP Sound Device: Audio (hw:2,0), ALSA (1 in, 0 out)
         3 sysdefault, ALSA (0 in, 128 out)
         4 lavrate, ALSA (0 in, 128 out)
         5 samplerate, ALSA (0 in, 128 out)
         6 speexrate, ALSA (0 in, 128 out)
         7 pulse, ALSA (32 in, 32 out)
         8 upmix, ALSA (0 in, 8 out)
         9 vdownmix, ALSA (0 in, 6 out)
        10 dmix, ALSA (0 in, 2 out)
      * 11 default, ALSA (32 in, 32 out)

    It means that our default device is 2 since the name of the external device is USB PnP Sound Device. So, we will set it as SD_DEFAULT_DEVICE=2 in our case.

    • OFFICE_NAME: it's a string value like Leuven office
    • DB_USER: Your PostgreSQL database username
    • DB_PASSWORD: the password of the specified user
    • DB_HOST: The host of the database
    • DB_PORT: Port number of the database
    • DB_NAME: Name of the database
    • DB_TABLE: Name of the table
  3. Sanity check: Run make run to see if the app works as expected. You can also have a coffee to test whether it captures the coffee machine sound.

  4. Enabling systemd commands to schedule jobs: After configuring coffee_machine_service.service and coffee_machine_service.timer based on your preferences, as shown above, run to fully deploy the app;

    make run-systemctl
  5. Check the coffee_machine.logs file under the project root directory, if the app works as expected

  6. Check service and timer status with the following commands

    systemctl status coffee_machine_service.service

    and

    systemctl status coffee_machine_service.timer

Having Questions / Improvements ?

Feel free to create an issue and we will do our best to help your coffee machine as well :)

Owner
dataroots
Supporting your data driven strategy.
dataroots
Python module for controlling Broadlink RM2/3 (Pro) remote controls, A1 sensor platforms and SP2/3 smartplugs

Python module for controlling Broadlink RM2/3 (Pro) remote controls, A1 sensor platforms and SP2/3 smartplugs

Matthew Garrett 1.2k Jan 04, 2023
DNP3 Stalker is a project to analyze and interact with DNP3 devices

DNP3 Stalker Purpose DNP3 Stalker is a project to analyze and interact with DNP3

Cutaway Security, LLC. 2 Feb 10, 2022
Universal Xiaomi MIoT integration for Home Assistant

Xiaomi MIoT Raw 简体中文 | English MIoT 协议是小米智能家居从 2018 年起推行的智能设备通信协议规范,此后凡是可接入米家的设备均通过此协议进行通信。此插件按照 MIoT 协议规范与设备通信,实现对设备的状态读取及控制。

1.9k Jan 02, 2023
rPico KMK powered macropad with IPS screen

MacroPact rPico KMK powered macropad with IPS screen Idea/Desing: Sean Yin Build/Coding: kbjunky ( In case of any problems hit me up on Discord kbjunk

81 Dec 21, 2022
Self Driving Car Prototype

Package Delivery Rover 🚀 This project is a prototype of Self Driving Car. It's based on embedded systems, to meet the current requirement of delivery

Abhishek Pawar 1 Oct 31, 2021
Sticklog2heatmap - Draw a heatmap of RC sticks from OpenTX logs or USB HID device

sticklog2heatmap Draw a heatmap of RC sticks from OpenTX logs or USB HID device

2 Feb 02, 2022
Lenovo Legion 5 Pro 2021 Linux RGB Keyboard Light Controller

Lenovo Legion 5 Pro 2021 Linux RGB Keyboard Light Controller This util allows to drive RGB keyboard light on Lenovo Legion 5 Pro 2021 Laptop Requireme

36 Dec 16, 2022
Bucatini: a soft PIPE PHY for FPGA SerDes

Bucatini: a soft PIPE PHY for FPGA SerDes Bucatini is a noodly gateware layer capable of transforming an FPGA SerDes into a PIPE PHY, allowing you to

Great Scott Gadgets 28 Dec 02, 2022
Control the lights of Alienware computers under GNU/Linux systems.

Before requesting support please consider that this software is not actively developed. I created it in 2014 for managing my Alienware M14X-R1 (where

rsm 111 Dec 05, 2022
Home Assistant custom components MPK-Lodz

MPK Łódź sensor This sensor uses unofficial API provided by MPK Łódź. Configuration options Key Type Required Default Description name string False MP

Piotr Machowski 3 Nov 01, 2022
Home assiatant Custom component: Camera Archiver

Camera archiver Archive your ftp camera meadia files on other ftp with files renaming and event creation. Event can be used for send information to el

1 Jan 06, 2022
A Raspberry Pi Pico powered Macro board, like a Streamdeck but cheaper and simpler.

Env-MCRO A Raspberry Pi Pico powered Macro board, like a Streamdeck but cheaper and simpler. (btw this image is a bit outdated, some of the silkscreen

EnviousData 68 Oct 14, 2022
A Home Assistant integration for Solaredge inverters

A Home Assistant integration for Solaredge inverters. Supports multiple inverters chained through RS485.

Seth 50 Dec 23, 2022
A versatile program that uses the raspberry pi camera and provides it as a service

PiCameleon Is a daemon program meant to provide the RaspberryPi Camera as a service while running according to a configuration.

André Esser 52 Oct 16, 2022
Python Client for ESPHome native API. Used by Home Assistant.

aioesphomeapi aioesphomeapi allows you to interact with devices flashed with ESPHome. Installation The module is available from the Python Package Ind

ESPHome 76 Jan 04, 2023
Andreas Frisch 1 Jan 10, 2022
This is the remake of the program PYOBD. It works on Python3 and all new libraries. It was tested on Linux, Windows, and it should work on MAC too.

This is the remake of the program PYOBD. It works on Python3 and all new libraries. It was tested on Linux, Windows, and it should work on MAC too. You just need an ELM327 USB or bluetooth device and

127 Jan 06, 2023
Huawei Solar sensors for Home Assistant

Huawei Solar Sensors This integration splits out the various values that are fetched from your Huawei Solar inverter into separate HomeAssistant senso

Thijs Walcarius 151 Dec 31, 2022
KIRI - Keyboard Interception, Remapping, and Injection using Raspberry Pi as an HID Proxy.

KIRI - Keyboard Interception, Remapping and Injection using Raspberry Pi as a HID Proxy. Near limitless abilities for a keyboard warrior. Features Sim

Viggo Falster 10 Dec 23, 2022
A dashboard for Raspberry Pi to display environmental weather data, rain radar, weather forecast, etc. written in Python

Weather Clock for Raspberry PI This project is a dashboard for Raspberry Pi to display environmental weather data, rain radar, weather forecast, etc.

Markus Geiger 1 May 01, 2022