LED On/Off

Control an LED with Matter:

examples/circuitmatter_simpletest.py
 1# SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries
 2#
 3# SPDX-License-Identifier: MIT
 4
 5"""Simple LED on and off as a light."""
 6
 7import board
 8import digitalio
 9
10import circuitmatter as cm
11from circuitmatter.device_types.lighting import on_off
12
13
14class LED(on_off.OnOffLight):
15    def __init__(self, name, led):
16        super().__init__(name)
17        self._led = led
18        self._led.direction = digitalio.Direction.OUTPUT
19
20    def on(self):
21        self._led.value = True
22
23    def off(self):
24        self._led.value = False
25
26
27matter = cm.CircuitMatter()
28led = LED("led1", digitalio.DigitalInOut(board.D13))
29matter.add_device(led)
30while True:
31    matter.process_packets()

NeoPixel

Control an RGB LED with Matter:

examples/one_rgb_light.py
 1# SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries
 2#
 3# SPDX-License-Identifier: MIT
 4
 5"""RGB LED strip as a full color light."""
 6
 7import board
 8import neopixel
 9
10import circuitmatter as cm
11from circuitmatter.device_types.lighting import extended_color
12
13
14class RGBPixel(extended_color.ExtendedColorLight):
15    def __init__(self, name, pixels):
16        super().__init__(name)
17        self._pixels = pixels
18        self._brightness = 0.1
19
20    @property
21    def color_rgb(self):
22        return self._color
23
24    @color_rgb.setter
25    def color_rgb(self, value):
26        self._pixels.fill(value)
27        print(f"new color 0x{value:06x}")
28
29    @property
30    def brightness(self):
31        return self._brightness
32
33    @brightness.setter
34    def brightness(self, value):
35        self._brightness = value
36        self._pixels.brightness = value
37        print(f"new brightness {value}")
38
39    def on(self):
40        self._pixels.brightness = self._brightness
41        print("on!")
42
43    def off(self):
44        self._pixels.brightness = 0
45        print("off!")
46
47
48matter = cm.CircuitMatter()
49# This is a 8mm NeoPixel breadboard LED. (https://www.adafruit.com/product/1734)
50# Any pixelbuf compatible strip should work. The RGBPixel class will control the
51# entire strip of pixels.
52np = neopixel.NeoPixel(board.D12, 1, pixel_order="RGB")
53led = RGBPixel("led1", np)
54matter.add_device(led)
55while True:
56    matter.process_packets()

Two On/Off LEDs

Control two LEDs with Matter:

examples/two_onoff_led.py
 1# SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries
 2#
 3# SPDX-License-Identifier: MIT
 4
 5"""Simple LED on and off as a light."""
 6
 7import board
 8import digitalio
 9
10import circuitmatter as cm
11from circuitmatter.device_types.lighting import on_off
12
13
14class LED(on_off.OnOffLight):
15    def __init__(self, name, led):
16        super().__init__(name)
17        self._led = led
18        self._led.direction = digitalio.Direction.OUTPUT
19
20    def on(self):
21        self._led.value = True
22
23    def off(self):
24        self._led.value = False
25
26
27matter = cm.CircuitMatter()
28led = LED("led1", digitalio.DigitalInOut(board.D19))
29matter.add_device(led)
30led = LED("led2", digitalio.DigitalInOut(board.D20))
31matter.add_device(led)
32while True:
33    matter.process_packets()

Record and Replay On/Off LED

Record and replay LED on/off state with Matter:

examples/replay.py
 1# SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries
 2#
 3# SPDX-License-Identifier: MIT
 4
 5"""Pure Python implementation of the Matter IOT protocol."""
 6
 7import json
 8import pathlib
 9import socket
