A custom HomeKit accessory with Python

Hi ๐Ÿ‘‹,

In this short article I want to showcase how I implemented a custom HomeKit accessory with python.

My Home Assistant’s SD card died ๐Ÿชฆ a few days ago and the support for GPIO based sensors will be removed in newer releases. This makes it unsuitable for my needs, while giving me the perfect opportunity to try other things.

To continue monitoring temperature and humidity in my home I’ve built a custom HomeKit accessory with HAP Python.

The Sensor

A BME680 air quality sensor is used to monitor temperature and humidity. It is connected to the PI according to the following diagram:

The communication with the Pi is done using the I2C protocol. If you want to use I2C in your own setup, it has to be enabled using raspi-config, as it doesn’t come enabled by default.

# Execute
sudo raspi-config
# Then select Interfacing options->I2C and enable it.

Connection can be tested with the following command:

sudo apt-get install build-essential libi2c-dev i2c-tools python-dev libffi-dev git
/usr/sbin/i2cdetect -y 1
pi@raspberrypi:~ $ i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:                         -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- 76 -- 

It will output the address that the sensor is using, in our case the 0x76 I2C address.

The Code for the Accessory

You can browse the full code for the accessory and bme680 sensor in my git repo.

To run the program, clone the repository and ensure that you’re running it under the pi user, otherwise you will need to change some things.

cd /home/pi && git clone git@github.com:dnutiu/bme680-homekit.git && cd bme680-homekit
sudo apt-get install libavahi-compat-libdnssd-dev
pip3 install -r requirements.txt

Verify that the program works by running python3 main.py. Running it the first time will prompt you to add the accessory to the Home app. If you miss this step you can repeat it by deleting the accessory.state file located in pi’s home directory and by running the program again.

After you’ve verified that it works, you can setup a systemd service to run the accessory’s python script when the PI boots

Copy the bme680-homekit.service to /etc/systemd/system and check that the service is running.

sudo cp bme680-homekit.service /etc/systemd/system
sudo systemctl status bme680-homekit

If you want to run this under another user rather than the pi, you’ll need to tweak the bme680-homekit.service file.

Congratulations for making it this far! ๐ŸŽ‰

You can browse more code examples in the HAP-Python repository.

Thanks for reading and have fun! ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป โš™๏ธ

Pytest Fixtures and Yield

Hi ๐Ÿ‘‹

In this short article I want to explain the use of the yield keyword in pytest fixtures.

What is pytest?

Pytest is a complex python framework used for writing tests. It has lots of advanced features and it supports plugins. Many projects prefer pytest in addition to Python’s unitttest library.

What is a fixture?

A test fixture is a piece of code that fixes some common functionality that is required for writing the unit tests. This functionality can be

  • a connection to the database
  • a testing http server or client
  • creation of a complex object

You can read more about test fixtures on Wikipedia.

What does yield keyword do?

In Python, the yield keyword is used for writing generator functions, in pytest, the yield can be used to finalize (clean-up) after the fixture code is executed. Pytest’s documentation states the following.

โ€œYieldโ€ fixtures yield instead of return. With these fixtures, we can run some code and pass an object back to the requesting fixture/test, just like with the other fixtures.

https://docs.pytest.org/en/6.2.x/fixture.html

An example code could be the following:

@pytest.fixture()
def my_object_fixture():
    print("1. fixture code.")
    yield MyObjectThatRequiresCleanUp()
    print("4. fixture code after yield.")

Running a sample test which utilizes the fixture will output:

collected 1 item                                                                                                                                                                       

tests\test_my_object.py 1. fixture code.
2. Initializing MyObjectThatRequiresCleanUp
3. test code.
.4. fixture code after yield.

Running the same test but now with the fixture my_object_fixture2, will output:

tests\test_my_object.py 1. fixture code.
2. Initializing MyObjectThatRequiresCleanUp
2.1 Entering
3. test code.
.3.1 Exiting
Clean exit
4. fixture code after yield.

I hope I could successfully ilustrate with these examples the order in which the testing and fixture code is run.

To run the tests, I’ve used pytest --capture=tee-sys . in the project root. The file contents are attached to the end of this article. The --capture parameter is used to capture and print the tests stdout. Pytest will only output stdout of failed tests and since our example test always passes this parameter was required.

