# Publishing data in a script

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.

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

"""
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'

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

# 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 a websocket MQTT client
client = mqtt.Client(transport='websockets')
client.ws_set_options(path='/eventbus')

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

    value = 20

    while True:
        # https://brewblox.netlify.app/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.7-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:

.
├── script.py
└── Dockerfile

To build the image, run:

docker build --tag pubscript pubscript/

# Running

To run the built image:

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://mitsuruog.github.io/what-mqtt/. Connect to wss://PI_ADDRESS:HTTPS_PORT/eventbus, and listen to your published topic.

Example address: wss://192.168.2.11:443/eventbus. Example topic: brewcast/history/pubscript (default in script.py)

You can also listen to all messages published to history by subscribing to brewcast/history/#. This will get very spammy if there are multiple services publishing data.

Last Updated: 7/16/2020, 11:47:52 AM