10import time
11
12import circuitmatter as cm
13from circuitmatter.device_types.lighting import on_off
14from circuitmatter.utility import random
15from circuitmatter.utility.mdns import DummyMDNS
16from circuitmatter.utility.mdns.avahi import Avahi
17from circuitmatter.utility.recording import RecordingRandom, RecordingSocketPool
18from circuitmatter.utility.replay import ReplayRandom, ReplaySocketPool
19
20
21class NeoPixel(on_off.OnOffLight):
22    pass
23
24
25def run(replay_file=None):
26    device_state = pathlib.Path("live-device-state.json")
27    if replay_file:
28        replay_lines = []
29        with open(replay_file) as f:
30            device_state_fn = f.readline().strip()
31            for line in f:
32                replay_lines.append(json.loads(line))
33        socketpool = ReplaySocketPool(replay_lines)
34        mdns_server = DummyMDNS()
35        random_source = ReplayRandom(replay_lines)
36        # Reset device state to before the captured run
37        if device_state_fn == "none":
38            device_state.unlink(missing_ok=True)
39        else:
40            device_state.write_text(pathlib.Path(device_state_fn).read_text())
41    else:
42        timestamp = time.strftime("%Y%m%d-%H%M%S")
43        record_file = open(f"test_data/recorded_packets-{timestamp}.jsonl", "w")
44        device_state_fn = f"test_data/device_state-{timestamp}.json"
45        replay_device_state = pathlib.Path(device_state_fn)
46        if device_state.exists():
47            record_file.write(f"{device_state_fn}\n")
48            # Save device state before we run so replays can use it.
49            replay_device_state.write_text(device_state.read_text())
50        else:
51            # No starting state.
52            record_file.write("none\n")
53        socketpool = RecordingSocketPool(record_file, socket)
54        mdns_server = Avahi()
55        random_source = RecordingRandom(record_file, random)
56
57    matter = cm.CircuitMatter(socketpool, mdns_server, random_source, device_state)
58    led = NeoPixel("neopixel1")
59    matter.add_device(led)
60    while True:
61        matter.process_packets()
62
63
64if __name__ == "__main__":
65    import sys
66
67    replay_file = None
68    if len(sys.argv) > 1:
69        replay_file = sys.argv[1]
70    run(replay_file=replay_file)

Record and Replay RGB LED

Record and replay RGB LED state with Matter:

examples/replay_rgb_light.py
 1# SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries
 2#
 3# SPDX-License-Identifier: MIT
 4
 5"""Pure Python implementation of the Matter IOT protocol."""
 6
 7import json
 8import pathlib
 9import socket
10import time
11
12import circuitmatter as cm
13from circuitmatter.device_types.lighting import extended_color
14from circuitmatter.utility import random
15from circuitmatter.utility.mdns import DummyMDNS
16from circuitmatter.utility.mdns.avahi import Avahi
17from circuitmatter.utility.recording import RecordingRandom, RecordingSocketPool
18from circuitmatter.utility.replay import ReplayRandom, ReplaySocketPool
19
20
21class NeoPixel(extended_color.ExtendedColorLight):
22    @property
23    def color_rgb(self):
24        return self._color
25
26    @color_rgb.setter
27    def color_rgb(self, value):
28        self._color = value
29        print(f"new color 0x{value:06x}")
30
31    @property
32    def brightness(self):
33        return self._brightness
34
35    @brightness.setter
36    def brightness(self, value):
37        self._brightness = value
38        print(f"new brightness {value}")
39
40    def on(self):
41        print("on!")
42
43    def off(self):
44        print("off!")
45
46
47def run(replay_file=None):
48    device_state = pathlib.Path("live-rgb-device-state.json")
49    if replay_file:
50        replay_lines = []
51        with open(replay_file) as f:
52            device_state_fn = f.readline().strip()
53            for line in f:
54                replay_lines.append(json.loads(line))
55        socketpool = ReplaySocketPool(replay_lines)
56        mdns_server = DummyMDNS()
57        random_source = ReplayRandom(replay_lines)
58        # Reset device state to before the captured run
59        if device_state_fn == "none":
60            device_state.unlink(missing_ok=True)
61        else:
62            device_state.write_text(pathlib.Path(device_state_fn).read_text())
63    else:
64        timestamp = time.strftime("%Y%m%d-%H%M%S")
65        record_file = open(f"test_data/recorded_packets-{timestamp}.jsonl", "w")
66        device_state_fn = f"test_data/device_state-{timestamp}.json"
67        replay_device_state = pathlib.Path(device_state_fn)
68        if device_state.exists():
69            record_file.write(f"{device_state_fn}\n")
70            # Save device state before we run so replays can use it.
71            replay_device_state.write_text(device_state.read_text())
72        else:
73            # No starting state.
74            record_file.write("none\n")
75        socketpool = RecordingSocketPool(record_file, socket)
76        mdns_server = Avahi()
77        random_source = RecordingRandom(record_file, random)
78
79    matter = cm.CircuitMatter(socketpool, mdns_server, random_source, device_state)
80    led = NeoPixel("neopixel1")
81    matter.add_device(led)
82    while True:
83        matter.process_packets()
84
85
86if __name__ == "__main__":
87    import sys
88
89    replay_file = None
90    if len(sys.argv) > 1:
91        replay_file = sys.argv[1]
92    run(replay_file=replay_file)