The Adafruit FunHouse is the ideal companion to your Home Assistant setup. You can send not just the temperature, humidity, and barometric pressure using the onboard sensors, but you can also map the attached buttons, slider, and capacitive touch pads to control different parts of your home. You can also use the PIR Sensor to detect motion.

This guide explains how to configure your FunHouse to work with Home Assistant to send environmental data, trigger home automation events using the onboard sensors, and even use the embedded DotStars to emulate an RGB lightbulb that you can control with Home Assistant.

Parts Needed

Top-down video of Adafruit Funhouse PCB. The TFT display shows a data readout, and the NeoPixel LEDs glow rainbow colors.
Home is where the heart is...it's also where we keep all our electronic bits. So why not wire it up with sensors and actuators to turn our house into an electronic wonderland....
$34.95
In Stock
Topdown video of 3-pin PIR sensor assembled onto a breadboard. A hand passes over the sensor, and a blue LED to light up.
PIR sensors are used to detect motion from pets/humanoids from about 5 meters away (possibly works on zombies, not guaranteed). This sensor is much smaller than most PIR modules, which...
Out of Stock
Angled shot of four magnet feet.
Got a glorious RGB Matrix project you want to mount and display in your workspace or home? If you have one of the matrix panels listed below, you'll need a pack of these...
$2.50
In Stock
USB Type A to Type C Cable - 1ft - 0.3 meter
As technology changes and adapts, so does Adafruit. This  USB Type A to Type C cable will help you with the transition to USB C, even if you're still...
$3.95
In Stock

CircuitPython is a derivative of MicroPython designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate.

Set Up CircuitPython

Follow the steps to get CircuitPython installed on your FunHouse.

Click the link above and download the latest .BIN and .UF2 file

(depending on how you program the ESP32S2 board you may need one or the other, might as well get both)

Download and save it to your desktop (or wherever is handy).

Plug your FunHouse into your computer using a known-good USB cable.

A lot of people end up using charge-only USB cables and it is very frustrating! So make sure you have a USB cable you know is good for data sync.

Option 1 - Load with UF2 Bootloader

This is by far the easiest way to load CircuitPython. However it requires your board has the UF2 bootloader installed. Some early boards do not (we hadn't written UF2 yet!) - in which case you can load using the built in ROM bootloader.

Still, try this first!

Try Launching UF2 Bootloader

Loading CircuitPython by drag-n-drop UF2 bootloader is the easier way and we recommend it.

Launch UF2 by double-clicking the Reset button (the one next to the USB C port). You may have to try a few times to get the timing right.

About a half second pause between clicks while the DotStars are purple seems to work well.

If the UF2 bootloader is installed, you will see a new disk drive appear called HOUSEBOOT

Copy the UF2 file you downloaded at the first step of this tutorial onto the HOUSEBOOT drive

If you're using Windows and you get an error at the end of the file copy that says Error from the file copy, Error 0x800701B1: A device which does not exist was specified. You can ignore this error, the bootloader sometimes disconnects without telling Windows, the install completed just fine and you can continue. If its really annoying, you can also upgrade the bootloader (the latest version of the UF2 bootloader fixes this warning)

Your board should auto-reset into CircuitPython, or you may need to press reset. A CIRCUITPY drive will appear. You're done! Go to the next pages.

Option 2 - Use Chrome Browser To Upload BIN file

You will need to do a full erase prior to uploading new firmware.

The next best option is to try using the Chrome-browser version of esptool we have written. This is handy if you don't have Python on your computer, or something is really weird with your setup that makes esptool not run (which happens sometimes and isn't worth debugging!) You can follow along on the Install UF2 Bootloader page and either load the UF2 bootloader and then come back to Option 1 on this page, or you can download the CircuitPython BIN file directly using the tool in the same manner as the bootloader.

Option 3 - Use esptool to load BIN file

For more advanced users, you can upload with esptool to the ROM (hardware) bootloader instead!

Follow the initial steps found in the Run esptool and check connection section of the Install UF2 Bootloader page to verify your environment is set up, your board is successfully connected, and which port it's using.

In the final command to write a binary file to the board, replace the port with your port, and replace "firmware.bin" with the the file you downloaded above.

The output should look something like the output in the image.

Press reset to exit the bootloader.

Your CIRCUITPY drive should appear!

You're all set! Go to the next pages.

One of the great things about the ESP32 is the built-in WiFi capabilities. This page covers the basics of getting connected using CircuitPython.

