Arm Community
Arm Community
  • Site
  • User
  • Site
  • Search
  • User
Arm Community blogs
Arm Community blogs
Internet of Things (IoT) blog Build a Matter home automation service using Raspberry Pi, Arm Virtual Hardware and Python
  • Blogs
  • Mentions
  • Sub-Groups
  • Tags
  • Jump...
  • Cancel
More blogs in Arm Community blogs
  • AI blog

  • Announcements

  • Architectures and Processors blog

  • Automotive blog

  • Embedded and Microcontrollers blog

  • Internet of Things (IoT) blog

  • Laptops and Desktops blog

  • Mobile, Graphics, and Gaming blog

  • Operating Systems blog

  • Servers and Cloud Computing blog

  • SoC Design and Simulation blog

  • Tools, Software and IDEs blog

Tags
  • Raspberry Pi
  • Smart Homes
  • Cortex-A
  • Cortex-M
  • python
  • Internet of Things (IoT)
  • Arm Virtual Hardware
Actions
  • RSS
  • More
  • Cancel
Related blog posts
Related forum threads

Build a Matter home automation service using Raspberry Pi, Arm Virtual Hardware and Python

Sandeep Mistry
Sandeep Mistry
November 17, 2022
6 minute read time.

In October of 2022, the Connectivity Standards Alliance announced the release of the Matter 1.0 specification and SDK. With this release, anyone building on Arm will be able to produce and sell home automation services. The combination of the Matter protocol and Arm standards such as PSA certified, Project Cassini, and Project Centauri removes the fragmentation of devices from different suppliers. The race is on as Matter compliant devices have already been introduced into the market. The expectation is that a few billion Matter compliant devices will be sold over the next few years.

The next question is how to open this opportunity to all developers besides the established embedded experts. Python is one way to do so. The number of Python developers is increasing 20% per year and was estimated to be approximately 10 million in 2021. All we need now is a platform to run Matter and Python. What better choice than the ubiquitous Raspberry Pi Model B.

Spoiler alert, the output of this exercise is a Matter lighting home automation service created using Python. The service runs on a Raspberry Pi or a virtual Raspberry Pi in the cloud through Arm Virtual Hardware (AVH) as the same code runs on both as is. The service controls a LED that is connected to a Raspberry Pi and control is over the IP network.

To understand more about Matter and the Arm Virtual Hardware and its benefits, you can read my previous blog in this series here.

Building a smart home device

What you need

Lighting device

  • Raspberry Pi 4 board
  • MicroSD card, 16GB or greater in size
  • USB C Power supply
  • Ethernet cable
  • Breadboard
  • LED
  • 1k ohm resistor
  • Jumper wires

Device controller

For the physical board

  • Raspberry Pi 4 board
  • MicroSD card, 16GB or greater in size
  • USB C Power supply
  • Ethernet cable

For the Arm Virtual Hardware Raspberry Pi 4 board

  • Register to access the Arm Virtual Hardware private beta
  • Already registered? Login here

The first implementation will run the light service between two Raspberry Pi boards.

building a smart home device with physical Raspberry Pi

Setting up the Lighting device

1. Use a breadboard and the jumper wires to connect the resistor and LED to the Raspberry Pi 4 board on GPIO17. Further information: https://www.raspberrypi.com/documentation/computers/os.html#gpio-pinout)

Raspberry Pi Breadboard with LED

2. Insert the microSD card into the microSD card reader and connect it to your PC.

3. Using Raspberry Pi Imager tool to flash a microSD card with

a. Click the “Choose OS” button, then click on “Raspberry Pi OS (other)” -> “Raspberry Pi OS Lite (64-bit)”

Raspberry Pi OS Lite

b. Click the “Gear” icon in the bottom corner

Raspberry Pi OS

c. Enter a name and set the username and password for SSH

Raspberry Pi Imager

d. Click the “Choose Storage” button and select the entry for the microSD card

e. Click the “Write” button

4. Insert the microSD card into the Raspberry Pi, connect the Ethernet cable to your network, and then connect power supply to the board to turn it on

5. SSH in to the Raspberry Pi using <username>@matter-light.local

6. Install build dependencies

sudo apt-get update

sudo apt-get install git gcc g++ python3 pkg-config libssl-dev libdbus-1-dev libglib2.0-dev libavahi-client-dev ninja-build python3-venv python3-dev python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev

7. Clone Matter repo and submodules

git clone https://github.com/project-chip/connectedhomeip.git

cd connectedhomeip

git checkout db49235c39635582ea522929f9905af03e3114c7

./scripts/checkout_submodules.py --shallow --platform linux

8. Bootstrap the build

./scripts/build/gn_bootstrap.sh

source scripts/activate.sh

9. Build the Python and install the wheel

./scripts/build_python_device.sh --chip_detail_logging true

10. Activate Python virtual environment

source ./out/python_env/bin/activate

11. Enable GPIO permissions

sudo usermod -a -G gpio <username>

12. Install the gpiozero package (recommended from here).

pip3 install gpiozero

13. Create a new file named lighting.py with the following:

