Skip to content

Docker: Publish History Data

The most common use case for integration with Brewblox is "I want to see my data in a graph". You can do that by publishing your data to the Brewblox eventbus.

Once you have published the data, you can view it using the Graph and Metrics widgets. The new fields should appear immediately when you next open the widget settings.

This tutorial shows you how to send data to the Brewblox eventbus, and run the script in a Docker container. It assumes you're either familiar with Docker, or have followed the dockerized script tutorial.

This script can be combined with reading a serial port.

Source code

On your Pi, create a new directory pubscript. In it, create two files:

script.py

py
"""
Code example for publishing data to the Brewblox eventbus

Dependencies:
- paho-mqtt
"""

import json
from random import random
from time import sleep

from paho.mqtt import client as mqtt

# 172.17.0.1 is the default IP address for the host running the Docker container
# Change this value if Brewblox is installed on a different computer
HOST = '172.17.0.1'

# 1883 is the default port for MQTT, but this can be changed in brewblox env settings.
PORT = 1883

# This is a constant value. You never need to change it.
HISTORY_TOPIC = 'brewcast/history'

# The history service is subscribed to all topics starting with 'brewcast/history'
# We can make our topic more specific to help debugging
TOPIC = HISTORY_TOPIC + '/pubscript'

# Create an MQTT client
client = mqtt.Client()

try:
    client.connect_async(host=HOST, port=PORT)
    client.loop_start()

    value = 20

    while True:
        # https://www.brewblox.com/dev/reference/history_events.html
        value += ((random() - 0.5) * 10)
        message = {
            'key': 'pubscript',
            'data': {'value[degC]': value}
        }

        client.publish(TOPIC, json.dumps(message))
        print(f'sent {message}')
        sleep(5)

finally:
    client.loop_stop()

Dockerfile

FROM python:3.11-slim

COPY script.py /app/script.py

RUN pip3 install paho-mqtt

CMD ["python3", "-u", "/app/script.py"]

Building

Your pubscript directory should look like this:

txt
.
├── script.py
└── Dockerfile

To build the image, run:

sh
docker build --tag pubscript pubscript/

Running

To run the built image:

sh
docker run --rm --tty pubscript

This is exactly the same as the command in the dockerized script tutorial.

Testing

It's often useful to listen in on what messages the eventbus actually received.

You can do so using https://mqtt-explorer.com/. Connect to mqtt://PI_ADDRESS:1883, and you can see all published events.