Conclusion

Pytest is a python testing framework that contains lots of features and scales well with large projects.

Test fixtures is a piece of code for fixing the test environment, for example a database connection or an object that requires a specific set of parameters when built. Instead of duplicating code, fixing the object’s creation into a fixture makes the tests easier to maintain and write.

yield is a python keyword and when it is used in conjunction with pytest fixtures it gives you a nice pythonic way of cleaning up the fixtures.

Thanks for reading! ๐Ÿ“š


Contents of the Pytest fixtures placed in tests/__init__.py

import pytest

from my_object import MyObjectThatRequiresCleanUp


@pytest.fixture()
def my_object_fixture():
    print("1. fixture code.")
    yield MyObjectThatRequiresCleanUp()
    print("4. fixture code after yield.")


@pytest.fixture()
def my_object_fixture2():
    print("1. fixture code.")
    with MyObjectThatRequiresCleanUp() as obj:
        yield obj
    print("4. fixture code after yield.")

Contents of my_object.py

class MyObjectThatRequiresCleanUp:
    def __init__(self):
        print("2. Initializing MyObjectThatRequiresCleanUp")

    def __enter__(self):
        print("2.1 Entering")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("3.1 Exiting")
        if exc_type is None:
            print("Clean exit")
        else:
            print("Exception occurred: {}".format(exc_type))

Contents of test_my_object.py placed in tests/test_my_object.py

from tests import my_object_fixture


def test_my_object(my_object_fixture):
    print("3. test code.")

PS: If you want to support this blog, I’ve made a Udemy course on FastAPI. Purchasing it through my referral link will give me 96% of the sale amount. Thanks!

How to document a project with MkDocs ๐Ÿ“น

Hello,

Welcome my third video tutorial, this time, on how to get started with MkDocs.

In this video I try to give you a basic overview of MkDocs and a configuration consisting of the material theme and search plugin.

Config

The MkDocs configuration used in the video.

site_name: My Cool Project Documentation
theme:
  name: material
  features:
    - search.suggest
    - search.highlight
    - content.tabs.link
plugins:
  - search
nav:
  - Introduction: "index.md"
  - Tutorial:
      - Tutorial Subsection: "pages/tutorial/tutorial_subsection.md"
  - About: "pages/about.md"
  - FAQ: "pages/faq.md"
markdown_extensions:
  - attr_list

Docker Deployment

When you’re ready to deploy your documentation website, say in Docker with Nginx the following Dockerfile and Nginx default.conf should do.

Dockerfile

FROM python:3.9 as builder

WORKDIR /app

COPY . .

RUN pip install mkdocs mkdocs-material && mkdocs build

FROM nginx as deploy

# Copy the build to the nginx directory.
COPY --from=builder /app/site/ /usr/share/nginx/html/

# Copy the nginx configuration to the nginx config directory.
COPY default.conf /etc/nginx/conf.d/

EXPOSE 8080:8080/tcp

default.conf

server {
    listen 8080;
    root /usr/share/nginx/html/;
    index index.html;
}

I thought that making videos will be easier that typing blog posts but to my surprise the difficulty is a bit higher. Fixing mistakes takes more time with videos and since I’m not that great of a presenter I struggle with presenting the content. Hopefully I will improve my skills with time and practice.

Thanks for reading! ๐Ÿป

How to write parametrized tests in Python with pytest ๐ŸŽฅ

Hi ๐Ÿ‘‹

Welcome to another video tutorial on how to write parametrized tests in Python using pytest.

If you want to follow along, here’s the code that I’ve tested in the video.

from typing import List


class Solution:
    def move_zeroes(self, nums: List[int]) -> None:
        last_zero = 0
        index = 0
        while index < len(nums):
            if nums[index] != 0:
                nums[last_zero], nums[index] = nums[index], nums[last_zero]
                last_zero += 1
            index += 1


def main():
    solution = Solution()
    arr = [1,0,1]
    solution.move_zeroes(arr)
    print(arr)


if __name__ == '__main__':
    main()

Thanks for watching! ๐Ÿ˜„