The first thing you need to do is update your code.py to the following. Click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, and copy the entire lib folder and the code.py file to your CIRCUITPY drive.

# SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import ipaddress
import ssl
import wifi
import socketpool
import adafruit_requests

# URLs to fetch from
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_QUOTES_URL = "https://www.adafruit.com/api/quotes.php"
JSON_STARS_URL = "https://api.github.com/repos/adafruit/circuitpython"

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

print("ESP32-S2 WebClient Test")

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

print("Available WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!"%secrets["ssid"])
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % (wifi.radio.ping(ipv4)*1000))

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

print("Fetching text from", TEXT_URL)
response = requests.get(TEXT_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

print("Fetching json from", JSON_QUOTES_URL)
response = requests.get(JSON_QUOTES_URL)
print("-" * 40)
print(response.json())
print("-" * 40)

print()

print("Fetching and parsing json from", JSON_STARS_URL)
response = requests.get(JSON_STARS_URL)
print("-" * 40)
print("CircuitPython GitHub Stars", response.json()["stargazers_count"])
print("-" * 40)

print("done")

Your CIRCUITPY drive should resemble the following.

CIRCUITPY

To get connected, the next thing you need to do is update the secrets.py file.

Secrets File

We expect people to share tons of projects as they build CircuitPython WiFi widgets. What we want to avoid is people accidentally sharing their passwords or secret tokens and API keys. So, we designed all our examples to use a secrets.py file, that is on your CIRCUITPY drive, to hold secret/private/custom data. That way you can share your main project without worrying about accidentally sharing private stuff.

The initial secrets.py file on your CIRCUITPY drive should look like this:

# SPDX-FileCopyrightText: 2020 Adafruit Industries
#
# SPDX-License-Identifier: Unlicense

# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'home_wifi_network',
    'password' : 'wifi_password',
    'aio_username' : 'my_adafruit_io_username',
    'aio_key' : 'my_adafruit_io_key',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    }

Inside is a Python dictionary named secrets with a line for each entry. Each entry has an entry name (say 'ssid') and then a colon to separate it from the entry key ('home_wifi_network') and finally a comma (,).

At a minimum you'll need to adjust the ssid and password for your local WiFi setup so do that now!

As you make projects you may need more tokens and keys, just add them one line at a time. See for example other tokens such as one for accessing GitHub or the Hackaday API. Other non-secret data like your timezone can also go here, just cause its called secrets doesn't mean you can't have general customization data in there!

For the correct time zone string, look at http://worldtimeapi.org/timezones and remember that if your city is not listed, look for a city in the same time zone, for example Boston, New York, Philadelphia, Washington DC, and Miami are all on the same time as New York.

Of course, don't share your secrets.py - keep that out of GitHub, Discord or other project-sharing sites.

Don't share your secrets.py file, it has your passwords and API keys in it!

If you connect to the serial console, you should see something like the following:

In order, the example code...

Checks the ESP32's MAC address.

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

Performs a scan of all access points and prints out the access point's name (SSID), signal strength (RSSI), and channel.

print("Avaliable WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

Connects to the access point you defined in the secrets.py file, prints out its local IP address, and attempts to ping google.com to check its network connectivity. 

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print(print("Connected to %s!"%secrets["ssid"]))
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % wifi.radio.ping(ipv4))

The code creates a socketpool using the wifi radio's available sockets. This is performed so we don't need to re-use sockets. Then, it initializes a a new instance of the requests interface - which makes getting data from the internet really really easy.

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

To read in plain-text from a web URL, call requests.get - you may pass in either a http, or a https url for SSL connectivity. 