from chip.server import (
    GetLibraryHandle,
    NativeLibraryHandleMethodArguments,
    PostAttributeChangeCallback,
)

from chip.exceptions import ChipStackError

import sys
import os

from gpiozero import LED

led = LED(17)

@PostAttributeChangeCallback
def attributeChangeCallback(
    endpoint: int,
    clusterId: int,
    attributeId: int,
    xx_type: int,
    size: int,
    value: bytes,
):
    if endpoint == 1:
        if clusterId == 6 and attributeId == 0:
            if len(value) >= 1 and value[0] == 1:
                print("[PY] light on")
                led.on()
            else:
                print("[PY] light off")
                led.off()

chipLib = GetLibraryHandle(attributeChangeCallback)

input('Press enter to quit')

sys.exit(0)

14. Start the application

python3 lighting.py

To reset the device config:

rm /tmp/chip_*

Setting up the device controller (physical) device

1. Repeat steps 2-8 above, but using the name “matter-controller.local” in step 3c and 5.

2. Build and install the Device Controller wheel:

./scripts/build_python.sh -d true -i separate

3. Activate the Python virtual environment

source ./out/python_env/bin/activate

Using Arm Virtual Hardware as the device controller device

In this section, the Raspberry Pi is replaced with an AVH Raspberry Pi. The same Python service code will run as above. The difference is that one can create 100 smart hubs as such and run 100 tests in parallel if necessary as opposed to creating a board farm.

Building a smart home device with Arm Virtual Hardware

1. Create new virtual Raspberry Pi device on AVH with the Raspberry Pi OS Lite OS option.

2. Using the console interface run steps 6-8 from “Setting up the Lighting device” section

3. Run steps 2-3 from “Setting up the Device Controller (physical) device” section

4. Download the AVH VPN profile to Lighting device

5. Install openvpn on lighting device

sudo apt-get install openvpn

6. Start a new SSH session and login using: <username>@matter-light.local

7. Start VPN connection

sudo openvpn --config 'app.avh.arm.com VPN - Default Project.ovpn'

8. Restart the Python lighting app in original SSH session.

Control

1. On Device Controller device run (make sure you are in git project root!)

chip-repl

2. Discover commissionable devices

devices = devCtrl.DiscoverCommissionableNodes(filter=3840, stopOnFirst=True, timeoutSecond=20)

3. Commission the device setting node id to 233 and using code 20202021 

devices[0].Commission(233, 20202021)

4. Turn the light on:

await devCtrl.SendCommand(233, 1, Clusters.OnOff.Commands.On())

5. Turn off the light: 

await devCtrl.SendCommand(233, 1, Clusters.OnOff.Commands.Off())

6. Toggle the light:

await devCtrl.SendCommand(233, 1, Clusters.OnOff.Commands.Toggle())

Conclusion

The age of true home automation starts now. The Matter protocol removes the last barrier for deployment. Arm and our ecosystem deliver the IP, tools, software services, and security frameworks to best address the wildly diverse nature of smart home devices. As such, Arm is the platform on which Matter-compliant devices will emerge first. There are many Arm-based platforms on the market today for developers to get started with, such as the Raspberry Pi and the NXP i.Mx8M based boards. The platform software is usually bundled with the hardware. The Matter SDK is open source from the Connectivity Standards Alliance (CSA). Any developer simply must create the automation service on top of the Matter platform. There is no limit to what is possible. If one can imagine it, then it can be created and deployed.

smart home hub software stack

It only takes a few minutes to prepare a Matter platform and to start creating a home automation service using Python. Arm has even made the starting point so much easier by offering the Raspberry Pi on Arm Virtual Hardware. Developers can get started even when they do not yet have the hardware on their desk.

In an ideal scenario, anyone can create and test the service on a virtual Raspberry Pi and then deploy the code worldwide to a real Raspberry Pi because AVH and the real Raspberry Pi are binary compatible. The IoT runs on Arm, and we have a responsibility to create greater opportunities for innovation and scale by continually raising the bar on performance, simplified development, and software reuse. As such, we introduced Arm Virtual Hardware, a transformative offering, to enable software development in the cloud to empower developers to capture emerging market opportunities.

Explore what Arm Virtual Hardware can do for your team then:

  • Explore resources and information
  • Explore the API that is available to access AVH functionality through scripts

Get started using this example by registering for the Arm Virtual Hardware private beta:

Register for Arm Virtual Hardware

Anonymous