print("Fetching text from", TEXT_URL)
response = requests.get(TEXT_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

Requests can also display a JSON-formatted response from a web URL using a call to requests.get

print("Fetching json from", JSON_QUOTES_URL)
response = requests.get(JSON_QUOTES_URL)
print("-" * 40)
print(response.json())
print("-" * 40)

Finally, you can fetch and parse a JSON URL using requests.get. This code snippet obtains the stargazers_count field from a call to the GitHub API.

print("Fetching and parsing json from", JSON_STARS_URL)
response = requests.get(JSON_STARS_URL)
print("-" * 40)
print("CircuitPython GitHub Stars", response.json()["stargazers_count"])
print("-" * 40)

OK you now have your ESP32 board set up with a proper secrets.py file and can connect over the Internet. If not, check that your secrets.py file has the right ssid and password and retrace your steps until you get the Internet connectivity working!

Now let's go over the code that runs on the sensor. The code checks the temperature and humidity, formats it, then publishes directly to the MQTT server.

MQTT Secrets Settings

Since the code publishes directly to the MQTT server, there are a few more secret settings that the code expects to find. If your MQTT server has no username and password, you can change the value to None, however in general, the Home Assistant MQTT broker is setup to be password protected by default.

'mqtt_broker': "192.168.1.1",
'mqtt_port': 1883,
'mqtt_username': 'myusername',
'mqtt_password': 'mypassword',

Temperature Reading

You may notice the temperature comes across a bit higher than the actual room temperature. To see some techniques to improve it, take a look at our Temperature Logger example.

Download the Project Bundle

Your project will use a specific set of CircuitPython libraries and the code.py file. In order to get the libraries you need, click on the Download Project Bundle link below, and uncompress the .zip file.

Next, drag the contents of the uncompressed bundle directory onto you microcontroller board's CIRCUITPY drive, replacing any existing files or directories with the same names, and adding any new ones that are necessary.

The files on your FunHouse should look like this:

# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import time
import json
from adafruit_display_shapes.circle import Circle
from adafruit_funhouse import FunHouse

PUBLISH_DELAY = 60
ENVIRONMENT_CHECK_DELAY = 5
ENABLE_PIR = True
MQTT_TOPIC = "funhouse/state"
LIGHT_STATE_TOPIC = "funhouse/light/state"
LIGHT_COMMAND_TOPIC = "funhouse/light/set"
INITIAL_LIGHT_COLOR = 0x008000
USE_FAHRENHEIT = True

try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

funhouse = FunHouse(default_bg=0x0F0F00)
funhouse.peripherals.dotstars.fill(INITIAL_LIGHT_COLOR)

# Don't display the splash yet to avoid
# redrawing labels after each one is added
funhouse.display.show(None)

# Add the labels
funhouse.add_text(
    text="Temperature:",
    text_position=(20, 30),
    text_color=0xFF8888,
    text_font="fonts/Arial-Bold-24.pcf",
)
temp_label = funhouse.add_text(
    text_position=(120, 60),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Humidity:",
    text_position=(20, 100),
    text_color=0x8888FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
hum_label = funhouse.add_text(
    text_position=(120, 130),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Pressure:",
    text_position=(20, 170),
    text_color=0xFF88FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
pres_label = funhouse.add_text(
    text_position=(120, 200),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)

# Now display the splash to draw all labels at once
funhouse.display.show(funhouse.splash)

status = Circle(229, 10, 10, fill=0xFF0000, outline=0x880000)
funhouse.splash.append(status)

def update_enviro():
    global environment

    temp = funhouse.peripherals.temperature
    unit = "C"
    if USE_FAHRENHEIT:
        temp = temp * (9 / 5) + 32
        unit = "F"

    environment["temperature"] = temp
    environment["pressure"] = funhouse.peripherals.pressure
    environment["humidity"] = funhouse.peripherals.relative_humidity
    environment["light"] = funhouse.peripherals.light

    funhouse.set_text("{:.1f}{}".format(environment["temperature"], unit), temp_label)
    funhouse.set_text("{:.1f}%".format(environment["humidity"]), hum_label)
    funhouse.set_text("{}hPa".format(environment["pressure"]), pres_label)


def connected(client, userdata, result, payload):
    status.fill = 0x00FF00
    status.outline = 0x008800
    print("Connected to MQTT! Subscribing...")
    client.subscribe(LIGHT_COMMAND_TOPIC)


def disconnected(client):
    status.fill = 0xFF0000
    status.outline = 0x880000


def message(client, topic, payload):
    print("Topic {0} received new value: {1}".format(topic, payload))
    if topic == LIGHT_COMMAND_TOPIC:
        settings = json.loads(payload)
        if settings["state"] == "on":
            if "brightness" in settings:
                funhouse.peripherals.dotstars.brightness = settings["brightness"] / 255
            else:
                funhouse.peripherals.dotstars.brightness = 0.3
            if "color" in settings:
                funhouse.peripherals.dotstars.fill(settings["color"])
        else:
            funhouse.peripherals.dotstars.brightness = 0
        publish_light_state()


def publish_light_state():
    funhouse.peripherals.led = True
    output = {
        "brightness": round(funhouse.peripherals.dotstars.brightness * 255),
        "state": "on" if funhouse.peripherals.dotstars.brightness > 0 else "off",
        "color": funhouse.peripherals.dotstars[0],
    }
    # Publish the Dotstar State
    print("Publishing to {}".format(LIGHT_STATE_TOPIC))
    funhouse.network.mqtt_publish(LIGHT_STATE_TOPIC, json.dumps(output))
    funhouse.peripherals.led = False


# Initialize a new MQTT Client object
funhouse.network.init_mqtt(
    secrets["mqtt_broker"],
    secrets["mqtt_port"],
    secrets["mqtt_username"],
    secrets["mqtt_password"],
)
funhouse.network.on_mqtt_connect = connected
funhouse.network.on_mqtt_disconnect = disconnected
funhouse.network.on_mqtt_message = message

print("Attempting to connect to {}".format(secrets["mqtt_broker"]))
funhouse.network.mqtt_connect()

last_publish_timestamp = None

last_peripheral_state = {
    "button_up": funhouse.peripherals.button_up,
    "button_down": funhouse.peripherals.button_down,
    "button_sel": funhouse.peripherals.button_sel,
    "captouch6": funhouse.peripherals.captouch6,
    "captouch7": funhouse.peripherals.captouch7,
    "captouch8": funhouse.peripherals.captouch8,
}

if ENABLE_PIR:
    last_peripheral_state["pir_sensor"] = funhouse.peripherals.pir_sensor

environment = {}
update_enviro()
last_environment_timestamp = time.monotonic()

# Provide Initial light state
publish_light_state()

while True:
    if not environment or (
        time.monotonic() - last_environment_timestamp > ENVIRONMENT_CHECK_DELAY
    ):
        update_enviro()
        last_environment_timestamp = time.monotonic()
    output = environment

    peripheral_state_changed = False
    for peripheral in last_peripheral_state:
        current_item_state = getattr(funhouse.peripherals, peripheral)
        output[peripheral] = "on" if current_item_state else "off"
        if last_peripheral_state[peripheral] != current_item_state:
            peripheral_state_changed = True
            last_peripheral_state[peripheral] = current_item_state

    if funhouse.peripherals.slider is not None:
        output["slider"] = funhouse.peripherals.slider
        peripheral_state_changed = True

    # Every PUBLISH_DELAY, write temp/hum/press/light or if a peripheral changed
    if (
        last_publish_timestamp is None
        or peripheral_state_changed
        or (time.monotonic() - last_publish_timestamp) > PUBLISH_DELAY
    ):
        funhouse.peripherals.led = True
        print("Publishing to {}".format(MQTT_TOPIC))
        funhouse.network.mqtt_publish(MQTT_TOPIC, json.dumps(output))
        funhouse.peripherals.led = False
        last_publish_timestamp = time.monotonic()

    # Check any topics we are subscribed to
    funhouse.network.mqtt_loop(0.5)

How the Code Works

First there are our imports. Many of the imports include built-in modules such as json as well as the adafruit_display_shapes, and the adafruit_funhouse libraries.

import time
import json
from adafruit_display_shapes.circle import Circle
from adafruit_funhouse import FunHouse

In the next section, there are quite a few settings that you can adjust.

First, the PUBLISH_DELAY setting is the amount of time in seconds to wait before updating the temperature and humidity.

The ENVIRONMENT_CHECK_DELAY is the amount of time to delay in between reading the environmental sensors such as temperature and humidity and updating the labels. The reason we have a delay is to give time to other events.

The ENABLE_PIR setting can be set to False if you either do not have a PIR sensor or would not like the sensor to automatically trigger anything.

The MQTT_TOPIC is the topic that holds the state of the FunHouse sensors. To read more about MQTT Topics, you can check out the MQTT Topics section of our All the Internet of Things Protocols guide.

The LIGHT_STATE_TOPIC is the topic that holds the state of the DotStar LEDs and is tells Home Assistant what the current state of the LEDS is to allow it to act like an RGB bulb.

The LIGHT_COMMAND_TOPIC is the topic that the FunHouse listens to in order to change the state of the DotStar LEDs through Home Assistant.

The INITIAL_LIGHT_COLOR setting is the initial color of the DotStar LEDs.

If USE_FAHRENHEIT is set to True, the temperature displayed on the screen will be in Fahrenheit. Changing this setting also affects the units that are sent to Home Assistant.

PUBLISH_DELAY = 60
ENVIRONMENT_CHECK_DELAY = 5
ENABLE_PIR = True
MQTT_TOPIC = "funhouse/state"
LIGHT_STATE_TOPIC = "funhouse/light/state"
LIGHT_COMMAND_TOPIC = "funhouse/light/set"
INITIAL_LIGHT_COLOR = 0x008000
USE_FAHRENHEIT = True

Next the script imports secrets. This includes the WiFi connection and the MQTT connection information.

try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

Next the FunHouse is initialized with a default background and the INITIAL_LIGHT_COLOR.

funhouse = FunHouse(default_bg=0x0F0F00)
funhouse.peripherals.dotstars.fill(INITIAL_LIGHT_COLOR)

In this next section, the display labels are created. funhouse.display.show(None) is called first first so that it doesn't draw each label sequentially and end the section with funhouse.display.show(funhouse.splash) to trigger drawing everything that's in the splash group, which is the group all labels are added to when created.

funhouse.display.show(None)
funhouse.add_text(
    text="Temperature:",
    text_position=(20, 30),
    text_color=0xFF8888,
    text_font="fonts/Arial-Bold-24.pcf",
)
temp_label = funhouse.add_text(
    text_position=(120, 60),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Humidity:",
    text_position=(20, 100),
    text_color=0x8888FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
hum_label = funhouse.add_text(
    text_position=(120, 130),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Pressure:",
    text_position=(20, 170),
    text_color=0xFF88FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
pres_label = funhouse.add_text(
    text_position=(120, 200),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.display.show(funhouse.splash)

Next the script creates the circle to indicated whether the board is connected to the MQTT server or not. It is created with a default color of red.

status = Circle(229, 10, 10, fill=0xFF0000, outline=0x880000)
funhouse.splash.append(status)

Next up is the update_enviro() function. This function will gather the environmental and light sensor settings, change the temperature to Fahrenheit if  set to do so, update the environment dictionary and change the labels on the display.

def update_enviro():
    global environment

    temp = funhouse.peripherals.temperature
    unit = "C"
    if USE_FAHRENHEIT:
        temp = temp * (9 / 5) + 32
        unit = "F"

    environment["temperature"] = temp
    environment["pressure"] = funhouse.peripherals.pressure
    environment["humidity"] = funhouse.peripherals.relative_humidity
    environment["light"] = funhouse.peripherals.light

    funhouse.set_text("{:.1f}{}".format(environment["temperature"], unit), temp_label)
    funhouse.set_text("{:.1f}%".format(environment["humidity"]), hum_label)
    funhouse.set_text("{}hPa".format(environment["pressure"]), pres_label)

After that are the MQTT connect and disconnect handlers. These handle updating the connection status indicator and subscribing to any topics.

def connected(client, userdata, result, payload):
    status.fill = 0x00FF00
    status.outline = 0x008800
    print("Connected to MQTT! Subscribing...")
    client.subscribe(LIGHT_COMMAND_TOPIC)


def disconnected(client):
    status.fill = 0xFF0000
    status.outline = 0x880000

For the message handler, it will wait for the any new message that it is subscribed to. Then it will make sure the topic is the value of the LIGHT_COMMAND_TOPIC before proceeding. Next it will decode the payload as JSON. If the state is "on", it will look for additional settings in the payload.

If it finds brightness, it will convert it from 0-255 to 0-1.0 and set the DotStars to that brightness. If it finds color, it will set the DotStars to that color using the fill() command. After it changes the DotStars, it will publish the light state so the Home Assistant UI can update its settings.

def message(client, topic, payload):
    print("Topic {0} received new value: {1}".format(topic, payload))
    if topic == LIGHT_COMMAND_TOPIC:
        settings = json.loads(payload)
        print(settings)
        if settings["state"] == "on":
            if "brightness" in settings:
                funhouse.peripherals.dotstars.brightness = settings["brightness"] / 255
            else:
                funhouse.peripherals.dotstars.brightness = 0.3
            if "color" in settings:
                funhouse.peripherals.dotstars.fill(settings["color"])
        else:
            funhouse.peripherals.dotstars.brightness = 0
        publish_light_state()

The publish_light_state() function will gather the current state of the DotStars and publish it in a way that is meaningful to Home Assistant.

def publish_light_state():
    funhouse.peripherals.led = True
    output = {
        "brightness": round(funhouse.peripherals.dotstars.brightness * 255),
        "state": "on" if funhouse.peripherals.dotstars.brightness > 0 else "off",
        "color": funhouse.peripherals.dotstars[0],
    }
    # Publish the Dotstar State
    print("Publishing to {}".format(LIGHT_STATE_TOPIC))
    funhouse.network.mqtt_publish(LIGHT_STATE_TOPIC, json.dumps(output))
    funhouse.peripherals.led = False

With the functions all defined, MQTT is initialized in the FunHouse library using the settings in the secrets file. The handler function are then set and the code attempts to connect to the MQTT server.

# Initialize a new MQTT Client object
funhouse.network.init_mqtt(
    secrets["mqtt_broker"],
    secrets["mqtt_port"],
    secrets["mqtt_username"],
    secrets["mqtt_password"],
)
funhouse.network.on_mqtt_connect = connected
funhouse.network.on_mqtt_disconnect = disconnected
funhouse.network.on_mqtt_message = message

print("Attempting to connect to {}".format(secrets["mqtt_broker"]))
funhouse.network.mqtt_connect()

After that, some data variables are set up with initial states. This includes a variable to hold the last time that we published the general FunHouse state to MQTT and the last values of the peripheral so we can monitor when they change.

We also update the environment and display with the update_enviro() function we defined earlier.

Finally we publish the current state of the DotStars with publish_light_state().

last_publish_timestamp = None

last_peripheral_state = {
    "button_up": funhouse.peripherals.button_up,
    "button_down": funhouse.peripherals.button_down,
    "button_sel": funhouse.peripherals.button_sel,
    "captouch6": funhouse.peripherals.captouch6,
    "captouch7": funhouse.peripherals.captouch7,
    "captouch8": funhouse.peripherals.captouch8,
}

if ENABLE_PIR:
    last_peripheral_state["pir_sensor"] = funhouse.peripherals.pir_sensor

environment = {}
update_enviro()
last_environment_timestamp = time.monotonic()

# Provide Initial light state
publish_light_state()

Now we get to the main loop.

First the code checks if the amount of time in ENVIRONMENT_CHECK_DELAY has passed and if so, calls update_enviro(). The current environment dictionary is used as the basis for the output data.

if not environment or (time.monotonic() - last_environment_timestamp > ENVIRONMENT_CHECK_DELAY):
    update_enviro()
    last_environment_timestamp = time.monotonic()
output = environment

In the next section each of the peripherals is checked and updated. If anything has changed, the peripheral_state_changed variable is set to True which triggers publishing an update a bit later on.

peripheral_state_changed = False
for peripheral in last_peripheral_state:
    current_item_state = getattr(funhouse.peripherals, peripheral)
    output[peripheral] = "on" if current_item_state else "off"
    if last_peripheral_state[peripheral] != current_item_state:
        peripheral_state_changed = True
        last_peripheral_state[peripheral] = current_item_state

Since the slider returns a number between 0-1 or None if not touched, this needs to be checked separately from the other Peripherals and is only added if it is being used.

if funhouse.peripherals.slider is not None:
    output["slider"] = funhouse.peripherals.slider
    peripheral_state_changed = True

If the peripheral_state_changed variable is True or the amount of time in PUBLISH_DELAY has elapsed, the state of the FunHouse is published.

if (
    last_publish_timestamp is None
    or peripheral_state_changed
    or (time.monotonic() - last_publish_timestamp) > PUBLISH_DELAY
):
    funhouse.peripherals.led = True
    print("Publishing to {}".format(MQTT_TOPIC))
    funhouse.network.mqtt_publish(MQTT_TOPIC, json.dumps(output))
    funhouse.peripherals.led = False
    last_publish_timestamp = time.monotonic()

Finally the MQTT loop is run. In order to increase the responsiveness of the buttons, a timeout value of 0.5 seems to work well. If the value is too small, it won't have enough time to respond to MQTT messages and if it is too large, it is possible to miss peripheral change events.

# Check any topics we are subscribed to
funhouse.network.mqtt_loop(0.5)

Debugging the Sensor

If you would like to monitor what the sensor is doing, you can look at our guide on Connecting to the Serial Console with CircuitPython. Once you are connected, it can help with any troubleshooting.

This guide assumes you already have a working and running Home Assistant server. If you don't, be sure to visit our Set up Home Assistant with a Raspberry Pi guide first.

Check Your Add-Ons

Start out by logging in and opening up your Home Assistant dashboard and checking that the File editor is installed. 

As part of the setup, you should have an add-on either called configurator or File editor with a wrench icon next to it. Go ahead and select it.

If you don't see it, it may not be installed. You can find it under Supervisor Add-on Store File editor and go through the installation procedure.

If you already have it, but it's just not showing up, be sure it is started and the option to show in the sidebar is selected.

Environment Data Setup

Next you'll want to open up the File Editor and add the Environment Data.

Click on the Folder Icon at the top and select configuration.yaml, then click on an area to the right of the file list to close it.

Add the following code to the bottom of the configuration file. Make sure the state_topic values match the MQTT_TOPIC value you used in the sensor code.

sensor Office_Temp:
- platform: mqtt
  name: "Temperature"
  state_topic: "funhouse/state"
  unit_of_measurement: '°F'
  value_template: "{{ value_json.temperature }}"
- platform: mqtt
  name: "Humidity"
  state_topic: "funhouse/state"
  unit_of_measurement: '%'
  value_template: "{{ value_json.humidity }}"
- platform: mqtt
  name: "Pressure"
  state_topic: "funhouse/state"
  unit_of_measurement: 'hPa'
  value_template: "{{ value_json.pressure }}"

Click the save button at the top.

If you have the Check Home Assistant configuration tool installed, now would be a good time to run it. It takes several minutes to run and you can check the log tab to see the results.

From the Configuration menu, choose Server Controls. Here you can check that the configuration is valid and click on Restart to load the configuration changes you made.

With the latest releases of Home Assistant, a LoveLace dashboard was added. If you haven't edited the Dashboard, it should automatically appear.

Otherwise, you may need to manually add a card to the dashboard.

Using the Peripherals for Automation

To create an automation event and use one of the peripherals to trigger an existing entity, is pretty easy. For instance, if you had a light named My_Light that you wanted to toggle when the Select button is pressed, you would add some code to configuration.yml similar to the following:

automation button_sel:
  trigger:
    - platform: mqtt
      topic: "funhouse/state"
      payload: "on"
      value_template: "{{ value_json.button_sel }}"
  action:
    service: light.toggle
    entity_id: light.My_Light

This adds an Automation trigger that checks the button_sel JSON value in the funhouse/state MQTT topic for a value of on. When these conditions are met, the action is triggered.

In the action section, the light.toggle event is fired on the light.My_Light entity.

Be sure to Restart your Server as described in the Environment Data Setup section.

Once you have restarted, try pressing the Middle button on your FunHouse. It should toggle your light. You may need to hold it down for a second or so for it to activate.

Emulating an RGB Bulb

You can also emulate an RGB light with the FunHouse DotStar LEDs. You'll want to add the following code to your configuration. 

light FunHouse_light:
  - platform: mqtt
    schema: template
    name: "FunHouse Light"
    command_topic: "funhouse/light/set"
    state_topic: "funhouse/light/state"
    command_on_template: >
      {"state": "on"
      {%- if brightness is defined -%}
      , "brightness": {{ brightness }}
      {%- endif -%}
      {%- if red is defined and green is defined and blue is defined -%}
      , "color": [{{ red }}, {{ green }}, {{ blue }}]
      {%- endif -%}
      }
    command_off_template: '{"state": "off"}'
    state_template: "{{ value_json.state }}"
    brightness_template: '{{ value_json.brightness }}'
    red_template: '{{ value_json.color[0] }}'
    green_template: '{{ value_json.color[1] }}'
    blue_template: '{{ value_json.color[2] }}'

Once you have added that to your configuration, go ahead and restart the server. The FunHouse Light should appear under your lights.

Go ahead and click on the bulb icon and a Color and Brightness dialog should come up. Go ahead and change the values.

Changing these values should update the value on your FunHouse.

Troubleshooting

If you see the icons, but there is no data, it is easiest to start by checking the MQTT messages. We have a guide on how to use Desktop MQTT Client for Adafruit.io, which can be used for the Home Assistant MQTT server as well.

Go ahead and configure a username and password to match your MQTT server and connect. Under subscribe, you can subscribe to the # topic to get all messages.

If you are seeing messages from the sensor, you may want to double check your Home Assistant configuration.

If you don't see any messages, you will want to follow the debugging section on the Code the Sensor page.

This guide was first published on Apr 22, 2021. It was last updated on Apr 22, 2021.