Top Comments

  • bluebird
    bluebird over 2 years ago +1
    I have completed steps 1-14 of the device setup and have also completed the controller setup, but even after sending commands, the LED does not light up. I think that "Discover Commissionable Devices"...
  • Alexis Ware
    Alexis Ware 2 months ago

    I recently came across your blog on Building a Matter Home Automation Service Using Raspberry Pi, Arm Virtual Hardware, and Python—thanks for sharing! Your insights on how Matter and Arm standards are reducing device fragmentation were very informative.

    While exploring more, I found this resource A Developer’s Guide to Matter Protocol: Building Smart Home Applications With Matter SDK: https://mobisoftinfotech.com/resources/blog/matter-protocol-smart-home-developers-guide . It covers Matter connectivity, security considerations, and smart home interoperability.

    What are some key performance optimizations for scaling a Matter over Thread network? Also, how do you see Matter Multi-Admin improving smart home connectivity? Looking forward to your insights—great read!

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
  • Andrew losty
    Andrew losty 11 months ago

    Have working Matter environment , are there any plans to add OTA over-the-air software update support to the Matter test environment.

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
  • Evil.storyteller
    Evil.storyteller over 1 year ago

    On step 8, gn_bootstrap.sh errors out with

    Collecting grpc>=1.0.0
      Downloading grpc-1.0.0.tar.gz (5.2 kB)
      Preparing metadata (setup.py): started
      Preparing metadata (setup.py): finished with status 'error'
      error: subprocess-exited-with-error

      × python setup.py egg_info did not run successfully.
      │ exit code: 1
      ╰─> [6 lines of output]
          Traceback (most recent call last):
            File "<string>", line 2, in <module>
            File "<pip-setuptools-caller>", line 34, in <module>
            File "/tmp/pip-install-59k8fwfy/grpc_7e77bd6b6ea24a128788d72b882923ba/setup.py", line 33, in <module>
              raise RuntimeError(HINT)
          RuntimeError: Please install the official package with: pip install grpcio
          [end of output]

      note: This error originates from a subprocess, and is likely not a problem with pip.
    error: metadata-generation-failed

    × Encountered error while generating package metadata.
    ╰─> See above for output.

    note: This is an issue with the package mentioned above, not pip.
    hint: See above for details.
    ninja: build stopped: subcommand failed.
    ['ninja', '-C', '/home/pi/connectedhomeip/.environment/gn_out', '-v', ':python_packages.install']

    Traceback (most recent call last):
      File "/home/pi/connectedhomeip/third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/virtualenv_setup/install.py", line 327, in install_packages
        subprocess.check_call(ninja_cmd, stdout=outs, stderr=outs)
      File "/usr/lib/python3.11/subprocess.py", line 413, in check_call
        raise CalledProcessError(retcode, cmd)
    subprocess.CalledProcessError: Command '['ninja', '-C', '/home/pi/connectedhomeip/.environment/gn_out', '-v', ':python_packages.install']' returned non-zero exit status 1.

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "/home/pi/connectedhomeip/third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/env_setup.py", line 795, in <module>
        sys.exit(main())
                 ^^^^^^
      File "/home/pi/connectedhomeip/third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/env_setup.py", line 787, in main
        return EnvSetup(**vars(parse())).setup()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pi/connectedhomeip/third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/env_setup.py", line 457, in setup
        result = step(spin)
                 ^^^^^^^^^^
      File "/home/pi/connectedhomeip/third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/env_setup.py", line 606, in virtualenv
        if not virtualenv_setup.install(
               ^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pi/connectedhomeip/third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/virtualenv_setup/install.py", line 342, in install
        install_packages(gn_target)
      File "/home/pi/connectedhomeip/third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/virtualenv_setup/install.py", line 330, in install_packages
        raise subprocess.CalledProcessError(err.returncode, err.cmd,
    subprocess.CalledProcessError: Command '['ninja', '-C', '/home/pi/connectedhomeip/.environment/gn_out', '-v', ':python_packages.install']' returned non-zero exit status 1.

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
  • KannanIdris
    KannanIdris over 1 year ago

    I am getting this error when commissioning:
    devices[0].Commission(233, 20202021)
    2024-01-26 20:30:03 raspberrypi42 chip.EM[10871] ERROR Failed to Send CHIP MessageCounter:243738286 on exchange 46631i sendCount: 4 max retries: 4
    2024-01-26 20:30:06 raspberrypi42 chip.SC[10871] ERROR PASESession timed out while waiting for a response from the peer. Expected message type was 33
    Established secure session with Device
    Failed to commission: ../../src/protocols/secure_channel/PASESession.cpp:254: CHIP Error 0x00000032: Timeout

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
  • bluebird
    bluebird over 2 years ago

    I have completed steps 1-14 of the device setup and have also completed the controller setup, but even after sending commands, the LED does not light up. I think that "Discover Commissionable Devices" is not working properly, but I'm just guessing. Any advice would be appreciated.

    • Cancel
    • Up +1 Down
    • Reply
    • More
    • Cancel
>
Internet of Things (IoT) blog
  • Building vision-enabled devices to capture the emerging wave in IoT

    Diya Soubra
    Diya Soubra
    IoT devices will drive an explosion in use cases with vision. Read more about the different use cases and what Arm technology is involved here.
    • December 9, 2024
  • The power of SystemReady for custom-built OS distributions

    Pere Garcia
    Pere Garcia
    Arm developed the SystemReady Devicetree band as part of the SystemReady program, learn more in this blog post.
    • November 22, 2024
  • Software, Tools, and Ecosystem for ML Edge Devices

    Reinhard Keil
    Reinhard Keil
    Learn how Arm and our Partners enable developers and the IoT software ecosystem to deliver smart, energy efficient ML edge devices.
    • July 17, 2024